repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_aer.utils import approximate_quantum_error, approximate_noise_model
import numpy as np
# Import Aer QuantumError functions that will be used
from qiskit_aer.noise import amplitude_damping_error, reset_error, pauli_error
from qiskit.quantum_info import Kraus
gamma = 0.23
error = amplitude_damping_error(gamma)
results = approximate_quantum_error(error, operator_string="reset")
print(results)
p = (1 + gamma - np.sqrt(1 - gamma)) / 2
q = 0
print("")
print("Expected results:")
print("P(0) = {}".format(1-(p+q)))
print("P(1) = {}".format(p))
print("P(2) = {}".format(q))
gamma = 0.23
K0 = np.array([[1,0],[0,np.sqrt(1-gamma)]])
K1 = np.array([[0,np.sqrt(gamma)],[0,0]])
results = approximate_quantum_error(Kraus([K0, K1]), operator_string="reset")
print(results)
reset_to_0 = Kraus([np.array([[1,0],[0,0]]), np.array([[0,1],[0,0]])])
reset_to_1 = Kraus([np.array([[0,0],[1,0]]), np.array([[0,0],[0,1]])])
reset_kraus = [reset_to_0, reset_to_1]
gamma = 0.23
error = amplitude_damping_error(gamma)
results = approximate_quantum_error(error, operator_list=reset_kraus)
print(results)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/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
|
import numpy as np
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
def udd10_pos(j):
return np.sin(np.pi*j/(2*10 + 2))**2
with pulse.build() as udd_sched:
pulse.play(x90, d0)
with pulse.align_func(duration=300, func=udd10_pos):
for _ in range(10):
pulse.play(x180, d0)
pulse.play(x90, d0)
udd_sched.draw()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
from collections import OrderedDict
import time
import os
import logging, warnings
from qiskit.optimization.algorithms import CplexOptimizer
from qiskit.optimization.algorithms.optimization_algorithm import OptimizationResultStatus
from dwave.system import LeapHybridSampler
from random_lp.lp_random_gen import create_models
from utilities.helpers import create_dwave_meo
TEST_DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y") + "/SPARSE/"
RES_DIR = 'RESULTS' + "/" + time.strftime("%d_%m_%Y") + "/SPARSE/"
os.makedirs(RES_DIR, exist_ok=True)
TEST_DIR
logger = logging.getLogger()
logger.setLevel(logging.INFO)
warnings.filterwarnings("ignore", category=DeprecationWarning)
qps = create_models(TEST_DIR)
# init Optimizers
cplex = CplexOptimizer()
hybrid = create_dwave_meo(LeapHybridSampler())
dwave = create_dwave_meo(num_reads=4096)
results = OrderedDict()
count_fail_hybrid, count_fail_dwave = 0, 0
for qp_name, qp in qps.items() :
print(qp_name)
print("number of qubits: ", qp.qubo.get_num_vars())
output_file_handler = logging.FileHandler(filename=RES_DIR + qp.name + ".log")
logger.addHandler(output_file_handler)
# set problem labels
for solver, label in zip([hybrid, dwave], ["hybrid_", "auto_emb_"]):
solver.min_eigen_solver.sampler.set_label(label + qp_name + "_" + str(qp.complexity()))
with open(RES_DIR + qp.name + '.res', 'w') as file:
file.write(str("Start " + qp.name + "\n " + str(qp.qubo.get_num_vars()) + " qubits needed"))
file.write("\n Leap: \n")
logger.info("\n Leap: \n ")
res_classic = cplex.solve(qp)
res_hybrid = hybrid.solve(qp)
problem_id = str(res_hybrid.min_eigen_solver_result.sampleset.info['problem_id'])
logger.info("\n problem id " + problem_id)
file.write("\n problem id: " + problem_id)
if res_hybrid.status != OptimizationResultStatus.SUCCESS:
file.write("\n No solution found with DWave Hybrid Sampler Leap.\n")
file.write("\n CPLEX:\n")
file.write(str(res_classic))
count_fail_hybrid = count_fail_hybrid + 1
if count_fail_hybrid > 2 :
break
else:
print("Leap successful!")
count_fail_hybrid = 0
if res_hybrid.fval == res_classic.fval:
file.write("\n Leap found optimal solution\n")
else:
print("\n optimal value Leap "+str(res_hybrid.fval) + " , cplex:"+ str(res_classic.fval))
file.write("\n Leap: \n")
file.write(str(res_hybrid))
file.write("\n CPLEX:\n")
file.write(str(res_classic))
if count_fail_dwave <= 2:
file.write("\n DWave Quantum: \n")
logger.info("\n DWave Quantum: \n ")
try:
res_quantum = dwave.solve(qp)
problem_id = str(res_quantum.min_eigen_solver_result.sampleset.info['problem_id'])
logger.info("\n problem id " + problem_id)
file.write("\n problem id: " + problem_id)
if res_quantum.status != OptimizationResultStatus.SUCCESS:
print("Dwave quantum solver found no solution.")
file.write("\n No solution found with DWave Quantum Solver \n")
count_fail_dwave = count_fail_dwave + 1
if count_fail_dwave == 3:
file.write("\n Stop testing DWave Quantum Solver \n")
else:
print("Dwave Quantum successful!")
count_fail_dwave = 0
if res_quantum.fval == res_classic.fval:
file.write("\n DWave quantum solver found optimal solution\n")
else:
print("\n optimal value Dwave quantum "+str(res_quantum.fval) + " , cplex:"+ str(res_classic.fval))
file.write("\n DWave quantum solver:\n")
file.write(str(res_quantum))
file.write("\n CPLEX:\n")
file.write(str(res_classic))
except Exception as ex:
print(qp_name, " ", type(ex).__name__, " : ", ex)
file.write("\n DWave Solver produced an exception:\n")
file.write(str(ex))
logger.removeHandler(output_file_handler)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice
from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel
line = LineLattice(2)
fermi = FermiHubbardModel.uniform_parameters(line, 2.0, 4.0, 3.0)
print(fermi.second_q_ops()) # Note: the trailing `s`
from qiskit_nature.second_q.hamiltonians.lattices import LineLattice
from qiskit_nature.second_q.hamiltonians import FermiHubbardModel
line = LineLattice(2)
fermi = FermiHubbardModel(line.uniform_parameters(2.0, 4.0), 3.0)
print(fermi.second_q_op()) # Note: NO trailing `s`
import numpy as np
from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
fermi = FermiHubbardModel.from_parameters(interaction, 3.0)
print(fermi.second_q_ops()) # Note: the trailing `s`
import numpy as np
from qiskit_nature.second_q.hamiltonians.lattices import Lattice
from qiskit_nature.second_q.hamiltonians import FermiHubbardModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
lattice = Lattice.from_adjacency_matrix(interaction)
fermi = FermiHubbardModel(lattice, 3.0)
print(fermi.second_q_op()) # Note: NO trailing `s`
from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice
from qiskit_nature.problems.second_quantization.lattice.models import IsingModel
line = LineLattice(2)
ising = IsingModel.uniform_parameters(line, 2.0, 4.0)
print(ising.second_q_ops()) # Note: the trailing `s`
from qiskit_nature.second_q.hamiltonians.lattices import LineLattice
from qiskit_nature.second_q.hamiltonians import IsingModel
line = LineLattice(2)
ising = IsingModel(line.uniform_parameters(2.0, 4.0))
print(ising.second_q_op()) # Note: NO trailing `s`
import numpy as np
from qiskit_nature.problems.second_quantization.lattice.models import IsingModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
ising = IsingModel.from_parameters(interaction)
print(ising.second_q_ops()) # Note: the trailing `s`
import numpy as np
from qiskit_nature.second_q.hamiltonians.lattices import Lattice
from qiskit_nature.second_q.hamiltonians import IsingModel
interaction = np.array([[4.0, 2.0], [2.0, 4.0]])
lattice = Lattice.from_adjacency_matrix(interaction)
ising = IsingModel(lattice)
print(ising.second_q_op()) # Note: NO trailing `s`
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/rubenandrebarreiro/summer-school-on-quantum-computing-software-for-near-term-quantum-devices-2020
|
rubenandrebarreiro
|
# Importing matplotlib, "in line"
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ, QuantumRegister, ClassicalRegister
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# In Jupyter Notebooks we can display this nicely using Latex.
# If not using Jupyter Notebooks you may need to remove the
# array_to_latex function and use print() instead.
from qiskit_textbook.tools import array_to_latex
# Create a Quantum Register for 2 Qubits (Quantum Bits), with a Total of 4 (2^2) Possible Processed States
qr = QuantumRegister(2)
# Create a Classical Register for 2 Bits (Classical Bits), with a Total of 2 Possible Processed States
cr = ClassicalRegister(2)
# Create a Quantum Circuit, with the two previously created Quantum and Classical Registers
qc = QuantumCircuit(qr,cr)
# Let's setup the set of necessary instructions, in order to build a Quantum Circuit,
# that implements a Quantum Entangled State in Quantum System with 2 Qubits (Quantum Bits),
# in which if a Qubit it's measured, independently of its outcome, the other Qubit (Quantum Bit)
# will collapse automatically, no matter the distance that separates the both Qubits (Quatum Bits),
# holding the opposite outcome, i.e., what's it's called, the Pauli Exclusion Principle,
# in Quantum Physics/Mechanics
# Per example:
# a) If the 1st Qubit (Quantum Bit) it's measured and collapse to the Classical State |0>,
# it's possible to state with certainty that the 2nd Qubit (Quantum Bit) will also collapse to
# the opposite Classical State |1>, for sure;
# b) If the 1st Qubit (Quantum Bit) it's measured and collapse to the Classical State |1>,
# it's possible to state with certainty that the 2nd Qubit (Quantum Bit) will also collapse to
# the opposite Classical State |0>, for sure;
# Note:
# - The observations derived from this experiment it's also valid, following the same idea,
# when the 2nd Qubit (Quantum Bit) it's measured instead of the 1st Qubit (Quantum Bit)
# Any Quantum Entanglement of States, it's implemented using the CX/CNOT Quantum Logic Gate
# (Controlled-X/Controlled-NOT), which acts on 2 Qubits (Quantum Bits), described as the following:
# - 1) Control Qubit (Quantum Bit);
# - 2) Target Qubit (Quantum Bit);
# This CX/CNOT Quantum Logic Gate (Controlled-X/Controlled-NOT) it's simple and
# has the following behaviour:
# - If the Control Qubit (Control Quantum Bit) it's set as |1>,
# performs the Pauli-X Quantum Logic Gate Operator (X Quantum Logic Gate Operator)
# onto the the Target Qubit (Target Quantum Bit);
# - Otherwise, if the Control Qubit (Control Quantum Bit) it's set as |0>,
# don't perform any Quantum Logic Gate Operator (X Quantum Logic Gate Operator)
# onto the the Target Qubit (Target Quantum Bit), letting it unchanged;
# The CX/CNOT Quantum Logic Gate (Controlled-X/Controlled-NOT) has a behaviour practically equal to a
# XOR Classical Logic Gate Operator (eXclusive OR Classical Logic Gate Operator):
# - CNOT x |q1,q2> = |q1, (q1 ⊕ q2)>;
# Note:
# - In Mathematics, the XOR Classical Logic Gate Operator (eXclusive OR Classical Logic Gate Operator)
# it's represented by the Modulo 2 Arithmetic Addition Operator
# (i.e., represented by the mathematically notation of ⊕);
# Initially, the Quantum Circuit has the both Qubits (Quantum Bits) set as |0>,
# thus the Quantum Circuit, it's represented as the Tensor Product of that two Qubits (Quantum Bits),
# forming a new Quantum State defined as |00>:
# - |Ψ> = |q1>|q2> = |0>|0> = |0> ⊗ |0> = |00>;
# Steps to build this Quantum Circuit:
# 1) Initially, let's set the 2nd Qubit (Quantum Bit),
# acting as the Control Qubit (Control Quantum Bit) as |1>,
# applying the Pauli-X Quantum Logic Quantum Gate Operator;
qc.x(1)
# 2) Let's apply a Barrier to it, in order to, ensure that all the
# previous Quantum Logic Gate Operators are applied correctly;
qc.barrier()
# 3) In order to, explore all the possible situations of this Experiment,
# let's put the Control Qubit (Control Quantum Bit) in this Quantum Circuit,
# in a Quantum Superposition of States, applying the Hadamard Quantum Logic Gate Operator to it,
# letting the Quantum System defined as:
# - |Ψ> = 1/√2 x (|01> + |11>),
# where the 1st Qubit (Quantum Bit) it's in Quantum Superposition of States;
qc.h(0)
# 4) In order to, explore all the possible situations of this Experiment,
# let's put the Control Qubit (Control Quantum Bit) in this Quantum Circuit,
# in a Quantum Superposition of States, applying the Hadamard Quantum Logic Gate Operator to it,
# letting the Quantum System defined as:
# - |Ψ> = 1/√2 x (|01> + |10>), where:
# - The 1st Qubit (Quantum Bit) it's in Quantum Superposition of States;
# - The 2nd Qubit (Quantum Bit) it's a result of the Pauli-X Quantum Logic Quantum Gate Operator,
# in the cases that the Control Qubit (Control Quantum Bit) it's set as |1>, i.e.,
# the 2nd term of the Quantum System, where |11> => |10>,
# after being applied the CX/CNOT Quantum Logic Gate (Controlled-X/Controlled-NOT);
qc.cnot(0,1)
# Draw the Quantum Circuit for the Pauli Exclusion Principle, in a graphically representation
qc.draw()
# Print the Quantum Circuit for the Pauli Exclusion Principle, in a text representation
print(qc)
# Print the Backends available in the Aer Module of the IBM Qiskit Library:
# - The Aer Module, it's the Module responsible for the Simulator of the IBM Qiskit Libraries;
Aer.backends()
# Getting the Backend for the Unitary Representation
# (i.e., the Quantum State represented as an Unitary Matrix)
backend = Aer.get_backend('unitary_simulator')
unitary = execute(qc,backend).result().get_unitary()
array_to_latex(unitary, pretext="\\text{Quantum Circuit (Unitary Matrix) = }\n")
# Getting the Backend for the Statevector Representation
# (i.e., the Quantum State represented as State Vector)
statevector_backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc,statevector_backend).result().get_statevector()
array_to_latex(final_state, pretext="\\text{Quantum Circuit (Statevector) = }\n", precision = 1)
# Plot the Bloch Spheres of the previously defined Quantum System (or, try it...),
# representing a Pauli Exclusion Principle
# Note:
# - In fact it's not possible to plot Bloch Spheres representing a whole Quantum System,
# which it's currently in a Quantum Entanglement of States, in IBM Qiskit;
plot_bloch_multivector(final_state)
# But, it's possible to plot the Q-Sphere of this Quantum Circuit
# (a "linear" combination of the several Bloch Spheres, involved) of
# the previously defined Quantum System, representing the Pauli Exclusion Principle
plot_state_qsphere(final_state)
# Now, that the Quantum Circuit it's practically defined, let's apply a Barrier to it, in order to,
# ensure that all the previous Quantum Logic Gate Operators are applied correctly
qc.barrier()
# Draw the Quantum Circuit again, after the Barrier be applied in it
qc.draw()
# Measure the State of the both Qubits (Quantum Bits), contained in the Quantum Circuit
qc.measure(0,0)
qc.measure(1,1)
# Draw the Quantum Circuit again, after the Measurement of the States be applied in it
qc.draw()
# Now, let's execute the Quantum Circuit in the QASM Simulator of the Aer Module,
# of the IBM Qiskit Library
backend = Aer.get_backend('qasm_simulator')
counts = execute(qc,backend,shots=2048).result().get_counts()
# Print the Counts of the Frequencies, resulting from this Experiment
print(counts)
# Plot the Counts of the Frequencies, resulting from this Experiment, through a Histogram
# (i.e., a Distribution of the Probabilities)
plot_histogram(counts)
# Import the IBM Q Experience, from the IBM Qiskit Library
from qiskit import IBMQ
# Update your account info saved locally
IBMQ.update_account()
# Run everytime to load your account info saved locally
IBMQ.load_account()
# Get a Provider, from the IBM Q Hub
provider = IBMQ.get_provider(hub='ibm-q')
# Print available Backends, from the Provider set before
provider.backends()
# Import the "Least Busy" function, in order to get a "Least Busy" Backend
from qiskit.providers.ibmq import least_busy
# Filter the available Backends, in order to get a list of "Large Enough Real Quantum Devices",
# i.e., containing 2 or more 2 Qubits (Quantum Bits)
large_enough_devices = provider.backends(filters = lambda b: b.configuration().n_qubits >= 2 and
not b.configuration().simulator
and b.status().operational==True)
# Or, select the "Least Busy" Backend, from the list of "Large Enough Real Quantum Devices"
backend = least_busy(large_enough_devices)
# Print the Best Backend available (i.e., the Least Busy Backend)
print("The Best Backend is: " + backend.name())
# Execute a Job for this Quantum Circuit, executing the Experiment, for 8192 Shots
job_exp = execute(qc,backend=backend,shots=8192)
# Get the Experiment Result from the previous executed Job for this Quantum Circuit
exp_result = job_exp.result()
# Get the Measurement Results, from the previous Experiment Result,
# executed by the Job for this Quantum Circuit
exp_measurement_result = exp_result.get_counts(qc)
# Print the Measurement Results, from the previous Experiment Result,
# executed by the Job for this Quantum Circuit
print(exp_measurement_result)
# Plot the Histogram (i.e., Frequencies) for the Measurement Results,
# from the previous Experiment Result, executed by the Job for this Quantum Circuit
plot_histogram(exp_measurement_result)
|
https://github.com/NesyaLab/qaoa
|
NesyaLab
|
#------------------------------------------------------------------------------
# qaoa_optimizers.py
#
# This module provides optimization routines for Quantum Approximate Optimization
# Algorithm (QAOA) [1],[2] instances applied to the Maximum Cut (MaxCut) problem [3].
# The functions facilitate the optimization of QAOA parameters using classical
# optimization methods.
#
# The module includes the following functions:
# - objective_function(init_point, circuit, shots): Computes the objective
# function for QAOA by running the quantum circuit and evaluating the MaxCut
# energy.
# - callback(x): Callback function for counting the number of optimization steps
# during the optimization process.
# - simple_optimization(circuit, method='COBYLA', seed=None, shots=1024,
# verbose=True): Performs a simple optimization routine using a specified
# classical optimization method (default is 'COBYLA') and returns the optimized
# parameters and objective function value.
#
# Refs.
# [1] https://arxiv.org/abs/1411.4028
# [2] https://learning.quantum.ibm.com/tutorial/quantum-approximate-optimization-algorithm
# [3] https://en.wikipedia.org/wiki/Maximum_cut
#
# © Leonardo Lavagna 2024
# @ NESYA https://github.com/NesyaLab
#------------------------------------------------------------------------------
import random
import numpy as np
from typing import List, Tuple
from networkx import Graph
from qiskit import QuantumCircuit, transpile
from qiskit_aer import Aer
from scipy.optimize import minimize
from functions import maxcut_utilities as m_utils
from config import backend, verbose
num_evaluations = 0
def objective_function(init_point, circuit, shots):
# Setup
G = circuit.G
qc = circuit.get_circuit()
qc = qc.assign_parameters(init_point)
# Executing the circuit to get the energies...
t_qc = transpile(qc, backend=backend)
job = backend.run(t_qc, shots=shots)
counts = job.result().get_counts(qc)
# Getting the results...
energy = m_utils.compute_maxcut_energy(G, m_utils.invert_counts(counts), verbose=verbose)
return -energy
def callback(x: List):
"""
Function to be called at each iteration of the optimization step (in the minimize method) to count the number of optimization steps.
Args:
x (list): current solution of the optimization step
"""
global num_evaluations
num_evaluations += 1
def simple_optimization(circuit, method: str = 'COBYLA', seed: int = None, shots: int = 1024, verbose: bool = True) -> Tuple[np.ndarray, float]:
"""
Perform a simple optimization routine.
Args:
circuit (QuantumCircuit): Quantum circuit.
method (str): Type of optimizer. The default is 'COBYLA'.
seed (int): Seed needed for reproducibility. The default is None.
verbose (bool): If True enters in debugging mode. The default is False.
Returns:
tuple: Optimized parameters and corresponding objective function value.
"""
# Setup
betas = circuit.betas
gammas = circuit.gammas
init_point = list(betas) + list(gammas)
if verbose:
print(" --------------------------------- ")
print("| Parameters for the optimization. |".upper())
print(" --------------------------------- ")
print("\t * betas:", betas)
print("\t * gammas:", gammas)
print("\t * init_point:", init_point)
# Optimizing...
if verbose is True:
print(" --------------- ")
print("| Optimizing... |".upper())
print(" --------------- ")
optimizer = minimize(objective_function, init_point, args=(circuit,shots), callback=callback, method=method)
elif verbose is False:
optimizer = minimize(objective_function, init_point, args=(circuit,shots), method=method)
# Getting the results...
optimal_value = -optimizer.fun
optimal_angles = optimizer.x
if verbose:
print(" --------- ")
print("| Results. |".upper())
print(" --------- ")
print("\t * optimal_anlges:", optimal_angles)
print("\t * optimal_value:", optimal_value)
return optimizer.x, optimizer.fun
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
#!pip install qiskit
# Include the necessary imports for this program
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Create a Quantum Register with 1 qubit (wire).
qr = QuantumRegister(1)
# Create a Classical Register with 1 bit (double wire).
cr = ClassicalRegister(1)
# Create a Quantum Circuit from the quantum and classical registers
circ = QuantumCircuit(qr, cr)
# Place an Hadamard gate on the qubit wire
circ.h(qr[0])
# Measure the qubit into the classical register
circ.measure(qr, cr)
# Draw the circuit
circ.draw(output='mpl')
# Import BasicAer
from qiskit import BasicAer
# Use BasicAer's qasm_simulator
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator, running it 100 times.
job_sim = execute(circ, backend_sim, shots=100)
# Grab the results from the job.
result_sim = job_sim.result()
# Print the counts, which are contained in a Python dictionary
counts = result_sim.get_counts(circ)
print(counts)
from qiskit.tools.visualization import plot_histogram
# Plot the results on a bar chart
plot_histogram(counts)
# Include the necessary imports for this program
# Create a Quantum Register with 1 qubit (wire).
# Create a Classical Register with 1 bit (double wire).
# Create a Quantum Circuit from the quantum and classical registers
# Place an X gate followed by a Hadamard gate on the qubit wire. The registers are zero-indexed.
# Measure the qubit into the classical register
# Draw the circuit
# Import BasicAer
# Use BasicAer's qasm_simulator
# Execute the circuit on the qasm simulator, running it 100 times.
# Grab the results from the job.
# Print the counts, which are contained in a Python dictionary
# Plot the results on a bar chart
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# 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.
"""The Variational Quantum Time Evolution Interface"""
from __future__ import annotations
from abc import ABC
from collections.abc import Mapping, Callable, Sequence
from typing import Type
import numpy as np
from scipy.integrate import OdeSolver
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.opflow import PauliSumOp
from qiskit.primitives import BaseEstimator
from qiskit.quantum_info.operators.base_operator import BaseOperator
from .solvers.ode.forward_euler_solver import ForwardEulerSolver
from .solvers.ode.ode_function_factory import OdeFunctionFactory
from .solvers.ode.var_qte_ode_solver import VarQTEOdeSolver
from .solvers.var_qte_linear_solver import VarQTELinearSolver
from .variational_principles.variational_principle import VariationalPrinciple
from .var_qte_result import VarQTEResult
from ..time_evolution_problem import TimeEvolutionProblem
from ...observables_evaluator import estimate_observables
class VarQTE(ABC):
"""Variational Quantum Time Evolution.
Algorithms that use variational principles to compute a time evolution for a given
Hermitian operator (Hamiltonian) and a quantum state prepared by a parameterized quantum
circuit.
Attributes:
ansatz (QuantumCircuit): Ansatz to be used for variational time evolution.
initial_parameters (Mapping[Parameter, float] | Sequence[float]): Initial
parameter values for an ansatz.
variational_principle (VariationalPrinciple): Variational Principle to be used.
estimator (BaseEstimator): An estimator primitive used for calculating expectation
values of ``TimeEvolutionProblem.aux_operators``.
ode_solver(Type[OdeSolver] | str): ODE solver callable that implements a SciPy
``OdeSolver`` interface or a string indicating a valid method offered by SciPy.
lse_solver (Callable[[np.ndarray, np.ndarray], np.ndarray] | None): Linear system
of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b``
and returns ``x``.
num_timesteps (int | None): The number of timesteps to take. If None, it is
automatically selected to achieve a timestep of approximately 0.01. Only
relevant in case of the ``ForwardEulerSolver``.
imag_part_tol (float): Allowed value of an imaginary part that can be neglected if no
imaginary part is expected.
num_instability_tol (float): The amount of negative value that is allowed to be
rounded up to 0 for quantities that are expected to be
non-negative.
References:
[1] Benjamin, Simon C. et al. (2019).
Theory of variational quantum simulation. `<https://doi.org/10.22331/q-2019-10-07-191>`_
"""
def __init__(
self,
ansatz: QuantumCircuit,
initial_parameters: Mapping[Parameter, float] | Sequence[float],
variational_principle: VariationalPrinciple,
estimator: BaseEstimator,
ode_solver: Type[OdeSolver] | str = ForwardEulerSolver,
lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None,
num_timesteps: int | None = None,
imag_part_tol: float = 1e-7,
num_instability_tol: float = 1e-7,
) -> None:
r"""
Args:
ansatz: Ansatz to be used for variational time evolution.
initial_parameters: Initial parameter values for an ansatz.
variational_principle: Variational Principle to be used.
estimator: An estimator primitive used for calculating expectation values of
TimeEvolutionProblem.aux_operators.
ode_solver: ODE solver callable that implements a SciPy ``OdeSolver`` interface or a
string indicating a valid method offered by SciPy.
lse_solver: Linear system of equations solver callable. It accepts ``A`` and ``b`` to
solve ``Ax=b`` and returns ``x``.
num_timesteps: The number of timesteps to take. If None, it is
automatically selected to achieve a timestep of approximately 0.01. Only
relevant in case of the ``ForwardEulerSolver``.
imag_part_tol: Allowed value of an imaginary part that can be neglected if no
imaginary part is expected.
num_instability_tol: The amount of negative value that is allowed to be
rounded up to 0 for quantities that are expected to be
non-negative.
"""
super().__init__()
self.ansatz = ansatz
self.initial_parameters = initial_parameters
self.variational_principle = variational_principle
self.estimator = estimator
self.num_timesteps = num_timesteps
self.lse_solver = lse_solver
self.ode_solver = ode_solver
self.imag_part_tol = imag_part_tol
self.num_instability_tol = num_instability_tol
# OdeFunction abstraction kept for potential extensions - unclear at the moment;
# currently hidden from the user
self._ode_function_factory = OdeFunctionFactory()
def evolve(self, evolution_problem: TimeEvolutionProblem) -> VarQTEResult:
"""Apply Variational Quantum Time Evolution to the given operator.
Args:
evolution_problem: Instance defining an evolution problem.
Returns:
Result of the evolution which includes a quantum circuit with bound parameters as an
evolved state and, if provided, observables evaluated on the evolved state.
Raises:
ValueError: If ``initial_state`` is included in the ``evolution_problem``.
"""
self._validate_aux_ops(evolution_problem)
if evolution_problem.initial_state is not None:
raise ValueError(
"An initial_state was provided to the TimeEvolutionProblem but this is not "
"supported by VarQTE. Please remove this state from the problem definition "
"and set VarQTE.initial_parameters with the corresponding initial parameter "
"values instead."
)
init_state_param_dict = self._create_init_state_param_dict(
self.initial_parameters, self.ansatz.parameters
)
# unwrap PauliSumOp (in the future this will be deprecated)
if isinstance(evolution_problem.hamiltonian, PauliSumOp):
hamiltonian = (
evolution_problem.hamiltonian.primitive * evolution_problem.hamiltonian.coeff
)
else:
hamiltonian = evolution_problem.hamiltonian
evolved_state, param_values, time_points = self._evolve(
init_state_param_dict,
hamiltonian,
evolution_problem.time,
evolution_problem.t_param,
)
observables = []
if evolution_problem.aux_operators is not None:
for values in param_values:
# cannot batch evaluation because estimate_observables
# only accepts single circuits
evol_state = self.ansatz.assign_parameters(
dict(zip(init_state_param_dict.keys(), values))
)
observable = estimate_observables(
self.estimator,
evol_state,
evolution_problem.aux_operators,
)
observables.append(observable)
# TODO: deprecate returning evaluated_aux_ops.
# As these are the observables for the last time step.
evaluated_aux_ops = observables[-1] if len(observables) > 0 else None
return VarQTEResult(
evolved_state, evaluated_aux_ops, observables, time_points, param_values
)
def _evolve(
self,
init_state_param_dict: Mapping[Parameter, float],
hamiltonian: BaseOperator,
time: float,
t_param: Parameter | None = None,
) -> tuple[QuantumCircuit | None, Sequence[Sequence[float]], Sequence[float]]:
r"""
Helper method for performing time evolution. Works both for imaginary and real case.
Args:
init_state_param_dict: Parameter dictionary with initial values for a given
parametrized state/ansatz.
hamiltonian: Operator used for Variational Quantum Time Evolution (VarQTE).
time: Total time of evolution.
t_param: Time parameter in case of a time-dependent Hamiltonian.
Returns:
Result of the evolution which is a quantum circuit with bound parameters as an
evolved state.
"""
init_state_parameters = list(init_state_param_dict.keys())
init_state_parameter_values = list(init_state_param_dict.values())
linear_solver = VarQTELinearSolver(
self.variational_principle,
hamiltonian,
self.ansatz,
init_state_parameters,
t_param,
self.lse_solver,
self.imag_part_tol,
)
# Convert the operator that holds the Hamiltonian and ansatz into a NaturalGradient operator
ode_function = self._ode_function_factory._build(
linear_solver, init_state_param_dict, t_param
)
ode_solver = VarQTEOdeSolver(
init_state_parameter_values, ode_function, self.ode_solver, self.num_timesteps
)
final_param_values, param_values, time_points = ode_solver.run(time)
param_dict_from_ode = dict(zip(init_state_parameters, final_param_values))
return self.ansatz.assign_parameters(param_dict_from_ode), param_values, time_points
@staticmethod
def _create_init_state_param_dict(
param_values: Mapping[Parameter, float] | Sequence[float],
init_state_parameters: Sequence[Parameter],
) -> Mapping[Parameter, float]:
r"""
If ``param_values`` is a dictionary, it looks for parameters present in an initial state
(an ansatz) in a ``param_values``. Based on that, it creates a new dictionary containing
only parameters present in an initial state and their respective values.
If ``param_values`` is a list of values, it creates a new dictionary containing
parameters present in an initial state and their respective values.
Args:
param_values: Dictionary which relates parameter values to the parameters or a list of
values.
init_state_parameters: Parameters present in a quantum state.
Returns:
Dictionary that maps parameters of an initial state to some values.
Raises:
ValueError: If the dictionary with parameter values provided does not include all
parameters present in the initial state or if the list of values provided is not the
same length as the list of parameters.
TypeError: If an unsupported type of ``param_values`` provided.
"""
if isinstance(param_values, Mapping):
init_state_parameter_values: Sequence[float] = []
for param in init_state_parameters:
if param in param_values.keys():
init_state_parameter_values.append(param_values[param])
else:
raise ValueError(
f"The dictionary with parameter values provided does not "
f"include all parameters present in the initial state."
f"Parameters present in the state: {init_state_parameters}, "
f"parameters in the dictionary: "
f"{list(param_values.keys())}."
)
elif isinstance(param_values, (Sequence, np.ndarray)):
if len(init_state_parameters) != len(param_values):
raise ValueError(
f"Initial state has {len(init_state_parameters)} parameters and the"
f" list of values has {len(param_values)} elements. They should be"
f" equal in length."
)
init_state_parameter_values = param_values
else:
raise TypeError(f"Unsupported type of param_values provided: {type(param_values)}.")
init_state_param_dict = dict(zip(init_state_parameters, init_state_parameter_values))
return init_state_param_dict
def _validate_aux_ops(self, evolution_problem: TimeEvolutionProblem) -> None:
if evolution_problem.aux_operators is not None and self.estimator is None:
raise ValueError(
"aux_operators were provided for evaluations but no ``estimator`` was provided."
)
|
https://github.com/matteoacrossi/oqs-jupyterbook
|
matteoacrossi
|
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from bokeh.layouts import layout
from bokeh.layouts import widgetbox
from bokeh.embed import file_html
from bokeh.io import show
from bokeh.io import output_notebook
from bokeh.models import Text
from bokeh.models import Plot
from bokeh.models import Slider
from bokeh.models import Circle
from bokeh.models import Range1d
from bokeh.models import CustomJS
from bokeh.models import HoverTool
from bokeh.models import LinearAxis
from bokeh.models import ColumnDataSource
from bokeh.models import SingleIntervalTicker
from bokeh.palettes import Spectral6
output_notebook()
def gendata():
xs = np.linspace(0,6*np.pi)
ws = np.linspace(.1,2.,20)
ys = [np.sin(x*ws) for x in xs]
return xs, ws, ys
xs, ws, ys = gendata()
ws_int = list(range(len(ws)))
data = pd.DataFrame(ys)
sources = {}
for w, _ in enumerate(ws):
new_df = pd.DataFrame({'x':xs,'fun':data[w]})
sources['_' + str(w)] = ColumnDataSource(new_df)
dictionary_of_sources = dict(zip([w for w in ws_int], ['_%s' % w for w in ws_int]))
dictionary_of_sources
js_source_array = str(dictionary_of_sources).replace("'", "")
js_source_array
xdr = Range1d(min(xs), max(xs))
ydr = Range1d(-2, 2)
plot = Plot(
x_range=xdr,
y_range=ydr,
plot_width=800,
plot_height=400,
outline_line_color=None,
toolbar_location=None,
min_border=20,
)
AXIS_FORMATS = dict(
minor_tick_in=None,
minor_tick_out=None,
major_tick_in=None,
major_label_text_font_size="10pt",
major_label_text_font_style="normal",
axis_label_text_font_size="10pt",
axis_line_color='#AAAAAA',
major_tick_line_color='#AAAAAA',
major_label_text_color='#666666',
major_tick_line_cap="round",
axis_line_cap="round",
axis_line_width=1,
major_tick_line_width=1,
)
xaxis = LinearAxis(ticker=SingleIntervalTicker(interval=1), axis_label="x", **AXIS_FORMATS)
yaxis = LinearAxis(ticker=SingleIntervalTicker(interval=20), axis_label="sin(w*x)", **AXIS_FORMATS)
plot.add_layout(xaxis, 'below')
plot.add_layout(yaxis, 'left')
renderer_source = sources['_%s' % ws_int[0]]
circle_glyph = Circle(
x='x', y='fun', size=20, fill_alpha=0.8, fill_color='#7c7e71',
line_color='#7c7e71', line_width=0.5, line_alpha=0.5)
circle_renderer = plot.add_glyph(renderer_source, circle_glyph)
# Add the slider
code = """
var w = slider.value,
sources = %s,
new_source_data = sources[w].data;
renderer_source.data = new_source_data;
""" % js_source_array
callback = CustomJS(args=sources, code=code)
slider = Slider(start=ws_int[0], end=ws_int[-1], value=1, step=1, title="w", callback=callback)
callback.args["renderer_source"] = renderer_source
callback.args["slider"] = slider
#callback.args["text_source"] = text_source
show(layout([[plot], [slider]], sizing_mode='scale_width'))
|
https://github.com/jeevesh2002/QuantumKatasQiskit
|
jeevesh2002
|
# Run this cell using Ctrl+Enter (⌘+Enter on Mac).
from testing import exercise, create_empty_matrix
from typing import List
import math, cmath
Matrix = List[List[complex]]
@exercise
def matrix_add(a : Matrix, b : Matrix) -> Matrix:
# You can get the size of a matrix like this:
rows = len(a)
columns = len(a[0])
# You can use the following function to initialize a rows×columns matrix filled with 0s to store your answer
c = create_empty_matrix(rows, columns)
for i in range(rows):
for j in range(columns):
# You can access elements of a matrix like this:
x = a[i][j]
y = b[i][j]
# You can modify the elements of a matrix like this:
c[i][j] = a[i][j] + b[i][j]
return c
@exercise
def scalar_mult(x : complex, a : Matrix) -> Matrix:
rows = len(a)
columns = len(a[0])
c = create_empty_matrix(rows, columns)
for i in range(rows):
for j in range(columns):
c[i][j] = a[i][j] * x
return c
@exercise
def matrix_mult(a : Matrix, b : Matrix) -> Matrix:
rows = len(a) # the number of rows of the left matrix
common = len(a[0]) # = len(b) - the common dimension of the matrices
columns = len(b[0]) # the number of columns of the right matrix
ans = create_empty_matrix(rows, columns)
for currentRow in range(rows):
for currentColumn in range(columns):
for k in range(common):
ans[currentRow][currentColumn] += a[currentRow][k] * b[k][currentColumn]
return ans
@exercise
def matrix_inverse(m : Matrix) -> Matrix:
# Extract each element of the array into a named variable
a = m[0][0]
b = m[0][1]
c = m[1][0]
d = m[1][1]
# Calculate the determinant
determinant = (a * d) - (b * c)
# Create the inverse of the matrix following the formula above
ans = [[d / determinant, -b / determinant], [-c / determinant, a / determinant]]
return ans
@exercise
def transpose(a : Matrix) -> Matrix:
rows = len(a)
columns = len(a[0])
# Note that the resulting matrix dimensions are swapped compared to the original ones
ans = create_empty_matrix(columns, rows)
for i in range(rows):
for j in range(columns):
ans[j][i] = a[i][j]
return ans
@exercise
def conjugate(a : Matrix) -> Matrix:
rows = len(a)
columns = len(a[0])
ans = create_empty_matrix(rows, columns)
for i in range(rows):
for j in range(columns):
ans[i][j] = complex(a[i][j].real, -a[i][j].imag)
return ans
@exercise
def adjoint(a : Matrix) -> Matrix:
# Call the transpose function with the input matrix a
transp = transpose(a)
# Call the conjugate function with the transposed matrix as input
ans = conjugate(transp)
return ans
from pytest import approx
@exercise
def is_matrix_unitary(a : Matrix) -> bool:
n = len(a)
# Calculate the adjoint matrix
adjointA = adjoint(a)
# Multiply the adjoint matrix by the input matrix
multipliedMatrix = matrix_mult(a, adjointA)
# Check whether the multiplication result is (approximately) identity matrix
for i in range(n):
for j in range(n):
# An identity matrix has 1's in all the places where the row index and column index are equal...
if i == j:
if multipliedMatrix[i][j] != approx(1):
return False
# ... and 0's in all the places where the row index and column index are different
else:
if multipliedMatrix[i][j] != approx(0):
return False
return True
@exercise
def inner_prod(v : Matrix, w : Matrix) -> complex:
# Calculate the adjoint of the v vector
adjointV = adjoint(v)
# Multiply the adjoint v and w. The result will be a matrix with only one element.
resultMatrix = matrix_mult(adjointV, w)
# To get the actual complex number, we have to take one element from the multiplication result.
return resultMatrix[0][0]
@exercise
def normalize(v : Matrix) -> Matrix:
norm = math.sqrt(inner_prod(v, v).real)
n = len(v)
ans = create_empty_matrix(n, 1)
# Divide each element of the vector by the norm
for i in range(n):
ans[i][0] = v[i][0] / norm
return ans
@exercise
def outer_prod(v : Matrix, w : Matrix) -> Matrix:
# Calculate adjoint of the W
adjointW = adjoint(w)
# Multiply V by W adjoint
return matrix_mult(v, adjointW)
@exercise
def tensor_product(a : Matrix, b : Matrix) -> Matrix:
aRows = len(a) # the number of rows for matrix a
aColumns = len(a[0]) # the number of columns for matrix a
bRows = len(b) # the number of rows for matrix b
bColumns = len(b[0]) # the number of columns for matrix b
ans = create_empty_matrix(aRows * bRows, aColumns * bColumns)
# Outer pair of loops, iterating trough the elements of the left matrix
for i in range(aRows):
for j in range(aColumns):
# Inner pair of loops, iterating through the elements of the right matrix
for k in range(bRows):
for l in range(bColumns):
ans[i * bRows + k][j * bColumns + l] = a[i][j] * b[k][l]
return ans
from pytest import approx
@exercise
def find_eigenvalue(a : Matrix, v : Matrix) -> float:
n = len(v)
multiplied = matrix_mult(a, v)
for i in range(n):
if (v[i][0] != approx(0)):
return multiplied[i][0] / v[i][0]
@exercise
def find_eigenvector(a : Matrix, x : float) -> Matrix:
# Check for possible edge cases
if (a[0][1] == 0):
if (a[0][0] - x == 0):
if (a[1][0] == 0):
return [[1], [0]]
else:
return [[(a[1][1] - x) / (-a[1][0])], [1]]
else:
return [[0], [1]]
v0 = 1
v1 = (a[0][0] - x) / (-a[0][1])
return [[v0], [v1]]
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Create circuit to test transpiler on
from qiskit import QuantumCircuit
from qiskit.circuit.library import GroverOperator, Diagonal
oracle = Diagonal([1]*7 + [-1])
qc = QuantumCircuit(3)
qc.h([0,1,2])
qc = qc.compose(GroverOperator(oracle))
# Use Statevector object to calculate the ideal output
from qiskit.quantum_info import Statevector
ideal_distribution = Statevector.from_instruction(qc).probabilities_dict()
from qiskit.visualization import plot_histogram
plot_histogram(ideal_distribution)
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = service.backend('ibm_algiers')
# Need to add measurements to the circuit
qc.measure_all()
from qiskit import transpile
circuits = []
for optimization_level in [0, 3]:
t_qc = transpile(qc,
backend,
optimization_level=optimization_level,
seed_transpiler=0)
print(f'CNOTs (optimization_level={optimization_level}): ',
t_qc.count_ops()['cx'])
circuits.append(t_qc)
from qiskit.transpiler import PassManager, InstructionDurations
from qiskit.transpiler.passes import ASAPSchedule, DynamicalDecoupling
from qiskit.circuit.library import XGate
# Get gate durations so the transpiler knows how long each operation takes
durations = InstructionDurations.from_backend(backend)
# This is the sequence we'll apply to idling qubits
dd_sequence = [XGate(), XGate()]
# Run scheduling and dynamic decoupling passes on circuit
pm = PassManager([ASAPSchedule(durations),
DynamicalDecoupling(durations, dd_sequence)]
)
circ_dd = pm.run(circuits[1])
# Add this new circuit to our list
circuits.append(circ_dd)
from qiskit_ibm_runtime import Sampler, Session
with Session(service=service, backend=backend):
sampler = Sampler()
job = sampler.run(
circuits=circuits, # sample all three circuits
skip_transpilation=True,
shots=8000)
result = job.result()
from qiskit.visualization import plot_histogram
binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists]
plot_histogram(binary_prob+[ideal_distribution],
bar_labels=False,
legend=['optimization_level=0',
'optimization_level=3',
'optimization_level=3 + dd',
'ideal distribution'])
from qiskit.quantum_info import hellinger_fidelity
for counts in result.quasi_dists:
print(
f"{hellinger_fidelity(counts.binary_probabilities(), ideal_distribution):.3f}"
)
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/quantastica/qiskit-toaster
|
quantastica
|
import unittest
from qiskit import QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.providers.aer import AerSimulator
import numpy as np
import logging
import os
try:
from . import common
except Exception:
import common
@unittest.skipUnless(
os.getenv("SLOW") == "1",
"Skipping this test (environment variable SLOW must be set to 1)",
)
class TestSpeed(common.TestToasterBase):
def test_qft25_toaster(self):
logging.info("======= Starting our function =======")
qc = self.get_qft25_qc()
stats = self.execute_and_get_stats(
self.toaster_backend(),
# Aer.get_backend("qasm_simulator"),
qc,
1,
)
print("QFT25 toaster:", stats)
logging.info("======= Ending our function =======")
def test_qft25_aer(self):
logging.info("======= Starting our function =======")
qc = self.get_qft25_qc()
qc.save_state()
stats = self.execute_and_get_stats(
AerSimulator(method="statevector"), qc, 1,
)
print("QFT25 toaster:", stats)
logging.info("======= Ending our function =======")
@classmethod
def execute_and_get_stats(cls, backend, qc, shots):
job = execute(
qc,
optimization_level=0,
backend=backend,
shots=shots,
seed_simulator=1,
)
job_result = job.result()
counts = job_result.get_counts(qc)
total_counts = 0
for c in counts:
total_counts += counts[c]
ret = dict()
ret["counts"] = counts
ret["totalcounts"] = total_counts
return ret
@staticmethod
def get_qft25_qc():
qc = QuantumCircuit()
q = QuantumRegister(25, "q")
qc.add_register(q)
qc.h(q[24])
qc.crz(np.pi / 2, q[23], q[24])
qc.h(q[23])
qc.crz(np.pi / 4, q[22], q[24])
qc.crz(np.pi / 2, q[22], q[23])
qc.h(q[22])
qc.crz(np.pi / 8, q[21], q[24])
qc.crz(np.pi / 4, q[21], q[23])
qc.crz(np.pi / 2, q[21], q[22])
qc.h(q[21])
qc.crz(np.pi / 16, q[20], q[24])
qc.crz(np.pi / 8, q[20], q[23])
qc.crz(np.pi / 4, q[20], q[22])
qc.crz(np.pi / 2, q[20], q[21])
qc.h(q[20])
qc.crz(np.pi / 32, q[19], q[24])
qc.crz(np.pi / 16, q[19], q[23])
qc.crz(np.pi / 8, q[19], q[22])
qc.crz(np.pi / 4, q[19], q[21])
qc.crz(np.pi / 2, q[19], q[20])
qc.h(q[19])
qc.crz(np.pi / 64, q[18], q[24])
qc.crz(np.pi / 32, q[18], q[23])
qc.crz(np.pi / 16, q[18], q[22])
qc.crz(np.pi / 8, q[18], q[21])
qc.crz(np.pi / 4, q[18], q[20])
qc.crz(np.pi / 2, q[18], q[19])
qc.h(q[18])
qc.crz(np.pi / 128, q[17], q[24])
qc.crz(np.pi / 64, q[17], q[23])
qc.crz(np.pi / 32, q[17], q[22])
qc.crz(np.pi / 16, q[17], q[21])
qc.crz(np.pi / 8, q[17], q[20])
qc.crz(np.pi / 4, q[17], q[19])
qc.crz(np.pi / 2, q[17], q[18])
qc.h(q[17])
qc.crz(np.pi / 256, q[16], q[24])
qc.crz(np.pi / 128, q[16], q[23])
qc.crz(np.pi / 64, q[16], q[22])
qc.crz(np.pi / 32, q[16], q[21])
qc.crz(np.pi / 16, q[16], q[20])
qc.crz(np.pi / 8, q[16], q[19])
qc.crz(np.pi / 4, q[16], q[18])
qc.crz(np.pi / 2, q[16], q[17])
qc.h(q[16])
qc.crz(np.pi / 512, q[15], q[24])
qc.crz(np.pi / 256, q[15], q[23])
qc.crz(np.pi / 128, q[15], q[22])
qc.crz(np.pi / 64, q[15], q[21])
qc.crz(np.pi / 32, q[15], q[20])
qc.crz(np.pi / 16, q[15], q[19])
qc.crz(np.pi / 8, q[15], q[18])
qc.crz(np.pi / 4, q[15], q[17])
qc.crz(np.pi / 2, q[15], q[16])
qc.h(q[15])
qc.crz(np.pi / 1024, q[14], q[24])
qc.crz(np.pi / 512, q[14], q[23])
qc.crz(np.pi / 256, q[14], q[22])
qc.crz(np.pi / 128, q[14], q[21])
qc.crz(np.pi / 64, q[14], q[20])
qc.crz(np.pi / 32, q[14], q[19])
qc.crz(np.pi / 16, q[14], q[18])
qc.crz(np.pi / 8, q[14], q[17])
qc.crz(np.pi / 4, q[14], q[16])
qc.crz(np.pi / 2, q[14], q[15])
qc.h(q[14])
qc.crz(np.pi / 2048, q[13], q[24])
qc.crz(np.pi / 1024, q[13], q[23])
qc.crz(np.pi / 512, q[13], q[22])
qc.crz(np.pi / 256, q[13], q[21])
qc.crz(np.pi / 128, q[13], q[20])
qc.crz(np.pi / 64, q[13], q[19])
qc.crz(np.pi / 32, q[13], q[18])
qc.crz(np.pi / 16, q[13], q[17])
qc.crz(np.pi / 8, q[13], q[16])
qc.crz(np.pi / 4, q[13], q[15])
qc.crz(np.pi / 2, q[13], q[14])
qc.h(q[13])
qc.crz(np.pi / 4096, q[12], q[24])
qc.crz(np.pi / 2048, q[12], q[23])
qc.crz(np.pi / 1024, q[12], q[22])
qc.crz(np.pi / 512, q[12], q[21])
qc.crz(np.pi / 256, q[12], q[20])
qc.crz(np.pi / 128, q[12], q[19])
qc.crz(np.pi / 64, q[12], q[18])
qc.crz(np.pi / 32, q[12], q[17])
qc.crz(np.pi / 16, q[12], q[16])
qc.crz(np.pi / 8, q[12], q[15])
qc.crz(np.pi / 4, q[12], q[14])
qc.crz(np.pi / 2, q[12], q[13])
qc.h(q[12])
qc.crz(np.pi / 8192, q[11], q[24])
qc.crz(np.pi / 4096, q[11], q[23])
qc.crz(np.pi / 2048, q[11], q[22])
qc.crz(np.pi / 1024, q[11], q[21])
qc.crz(np.pi / 512, q[11], q[20])
qc.crz(np.pi / 256, q[11], q[19])
qc.crz(np.pi / 128, q[11], q[18])
qc.crz(np.pi / 64, q[11], q[17])
qc.crz(np.pi / 32, q[11], q[16])
qc.crz(np.pi / 16, q[11], q[15])
qc.crz(np.pi / 8, q[11], q[14])
qc.crz(np.pi / 4, q[11], q[13])
qc.crz(np.pi / 2, q[11], q[12])
qc.h(q[11])
qc.crz(np.pi / 16384, q[10], q[24])
qc.crz(np.pi / 8192, q[10], q[23])
qc.crz(np.pi / 4096, q[10], q[22])
qc.crz(np.pi / 2048, q[10], q[21])
qc.crz(np.pi / 1024, q[10], q[20])
qc.crz(np.pi / 512, q[10], q[19])
qc.crz(np.pi / 256, q[10], q[18])
qc.crz(np.pi / 128, q[10], q[17])
qc.crz(np.pi / 64, q[10], q[16])
qc.crz(np.pi / 32, q[10], q[15])
qc.crz(np.pi / 16, q[10], q[14])
qc.crz(np.pi / 8, q[10], q[13])
qc.crz(np.pi / 4, q[10], q[12])
qc.crz(np.pi / 2, q[10], q[11])
qc.h(q[10])
qc.crz(np.pi / 32768, q[9], q[24])
qc.crz(np.pi / 16384, q[9], q[23])
qc.crz(np.pi / 8192, q[9], q[22])
qc.crz(np.pi / 4096, q[9], q[21])
qc.crz(np.pi / 2048, q[9], q[20])
qc.crz(np.pi / 1024, q[9], q[19])
qc.crz(np.pi / 512, q[9], q[18])
qc.crz(np.pi / 256, q[9], q[17])
qc.crz(np.pi / 128, q[9], q[16])
qc.crz(np.pi / 64, q[9], q[15])
qc.crz(np.pi / 32, q[9], q[14])
qc.crz(np.pi / 16, q[9], q[13])
qc.crz(np.pi / 8, q[9], q[12])
qc.crz(np.pi / 4, q[9], q[11])
qc.crz(np.pi / 2, q[9], q[10])
qc.h(q[9])
qc.crz(np.pi / 65536, q[8], q[24])
qc.crz(np.pi / 32768, q[8], q[23])
qc.crz(np.pi / 16384, q[8], q[22])
qc.crz(np.pi / 8192, q[8], q[21])
qc.crz(np.pi / 4096, q[8], q[20])
qc.crz(np.pi / 2048, q[8], q[19])
qc.crz(np.pi / 1024, q[8], q[18])
qc.crz(np.pi / 512, q[8], q[17])
qc.crz(np.pi / 256, q[8], q[16])
qc.crz(np.pi / 128, q[8], q[15])
qc.crz(np.pi / 64, q[8], q[14])
qc.crz(np.pi / 32, q[8], q[13])
qc.crz(np.pi / 16, q[8], q[12])
qc.crz(np.pi / 8, q[8], q[11])
qc.crz(np.pi / 4, q[8], q[10])
qc.crz(np.pi / 2, q[8], q[9])
qc.h(q[8])
qc.crz(np.pi / 1.31072e5, q[7], q[24])
qc.crz(np.pi / 65536, q[7], q[23])
qc.crz(np.pi / 32768, q[7], q[22])
qc.crz(np.pi / 16384, q[7], q[21])
qc.crz(np.pi / 8192, q[7], q[20])
qc.crz(np.pi / 4096, q[7], q[19])
qc.crz(np.pi / 2048, q[7], q[18])
qc.crz(np.pi / 1024, q[7], q[17])
qc.crz(np.pi / 512, q[7], q[16])
qc.crz(np.pi / 256, q[7], q[15])
qc.crz(np.pi / 128, q[7], q[14])
qc.crz(np.pi / 64, q[7], q[13])
qc.crz(np.pi / 32, q[7], q[12])
qc.crz(np.pi / 16, q[7], q[11])
qc.crz(np.pi / 8, q[7], q[10])
qc.crz(np.pi / 4, q[7], q[9])
qc.crz(np.pi / 2, q[7], q[8])
qc.h(q[7])
qc.crz(np.pi / 2.62144e5, q[6], q[24])
qc.crz(np.pi / 1.31072e5, q[6], q[23])
qc.crz(np.pi / 65536, q[6], q[22])
qc.crz(np.pi / 32768, q[6], q[21])
qc.crz(np.pi / 16384, q[6], q[20])
qc.crz(np.pi / 8192, q[6], q[19])
qc.crz(np.pi / 4096, q[6], q[18])
qc.crz(np.pi / 2048, q[6], q[17])
qc.crz(np.pi / 1024, q[6], q[16])
qc.crz(np.pi / 512, q[6], q[15])
qc.crz(np.pi / 256, q[6], q[14])
qc.crz(np.pi / 128, q[6], q[13])
qc.crz(np.pi / 64, q[6], q[12])
qc.crz(np.pi / 32, q[6], q[11])
qc.crz(np.pi / 16, q[6], q[10])
qc.crz(np.pi / 8, q[6], q[9])
qc.crz(np.pi / 4, q[6], q[8])
qc.crz(np.pi / 2, q[6], q[7])
qc.h(q[6])
qc.crz(np.pi / 5.24288e5, q[5], q[24])
qc.crz(np.pi / 2.62144e5, q[5], q[23])
qc.crz(np.pi / 1.31072e5, q[5], q[22])
qc.crz(np.pi / 65536, q[5], q[21])
qc.crz(np.pi / 32768, q[5], q[20])
qc.crz(np.pi / 16384, q[5], q[19])
qc.crz(np.pi / 8192, q[5], q[18])
qc.crz(np.pi / 4096, q[5], q[17])
qc.crz(np.pi / 2048, q[5], q[16])
qc.crz(np.pi / 1024, q[5], q[15])
qc.crz(np.pi / 512, q[5], q[14])
qc.crz(np.pi / 256, q[5], q[13])
qc.crz(np.pi / 128, q[5], q[12])
qc.crz(np.pi / 64, q[5], q[11])
qc.crz(np.pi / 32, q[5], q[10])
qc.crz(np.pi / 16, q[5], q[9])
qc.crz(np.pi / 8, q[5], q[8])
qc.crz(np.pi / 4, q[5], q[7])
qc.crz(np.pi / 2, q[5], q[6])
qc.h(q[5])
qc.crz(np.pi / 1.048576e6, q[4], q[24])
qc.crz(np.pi / 5.24288e5, q[4], q[23])
qc.crz(np.pi / 2.62144e5, q[4], q[22])
qc.crz(np.pi / 1.31072e5, q[4], q[21])
qc.crz(np.pi / 65536, q[4], q[20])
qc.crz(np.pi / 32768, q[4], q[19])
qc.crz(np.pi / 16384, q[4], q[18])
qc.crz(np.pi / 8192, q[4], q[17])
qc.crz(np.pi / 4096, q[4], q[16])
qc.crz(np.pi / 2048, q[4], q[15])
qc.crz(np.pi / 1024, q[4], q[14])
qc.crz(np.pi / 512, q[4], q[13])
qc.crz(np.pi / 256, q[4], q[12])
qc.crz(np.pi / 128, q[4], q[11])
qc.crz(np.pi / 64, q[4], q[10])
qc.crz(np.pi / 32, q[4], q[9])
qc.crz(np.pi / 16, q[4], q[8])
qc.crz(np.pi / 8, q[4], q[7])
qc.crz(np.pi / 4, q[4], q[6])
qc.crz(np.pi / 2, q[4], q[5])
qc.h(q[4])
qc.crz(np.pi / 2.097152e6, q[3], q[24])
qc.crz(np.pi / 1.048576e6, q[3], q[23])
qc.crz(np.pi / 5.24288e5, q[3], q[22])
qc.crz(np.pi / 2.62144e5, q[3], q[21])
qc.crz(np.pi / 1.31072e5, q[3], q[20])
qc.crz(np.pi / 65536, q[3], q[19])
qc.crz(np.pi / 32768, q[3], q[18])
qc.crz(np.pi / 16384, q[3], q[17])
qc.crz(np.pi / 8192, q[3], q[16])
qc.crz(np.pi / 4096, q[3], q[15])
qc.crz(np.pi / 2048, q[3], q[14])
qc.crz(np.pi / 1024, q[3], q[13])
qc.crz(np.pi / 512, q[3], q[12])
qc.crz(np.pi / 256, q[3], q[11])
qc.crz(np.pi / 128, q[3], q[10])
qc.crz(np.pi / 64, q[3], q[9])
qc.crz(np.pi / 32, q[3], q[8])
qc.crz(np.pi / 16, q[3], q[7])
qc.crz(np.pi / 8, q[3], q[6])
qc.crz(np.pi / 4, q[3], q[5])
qc.crz(np.pi / 2, q[3], q[4])
qc.h(q[3])
qc.crz(np.pi / 4.194304e6, q[2], q[24])
qc.crz(np.pi / 2.097152e6, q[2], q[23])
qc.crz(np.pi / 1.048576e6, q[2], q[22])
qc.crz(np.pi / 5.24288e5, q[2], q[21])
qc.crz(np.pi / 2.62144e5, q[2], q[20])
qc.crz(np.pi / 1.31072e5, q[2], q[19])
qc.crz(np.pi / 65536, q[2], q[18])
qc.crz(np.pi / 32768, q[2], q[17])
qc.crz(np.pi / 16384, q[2], q[16])
qc.crz(np.pi / 8192, q[2], q[15])
qc.crz(np.pi / 4096, q[2], q[14])
qc.crz(np.pi / 2048, q[2], q[13])
qc.crz(np.pi / 1024, q[2], q[12])
qc.crz(np.pi / 512, q[2], q[11])
qc.crz(np.pi / 256, q[2], q[10])
qc.crz(np.pi / 128, q[2], q[9])
qc.crz(np.pi / 64, q[2], q[8])
qc.crz(np.pi / 32, q[2], q[7])
qc.crz(np.pi / 16, q[2], q[6])
qc.crz(np.pi / 8, q[2], q[5])
qc.crz(np.pi / 4, q[2], q[4])
qc.crz(np.pi / 2, q[2], q[3])
qc.h(q[2])
qc.crz(np.pi / 8.388608e6, q[1], q[24])
qc.crz(np.pi / 4.194304e6, q[1], q[23])
qc.crz(np.pi / 2.097152e6, q[1], q[22])
qc.crz(np.pi / 1.048576e6, q[1], q[21])
qc.crz(np.pi / 5.24288e5, q[1], q[20])
qc.crz(np.pi / 2.62144e5, q[1], q[19])
qc.crz(np.pi / 1.31072e5, q[1], q[18])
qc.crz(np.pi / 65536, q[1], q[17])
qc.crz(np.pi / 32768, q[1], q[16])
qc.crz(np.pi / 16384, q[1], q[15])
qc.crz(np.pi / 8192, q[1], q[14])
qc.crz(np.pi / 4096, q[1], q[13])
qc.crz(np.pi / 2048, q[1], q[12])
qc.crz(np.pi / 1024, q[1], q[11])
qc.crz(np.pi / 512, q[1], q[10])
qc.crz(np.pi / 256, q[1], q[9])
qc.crz(np.pi / 128, q[1], q[8])
qc.crz(np.pi / 64, q[1], q[7])
qc.crz(np.pi / 32, q[1], q[6])
qc.crz(np.pi / 16, q[1], q[5])
qc.crz(np.pi / 8, q[1], q[4])
qc.crz(np.pi / 4, q[1], q[3])
qc.crz(np.pi / 2, q[1], q[2])
qc.h(q[1])
qc.crz(np.pi / 1.6777216e7, q[0], q[24])
qc.crz(np.pi / 8.388608e6, q[0], q[23])
qc.crz(np.pi / 4.194304e6, q[0], q[22])
qc.crz(np.pi / 2.097152e6, q[0], q[21])
qc.crz(np.pi / 1.048576e6, q[0], q[20])
qc.crz(np.pi / 5.24288e5, q[0], q[19])
qc.crz(np.pi / 2.62144e5, q[0], q[18])
qc.crz(np.pi / 1.31072e5, q[0], q[17])
qc.crz(np.pi / 65536, q[0], q[16])
qc.crz(np.pi / 32768, q[0], q[15])
qc.crz(np.pi / 16384, q[0], q[14])
qc.crz(np.pi / 8192, q[0], q[13])
qc.crz(np.pi / 4096, q[0], q[12])
qc.crz(np.pi / 2048, q[0], q[11])
qc.crz(np.pi / 1024, q[0], q[10])
qc.crz(np.pi / 512, q[0], q[9])
qc.crz(np.pi / 256, q[0], q[8])
qc.crz(np.pi / 128, q[0], q[7])
qc.crz(np.pi / 64, q[0], q[6])
qc.crz(np.pi / 32, q[0], q[5])
qc.crz(np.pi / 16, q[0], q[4])
qc.crz(np.pi / 8, q[0], q[3])
qc.crz(np.pi / 4, q[0], q[2])
qc.crz(np.pi / 2, q[0], q[1])
qc.h(q[0])
qc.swap(q[0], q[24])
qc.swap(q[1], q[23])
qc.swap(q[2], q[22])
qc.swap(q[3], q[21])
qc.swap(q[4], q[20])
qc.swap(q[5], q[19])
qc.swap(q[6], q[18])
qc.swap(q[7], q[17])
qc.swap(q[8], q[16])
qc.swap(q[9], q[15])
qc.swap(q[10], q[14])
qc.swap(q[11], q[13])
qc.measure_all()
return qc
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
%matplotlib inline
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits per dimension to represent the uncertainty
num_uncertainty_qubits = 2
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# map to higher dimensional distribution
# for simplicity assuming dimensions are independent and identically distributed)
dimension = 2
num_qubits = [num_uncertainty_qubits] * dimension
low = low * np.ones(dimension)
high = high * np.ones(dimension)
mu = mu * np.ones(dimension)
cov = sigma**2 * np.eye(dimension)
# construct circuit
u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high)))
# plot PDF of uncertainty model
x = [v[0] for v in u.values]
y = [v[1] for v in u.values]
z = u.probabilities
# z = map(float, z)
# z = list(map(float, z))
resolution = np.array([2**n for n in num_qubits]) * 1j
grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]]
grid_z = griddata((x, y), z, (grid_x, grid_y))
plt.figure(figsize=(10, 8))
ax = plt.axes(projection="3d")
ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral)
ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15)
ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15)
ax.set_zlabel("Probability (\%)", size=15)
plt.show()
# determine number of qubits required to represent total loss
weights = []
for n in num_qubits:
for i in range(n):
weights += [2**i]
# create aggregation circuit
agg = WeightedAdder(sum(num_qubits), weights)
n_s = agg.num_sum_qubits
n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 3.5
# map strike price from [low, high] to {0, ..., 2^n-1}
max_value = 2**n_s - 1
low_ = low[0]
high_ = high[0]
mapped_strike_price = (
(strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [0, mapped_strike_price]
slopes = [0, 1]
offsets = [0, 0]
f_min = 0
f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price
basket_objective = LinearAmplitudeFunction(
n_s,
slopes,
offsets,
domain=(0, max_value),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define overall multivariate problem
qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution
qr_obj = QuantumRegister(1, "obj") # to encode the function values
ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum
ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits
objective_index = u.num_qubits
basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar)
basket_option.append(u, qr_state)
basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux])
basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas])
print(basket_option.draw())
print("objective qubit index", objective_index)
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = np.linspace(sum(low), sum(high))
y = np.maximum(0, x - strike_price)
plt.plot(x, y, "r-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value
sum_values = np.sum(u.values, axis=1)
exact_value = np.dot(
u.probabilities[sum_values >= strike_price],
sum_values[sum_values >= strike_price] - strike_price,
)
print("exact expected value:\t%.4f" % exact_value)
num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas
print("state qubits: ", num_state_qubits)
transpiled = transpile(basket_option, basis_gates=["u", "cx"])
print("circuit width:", transpiled.width())
print("circuit depth:", transpiled.depth())
basket_option_measure = basket_option.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(basket_option_measure)
# evaluate the result
value = 0
probabilities = job.result().quasi_dists[0].binary_probabilities()
for i, prob in probabilities.items():
if prob > 1e-4 and i[-num_state_qubits:][0] == "1":
value += prob
# map value to original range
mapped_value = (
basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_)
)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % mapped_value)
print("Exact Expected Payoff: %.4f" % exact_value)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=basket_option,
objective_qubits=[objective_index],
post_processing=basket_objective.post_processing,
)
# construct amplitude estimation
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)
/ (2**num_uncertainty_qubits - 1)
* (high_ - low_)
)
print("Exact value: \t%.4f" % exact_value)
print(
"Estimated value: \t%.4f"
% (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_))
)
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import *
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.quantum_info import Statevector
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_state_qsphere
from qiskit.quantum_info import Operator
from qiskit.tools.visualization import plot_histogram
from IPython.display import display, Math, Latex
import math
def reflect(mcq, n):
for i in range(int(n/2)):
mcq.swap(i, n-i-1)
def myQFT(mcq, n):
for x_k in range(n):
mcq.h(x_k)
for x_j in range(x_k+1, n):
angle = math.pi/2**(x_j-x_k)
mcq.cu1(angle, x_j, x_k)
n = 4
qbt1 = QuantumRegister(n)
cbt1 = ClassicalRegister(n)
mcq1 = QuantumCircuit(qbt1, cbt1)
myQFT(mcq1, n)
mcq1.barrier()
reflect(mcq1, n)
mcq1.barrier()
mcq1.measure(range(n), range(n))
backend = BasicAer.get_backend('qasm_simulator')
atp = 1024
res = execute(mcq1, backend=backend, shots=atp).result()
ans1 = res.get_counts()
mcq1.draw('mpl')
qbt2 = QuantumRegister(n)
cbt2 = ClassicalRegister(n)
mcq2 = QuantumCircuit(qbt2, cbt2)
mcq2.append(QFT(n, do_swaps=True), qbt2)
#mcq2.h(range(n))
mcq2.measure(range(n), range(n))
backend = BasicAer.get_backend('qasm_simulator')
atp = 1024
res = execute(mcq2, backend=backend, shots=atp).result()
ans2 = res.get_counts()
mcq2.draw('mpl')
legend = ['myQFT','qiskitQFT']
plot_histogram([ans1,ans2], legend=legend)
|
https://github.com/Alice-Bob-SW/emulation-examples
|
Alice-Bob-SW
|
from qiskit_alice_bob_provider.local.provider import AliceBobLocalProvider
from qiskit import QuantumCircuit, execute, transpile
from qiskit.visualization import plot_histogram
from qiskit.providers.fake_provider import FakeVigo
from qiskit_aer import AerSimulator
import matplotlib.pyplot as mp
from typing import Optional
provider = AliceBobLocalProvider()
provider.backends()
def build_bit_flip_circuit(delay_duration_us: float) -> QuantumCircuit:
circ = QuantumCircuit(1, 1)
circ.reset(0)
circ.delay(delay_duration_us, 0, unit='us')
circ.measure(0, 0)
return circ
circ = build_bit_flip_circuit(30)
circ.draw('mpl')
counts = []
shots = 10000
sweep_range = range(1,5)
for nb_photons in range(1,5):
backend = provider.get_backend('EMU:1Q:LESCANNE_2020', average_nb_photons=nb_photons)
job = execute(circ, backend, shots=shots)
counts.append(job.result().get_counts())
plot_histogram(counts, legend = ["average_nb_photons = %i" % i for i in sweep_range])
def build_phase_flip_circuit_cats(delay_duration_us: float) -> QuantumCircuit:
circ = QuantumCircuit(1, 1)
circ.initialize('+')
circ.delay(delay_duration_us, 0, unit='us')
circ.measure_x(0, 0)
return circ
circ_fp = build_phase_flip_circuit_cats(0.1)
circ_fp.draw('mpl')
counts = []
shots = 10000
sweep_range = range(1,5)
for nb_photons in range(1,5):
backend = provider.get_backend('EMU:1Q:LESCANNE_2020', average_nb_photons=nb_photons)
job = execute(circ_fp, backend, shots=shots)
counts.append(job.result().get_counts())
plot_histogram(counts, legend = ["average_nb_photons = %i" % i for i in sweep_range])
def build_phase_flip_circuit_transmons(delay_duration_us: float) -> QuantumCircuit:
circ = QuantumCircuit(1, 1)
circ.reset(0)
circ.h(0)
circ.delay(delay_duration_us, 0, unit='us')
circ.h(0)
circ.measure(0, 0)
return circ
circ_transmons = build_phase_flip_circuit_transmons(0.1)
circ_transmons.draw('mpl')
def _measurement_cycle(distance: int) -> QuantumCircuit:
cycle = QuantumCircuit(2 * distance - 1, distance - 1, name='cycle')
for i in range(distance - 1):
ancilla_idx = 2 * i + 1
cycle.initialize('+', ancilla_idx)
for i in range(distance - 1):
ancilla_idx = 2 * i + 1
cycle.cx(ancilla_idx, ancilla_idx + 1)
for i in range(distance - 1):
ancilla_idx = 2 * i + 1
cycle.cx(ancilla_idx, ancilla_idx - 1)
for i in range(distance - 1):
ancilla_idx = 2 * i + 1
cycle.measure_x(ancilla_idx, i)
return cycle
def error_correction_cycle(distance: int, repetitions: int, initial_state: Optional[str] = None) -> QuantumCircuit:
if initial_state is None:
initial_state = distance * '+'
circuit = QuantumCircuit(2 * distance - 1, distance + repetitions * (distance - 1))
circuit.initialize(initial_state, range(0, distance * 2, 2))
circuit.barrier()
for cycle_idx in range(repetitions):
first_bit = distance + cycle_idx * (distance - 1)
circuit.append(_measurement_cycle(distance).to_instruction(), range(2 * distance - 1), range(first_bit, first_bit + distance - 1))
circuit.barrier()
for i in range(distance):
circuit.measure_x(2 * i, i)
return circuit
circ = error_correction_cycle(distance=3, repetitions=1)
backend = provider.get_backend('EMU:40Q:LOGICAL_TARGET')
transpile(circ, backend).draw('mpl')
from qiskit_alice_bob_provider.local.provider import AliceBobLocalProvider
from qiskit import QuantumCircuit, execute
from qiskit.visualization import plot_histogram
shots = 10000
provider = AliceBobLocalProvider()
backend = provider.get_backend('EMU:15Q:LOGICAL_EARLY')
circ = QuantumCircuit(2,2)
circ.reset(0)
circ.h(0)
circ.cx(0,1)
circ.measure(0,0)
circ.measure(1,1)
circ.draw('mpl')
job = execute(circ, backend, shots=shots)
plot_histogram(job.result().get_counts())
|
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.
"""BasicAer provider integration tests."""
import unittest
from qiskit import BasicAer
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import execute
from qiskit.result import Result
from qiskit.providers.basicaer import BasicAerError
from qiskit.test import QiskitTestCase
class TestBasicAerIntegration(QiskitTestCase):
"""Qiskit BasicAer simulator integration tests."""
def setUp(self):
super().setUp()
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
self._qc1 = QuantumCircuit(qr, cr, name="qc1")
self._qc2 = QuantumCircuit(qr, cr, name="qc2")
self._qc1.measure(qr[0], cr[0])
self.backend = BasicAer.get_backend("qasm_simulator")
self._result1 = execute(self._qc1, self.backend).result()
def test_builtin_simulator_result_fields(self):
"""Test components of a result from a local simulator."""
self.assertEqual("qasm_simulator", self._result1.backend_name)
self.assertIsInstance(self._result1.job_id, str)
self.assertEqual(self._result1.status, "COMPLETED")
self.assertEqual(self._result1.results[0].status, "DONE")
def test_basicaer_execute(self):
"""Test Compiler and run."""
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
job = execute(qc, self.backend)
result = job.result()
self.assertIsInstance(result, Result)
def test_basicaer_execute_two(self):
"""Test Compiler and run."""
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
qc_extra = QuantumCircuit(qubit_reg, clbit_reg, name="extra")
qc_extra.measure(qubit_reg, clbit_reg)
job = execute([qc, qc_extra], self.backend)
result = job.result()
self.assertIsInstance(result, Result)
def test_basicaer_num_qubits(self):
"""Test BasicAerError is raised if num_qubits too large to simulate."""
qc = QuantumCircuit(50, 1)
qc.x(0)
qc.measure(0, 0)
with self.assertRaises(BasicAerError):
execute(qc, self.backend)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/0tt3r/QuaC-qiskit
|
0tt3r
|
# -*- coding: utf-8 -*-
"""This module contains test cases for ensuring gate addition and functionality is working properly
in the library.
"""
import random
import unittest
import numpy as np
from qiskit import execute, QuantumCircuit, Aer, transpile
from qiskit.circuit.random import random_circuit
from qiskit.ignis.characterization import t1_circuits, T1Fitter, t2_circuits, T2Fitter, zz_circuits, ZZFitter
from qiskit.ignis.mitigation import TensoredMeasFitter
from qiskit.test.mock import FakeYorktown
from quac_qiskit import Quac
from quac_qiskit.models import QuacNoiseModel
class NoiseModelTestCase(unittest.TestCase):
"""Tests QuaC noise model functionality by recovering model parameters with Qiskit fitters
"""
def setUp(self):
# Set up QuaC simulators
self.quac_sim = Quac.get_backend("fake_yorktown_density_simulator", t1=True, t2=False, meas=False, zz=False)
self.qasm_sim = Aer.get_backend("qasm_simulator")
def test_t1_recovery(self):
cal_circs, t1_delay = t1_circuits(np.linspace(10, 900, 10, dtype='int'),
FakeYorktown().properties().gate_length('id', [0]) * 1e9,
[0, 1, 2, 3, 4])
true_t1 = [1000 * (1 + random.random()) for _ in range(5)]
t1_noise_model = QuacNoiseModel(
true_t1,
[float('inf') for _ in range(5)]
)
t1_result = execute(cal_circs, self.quac_sim, quac_noise_model=t1_noise_model).result()
t1_fit = T1Fitter(t1_result, t1_delay, [0, 1, 2, 3, 4],
fit_p0=[1, 1000, 0],
fit_bounds=([0, 0, -1], [2, 1e10, 1]),
time_unit="nano-seconds")
derived_t1 = t1_fit.time()
max_diff = abs(np.array(derived_t1) - np.array(true_t1)).max()
self.assertLess(max_diff, 1e-3)
def test_t2_recovery(self):
cal_circs, t2_delay = t2_circuits(np.floor(np.linspace(10, 900, 10, dtype='int') / 2).astype('int'),
FakeYorktown().properties().gate_length('id', [0]) * 1e9,
[0, 1, 2, 3, 4])
true_t2 = [10000 * (1 + random.random()) for _ in range(5)]
t2_noise_model = QuacNoiseModel(
[float('inf') for _ in range(5)],
true_t2
)
t2_result = execute(cal_circs, self.quac_sim, quac_noise_model=t2_noise_model).result()
t2_fit = T2Fitter(t2_result, t2_delay, [0, 1, 2, 3, 4],
fit_p0=[1, 10000, 0],
fit_bounds=([0, 0, -1], [2, 1e10, 1]),
time_unit="nano-seconds")
derived_t2 = t2_fit.time()
max_diff = abs(np.array(derived_t2) - np.array(true_t2)).max()
self.assertLess(max_diff, 1e-3)
def test_meas_recovery(self):
qubits = list(range(5)) # we are working with a 5-qubit machine
# Develop random measurement matrices for each qubit of the form
# [ P(0|0) P(0|1) ]
# [ P(1|0) P(1|1) ]
meas_mats = []
for _ in qubits:
stay_zero = random.random()
stay_one = random.random()
meas_mats.append(
np.array([
[stay_zero, 1 - stay_one],
[1 - stay_zero, stay_one]
])
)
# Encode measurement matrices in QuacNoiseModel object
meas_noise_model = QuacNoiseModel(
[float('inf') for _ in qubits],
[float('inf') for _ in qubits],
meas_mats
)
# Develop Quac-specfic measurement matrix calibration circuits
# (cannot run circuits with 0 gates in Quac backends)
empty_circ = QuantumCircuit(len(qubits))
for i in qubits:
empty_circ.id(i)
empty_circ.measure_all()
empty_circ.name = f"cal_{''.join(['0' for _ in qubits])}"
full_circ = QuantumCircuit(len(qubits))
for i in qubits:
full_circ.x(i)
full_circ.measure_all()
full_circ.name = f"cal_{''.join(['1' for _ in qubits])}"
meas_cal_circs = [empty_circ, full_circ]
# Recover measurement matrices with Qiskit fitter
meas_result = execute(meas_cal_circs, self.quac_sim, quac_noise_model=meas_noise_model).result()
meas_fit = TensoredMeasFitter(meas_result, [[i] for i in qubits])
meas_matrices = meas_fit.cal_matrices
max_diff = max([(meas_matrices[ind] - meas_mats[ind]).max() for ind in qubits])
self.assertLess(max_diff, 1e-10)
def test_zz_recovery(self):
qubits = list(range(5))
num_of_gates = np.arange(0, 600, 30)
gate_time = FakeYorktown().properties().gate_length('id', [0]) * 1e9
# Develop zz-only noise model
zz_dict = {}
for qubit1 in qubits:
for qubit2 in qubits:
if qubit1 < qubit2:
zz_dict[(qubit1, qubit2)] = (1 + random.random() * 2) * 1e-5
zz_noise_model = QuacNoiseModel(
[float('inf') for _ in qubits],
[float('inf') for _ in qubits],
[np.eye(2) for _ in qubits],
zz_dict
)
for qubit1 in qubits:
for qubit2 in qubits:
if qubit1 < qubit2:
print(qubit1)
print(qubit2)
zz_circs, xdata, osc_freq = zz_circuits(num_of_gates, gate_time, [qubit1], [qubit2], nosc=2)
zz_result = execute(zz_circs, self.quac_sim, quac_noise_model=zz_noise_model,
shots=1).result()
fit = ZZFitter(zz_result, xdata, [qubit1], [qubit2],
fit_p0=[1, osc_freq, -np.pi / 20, 0],
fit_bounds=([-0.5, 0, -np.pi, -0.5],
[1.5, 1e10, np.pi, 1.5]),
time_unit="nano-seconds"
)
self.assertLess(abs(abs(fit.ZZ_rate()[0]) - zz_dict[(qubit1, qubit2)]), 1e-10)
def test_noise_model_from_backend(self):
yorktown_quac_noise_model_t1t2 = QuacNoiseModel.from_backend(FakeYorktown(), t1=True, t2=True,
meas=False, zz=False)
yorktown_quac_noise_model_meas = QuacNoiseModel.from_backend(FakeYorktown(), t1=False, t2=False,
meas=True, zz=False)
qubits = list(range(5))
cal_circs, t1_delay = t1_circuits(np.linspace(10, 900, 10, dtype='int'),
FakeYorktown().properties().gate_length('id', [0]) * 1e9,
qubits)
true_t1 = [FakeYorktown().properties().t1(q) * 1e9 for q in qubits]
t1_result = execute(cal_circs, self.quac_sim, quac_noise_model=yorktown_quac_noise_model_t1t2,
optimization_level=0).result()
t1_fit = T1Fitter(t1_result, t1_delay, qubits,
fit_p0=[1, 10000, 0],
fit_bounds=([0, 0, -1], [2, 1e10, 1]),
time_unit="nano-seconds")
derived_t1 = t1_fit.time()
max_diff = abs(np.array(derived_t1) - np.array(true_t1)).max()
self.assertLess(max_diff, 1e-2)
# Test T2 recovery
cal_circs, t2_delay = t2_circuits(np.floor(np.linspace(10, 900, 10, dtype='int') / 2).astype('int'),
FakeYorktown().properties().gate_length('id', [0]) * 1e9,
qubits)
true_t2 = [FakeYorktown().properties().t2(q) * 1e9 for q in qubits]
t2_result = execute(cal_circs, self.quac_sim, quac_noise_model=yorktown_quac_noise_model_t1t2).result()
t2_fit = T2Fitter(t2_result, t2_delay, qubits,
fit_p0=[1, 10000, 0],
fit_bounds=([0, 0, -1], [2, 1e10, 1]),
time_unit="nano-seconds")
derived_t2 = t2_fit.time()
max_diff = abs(np.array(derived_t2) - np.array(true_t2)).max()
self.assertLess(max_diff, 1e-2)
# Recover measurement error
meas_mats = []
for q in qubits:
flip_1_to_0 = FakeYorktown().properties().qubit_property(q, "prob_meas0_prep1")[0]
flip_0_to_1 = FakeYorktown().properties().qubit_property(q, "prob_meas1_prep0")[0]
meas_mats.append(
np.array([
[1 - flip_0_to_1, flip_1_to_0],
[flip_0_to_1, 1 - flip_1_to_0]
])
)
# Develop Quac-specfic measurement matrix calibration circuits
# (cannot run circuits with 0 gates in Quac backends)
empty_circ = QuantumCircuit(len(qubits))
for i in qubits:
empty_circ.id(i)
empty_circ.measure_all()
empty_circ.name = f"cal_{''.join(['0' for _ in qubits])}"
full_circ = QuantumCircuit(len(qubits))
for i in qubits:
full_circ.x(i)
full_circ.measure_all()
full_circ.name = f"cal_{''.join(['1' for _ in qubits])}"
meas_cal_circs = [empty_circ, full_circ]
# Recover measurement matrices with Qiskit fitter
meas_result = execute(meas_cal_circs, self.quac_sim, quac_noise_model=yorktown_quac_noise_model_meas).result()
meas_fit = TensoredMeasFitter(meas_result, [[i] for i in qubits])
meas_matrices = meas_fit.cal_matrices
max_diff = max([(meas_matrices[ind] - meas_mats[ind]).max() for ind in qubits])
self.assertLess(max_diff, 1e-10)
def test_noise_model_to_and_from_array(self):
random_circs = [random_circuit(5, 5, measure=True) for _ in range(100)]
true_t1 = [1000 * (1 + random.random()) for _ in range(5)]
true_t2 = [10000 * (1 + random.random()) for _ in range(5)]
# Develop random measurement matrices for each qubit of the form
# [ P(0|0) P(0|1) ]
# [ P(1|0) P(1|1) ]
meas_mats = []
for _ in range(5):
stay_zero = random.random()
stay_one = random.random()
meas_mats.append(
np.array([
[stay_zero, 1 - stay_one],
[1 - stay_zero, stay_one]
])
)
zz = {}
for qubit1 in range(5):
for qubit2 in range(5):
if qubit1 != qubit2:
zz[(qubit1, qubit2)] = random.randrange(1, 10) * 1e-5
random_quac_noise_model = QuacNoiseModel(
true_t1,
true_t2,
[meas_mats[0] for _ in range(5)],
None
)
recovered_quac_noise_model = QuacNoiseModel.from_array(random_quac_noise_model.to_array(), 5)
for circ in random_circs:
transpiled_circ = transpile(circ, self.quac_sim, optimization_level=0)
dist_original = execute(transpiled_circ, self.quac_sim,
quac_noise_model=random_quac_noise_model,
optimization_level=0).result().get_counts()
dist_recovered = execute(transpiled_circ, self.quac_sim,
quac_noise_model=recovered_quac_noise_model,
optimization_level=0).result().get_counts()
self.assertEqual(dist_original, dist_recovered)
if __name__ == '__main__':
unittest.main()
|
https://github.com/jaykomarraju/Quantum-Optimization-for-Solar-Farm
|
jaykomarraju
|
import numpy as np
import networkx as nx
from qiskit import Aer
from qiskit.algorithms import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.algorithms import MinimumEigenOptimizer
num_time_slots = 24
# Define the QUBO problem
qubo = QuadraticProgram()
# Add binary variables for charging (c) and discharging (d) states
for t in range(num_time_slots):
qubo.binary_var(f'c_{t}')
qubo.binary_var(f'd_{t}')
# Define the objective function
# (In practice, you need to calculate Jij and hi based on the solar farm data)
Jij = np.random.rand(num_time_slots, num_time_slots) * 0.5
hi_c = -1 + np.random.rand(num_time_slots)
hi_d = 1 - np.random.rand(num_time_slots)
# Set linear and quadratic terms of the objective function
linear_terms = {}
quadratic_terms = {}
for t in range(num_time_slots):
linear_terms[f'c_{t}'] = hi_c[t]
linear_terms[f'd_{t}'] = hi_d[t]
for s in range(num_time_slots):
if t != s:
quadratic_terms[(f'c_{t}', f'c_{s}')] = Jij[t, s]
quadratic_terms[(f'd_{t}', f'd_{s}')] = Jij[t, s]
qubo.minimize(linear=linear_terms, quadratic=quadratic_terms)
# Set up the quantum instance
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, seed_simulator=42, seed_transpiler=42, shots=10000)
# Set up the QAOA algorithm and optimizer
optimizer = COBYLA(maxiter=500)
qaoa = QAOA(optimizer=optimizer, reps=5, quantum_instance=quantum_instance)
# Set up the minimum eigen optimizer
min_eig_optimizer = MinimumEigenOptimizer(qaoa)
# Solve the problem
result = min_eig_optimizer.solve(qubo)
print("QAOA result:", result)
# Solve the problem using a classical solver (NumPyMinimumEigensolver)
exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
exact_result = exact_solver.solve(qubo)
print("Classical result:", exact_result)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import networkx as nx
import numpy as np
import plotly.graph_objects as go
import matplotlib as mpl
import pandas as pd
from IPython.display import clear_output
from plotly.subplots import make_subplots
from matplotlib import pyplot as plt
from qiskit import Aer
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_city
from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM
from time import time
from copy import copy
from typing import List
from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs
mpl.rcParams['figure.dpi'] = 300
from qiskit.circuit import Parameter, ParameterVector
#Parameters are initialized with a simple string identifier
parameter_0 = Parameter('θ[0]')
parameter_1 = Parameter('θ[1]')
circuit = QuantumCircuit(1)
#We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates
circuit.ry(theta = parameter_0, qubit = 0)
circuit.rx(theta = parameter_1, qubit = 0)
circuit.draw('mpl')
parameter = Parameter('θ')
circuit = QuantumCircuit(1)
circuit.ry(theta = parameter, qubit = 0)
circuit.rx(theta = parameter, qubit = 0)
circuit.draw('mpl')
#Set the number of layers and qubits
n=3
num_layers = 2
#ParameterVectors are initialized with a string identifier and an integer specifying the vector length
parameters = ParameterVector('θ', n*(num_layers+1))
circuit = QuantumCircuit(n, n)
for layer in range(num_layers):
#Appending the parameterized Ry gates using parameters from the vector constructed above
for i in range(n):
circuit.ry(parameters[n*layer+i], i)
circuit.barrier()
#Appending the entangling CNOT gates
for i in range(n):
for j in range(i):
circuit.cx(j,i)
circuit.barrier()
#Appending one additional layer of parameterized Ry gates
for i in range(n):
circuit.ry(parameters[n*num_layers+i], i)
circuit.barrier()
circuit.draw('mpl')
print(circuit.parameters)
#Create parameter dictionary with random values to bind
param_dict = {parameter: np.random.random() for parameter in parameters}
print(param_dict)
#Assign parameters using the assign_parameters method
bound_circuit = circuit.assign_parameters(parameters = param_dict)
bound_circuit.draw('mpl')
new_parameters = ParameterVector('Ψ',9)
new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)])
new_circuit.draw('mpl')
#Run the circuit with assigned parameters on Aer's statevector simulator
simulator = Aer.get_backend('statevector_simulator')
result = simulator.run(bound_circuit).result()
statevector = result.get_statevector(bound_circuit)
plot_state_city(statevector)
#The following line produces an error when run because 'circuit' still contains non-assigned parameters
#result = simulator.run(circuit).result()
for key in graphs.keys():
print(key)
graph = nx.Graph()
#Add nodes and edges
graph.add_nodes_from(np.arange(0,6,1))
edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)]
graph.add_weighted_edges_from(edges)
graphs['custom'] = graph
#Display widget
display_maxcut_widget(graphs['custom'])
def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float:
"""
Computes the maxcut cost function value for a given graph and cut represented by some bitstring
Args:
graph: The graph to compute cut values for
bitstring: A list of integer values '0' or '1' specifying a cut of the graph
Returns:
The value of the cut
"""
#Get the weight matrix of the graph
weight_matrix = nx.adjacency_matrix(graph).toarray()
size = weight_matrix.shape[0]
value = 0.
#INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE
for i in range(size):
for j in range(size):
value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j])
return value
def plot_maxcut_histogram(graph: nx.Graph) -> None:
"""
Plots a bar diagram with the values for all possible cuts of a given graph.
Args:
graph: The graph to compute cut values for
"""
num_vars = graph.number_of_nodes()
#Create list of bitstrings and corresponding cut values
bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)]
values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings]
#Sort both lists by largest cut value
values, bitstrings = zip(*sorted(zip(values, bitstrings)))
#Plot bar diagram
bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value')))
fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600))
fig.show()
plot_maxcut_histogram(graph = graphs['custom'])
from qc_grader import grade_lab2_ex1
bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE
# Note that the grading function is expecting a list of integers '0' and '1'
grade_lab2_ex1(bitstring)
from qiskit_optimization import QuadraticProgram
quadratic_program = QuadraticProgram('sample_problem')
print(quadratic_program.export_as_lp_string())
quadratic_program.binary_var(name = 'x_0')
quadratic_program.integer_var(name = 'x_1')
quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8)
quadratic = [[0,1,2],[3,4,5],[0,1,2]]
linear = [10,20,30]
quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5)
print(quadratic_program.export_as_lp_string())
def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram:
"""Constructs a quadratic program from a given graph for a MaxCut problem instance.
Args:
graph: Underlying graph of the problem.
Returns:
QuadraticProgram
"""
#Get weight matrix of graph
weight_matrix = nx.adjacency_matrix(graph)
shape = weight_matrix.shape
size = shape[0]
#Build qubo matrix Q from weight matrix W
qubo_matrix = np.zeros((size, size))
qubo_vector = np.zeros(size)
for i in range(size):
for j in range(size):
qubo_matrix[i, j] -= weight_matrix[i, j]
for i in range(size):
for j in range(size):
qubo_vector[i] += weight_matrix[i,j]
#INSERT YOUR CODE HERE
quadratic_program=QuadraticProgram('sample_problem')
for i in range(size):
quadratic_program.binary_var(name='x_{}'.format(i))
quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector)
return quadratic_program
quadratic_program = quadratic_program_from_graph(graphs['custom'])
print(quadratic_program.export_as_lp_string())
from qc_grader import grade_lab2_ex2
# Note that the grading function is expecting a quadratic program
grade_lab2_ex2(quadratic_program)
def qaoa_circuit(qubo: QuadraticProgram, p: int = 1):
"""
Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers.
Args:
qubo: The quadratic program instance
p: The number of layers in the QAOA circuit
Returns:
The parameterized QAOA circuit
"""
size = len(qubo.variables)
qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True)
qubo_linearity = qubo.objective.linear.to_array()
#Prepare the quantum and classical registers
qaoa_circuit = QuantumCircuit(size,size)
#Apply the initial layer of Hadamard gates to all qubits
qaoa_circuit.h(range(size))
#Create the parameters to be used in the circuit
gammas = ParameterVector('gamma', p)
betas = ParameterVector('beta', p)
#Outer loop to create each layer
for i in range(p):
#Apply R_Z rotational gates from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
qubo_matrix_sum_of_col = 0
for k in range(size):
qubo_matrix_sum_of_col+= qubo_matrix[j][k]
qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j)
#Apply R_ZZ rotational gates for entangled qubit rotations from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
for k in range(size):
if j!=k:
qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k)
# Apply single qubit X - rotations with angle 2*beta_i to all qubits
#INSERT YOUR CODE HERE
for j in range(size):
qaoa_circuit.rx(2*betas[i],j)
return qaoa_circuit
quadratic_program = quadratic_program_from_graph(graphs['custom'])
custom_circuit = qaoa_circuit(qubo = quadratic_program)
test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters))
from qc_grader import grade_lab2_ex3
# Note that the grading function is expecting a quantum circuit
grade_lab2_ex3(test)
from qiskit.algorithms import QAOA
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = Aer.get_backend('statevector_simulator')
qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1])
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
quadratic_program = quadratic_program_from_graph(graphs['custom'])
result = eigen_optimizer.solve(quadratic_program)
print(result)
def plot_samples(samples):
"""
Plots a bar diagram for the samples of a quantum algorithm
Args:
samples
"""
#Sort samples by probability
samples = sorted(samples, key = lambda x: x.probability)
#Get list of probabilities, function values and bitstrings
probabilities = [sample.probability for sample in samples]
values = [sample.fval for sample in samples]
bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples]
#Plot bar diagram
sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value')))
fig = go.Figure(
data=sample_plot,
layout = dict(
xaxis=dict(
type = 'category'
)
)
)
fig.show()
plot_samples(result.samples)
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name])
trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]}
offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum()
def callback(eval_count, params, mean, std_dev):
trajectory['beta_0'].append(params[1])
trajectory['gamma_0'].append(params[0])
trajectory['energy'].append(-mean + offset)
optimizers = {
'cobyla': COBYLA(),
'slsqp': SLSQP(),
'adam': ADAM()
}
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
result = eigen_optimizer.solve(quadratic_program)
fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples)
fig.show()
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graphs[graph_name])
#Create callback to record total number of evaluations
max_evals = 0
def callback(eval_count, params, mean, std_dev):
global max_evals
max_evals = eval_count
#Create empty lists to track values
energies = []
runtimes = []
num_evals=[]
#Run QAOA for different values of p
for p in range(1,10):
print(f'Evaluating for p = {p}...')
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
start = time()
result = eigen_optimizer.solve(quadratic_program)
runtimes.append(time()-start)
num_evals.append(max_evals)
#Calculate energy of final state from samples
avg_value = 0.
for sample in result.samples:
avg_value += sample.probability*sample.fval
energies.append(avg_value)
#Create and display plots
energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma'))
runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma'))
num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma'))
fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations'])
fig.update_layout(width=1800,height=600, showlegend=False)
fig.add_trace(energy_plot, row=1, col=1)
fig.add_trace(runtime_plot, row=1, col=2)
fig.add_trace(num_evals_plot, row=1, col=3)
clear_output()
fig.show()
def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None):
num_shots = 1000
seed = 42
simulator = Aer.get_backend('qasm_simulator')
simulator.set_options(seed_simulator = 42)
#Generate circuit
circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1)
circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes()))
#Create dictionary with precomputed cut values for all bitstrings
cut_values = {}
size = graph.number_of_nodes()
for i in range(2**size):
bitstr = '{:b}'.format(i).rjust(size, '0')[::-1]
x = [int(bit) for bit in bitstr]
cut_values[bitstr] = maxcut_cost_fn(graph, x)
#Perform grid search over all parameters
data_points = []
max_energy = None
for beta in np.linspace(0,np.pi, 50):
for gamma in np.linspace(0, 4*np.pi, 50):
bound_circuit = circuit.assign_parameters([beta, gamma])
result = simulator.run(bound_circuit, shots = num_shots).result()
statevector = result.get_counts(bound_circuit)
energy = 0
measured_cuts = []
for bitstring, count in statevector.items():
measured_cuts = measured_cuts + [cut_values[bitstring]]*count
if cvar is None:
#Calculate the mean of all cut values
energy = sum(measured_cuts)/num_shots
else:
#raise NotImplementedError()
#INSERT YOUR CODE HERE
measured_cuts = sorted(measured_cuts, reverse = True)
for w in range(int(cvar*num_shots)):
energy += measured_cuts[w]/int((cvar*num_shots))
#Update optimal parameters
if max_energy is None or energy > max_energy:
max_energy = energy
optimum = {'beta': beta, 'gamma': gamma, 'energy': energy}
#Update data
data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy})
#Create and display surface plot from data_points
df = pd.DataFrame(data_points)
df = df.pivot(index='beta', columns='gamma', values='energy')
matrix = df.to_numpy()
beta_values = df.index.tolist()
gamma_values = df.columns.tolist()
surface_plot = go.Surface(
x=gamma_values,
y=beta_values,
z=matrix,
coloraxis = 'coloraxis'
)
fig = go.Figure(data = surface_plot)
fig.show()
#Return optimum
return optimum
graph = graphs['custom']
optimal_parameters = plot_qaoa_energy_landscape(graph = graph)
print('Optimal parameters:')
print(optimal_parameters)
optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2)
print(optimal_parameters)
from qc_grader import grade_lab2_ex4
# Note that the grading function is expecting a python dictionary
# with the entries 'beta', 'gamma' and 'energy'
grade_lab2_ex4(optimal_parameters)
|
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.
"""Compiler Test."""
import os
import unittest
from qiskit import BasicAer
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit import execute
from qiskit.circuit.library import U1Gate, U2Gate
from qiskit.compiler import transpile, assemble
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeRueschlikon, FakeTenerife
from qiskit.qobj import QasmQobj
class TestCompiler(QiskitTestCase):
"""Qiskit Compiler Tests."""
def setUp(self):
super().setUp()
self.seed_simulator = 42
self.backend = BasicAer.get_backend("qasm_simulator")
def test_example_multiple_compile(self):
"""Test a toy example compiling multiple circuits.
Pass if the results are correct.
"""
backend = BasicAer.get_backend("qasm_simulator")
coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]]
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
bell = QuantumCircuit(qr, cr)
ghz = QuantumCircuit(qr, cr)
# Create a GHZ state
ghz.h(qr[0])
for i in range(4):
ghz.cx(qr[i], qr[i + 1])
# Insert a barrier before measurement
ghz.barrier()
# Measure all of the qubits in the standard basis
for i in range(5):
ghz.measure(qr[i], cr[i])
# Create a Bell state
bell.h(qr[0])
bell.cx(qr[0], qr[1])
bell.barrier()
bell.measure(qr[0], cr[0])
bell.measure(qr[1], cr[1])
shots = 2048
bell_backend = transpile(bell, backend=backend)
ghz_backend = transpile(ghz, backend=backend, coupling_map=coupling_map)
bell_qobj = assemble(bell_backend, shots=shots, seed_simulator=10)
ghz_qobj = assemble(ghz_backend, shots=shots, seed_simulator=10)
bell_result = backend.run(bell_qobj).result()
ghz_result = backend.run(ghz_qobj).result()
threshold = 0.05 * shots
counts_bell = bell_result.get_counts()
target_bell = {"00000": shots / 2, "00011": shots / 2}
self.assertDictAlmostEqual(counts_bell, target_bell, threshold)
counts_ghz = ghz_result.get_counts()
target_ghz = {"00000": shots / 2, "11111": shots / 2}
self.assertDictAlmostEqual(counts_ghz, target_ghz, threshold)
def test_compile_coupling_map(self):
"""Test compile_coupling_map.
If all correct should return data with the same stats. The circuit may
be different.
"""
backend = BasicAer.get_backend("qasm_simulator")
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
qc = QuantumCircuit(qr, cr, name="qccccccc")
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.cx(qr[0], qr[2])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
shots = 2048
coupling_map = [[0, 1], [1, 2]]
initial_layout = [0, 1, 2]
qc_b = transpile(
qc, backend=backend, coupling_map=coupling_map, initial_layout=initial_layout
)
qobj = assemble(qc_b, shots=shots, seed_simulator=88)
job = backend.run(qobj)
result = job.result()
qasm_to_check = qc.qasm()
self.assertEqual(len(qasm_to_check), 173)
counts = result.get_counts(qc)
target = {"000": shots / 2, "111": shots / 2}
threshold = 0.05 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_example_swap_bits(self):
"""Test a toy example swapping a set bit around.
Uses the mapper. Pass if results are correct.
"""
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],
]
# ┌───┐ ░ ┌─┐
# q0_0: ┤ X ├─X───────────░─┤M├───────────────
# └───┘ │ ░ └╥┘ ┌─┐
# q0_1: ──────┼─────X──X──░──╫────┤M├─────────
# │ │ │ ░ ║ └╥┘ ┌─┐
# q0_2: ──────X──X──┼──┼──░──╫─────╫────┤M├───
# │ │ │ ░ ║ ┌─┐ ║ └╥┘
# q1_0: ─────────┼──┼──┼──░──╫─┤M├─╫─────╫────
# │ │ │ ░ ║ └╥┘ ║ ┌─┐ ║
# q1_1: ─────────┼──┼──X──░──╫──╫──╫─┤M├─╫────
# │ │ ░ ║ ║ ║ └╥┘ ║ ┌─┐
# q1_2: ─────────X──X─────░──╫──╫──╫──╫──╫─┤M├
# ░ ║ ║ ║ ║ ║ └╥┘
# c0: 6/═════════════════════╩══╩══╩══╩══╩══╩═
# 0 3 1 4 2 5
n = 3 # make this at least 3
qr0 = QuantumRegister(n)
qr1 = QuantumRegister(n)
ans = ClassicalRegister(2 * n)
qc = QuantumCircuit(qr0, qr1, ans)
# Set the first bit of qr0
qc.x(qr0[0])
# Swap the set bit
qc.swap(qr0[0], qr0[n - 1])
qc.swap(qr0[n - 1], qr1[n - 1])
qc.swap(qr1[n - 1], qr0[1])
qc.swap(qr0[1], qr1[1])
# Insert a barrier before measurement
qc.barrier()
# Measure all of the qubits in the standard basis
for j in range(n):
qc.measure(qr0[j], ans[j])
qc.measure(qr1[j], ans[j + n])
# First version: no mapping
result = execute(
qc, backend=backend, coupling_map=None, shots=1024, seed_simulator=14
).result()
self.assertEqual(result.get_counts(qc), {"010000": 1024})
# Second version: map to coupling graph
result = execute(
qc, backend=backend, coupling_map=coupling_map, shots=1024, seed_simulator=14
).result()
self.assertEqual(result.get_counts(qc), {"010000": 1024})
def test_parallel_compile(self):
"""Trigger parallel routines in compile."""
backend = FakeRueschlikon()
qr = QuantumRegister(16)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
for k in range(1, 15):
qc.cx(qr[0], qr[k])
qc.measure(qr[5], cr[0])
qlist = [qc for k in range(10)]
qobj = assemble(transpile(qlist, backend=backend))
self.assertEqual(len(qobj.experiments), 10)
def test_no_conflict_backend_passmanager(self):
"""execute(qc, backend=..., passmanager=...)
See: https://github.com/Qiskit/qiskit-terra/issues/5037
"""
backend = BasicAer.get_backend("qasm_simulator")
qc = QuantumCircuit(2)
qc.append(U1Gate(0), [0])
qc.measure_all()
job = execute(qc, backend=backend, pass_manager=PassManager())
result = job.result().get_counts()
self.assertEqual(result, {"00": 1024})
def test_compile_single_qubit(self):
"""Compile a single-qubit circuit in a non-trivial layout"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
layout = {qr[0]: 12}
cmap = [
[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],
]
circuit2 = transpile(
circuit, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout
)
qobj = assemble(circuit2)
compiled_instruction = qobj.experiments[0].instructions[0]
self.assertEqual(compiled_instruction.name, "u2")
self.assertEqual(compiled_instruction.qubits, [12])
self.assertEqual(compiled_instruction.params, [0, 3.141592653589793])
def test_compile_pass_manager(self):
"""Test compile with and without an empty pass manager."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.append(U1Gate(3.14), [qr[0]])
qc.append(U2Gate(3.14, 1.57), [qr[0]])
qc.barrier(qr)
qc.measure(qr, cr)
backend = BasicAer.get_backend("qasm_simulator")
qrtrue = assemble(transpile(qc, backend, seed_transpiler=8), seed_simulator=42)
rtrue = backend.run(qrtrue).result()
qrfalse = assemble(PassManager().run(qc), seed_simulator=42)
rfalse = backend.run(qrfalse).result()
self.assertEqual(rtrue.get_counts(), rfalse.get_counts())
def test_mapper_overoptimization(self):
"""Check mapper overoptimization.
The mapper should not change the semantics of the input.
An overoptimization introduced issue #81:
https://github.com/Qiskit/qiskit-terra/issues/81
"""
# ┌───┐ ┌─┐
# q0_0: ┤ X ├──■───────┤M├───────────
# ├───┤┌─┴─┐┌───┐└╥┘ ┌─┐
# q0_1: ┤ Y ├┤ X ├┤ S ├─╫───■──┤M├───
# ├───┤└───┘├───┤ ║ ┌─┴─┐└╥┘┌─┐
# q0_2: ┤ Z ├──■──┤ T ├─╫─┤ X ├─╫─┤M├
# └───┘┌─┴─┐├───┤ ║ └┬─┬┘ ║ └╥┘
# q0_3: ─────┤ X ├┤ H ├─╫──┤M├──╫──╫─
# └───┘└───┘ ║ └╥┘ ║ ║
# c0: 4/════════════════╩═══╩═══╩══╩═
# 0 3 1 2
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
circ = QuantumCircuit(qr, cr)
circ.x(qr[0])
circ.y(qr[1])
circ.z(qr[2])
circ.cx(qr[0], qr[1])
circ.cx(qr[2], qr[3])
circ.s(qr[1])
circ.t(qr[2])
circ.h(qr[3])
circ.cx(qr[1], qr[2])
circ.measure(qr[0], cr[0])
circ.measure(qr[1], cr[1])
circ.measure(qr[2], cr[2])
circ.measure(qr[3], cr[3])
coupling_map = [[0, 2], [1, 2], [2, 3]]
shots = 1000
result1 = execute(
circ,
backend=self.backend,
coupling_map=coupling_map,
seed_simulator=self.seed_simulator,
seed_transpiler=8,
shots=shots,
)
count1 = result1.result().get_counts()
result2 = execute(
circ,
backend=self.backend,
coupling_map=None,
seed_simulator=self.seed_simulator,
seed_transpiler=8,
shots=shots,
)
count2 = result2.result().get_counts()
self.assertDictAlmostEqual(count1, count2, shots * 0.02)
def test_grovers_circuit(self):
"""Testing a circuit originated in the Grover algorithm"""
shots = 1000
coupling_map = None
# 6-qubit grovers
#
# ┌───┐┌───┐ ┌───┐┌───┐ ┌───┐ ┌───┐┌───┐ ░ ┌─┐
# q0_0: ┤ H ├┤ X ├──■──┤ X ├┤ X ├──■──┤ X ├──■──┤ X ├┤ H ├──────░─┤M├───
# ├───┤└───┘ │ └───┘└───┘ │ ├───┤ │ ├───┤├───┤ ░ └╥┘┌─┐
# q0_1: ┤ H ├──■────┼─────────■────┼──┤ X ├──■──┤ X ├┤ H ├──────░──╫─┤M├
# ├───┤ │ ┌─┴─┐ │ ┌─┴─┐└───┘ │ └───┘└───┘ ░ ║ └╥┘
# q0_2: ┤ X ├──┼──┤ X ├──■────┼──┤ X ├───────┼──────────────────░──╫──╫─
# ├───┤┌─┴─┐└───┘ │ ┌─┴─┐└───┘ │ ░ ║ ║
# q0_3: ┤ X ├┤ X ├───────■──┤ X ├────────────┼──────────────────░──╫──╫─
# └───┘└───┘ ┌─┴─┐├───┤┌───┐ ┌─┴─┐┌───┐┌───┐┌───┐ ░ ║ ║
# q0_4: ───────────────┤ X ├┤ X ├┤ H ├─────┤ X ├┤ H ├┤ X ├┤ H ├─░──╫──╫─
# └───┘└───┘└───┘ └───┘└───┘└───┘└───┘ ░ ║ ║
# q0_5: ────────────────────────────────────────────────────────░──╫──╫─
# ░ ║ ║
# c0: 2/═══════════════════════════════════════════════════════════╩══╩═
# 0 1
qr = QuantumRegister(6)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr, name="grovers")
circuit.h(qr[0])
circuit.h(qr[1])
circuit.x(qr[2])
circuit.x(qr[3])
circuit.x(qr[0])
circuit.cx(qr[0], qr[2])
circuit.x(qr[0])
circuit.cx(qr[1], qr[3])
circuit.ccx(qr[2], qr[3], qr[4])
circuit.cx(qr[1], qr[3])
circuit.x(qr[0])
circuit.cx(qr[0], qr[2])
circuit.x(qr[0])
circuit.x(qr[1])
circuit.x(qr[4])
circuit.h(qr[4])
circuit.ccx(qr[0], qr[1], qr[4])
circuit.h(qr[4])
circuit.x(qr[0])
circuit.x(qr[1])
circuit.x(qr[4])
circuit.h(qr[0])
circuit.h(qr[1])
circuit.h(qr[4])
circuit.barrier(qr)
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
result = execute(
circuit,
backend=self.backend,
coupling_map=coupling_map,
seed_simulator=self.seed_simulator,
shots=shots,
)
counts = result.result().get_counts()
expected_probs = {"00": 0.64, "01": 0.117, "10": 0.113, "11": 0.13}
target = {key: shots * val for key, val in expected_probs.items()}
threshold = 0.04 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_math_domain_error(self):
"""Check for floating point errors.
The math library operates over floats and introduces floating point
errors that should be avoided.
See: https://github.com/Qiskit/qiskit-terra/issues/111
"""
# ┌───┐┌───┐ ┌─┐
# q0_0: ┤ Y ├┤ X ├─────┤M├─────────────────────
# └───┘└─┬─┘ └╥┘ ┌─┐
# q0_1: ───────■────────╫─────────────■──┤M├───
# ┌───┐┌───┐┌───┐ ║ ┌───┐┌───┐┌─┴─┐└╥┘┌─┐
# q0_2: ┤ Z ├┤ H ├┤ Y ├─╫─┤ T ├┤ Z ├┤ X ├─╫─┤M├
# └┬─┬┘└───┘└───┘ ║ └───┘└───┘└───┘ ║ └╥┘
# q0_3: ─┤M├────────────╫─────────────────╫──╫─
# └╥┘ ║ ║ ║
# c0: 4/══╩═════════════╩═════════════════╩══╩═
# 3 0 1 2
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
circ = QuantumCircuit(qr, cr)
circ.y(qr[0])
circ.z(qr[2])
circ.h(qr[2])
circ.cx(qr[1], qr[0])
circ.y(qr[2])
circ.t(qr[2])
circ.z(qr[2])
circ.cx(qr[1], qr[2])
circ.measure(qr[0], cr[0])
circ.measure(qr[1], cr[1])
circ.measure(qr[2], cr[2])
circ.measure(qr[3], cr[3])
coupling_map = [[0, 2], [1, 2], [2, 3]]
shots = 2000
job = execute(
circ,
backend=self.backend,
coupling_map=coupling_map,
seed_simulator=self.seed_simulator,
shots=shots,
)
counts = job.result().get_counts()
target = {"0001": shots / 2, "0101": shots / 2}
threshold = 0.04 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_random_parameter_circuit(self):
"""Run a circuit with randomly generated parameters."""
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "random_n5_d5.qasm"))
coupling_map = [[0, 1], [1, 2], [2, 3], [3, 4]]
shots = 1024
qobj = execute(
circ,
backend=self.backend,
coupling_map=coupling_map,
shots=shots,
seed_simulator=self.seed_simulator,
)
counts = qobj.result().get_counts()
expected_probs = {
"00000": 0.079239867254200971,
"00001": 0.032859032998526903,
"00010": 0.10752610993531816,
"00011": 0.018818532050952699,
"00100": 0.054830807251011054,
"00101": 0.0034141983951965164,
"00110": 0.041649309748902276,
"00111": 0.039967731207338125,
"01000": 0.10516937819949743,
"01001": 0.026635620063700002,
"01010": 0.0053475143548793866,
"01011": 0.01940513314416064,
"01100": 0.0044028405481225047,
"01101": 0.057524760052126644,
"01110": 0.010795354134597078,
"01111": 0.026491296821535528,
"10000": 0.094827455395274859,
"10001": 0.0008373965072688836,
"10010": 0.029082297894094441,
"10011": 0.012386622870598416,
"10100": 0.018739140061148799,
"10101": 0.01367656456536896,
"10110": 0.039184170706009248,
"10111": 0.062339335178438288,
"11000": 0.00293674365989009,
"11001": 0.012848433960739968,
"11010": 0.018472497159499782,
"11011": 0.0088903691234912003,
"11100": 0.031305389080034329,
"11101": 0.0004788556283690458,
"11110": 0.002232419390471667,
"11111": 0.017684822659235985,
}
target = {key: shots * val for key, val in expected_probs.items()}
threshold = 0.04 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_yzy_zyz_cases(self):
"""yzy_to_zyz works in previously failed cases.
See: https://github.com/Qiskit/qiskit-terra/issues/607
"""
backend = FakeTenerife()
qr = QuantumRegister(2)
circ1 = QuantumCircuit(qr)
circ1.cx(qr[0], qr[1])
circ1.rz(0.7, qr[1])
circ1.rx(1.570796, qr[1])
qobj1 = assemble(transpile(circ1, backend))
self.assertIsInstance(qobj1, QasmQobj)
circ2 = QuantumCircuit(qr)
circ2.y(qr[0])
circ2.h(qr[0])
circ2.s(qr[0])
circ2.h(qr[0])
qobj2 = assemble(transpile(circ2, backend))
self.assertIsInstance(qobj2, QasmQobj)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/peiyong-addwater/Hackathon-QNLP
|
peiyong-addwater
|
import collections
import pickle
import warnings
warnings.filterwarnings("ignore")
import os
from random import shuffle
import random
from discopy.tensor import Tensor
from discopy import Word
from discopy.rigid import Functor
from discopy import grammar
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from jax import numpy as jnp
import torch
import numpy as np
from lambeq import AtomicType, IQPAnsatz, remove_cups, NumpyModel, spiders_reader,SpiderAnsatz
from lambeq import BobcatParser, TreeReader, cups_reader, DepCCGParser
from lambeq import Dataset
from lambeq import QuantumTrainer, SPSAOptimizer
from lambeq import TketModel, PytorchModel, PytorchTrainer
from lambeq import Rewriter
from pytket.extensions.qiskit import AerBackend
import seaborn as sns
import matplotlib.pyplot as plt
from pytket.circuit.display import render_circuit_jupyter
pd.set_option('display.width', 1000)
pd.options.display.max_colwidth=80
print(os.getcwd())
warnings.filterwarnings("ignore")
os.environ["TOKENIZERS_PARALLELISM"] = "false"
BATCH_SIZE = 20
EPOCHS = 100
SEED = 0
LEARNING_RATE = 3e-2
TRAIN_INDEX_RATIO = 0.08
VAL_INDEX_RATIO = TRAIN_INDEX_RATIO + 0.01
TEST_INDEX_RATIO = VAL_INDEX_RATIO + 0.01
assert TEST_INDEX_RATIO <= 1
def load_pickled_dict_to_df(filename):
saved_dict = pickle.load(open(filename, 'rb'))
df = pd.DataFrame.from_dict(saved_dict)
df = df.sample(frac=1, random_state=SEED).reset_index(drop=True)
sentiment = []
for i in df['target']:
if i == "Positive":
sentiment.append(1)
else:
sentiment.append(0)
df["Sentiment"] = sentiment
return df
cleaned_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data.pkl')
cleaned_lemmatized_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data_lematize.pkl')
cleaned_lemmatized_stemmed_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data_stem_lematize.pkl')
#cleaned_qnlp = load_pickled_dict_to_df(cleaned_qnlp_filename)
#cleaned_lemmatized_qnlp = load_pickled_dict_to_df(cleaned_lemmatized_qnlp_filename)
cleaned__lemmatized_stemmed_qnlp = load_pickled_dict_to_df(cleaned_lemmatized_stemmed_qnlp_filename)
#cleaned_qnlp.head(10)
#cleaned_qnlp.info()
#sns.countplot(x = "target", data = cleaned_qnlp)
#cleaned_lemmatized_qnlp.head(10)
#cleaned_lemmatized_qnlp.info()
#sns.countplot(x='target', data = cleaned_lemmatized_qnlp)
cleaned__lemmatized_stemmed_qnlp.head(10)
cleaned__lemmatized_stemmed_qnlp.info()
sns.countplot(x='target', data = cleaned__lemmatized_stemmed_qnlp)
parser = BobcatParser(verbose='text')
# parser = DepCCGParser(root_cats=['S[dcl]'])
# parser = spiders_reader
NUM_DATA = 2578
sig = torch.sigmoid
def accuracy(y_hat, y):
return torch.sum(torch.eq(torch.round(sig(y_hat)), y))/len(y)/2 # half due to double-counting
rewriter = Rewriter(['prepositional_phrase', 'determiner', 'auxiliary', 'connector',
'coordination', 'object_rel_pronoun', 'subject_rel_pronoun',
'postadverb', 'preadverb'])
def rewrite(diagram):
# diagram = rewriter(diagram)
return remove_cups(diagram)
def create_diagrams_and_labels(total_df, NUM_DATA = 2578):
total_text = total_df['data'].tolist()
total_labels = total_df["Sentiment"].tolist()
total_labels = [[t, 1-t] for t in total_labels] # [1, 0] for positive, [0, 1] for negative
train_diagrams = parser.sentences2diagrams(total_text[:round(NUM_DATA*TRAIN_INDEX_RATIO)])
train_labels = total_labels[:round(NUM_DATA*TRAIN_INDEX_RATIO)]
dev_diagrams = parser.sentences2diagrams(total_text[round(NUM_DATA*TRAIN_INDEX_RATIO):round(NUM_DATA*VAL_INDEX_RATIO)])
dev_labels = total_labels[round(NUM_DATA*TRAIN_INDEX_RATIO):round(NUM_DATA*VAL_INDEX_RATIO)]
test_diagrams = parser.sentences2diagrams(total_text[round(NUM_DATA*VAL_INDEX_RATIO):round(NUM_DATA*TEST_INDEX_RATIO)])
test_labels = total_labels[round(NUM_DATA*VAL_INDEX_RATIO):round(NUM_DATA*TEST_INDEX_RATIO)]
return train_diagrams, train_labels, dev_diagrams, dev_labels, test_diagrams, test_labels
raw_train_diagrams_1, train_labels_1, raw_dev_diagrams_1, dev_labels_1, raw_test_diagrams_1, test_labels_1 = create_diagrams_and_labels(cleaned__lemmatized_stemmed_qnlp)
print(len(raw_train_diagrams_1))
raw_train_diagrams_1[0].draw(figsize=(12,3))
train_diagrams_1 = [rewrite(diagram) for diagram in raw_train_diagrams_1]
dev_diagrams_1 = [rewrite(diagram) for diagram in raw_dev_diagrams_1]
test_diagrams_1 = [rewrite(diagram) for diagram in raw_test_diagrams_1]
train_diagrams_1[0].draw(figsize=(6,5))
# ansatz_1 = IQPAnsatz({AtomicType.NOUN: 1, AtomicType.SENTENCE: 1, AtomicType.PREPOSITIONAL_PHRASE: 1, AtomicType.NOUN_PHRASE:1, AtomicType.CONJUNCTION:1}, n_layers=1, n_single_qubit_params=3)
ansatz_1 = SpiderAnsatz({AtomicType.NOUN: 2, AtomicType.SENTENCE: 2, AtomicType.PREPOSITIONAL_PHRASE: 2, AtomicType.NOUN_PHRASE:2, AtomicType.CONJUNCTION:2})
train_circuits_1 = [ansatz_1(diagram) for diagram in train_diagrams_1]
dev_circuits_1 = [ansatz_1(diagram) for diagram in dev_diagrams_1]
test_circuits_1 = [ansatz_1(diagram) for diagram in test_diagrams_1]
train_circuits_1[0].draw(figsize=(9, 12))
all_circuits_1 = train_circuits_1 + dev_circuits_1 + test_circuits_1
model_1 = PytorchModel.from_diagrams(all_circuits_1)
trainer_1 = PytorchTrainer(
model=model_1,
loss_function=torch.nn.BCEWithLogitsLoss(),
optimizer=torch.optim.AdamW, # type: ignore
learning_rate=LEARNING_RATE,
epochs=EPOCHS,
evaluate_functions={"acc": accuracy},
evaluate_on_train=True,
verbose='text',
seed=SEED)
)
train_dataset_1 = Dataset(
train_circuits_1,
train_labels_1,
batch_size=BATCH_SIZE)
val_dataset_1 = Dataset(dev_circuits_1, dev_labels_1, shuffle=False)
trainer_1.fit(train_dataset_1, val_dataset_1, logging_step=5)
fig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(12, 8))
ax_tl.set_title('Training set')
ax_tr.set_title('Development set')
ax_bl.set_xlabel('Iterations')
ax_br.set_xlabel('Iterations')
ax_bl.set_ylabel('Accuracy')
ax_tl.set_ylabel('Loss')
colours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color'])
ax_tl.plot(trainer_1.train_epoch_costs, color=next(colours))
ax_bl.plot(trainer_1.train_results['acc'], color=next(colours))
ax_tr.plot(trainer_1.val_costs, color=next(colours))
ax_br.plot(trainer_1.val_results['acc'], color=next(colours))
test_acc_1 = acc(model_1(test_circuits_1), test_labels_1)
print('Test accuracy:', test_acc_1)
|
https://github.com/maheshwaripranav/Qiskit-Fall-Fest-Kolkata-Hackathon
|
maheshwaripranav
|
import numpy as np
from qiskit import QuantumCircuit, Aer
import matplotlib.pyplot as plt
angles = np.array([ord("Z")-ord(i) for i in input().upper()])
print(angles)
angles = 2*np.arcsin(np.sqrt(angles/25))
print(angles)
n = len(angles)
qc = QuantumCircuit(n,n)
for i in range(len(angles)):
qc.ry(angles[i],i)
qc.draw()
#for i in range(len(angles)):
# qc.ry(-angles[i],i)
qc.measure(range(4),range(4))
qc.draw()
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(qc, shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts()
arr = [0 for _ in range(n)]
for state, count in counts.items():
state = state[::-1]
for i in range(n):
arr[i] += int(state[i])*count/1024
output = ""
for i in range(n):
output += chr(ord("A")+25-int(round(arr[i]*25,0)))
print(output)
|
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
|
geduardo
|
import numpy as np
from qiskit import *
q = QuantumRegister(1)
# Create a Quantum Circuit acting on a quantum register of n qubits
qc = QuantumCircuit(q)
qc.draw(filename="0.png")
qc.h(0)
qc.draw()
qc.z(0)
qc.draw()
qc.h(0)
qc.draw()
qc.measure(0,0)
qc.draw()
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector([0,0,1], title='Intial state')
plot_bloch_vector([1,0,0], title='H gate')
plot_bloch_vector([-1,0,0], title='Z gate')
plot_bloch_vector([0,0,-1], title='H gate')
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
CCXFactory
============
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state.cnot._CCXFactory
This class is the abstract base class for the multiple-controlled X-gates (short ccx) that are primarily used
for binary input data of the classifier.
.. autosummary::
:nosignatures:
CCXFactory
CCXFactory
#############
.. autoclass:: CCXFactory
:members:
"""
import abc
from typing import List, Union, Tuple
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.register import Register
class CCXFactory(object):
"""
Abstract base class for using a multi-ccx gate within the context of the classifier
"""
@abc.abstractmethod
def ccx(self, qc, conditial_case, control_qubits, tgt):
# type: (CCXFactory, QuantumCircuit, int, Union[List[Tuple[Register, int]], QuantumRegister], Union[Tuple[Register, int], QuantumRegister]) ->QuantumCircuit
"""
This method applies to a quantum circuit on the control qubits the desired controlled operation on the target
if the quantum state coincides with the (binary representation of the) conditional case.
This abstract method must be implemented in order to be used by the
:py:class:`_QmlUniformAmplitudeStateCircuitBuilder` and so that the correct state for the classifier can be
applied.
:param qc: the circuit to apply this operation to
:param conditial_case: an integer whose binary representation signifies the branch to controll on
:param control_qubits: the qubits that hold the desired conditional case
:param tgt: the target to be applied the controlled X gate on
:return: the circuit after application of the gate
"""
pass
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import warnings
import numpy as np
from numpy import pi
from qiskit import IBMQ, QuantumRegister, ClassicalRegister, QuantumCircuit, execute, transpile, BasicAer
from qiskit_optimization.algorithms import CplexOptimizer
from qiskit_optimization import QuadraticProgram
from qiskit.visualization import plot_histogram
from qiskit.providers.ibmq.job import job_monitor
from qiskit.providers.ibmq import least_busy
from utilities.helpers import create_qaoa_meo
qp = QuadraticProgram()
qp.read_from_lp_file("example_5_qubits.lp")
# solve classically as reference
cplex = CplexOptimizer()
print(cplex.solve(qp))
print(qp)
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
shots = 4096
# solve qp with Minimum Eigen Optimizer QAOA and simulator
EVALUATIONS = 20
def qaoa_callback(eval_ct: int, opt_pars: np.ndarray, mean: float, stdev: float) -> None:
"""Print parameterset of last iteration."""
if eval_ct == EVALUATIONS:
print("Evaluation count reached ", eval_ct, "with pars:", opt_pars)
# Evaluation count reached 20 with pars: [-0.96598411 -0.26119604] original on ibmq_qasm_simulator
qaoa = create_qaoa_meo(max_iter=EVALUATIONS, qaoa_callback=qaoa_callback)
res = qaoa.solve(qp)
res
def create_qaoa_circuit() -> QuantumCircuit:
""" taken from IBMQ Experience Job ID 608e53f752b7af33fe34177f """
qreg_q = QuantumRegister(5, 'q')
circuit = QuantumCircuit(qreg_q)
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.cx(qreg_q[1], qreg_q[0])
circuit.rz(2.4149602828076864, qreg_q[0])
circuit.cx(qreg_q[1], qreg_q[0])
circuit.h(qreg_q[2])
circuit.cx(qreg_q[2], qreg_q[0])
circuit.rz(1.9319682262461493, qreg_q[0])
circuit.cx(qreg_q[2], qreg_q[0])
circuit.cx(qreg_q[2], qreg_q[1])
circuit.rz(-1.448976169684612, qreg_q[1])
circuit.cx(qreg_q[2], qreg_q[1])
circuit.h(qreg_q[3])
circuit.cx(qreg_q[3], qreg_q[0])
circuit.rz(1.9319682262461493, qreg_q[0])
circuit.cx(qreg_q[3], qreg_q[0])
circuit.cx(qreg_q[3], qreg_q[1])
circuit.rz(-2.4149602828076864, qreg_q[1])
circuit.cx(qreg_q[3], qreg_q[1])
circuit.cx(qreg_q[3], qreg_q[2])
circuit.rz(4.346928509053836, qreg_q[2])
circuit.cx(qreg_q[3], qreg_q[2])
circuit.h(qreg_q[4])
circuit.cx(qreg_q[4], qreg_q[0])
circuit.rz(1.448976169684612, qreg_q[0])
circuit.cx(qreg_q[4], qreg_q[0])
circuit.u3(0.5223920854580901, 1.5707963267948963, -3.4941874092818432, qreg_q[0])
circuit.cx(qreg_q[4], qreg_q[1])
circuit.rz(0.9659841131230746, qreg_q[1])
circuit.cx(qreg_q[4], qreg_q[1])
circuit.u3(0.5223920854580902, 1.5707963267948968, -0.12182015711028482, qreg_q[1])
circuit.cx(qreg_q[4], qreg_q[2])
circuit.rz(-0.9659841131230746, qreg_q[2])
circuit.cx(qreg_q[4], qreg_q[2])
circuit.u3(0.5223920854580902, 1.5707963267948966, 2.293140125697402, qreg_q[2])
circuit.cx(qreg_q[4], qreg_q[3])
circuit.rz(-0.4829920565615373, qreg_q[3])
circuit.cx(qreg_q[4], qreg_q[3])
circuit.u3(0.5223920854580901, 1.5707963267948968, 2.7847093260181426, qreg_q[3])
circuit.rx(-0.5223920854580901, qreg_q[4])
circuit.measure_all()
return circuit
warnings.filterwarnings("ignore", category=DeprecationWarning)
circuit = create_qaoa_circuit()
job = execute(circuit, BasicAer.get_backend('qasm_simulator'), shots=shots)
counts = job.result().get_counts()
plot_histogram(counts)
backend = provider.get_backend("ibmq_athens")
job = execute(circuit, backend, shots=shots, job_name="qaoa_5_real", job_tags=["qaoa", "athens"])
job_monitor(job)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
import copy
# Problem modelling imports
from docplex.mp.model import Model
# Qiskit imports
from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit.utils.algorithm_globals import algorithm_globals
from qiskit_optimization.algorithms import MinimumEigenOptimizer, CplexOptimizer
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.problems.variable import VarType
from qiskit_optimization.converters.quadratic_program_to_qubo import QuadraticProgramToQubo
from qiskit_optimization.translators import from_docplex_mp
def create_problem(mu: np.array, sigma: np.array, total: int = 3) -> QuadraticProgram:
"""Solve the quadratic program using docplex."""
mdl = Model()
x = [mdl.binary_var("x%s" % i) for i in range(len(sigma))]
objective = mdl.sum([mu[i] * x[i] for i in range(len(mu))])
objective -= 2 * mdl.sum(
[sigma[i, j] * x[i] * x[j] for i in range(len(mu)) for j in range(len(mu))]
)
mdl.maximize(objective)
cost = mdl.sum(x)
mdl.add_constraint(cost == total)
qp = from_docplex_mp(mdl)
return qp
def relax_problem(problem) -> QuadraticProgram:
"""Change all variables to continuous."""
relaxed_problem = copy.deepcopy(problem)
for variable in relaxed_problem.variables:
variable.vartype = VarType.CONTINUOUS
return relaxed_problem
mu = np.array([3.418, 2.0913, 6.2415, 4.4436, 10.892, 3.4051])
sigma = np.array(
[
[1.07978412, 0.00768914, 0.11227606, -0.06842969, -0.01016793, -0.00839765],
[0.00768914, 0.10922887, -0.03043424, -0.0020045, 0.00670929, 0.0147937],
[0.11227606, -0.03043424, 0.985353, 0.02307313, -0.05249785, 0.00904119],
[-0.06842969, -0.0020045, 0.02307313, 0.6043817, 0.03740115, -0.00945322],
[-0.01016793, 0.00670929, -0.05249785, 0.03740115, 0.79839634, 0.07616951],
[-0.00839765, 0.0147937, 0.00904119, -0.00945322, 0.07616951, 1.08464544],
]
)
qubo = create_problem(mu, sigma)
print(qubo.prettyprint())
result = CplexOptimizer().solve(qubo)
print(result.prettyprint())
qp = relax_problem(QuadraticProgramToQubo().convert(qubo))
print(qp.prettyprint())
sol = CplexOptimizer().solve(qp)
print(sol.prettyprint())
c_stars = sol.samples[0].x
print(c_stars)
algorithm_globals.random_seed = 12345
qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 1.0])
exact_mes = NumPyMinimumEigensolver()
qaoa = MinimumEigenOptimizer(qaoa_mes)
qaoa_result = qaoa.solve(qubo)
print(qaoa_result.prettyprint())
from qiskit import QuantumCircuit
thetas = [2 * np.arcsin(np.sqrt(c_star)) for c_star in c_stars]
init_qc = QuantumCircuit(len(sigma))
for idx, theta in enumerate(thetas):
init_qc.ry(theta, idx)
init_qc.draw(output="mpl")
from qiskit.circuit import Parameter
beta = Parameter("β")
ws_mixer = QuantumCircuit(len(sigma))
for idx, theta in enumerate(thetas):
ws_mixer.ry(-theta, idx)
ws_mixer.rz(-2 * beta, idx)
ws_mixer.ry(theta, idx)
ws_mixer.draw(output="mpl")
ws_qaoa_mes = QAOA(
sampler=Sampler(),
optimizer=COBYLA(),
initial_state=init_qc,
mixer=ws_mixer,
initial_point=[0.0, 1.0],
)
ws_qaoa = MinimumEigenOptimizer(ws_qaoa_mes)
ws_qaoa_result = ws_qaoa.solve(qubo)
print(ws_qaoa_result.prettyprint())
def format_qaoa_samples(samples, max_len: int = 10):
qaoa_res = []
for s in samples:
if sum(s.x) == 3:
qaoa_res.append(("".join([str(int(_)) for _ in s.x]), s.fval, s.probability))
res = sorted(qaoa_res, key=lambda x: -x[1])[0:max_len]
return [(_[0] + f": value: {_[1]:.3f}, probability: {1e2*_[2]:.1f}%") for _ in res]
format_qaoa_samples(qaoa_result.samples)
format_qaoa_samples(ws_qaoa_result.samples)
from qiskit_optimization.algorithms import WarmStartQAOAOptimizer
qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 1.0])
ws_qaoa = WarmStartQAOAOptimizer(
pre_solver=CplexOptimizer(), relax_for_pre_solver=True, qaoa=qaoa_mes, epsilon=0.0
)
ws_result = ws_qaoa.solve(qubo)
print(ws_result.prettyprint())
format_qaoa_samples(ws_result.samples)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/lynnlangit/learning-quantum
|
lynnlangit
|
"""The following is python code utilizing the qiskit library that can be run on extant quantum
hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding,
for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find
r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1,
results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>).
To find the factor, use the equivalence a^r mod 15. From this:
(a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r
values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15
Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients,
gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15,
so the result of running shors algorithm to find the prime factors of an integer using quantum
hardware are demonstrated. Note, this is not the same as the technical implementation of shor's
algorithm described in this section for breaking the discrete log hardness assumption,
though the proof of concept remains."""
# Import libraries
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from numpy import pi
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.visualization import plot_histogram
# Initialize qubit registers
qreg_q = QuantumRegister(5, 'q')
creg_c = ClassicalRegister(5, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.reset(qreg_q[0])
circuit.reset(qreg_q[1])
circuit.reset(qreg_q[2])
circuit.reset(qreg_q[3])
circuit.reset(qreg_q[4])
# Apply Hadamard transformations to qubit registers
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.h(qreg_q[2])
# Apply first QFT, modular exponentiation, and another QFT
circuit.h(qreg_q[1])
circuit.cx(qreg_q[2], qreg_q[3])
circuit.crx(pi/2, qreg_q[0], qreg_q[1])
circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4])
circuit.h(qreg_q[0])
circuit.rx(pi/2, qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
# Measure the qubit registers 0-2
circuit.measure(qreg_q[2], creg_c[2])
circuit.measure(qreg_q[1], creg_c[1])
circuit.measure(qreg_q[0], creg_c[0])
# Get least busy quantum hardware backend to run on
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
# Run the circuit on available quantum hardware and plot histogram
from qiskit.tools.monitor import job_monitor
job = execute(circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(circuit)
plot_histogram(answer)
#largest amplitude results correspond with r values used to find the prime factor of N.
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector
# Let's do an X-gate on a |0> qubit
qc=QuantumCircuit(1)
qc.x(0)
qc.draw('mpl')#mpl stands for the matplotlib argument
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc, backend).result().get_statevector()
print(out)
# Do Y-gate on qubit 0
qc.y(0)
# Do Z-gate on qubit 0
qc.z(0)
qc.draw('mpl')
#create circuit with three qubit
qc = QuantumCircuit(3)
# Apply H-gate to each qubit:
for qubit in range(3):
qc.h(qubit)
# See the circuit:
qc.draw('mpl')
qc.i(0)
qc.draw('mpl')
|
https://github.com/RedHatParichay/qiskit-lancasterleipzig-2023
|
RedHatParichay
|
## Blank Code Cell
## Use only if you need to install the grader and/or Qiskit
## If you are running this notebook in the IBM Quantum Lab - you can ignore this cell
!pip install qiskit
!pip install 'qc-grader[qiskit] @ git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git'
## Run this cell to make sure your grader is setup correctly
%set_env QC_GRADE_ONLY=true
%set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com
from qiskit import QuantumCircuit
from qiskit.circuit import QuantumRegister, ClassicalRegister
qr = QuantumRegister(1)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
# unpack the qubit and classical bits from the registers
(q0,) = qr
b0, b1 = cr
# apply Hadamard
qc.h(q0)
# measure
qc.measure(q0, b0)
# begin if test block. the contents of the block are executed if b0 == 1
with qc.if_test((b0, 1)):
# if the condition is satisfied (b0 == 1), then flip the bit back to 0
qc.x(q0)
# finally, measure q0 again
qc.measure(q0, b1)
qc.draw(output="mpl", idle_wires=False)
from qiskit_aer import AerSimulator
# initialize the simulator
backend_sim = AerSimulator()
# run the circuit
reset_sim_job = backend_sim.run(qc)
# get the results
reset_sim_result = reset_sim_job.result()
# retrieve the bitstring counts
reset_sim_counts = reset_sim_result.get_counts()
print(f"Counts: {reset_sim_counts}")
from qiskit.visualization import *
# plot histogram
plot_histogram(reset_sim_counts)
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
q0, q1 = qr
b0, b1 = cr
qc.h(q0)
qc.measure(q0, b0)
## Write your code below this line ##
## Do not change the code below this line ##
qc.measure(q1, b1)
qc.draw(output="mpl", idle_wires=False)
backend_sim = AerSimulator()
job_1 = backend_sim.run(qc)
result_1 = job_1.result()
counts_1 = result_1.get_counts()
print(f"Counts: {counts_1}")
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3b
grade_ex3b(qc)
controls = QuantumRegister(2, name="control")
target = QuantumRegister(1, name="target")
mid_measure = ClassicalRegister(2, name="mid")
final_measure = ClassicalRegister(1, name="final")
base = QuantumCircuit(controls, target, mid_measure, final_measure)
def trial(
circuit: QuantumCircuit,
target: QuantumRegister,
controls: QuantumRegister,
measures: ClassicalRegister,
):
"""Probabilistically perform Rx(theta) on the target, where cos(theta) = 3/5."""
## Write your code below this line, making sure it's indented to where this comment begins from ##
## Do not change the code below this line ##
qc = base.copy_empty_like()
trial(qc, target, controls, mid_measure)
qc.draw("mpl", cregbundle=False)
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3c
grade_ex3c(qc)
def reset_controls(
circuit: QuantumCircuit, controls: QuantumRegister, measures: ClassicalRegister
):
"""Reset the control qubits if they are in |1>."""
## Write your code below this line, making sure it's indented to where this comment begins from ##
## Do not change the code below this line ##
qc = base.copy_empty_like()
trial(qc, target, controls, mid_measure)
reset_controls(qc, controls, mid_measure)
qc.measure(controls, mid_measure)
qc.draw("mpl", cregbundle=False)
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3d
grade_ex3d(qc)
# Set the maximum number of trials
max_trials = 2
# Create a clean circuit with the same structure (bits, registers, etc) as the initial base we set up.
circuit = base.copy_empty_like()
# The first trial does not need to reset its inputs, since the controls are guaranteed to start in the |0> state.
trial(circuit, target, controls, mid_measure)
# Manually add the rest of the trials. In the future, we will be able to use a dynamic `while` loop to do this, but for now,
# we statically add each loop iteration with a manual condition check on each one.
# This involves more classical synchronizations than the while loop, but will suffice for now.
for _ in range(max_trials - 1):
reset_controls(circuit, controls, mid_measure)
with circuit.if_test((mid_measure, 0b00)) as else_:
# This is the success path, but Qiskit can't directly
# represent a negative condition yet, so we have an
# empty `true` block in order to use the `else` branch.
pass
with else_:
## Write your code below this line, making sure it's indented to where this comment begins from ##
## Do not change the code below this line ##
# We need to measure the control qubits again to ensure we get their final results; this is a hardware limitation.
circuit.measure(controls, mid_measure)
# Finally, let's measure our target, to check that we're getting the rotation we desired.
circuit.measure(target, final_measure)
circuit.draw("mpl", cregbundle=False)
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3e
grade_ex3e(circuit)
sim = AerSimulator()
job = sim.run(circuit, shots=1000)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
|
https://github.com/Tojarieh97/VQE
|
Tojarieh97
|
%load_ext autoreload
%autoreload 2
from qiskit.circuit.library.standard_gates import RXGate, RZGate, CXGate, CZGate
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
def get_thetas_circuit(thetas, D2):
qr = QuantumRegister(4, name="qubit")
qc = QuantumCircuit(qr)
for d in range(D2):
qc.append(RXGate(thetas[0]), [qr[0]])
qc.append(RXGate(thetas[1]), [qr[1]])
qc.append(RXGate(thetas[2]), [qr[2]])
qc.append(RXGate(thetas[3]), [qr[3]])
qc.append(RZGate(thetas[4]), [qr[0]])
qc.append(RZGate(thetas[5]), [qr[1]])
qc.append(RZGate(thetas[6]), [qr[2]])
qc.append(RZGate(thetas[7]), [qr[3]])
qc.append(CZGate(), [qr[0], qr[1]])
qc.append(CZGate(), [qr[1], qr[2]])
qc.append(CZGate(), [qr[2], qr[3]])
qc.barrier(qr)
qc.append(RXGate(thetas[0]), [qr[0]])
qc.append(RXGate(thetas[1]), [qr[1]])
qc.append(RXGate(thetas[2]), [qr[2]])
qc.append(RXGate(thetas[3]), [qr[3]])
qc.append(RZGate(thetas[4]), [qr[0]])
qc.append(RZGate(thetas[5]), [qr[1]])
qc.append(RZGate(thetas[6]), [qr[2]])
qc.append(RZGate(thetas[7]), [qr[3]])
return qc
def get_phis_circuit(phis, D1, input_state):
qr = QuantumRegister(4, name="qubit")
qc = QuantumCircuit(qr)
qc.initialize(input_state)
for d in range(D1):
qc.append(RXGate(phis[0]), [qr[2]])
qc.append(RXGate(phis[1]), [qr[3]])
qc.append(RZGate(phis[2]), [qr[2]])
qc.append(RZGate(phis[3]), [qr[3]])
qc.append(CZGate(), [qr[2], qr[3]])
qc.barrier(qr)
return qc
def get_full_variational_quantum_circuit(thetas, phis, D1, D2, input_state):
thetas_quantum_circuit = get_thetas_circuit(thetas, D2)
phis_quantum_circuit = get_phis_circuit(phis, D1, input_state)
variational_quantum_circuit = phis_quantum_circuit.compose(thetas_quantum_circuit)
return variational_quantum_circuit
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
from mirror_gates.noisy_fidelity import heuristic_fidelity
import numpy as np
import matplotlib.pyplot as plt
import LovelyPlots.utils as lp # noqa: F401
import matplotlib.pyplot as plt
import numpy as np
import scienceplots # noqa: F401
# Constants
N = 16
start_value = 0
end_value = 10_000
num_points = 1000
# Generate Qiskit data
qiskit_durations = np.linspace(
start_value, end_value, num_points
) # Define start_value, end_value, and num_points as per your data
qiskit_fidelities = heuristic_fidelity(N, qiskit_durations)
# Generate MIRAGE data (shifted by depth reduction)
mirage_durations_hh = qiskit_durations * (1 - 0.3119) # 31.19% reduction for heavy-hex
mirage_fidelities_hh = heuristic_fidelity(N, mirage_durations_hh)
with plt.style.context(["ieee"]):
# Plot Qiskit data
plt.plot(qiskit_durations, qiskit_fidelities, label="Qiskit", color="blue")
# Plot MIRAGE data using Qiskit's durations as the x-axis
plt.plot(
qiskit_durations,
mirage_fidelities_hh,
label="MIRAGE (Heavy-Hex)",
color="green",
)
# Add labels, title, legend, etc.
plt.xlabel("Baseline Circuit Duration (Qiskit)")
plt.ylabel("Fidelity")
plt.title("Fidelity vs. Baseline Circuit Duration")
plt.legend()
plt.grid(True)
# Show the plot
plt.show()
circuits = [
"ae_n16",
"bigadder_n18",
"knn_n25",
"multiplier_n15",
"portfolioqaoa_n16",
"qec9xz_n17",
"qft_n18",
"qftentangled_n16",
"qpeexact_n16",
"qram_n20",
"sat_n11",
"seca_n11",
"swap_test_n25",
]
# Values taken from outputs of previous runs
# experiment 1
sqrtiswap_mirage_hh = [
71.369,
103.163,
70.141,
168.167,
113.540,
21.699,
58.570,
51.719,
70.866,
81.952,
225.484,
37.187,
70.141,
]
sqrtiswap_qiskit_hh = [
122.362,
131.494,
79.406,
195.946,
250.689,
30.773,
108.342,
120.588,
167.700,
94.756,
286.870,
49.257,
79.700,
]
# experiment 2
sqrtiswap_mirage_sl = [
67.312,
87.793,
64.635,
147.498,
90.500,
15.751,
52.341,
52.662,
66.810,
76.280,
209.375,
33.892,
64.635,
]
sqrtiswap_qiskit_sl = [
120.638,
109.040,
69.573,
175.528,
236.824,
22.211,
108.948,
95.484,
139.716,
83.561,
235.682,
49.288,
69.392,
]
# experiment 3
cnot_mirage_hh = [
151.813,
158.463,
126.188,
303.863,
181.000,
37.859,
121.184,
97.834,
150.797,
135.909,
356.949,
55.177,
126.188,
]
cnot_qiskit_hh = [
261.086,
192.257,
131.488,
283.823,
431.180,
42.951,
215.338,
223.833,
325.028,
148.078,
440.340,
69.558,
130.761,
]
# experiment 4
syc_mirage_sl = [
136.397,
194.039,
148.365,
336.419,
181.000,
41.089,
100.184,
101.762,
136.397,
155.747,
458.447,
76.565,
148.365,
]
syc_qiskit_sl = [
213.839,
217.868,
143.501,
365.007,
398.886,
49.669,
209.958,
219.996,
271.189,
163.659,
483.290,
96.168,
143.910,
]
# sort so circuits appear as same order they do in the paper
sorted_circuits = [
"qec9xz_n17",
"seca_n11",
"knn_n25",
"swap_test_n25",
"qram_n20",
"qft_n18",
"qftentangled_n16",
"ae_n16",
"bigadder_n18",
"qpeexact_n16",
"multiplier_n15",
"portfolioqaoa_n16",
"sat_n11",
]
# Create a dictionary with circuits as keys and their index in sorted_circuits as values
index_map = {circuit: index for index, circuit in enumerate(sorted_circuits)}
# Sort all your lists based on the order in sorted_circuits
sqrtiswap_mirage_hh = [
x
for _, x in sorted(
zip(circuits, sqrtiswap_mirage_hh), key=lambda pair: index_map[pair[0]]
)
]
sqrtiswap_qiskit_hh = [
x
for _, x in sorted(
zip(circuits, sqrtiswap_qiskit_hh), key=lambda pair: index_map[pair[0]]
)
]
sqrtiswap_mirage_sl = [
x
for _, x in sorted(
zip(circuits, sqrtiswap_mirage_sl), key=lambda pair: index_map[pair[0]]
)
]
sqrtiswap_qiskit_sl = [
x
for _, x in sorted(
zip(circuits, sqrtiswap_qiskit_sl), key=lambda pair: index_map[pair[0]]
)
]
cnot_mirage_hh = [
x
for _, x in sorted(
zip(circuits, cnot_mirage_hh), key=lambda pair: index_map[pair[0]]
)
]
cnot_qiskit_hh = [
x
for _, x in sorted(
zip(circuits, cnot_qiskit_hh), key=lambda pair: index_map[pair[0]]
)
]
syc_mirage_sl = [
x
for _, x in sorted(
zip(circuits, syc_mirage_sl), key=lambda pair: index_map[pair[0]]
)
]
syc_qiskit_sl = [
x
for _, x in sorted(
zip(circuits, syc_qiskit_sl), key=lambda pair: index_map[pair[0]]
)
]
circuits = sorted_circuits
import matplotlib.pyplot as plt
import numpy as np
# Function to convert depth to duration
def depth_to_duration(depth, gate_time_1q=25, gate_time_2q=100):
return (gate_time_1q * depth + gate_time_2q * depth) + gate_time_1q
def hf(n, d):
return heuristic_fidelity(n, d, T1=1600_000, T2=1600_000)
# Calculate durations for all experiments
durations_mirage_hh = [depth_to_duration(d) for d in sqrtiswap_mirage_hh]
durations_qiskit_hh = [depth_to_duration(d) for d in sqrtiswap_qiskit_hh]
durations_mirage_sl = [depth_to_duration(d) for d in sqrtiswap_mirage_sl]
durations_qiskit_sl = [depth_to_duration(d) for d in sqrtiswap_qiskit_sl]
durations_cnot_mirage_hh = [depth_to_duration(d) for d in cnot_mirage_hh]
durations_cnot_qiskit_hh = [depth_to_duration(d) for d in cnot_qiskit_hh]
durations_syc_mirage_sl = [depth_to_duration(d) for d in syc_mirage_sl]
durations_syc_qiskit_sl = [depth_to_duration(d) for d in syc_qiskit_sl]
# Calculate fidelities for all experiments
fidelities_mirage_hh = [
hf(int(circuit.split("_")[-1][1:]), d)
for circuit, d in zip(circuits, durations_mirage_hh)
]
fidelities_qiskit_hh = [
hf(int(circuit.split("_")[-1][1:]), d)
for circuit, d in zip(circuits, durations_qiskit_hh)
]
fidelities_mirage_sl = [
hf(int(circuit.split("_")[-1][1:]), d)
for circuit, d in zip(circuits, durations_mirage_sl)
]
fidelities_qiskit_sl = [
hf(int(circuit.split("_")[-1][1:]), d)
for circuit, d in zip(circuits, durations_qiskit_sl)
]
fidelities_cnot_mirage_hh = [
hf(int(circuit.split("_")[-1][1:]), d)
for circuit, d in zip(circuits, durations_cnot_mirage_hh)
]
fidelities_cnot_qiskit_hh = [
hf(int(circuit.split("_")[-1][1:]), d)
for circuit, d in zip(circuits, durations_cnot_qiskit_hh)
]
fidelities_syc_mirage_sl = [
hf(int(circuit.split("_")[-1][1:]), d)
for circuit, d in zip(circuits, durations_syc_mirage_sl)
]
fidelities_syc_qiskit_sl = [
hf(int(circuit.split("_")[-1][1:]), d)
for circuit, d in zip(circuits, durations_syc_qiskit_sl)
]
# Calculate relative changes in fidelity for all experiments
relative_changes_hh = [
(fm - fq) / fq for fm, fq in zip(fidelities_mirage_hh, fidelities_qiskit_hh)
]
relative_changes_sl = [
(fm - fq) / fq for fm, fq in zip(fidelities_mirage_sl, fidelities_qiskit_sl)
]
relative_changes_cnot_hh = [
(fm - fq) / fq
for fm, fq in zip(fidelities_cnot_mirage_hh, fidelities_cnot_qiskit_hh)
]
relative_changes_syc_sl = [
(fm - fq) / fq for fm, fq in zip(fidelities_syc_mirage_sl, fidelities_syc_qiskit_sl)
]
relative_changes_hh = [
(fm - fq) for fm, fq in zip(fidelities_mirage_hh, fidelities_qiskit_hh)
]
relative_changes_sl = [
(fm - fq) for fm, fq in zip(fidelities_mirage_sl, fidelities_qiskit_sl)
]
relative_changes_cnot_hh = [
(fm - fq) for fm, fq in zip(fidelities_cnot_mirage_hh, fidelities_cnot_qiskit_hh)
]
relative_changes_syc_sl = [
(fm - fq) for fm, fq in zip(fidelities_syc_mirage_sl, fidelities_syc_qiskit_sl)
]
# # Zip all data together using circuits as the key
# data = list(
# zip(
# circuits,
# relative_changes_hh,
# relative_changes_sl,
# relative_changes_cnot_hh,
# relative_changes_syc_sl,
# )
# )
# # Sort the data by the values of sqrtiswap_mirage_hh (Experiment 1)
# sorted_data = sorted(data, key=lambda x: x[1])
# # Unzip the sorted data back into individual lists
# (
# circuits,
# relative_changes_hh,
# relative_changes_sl,
# relative_changes_cnot_hh,
# relative_changes_syc_sl,
# ) = map(list, zip(*sorted_data))
# arithmetic mean
relative_changes_hh.append(np.mean(relative_changes_hh))
relative_changes_sl.append(np.mean(relative_changes_sl))
relative_changes_cnot_hh.append(np.mean(relative_changes_cnot_hh))
relative_changes_syc_sl.append(np.mean(relative_changes_syc_sl))
circuits.append("Average")
from typing import List, Tuple
import LovelyPlots.utils as lp # noqa: F401
import matplotlib.pyplot as plt
import numpy as np
import scienceplots # noqa: F401
from matplotlib.colors import ListedColormap
from matplotlib.figure import Axes, Figure
from matplotlib.ticker import MaxNLocator
from transpile_benchy.benchmark import Benchmark
from transpile_benchy.metrics.abc_metrics import MetricInterface
def _initialize_plot(legend_show: bool) -> Tuple[Figure, Axes]:
"""Initialize the plot and returns the fig and ax."""
ref_size = 1.25 # Assume need .4 for legend
legend_offset = 0.5
if legend_show:
fig, axs = plt.subplots(
2,
figsize=(
3.5,
ref_size + legend_offset,
), # 2 inch for plot + 1 inch for legend
sharex=True,
gridspec_kw={
"height_ratios": [legend_offset, ref_size + legend_offset],
"hspace": 0.01,
}, # 1:2 ratio for legend:plot
)
ax = axs[1]
else:
fig, ax = plt.subplots(figsize=(3.5, ref_size)) # Just 2 inch for the plot
return fig, ax
names = [
"HH-$\sqrt{\mathrm{iSWAP}}$",
"SL-$\sqrt{\mathrm{iSWAP}}$",
"HH-$\mathrm{CNOT}$",
"SL-$\mathrm{SYC}$",
]
cmap = plt.cm.get_cmap("tab10", 10)
plt.rc("legend", fontsize=8)
plt.rc("axes", labelsize=8)
with plt.style.context(["ieee"]):
# Set up the figure and axes
fig, ax = _initialize_plot(True)
bar_width = 0.2
index = np.arange(len(circuits))
# Add bars for each experiment using the relative changes
ax.bar(
index - 1.5 * bar_width,
relative_changes_hh,
width=bar_width,
label=r"HH-$\sqrt{\texttt{iSWAP}}$",
color=cmap(0),
)
ax.bar(
index - 0.5 * bar_width,
relative_changes_sl,
width=bar_width,
label=r"SL-$\sqrt{\texttt{iSWAP}}$",
# color="red",
color=cmap(1),
)
ax.bar(
index + 0.5 * bar_width,
relative_changes_cnot_hh,
width=bar_width,
label=r"HH-$\texttt{CNOT}$",
# color="green",
color=cmap(2),
)
ax.bar(
index + 1.5 * bar_width,
relative_changes_syc_sl,
width=bar_width,
label=r"SL-$\texttt{SYC}$",
# color="orange",
color=cmap(3),
)
# Add labels, title, and legend
ax.set_ylabel("Absolute Fidelity Change")
ax.set_xticks(index)
ax.set_xticklabels(
circuits,
rotation=30,
ha="right",
fontsize=7,
)
# ax.set_yscale("log")
ax.get_yaxis().set_major_formatter(plt.ScalarFormatter())
# we need more ticks on y-axis
ax.yaxis.set_major_locator(MaxNLocator(5))
ax.set_yticklabels(["{:.0f}%".format(val * 100) for val in ax.get_yticks()])
for j, name in enumerate(names):
fig.axes[0].bar(0, 0, color=cmap(j), label=f"{name}")
fig.axes[0].legend(
loc="upper center",
ncol=2,
fontsize=8,
frameon=False,
bbox_to_anchor=(0.5, 1.5), # 1.10
)
fig.axes[0].axis("off")
# show grid
# fig.axes[1].grid(True, axis="y", which="major", linestyle="--", alpha=0.5)
# Show the plot
plt.tight_layout()
fig
fig.savefig(
"test.pdf",
bbox_inches="tight",
pad_inches=0,
)
|
https://github.com/DmitriiNabok/QuantumKitchenSinks
|
DmitriiNabok
|
import numpy as np
import matplotlib.pyplot as plt
import time
# Qiskit
from qiskit.circuit import QuantumCircuit, ParameterVector
# Scikit
from sklearn.model_selection import train_test_split, StratifiedKFold, StratifiedShuffleSplit, GridSearchCV
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from qks.QuantumKitchenSinks import QuantumKitchenSinks
from qks.ProjectedQuantumKitchenSinks import ProjectedQuantumKitchenSinks
seed = 12345
np.random.seed(seed)
from sklearn.datasets import make_blobs
from sklearn.preprocessing import MinMaxScaler
from qks.visualization_tools import plot_dataset, plot_predictions, plot_decisions
n_samples = 400
X, y = make_blobs(n_samples=n_samples, n_features=2, centers=9, random_state=110, shuffle=True, cluster_std=1.2)
y[y%2 == 0] = -1
y[y > 0] = 1
xmin = -1; xmax = 1
X = MinMaxScaler(feature_range=(xmin, xmax)).fit_transform(X)
axes = [xmin, xmax, xmin, xmax]
train_size = 20
test_size = 20
X_train, X_test, y_train, y_test = train_test_split(
X, y,
train_size=train_size, test_size=test_size,
random_state=seed
)
# Visualize the dataset
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(18, 6))
axes = [xmin, xmax, xmin, xmax]
ax1.set_title("Total", fontsize=24)
plot_dataset(X, y, ax1, axes)
ax2.set_title("Train", fontsize=24)
plot_dataset(X_train, y_train, ax2, axes, marker='s', size=80)
ax3.set_title("Test", fontsize=22)
plot_dataset(X_test, y_test, ax3, axes, marker='^', size=100)
plt.rcParams['font.size'] = 15
plt.tight_layout()
plt.show()
from sklearn.svm import SVC
param_grid = {
"gamma": [0.001, 0.005, 0.01, 0.1, 0.5, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 5.0, 10.0],
"C": [1, 2, 4, 6, 8, 10, 100, 1000],
}
gs = GridSearchCV(
estimator=SVC(kernel='rbf'),
param_grid=param_grid,
scoring='balanced_accuracy',
n_jobs=1,
refit=True,
cv=StratifiedKFold(n_splits=2, shuffle=True, random_state=seed),
)
gs.fit(X_train, y_train)
print('Best grid search parameters:', gs.best_params_)
print('Best training score:', gs.best_score_)
clf = gs.best_estimator_
y_pred = clf.predict(X_train)
acc_tr = metrics.balanced_accuracy_score(y_true=y_train, y_pred=y_pred)
mcc_tr = metrics.matthews_corrcoef(y_true=y_train, y_pred=y_pred)
y_pred = clf.predict(X_test)
acc_te = metrics.balanced_accuracy_score(y_true=y_test, y_pred=y_pred)
mcc_te = metrics.matthews_corrcoef(y_true=y_test, y_pred=y_pred)
print()
print(f"Scores ACC-MCC (train - test): {acc_tr:.2f} {mcc_tr:.2f} {acc_te:.2f} {mcc_te:.2f}")
print()
t0 = time.perf_counter()
fig, ax = plt.subplots(1, 1, figsize=(6, 5))
N = 10
x0s = np.linspace(xmin, xmax, N)
x1s = np.linspace(xmin, xmax, N)
x0, x1 = np.meshgrid(x0s, x1s)
XX = np.c_[x0.ravel(), x1.ravel()]
y_pred = clf.decision_function(XX).reshape(x0.shape)
ax.contourf(x0, x1, y_pred, cmap=plt.cm.RdBu, alpha=1.0)
ax.scatter(X[:, 0], X[:, 1], s=80, c=y,
marker='s', cmap=plt.cm.Paired_r, edgecolors="k")
plt.tight_layout()
plt.show()
t1 = time.perf_counter()
print( 'Timing info:', time.strftime("%Hh%Mm%Ss", time.gmtime(t1-t0)) )
#####################################################
# Wrapper for the quantum kitchen sinks classifier
#####################################################
def clf_QKS(fm, X_train, y_train, X_test, y_test, n_episodes, stddev):
""" """
n_features = len(X_train[0])
qks = QuantumKitchenSinks(
n_features, fm,
n_episodes=n_episodes, stddev=stddev, sampling='normal',
seed=seed
)
emb_tr = qks.embedding(X_train)
clf = LogisticRegression(random_state=seed, max_iter=1000).fit(emb_tr, y_train)
y_pred = clf.predict(emb_tr)
acc_tr = metrics.balanced_accuracy_score(y_true=y_train, y_pred=y_pred)
mcc_tr = metrics.matthews_corrcoef(y_true=y_train, y_pred=y_pred)
emb_te = qks.embedding(X_test)
y_pred = clf.predict(emb_te)
acc_te = metrics.balanced_accuracy_score(y_true=y_test, y_pred=y_pred)
mcc_te = metrics.matthews_corrcoef(y_true=y_test, y_pred=y_pred)
return clf, qks, [acc_tr, mcc_tr, acc_te, mcc_te]
#############################################################
# Feature Map
#############################################################
n_features = len(X[0])
n_qubits = 2
n_layers = 1
n_params = 2
theta = ParameterVector('θ', length=n_params)
fm = QuantumCircuit(n_qubits)
j = 0
for r in range(n_layers):
for i in range(n_qubits):
fm.ry(theta[j%n_params], i); j += 1
for i in range(n_qubits-1):
fm.cx(i, i+1)
print(fm.draw(fold=120, plot_barriers=False))
#############################################################
# QKS
#############################################################
t0 = time.perf_counter()
clf, qks, scores = clf_QKS(fm, X_train, y_train, X_test, y_test, n_episodes=10, stddev=3.0)
print()
print(f"Scores ACC-MCC (train - test): {scores[0]:.2f} {scores[1]:.2f} {scores[2]:.2f} {scores[3]:.2f}")
print()
t1 = time.perf_counter()
print( 'Timing info:', time.strftime("%Hh%Mm%Ss", time.gmtime(t1-t0)) )
t0 = time.perf_counter()
fig, ax = plt.subplots(1, 1, figsize=(6, 5))
N = 10
x0s = np.linspace(xmin, xmax, N)
x1s = np.linspace(xmin, xmax, N)
x0, x1 = np.meshgrid(x0s, x1s)
XX = np.c_[x0.ravel(), x1.ravel()]
emb_X = qks.embedding(XX)
y_pred = clf.decision_function(emb_X).reshape(x0.shape)
ax.contourf(x0, x1, y_pred, cmap=plt.cm.RdBu, alpha=1.0)
ax.scatter(X[:, 0], X[:, 1], s=80, c=y,
marker='s', cmap=plt.cm.Paired_r, edgecolors="k")
plt.tight_layout()
plt.show()
t1 = time.perf_counter()
print( 'Timing info:', time.strftime("%Hh%Mm%Ss", time.gmtime(t1-t0)) )
#############################################################
# Wrapper for the projected quantum kitchen sinks classifier
#############################################################
def clf_pQKS(fm, X_train, y_train, X_test, y_test, n_episodes, stddev, proj='z'):
""" """
n_features = len(X_train[0])
qks = ProjectedQuantumKitchenSinks(
n_features, fm, projection=proj,
n_episodes=n_episodes, stddev=stddev, sampling='normal',
seed=seed, method='statevector'
)
emb_tr = qks.embedding(X_train)
clf = LogisticRegression(random_state=seed, max_iter=1000).fit(emb_tr, y_train)
y_pred = clf.predict(emb_tr)
acc_tr = metrics.balanced_accuracy_score(y_true=y_train, y_pred=y_pred)
mcc_tr = metrics.matthews_corrcoef(y_true=y_train, y_pred=y_pred)
emb_te = qks.embedding(X_test)
y_pred = clf.predict(emb_te)
acc_te = metrics.balanced_accuracy_score(y_true=y_test, y_pred=y_pred)
mcc_te = metrics.matthews_corrcoef(y_true=y_test, y_pred=y_pred)
return clf, qks, [acc_tr, mcc_tr, acc_te, mcc_te]
#############################################################
# Feature Map
#############################################################
n_features = len(X[0])
n_qubits = 2
n_layers = 1
n_params = 2
theta = ParameterVector('θ', length=n_params)
fm = QuantumCircuit(n_qubits)
j = 0
for r in range(n_layers):
for i in range(n_qubits):
fm.ry(theta[j%n_params], i); j += 1
for i in range(n_qubits-1):
fm.cx(i, i+1)
print(fm.draw(fold=120, plot_barriers=False))
#############################################################
# Projected QKS
#############################################################
t0 = time.perf_counter()
clf, qks, scores = clf_pQKS(fm, X_train, y_train, X_test, y_test, n_episodes=10, stddev=3.0, proj='z')
print()
print(f"Scores ACC-MCC (train - test): {scores[0]:.2f} {scores[1]:.2f} {scores[2]:.2f} {scores[3]:.2f}")
print()
t1 = time.perf_counter()
print( 'Timing info:', time.strftime("%Hh%Mm%Ss", time.gmtime(t1-t0)) )
# z 1.00 1.00 0.94 0.90
# xyz_sum 1.00 1.00 0.89 0.81
# xyz 1.00 1.00 0.89 0.81
t0 = time.perf_counter()
fig, ax = plt.subplots(1, 1, figsize=(6, 5))
N = 10
x0s = np.linspace(xmin, xmax, N)
x1s = np.linspace(xmin, xmax, N)
x0, x1 = np.meshgrid(x0s, x1s)
XX = np.c_[x0.ravel(), x1.ravel()]
emb_X = qks.embedding(XX)
y_pred = clf.decision_function(emb_X).reshape(x0.shape)
ax.contourf(x0, x1, y_pred, cmap=plt.cm.RdBu, alpha=1.0)
ax.scatter(X[:, 0], X[:, 1], s=80, c=y,
marker='s', cmap=plt.cm.Paired_r, edgecolors="k")
plt.tight_layout()
plt.show()
t1 = time.perf_counter()
print( 'Timing info:', time.strftime("%Hh%Mm%Ss", time.gmtime(t1-t0)) )
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
from qiskit import *
from qiskit.tools.visualization import plot_bloch_multivector, plot_histogram
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.draw(output='mpl')
simulator = Aer.get_backend('statevector_simulator')
result = execute(qc, backend=simulator).result()
statevector = result.get_statevector()
print(statevector)
plot_bloch_multivector(statevector)
qc.measure([0],[0])
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend=simulator, shots=1024).result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
qc = QuantumCircuit(1, 1)
qc.x(0)
simulator = Aer.get_backend('unitary_simulator')
result = execute(qc, backend=simulator).result()
unitary = result.get_unitary()
print(unitary)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This code creates the gates for all four Bell states
and prints the LaTex code for the circuit
'''
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
import os
import shutil
use_classical_register = False
LaTex_folder_Bell_states = str(os.getcwd())+'/Latex_quantum_gates/Bell_states/'
if not os.path.exists(LaTex_folder_Bell_states):
os.makedirs(LaTex_folder_Bell_states)
else:
shutil.rmtree(LaTex_folder_Bell_states)
os.makedirs(LaTex_folder_Bell_states)
for not0 in [False,True]:
for not1 in [False,True]:
qr = QuantumRegister(2,name='q') # initialise a two-bit quantum register
cr = ClassicalRegister(2, name='c') # initialise a two-bit classical register
if(not use_classical_register):
circuit = QuantumCircuit(qr) # put only quantum registers into circuit
else:
circuit = QuantumCircuit(qr, cr) # put classical and quantum registers into circuit
if(not0):
circuit.x(qr[0])
if(not1):
circuit.x(qr[1])
circuit.h(qr[0]) # add a Hadamard gate to first qubit
circuit.cx(qr[0],qr[1]) # at a CNOT gate to the second qubit depending on the state of the first one
if(use_classical_register):
circuit.measure(qr,cr) # measure the quantum bits
LaTex_code = circuit.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'Bell_state_creator_beta_'
if(not0):
f_name += '1'
else:
f_name += '0'
if(not1):
f_name += '1'
else:
f_name += '0'
f_name += '.tex'
with open(LaTex_folder_Bell_states+f_name, 'w') as f:
f.write(LaTex_code)
|
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/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
from transpile_benchy.metrics.gate_counts import (
DepthMetric,
TotalMetric,
TotalSwaps,
)
from qiskit.circuit.library import iSwapGate
from qiskit.transpiler import CouplingMap
from mirror_gates.pass_managers import Mirage, QiskitLevel3
from mirror_gates.utilities import SubsMetric
from mirror_gates.logging import transpile_benchy_logger
# N = 4
# coupling_map = CouplingMap.from_line(N)
coupling_map = CouplingMap.from_heavy_hex(5)
# coupling_map = CouplingMap.from_grid(6, 6)
from transpile_benchy.library import CircuitLibrary
library = CircuitLibrary.from_txt("../../../circuits/medium_circuits.txt")
# library = CircuitLibrary.from_txt("../../circuits/debug.txt")
# XXX set consolidate to False
# this is allowed only because my pass manager will preserve consolidation
# see post_stage, I call fastconsolidate manually
# NOTE: use TotalSwaps to verify baselines have > 0 swaps
# otherwise, there is no room for improvement.
# we can include these if we want to show our methods will still work
# but somewhat trivial since we just append VF2Layout
metrics = [
DepthMetric(consolidate=False),
TotalMetric(consolidate=False),
TotalSwaps(consolidate=False),
SubsMetric(),
]
transpilers = [
# QiskitLevel3(coupling_map, cx_basis=True),
# Mirage(coupling_map, cx_basis=True, parallel=0),
QiskitLevel3(coupling_map),
Mirage(coupling_map, logger=transpile_benchy_logger),
]
from transpile_benchy.benchmark import Benchmark
benchmark = Benchmark(
transpilers=transpilers,
circuit_library=library,
metrics=metrics,
logger=transpile_benchy_logger,
num_runs=5,
)
benchmark.run()
# print(benchmark)
print(benchmark)
benchmark.summary_statistics(transpilers[0], transpilers[1])
from transpile_benchy.render import plot_benchmark
plot_benchmark(benchmark, save=1, legend_show=1, filename="hex", color_override=[0, 3])
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the RemoveBarriers pass"""
import unittest
from qiskit.transpiler.passes import RemoveBarriers
from qiskit.converters import circuit_to_dag
from qiskit import QuantumCircuit
from qiskit.test import QiskitTestCase
class TestMergeAdjacentBarriers(QiskitTestCase):
"""Test the MergeAdjacentBarriers pass"""
def test_remove_barriers(self):
"""Remove all barriers"""
circuit = QuantumCircuit(2)
circuit.barrier()
circuit.barrier()
pass_ = RemoveBarriers()
result_dag = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result_dag.size(), 0)
def test_remove_barriers_other_gates(self):
"""Remove all barriers, leave other gates intact"""
circuit = QuantumCircuit(1)
circuit.barrier()
circuit.x(0)
circuit.barrier()
circuit.h(0)
pass_ = RemoveBarriers()
result_dag = pass_.run(circuit_to_dag(circuit))
op_nodes = result_dag.op_nodes()
self.assertEqual(result_dag.size(), 2)
for ii, name in enumerate(["x", "h"]):
self.assertEqual(op_nodes[ii].name, name)
def test_simple_if_else(self):
"""Test that the pass recurses into an if-else."""
pass_ = RemoveBarriers()
base_test = QuantumCircuit(1, 1)
base_test.barrier()
base_test.measure(0, 0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
test = QuantumCircuit(1, 1)
test.if_else(
(test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits
)
expected = QuantumCircuit(1, 1)
expected.if_else(
(expected.clbits[0], True),
base_expected.copy(),
base_expected.copy(),
expected.qubits,
expected.clbits,
)
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that the pass recurses into nested control flow."""
pass_ = RemoveBarriers()
base_test = QuantumCircuit(1, 1)
base_test.barrier()
base_test.measure(0, 0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
body_test = QuantumCircuit(1, 1)
body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits)
body_expected = QuantumCircuit(1, 1)
body_expected.for_loop(
(0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits
)
test = QuantumCircuit(1, 1)
test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits)
expected = QuantumCircuit(1, 1)
expected.while_loop(
(expected.clbits[0], True), body_expected, expected.qubits, expected.clbits
)
self.assertEqual(pass_(test), expected)
if __name__ == "__main__":
unittest.main()
|
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/GabrielPontolillo/QiskitPBT
|
GabrielPontolillo
|
import random
from qiskit import QuantumCircuit
from QiskitPBT.case_studies.deutsch_jozsa.deutsch_jozsa import deutsch_jozsa_circ
from QiskitPBT.case_studies.deutsch_jozsa.dj_helpers import BalancedOracleInputGenerator, vmerge
from QiskitPBT.property import Property
class DeutschJozsaVMergeTwoBalancedOracles(Property):
# specify the inputs that are to be generated
def get_input_generators(self):
return [BalancedOracleInputGenerator(2, 5), BalancedOracleInputGenerator(1, 5)]
# specify the preconditions for the test
def preconditions(self, oracle1, oracle2):
return True
# specify the operations to be performed on the input
def operations(self, oracle1: QuantumCircuit, oracle2: QuantumCircuit):
circ = deutsch_jozsa_circ(vmerge(oracle1, oracle2))
# if oracle is constant this should be all 0
baseline = QuantumCircuit(circ.num_qubits - 1, circ.num_qubits - 1)
self.statistical_analysis.assert_different(self, list(range(circ.num_qubits - 1)), circ, list(range(oracle1.num_qubits - 1)), baseline, basis=["z"])
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
import cirq
import numpy as np
from qiskit import QuantumCircuit, execute, Aer
import seaborn as sns
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (15,10)
q0, q1, q2 = [cirq.LineQubit(i) for i in range(3)]
circuit = cirq.Circuit()
#entagling the 2 quibits in different laboratories
#and preparing the qubit to send
circuit.append(cirq.H(q0))
circuit.append(cirq.H(q1))
circuit.append(cirq.CNOT(q1, q2))
#entangling the qubit we want to send to the one in the first laboratory
circuit.append(cirq.CNOT(q0, q1))
circuit.append(cirq.H(q0))
#measurements
circuit.append(cirq.measure(q0, q1))
#last transformations to obtain the qubit information
circuit.append(cirq.CNOT(q1, q2))
circuit.append(cirq.CZ(q0, q2))
#measure of the qubit in the receiving laboratory along z axis
circuit.append(cirq.measure(q2, key = 'Z'))
circuit
#starting simulation
sim = cirq.Simulator()
results = sim.run(circuit, repetitions=100)
sns.histplot(results.measurements['Z'], discrete = True)
100 - np.count_nonzero(results.measurements['Z']), np.count_nonzero(results.measurements['Z'])
#in qiskit the qubits are integrated in the circuit
qc = QuantumCircuit(3, 1)
#entangling
qc.h(0)
qc.h(1)
qc.cx(1, 2)
qc.cx(0, 1)
#setting for measurment
qc.h(0)
qc.measure([0,1], [0,0])
#transformation to obtain qubit sent
qc.cx(1, 2)
qc.cz(0, 2)
qc.measure(2, 0)
print(qc)
#simulation
simulator = Aer.get_backend('qasm_simulator')
job = execute(qc, simulator, shots=100)
res = job.result().get_counts(qc)
plt.bar(res.keys(), res.values())
res
|
https://github.com/pranavdurai10/quantum-gates
|
pranavdurai10
|
'''
///////////////////////////////////////////////////////////////////////////
Code written by Pranav Durai for Quantum Computer on 29.05.2023 @ 22:57:01
Component: Pauli-Z-Gate (bit-flip-gate)
Framework: Qiskit 0.43.0
///////////////////////////////////////////////////////////////////////////
'''
# Import necessary libraries
from qiskit import QuantumCircuit, Aer, execute
# Create a quantum circuit with one qubit
circuit = QuantumCircuit(1)
# Apply Pauli-Z gate to the qubit
circuit.z(0)
# Measure the qubit
circuit.measure_all()
# Simulate the circuit using the local Aer simulator
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=1)
# Get the result
result = job.result()
counts = result.get_counts(circuit)
# Print the measurement outcome
print("Measurement outcome:", list(counts.keys())[0])
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for pass cancelling 2 consecutive CNOTs on the same qubits."""
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Clbit, Qubit
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import CXCancellation
from qiskit.test import QiskitTestCase
class TestCXCancellation(QiskitTestCase):
"""Test the CXCancellation pass."""
def test_pass_cx_cancellation(self):
"""Test the cx cancellation pass.
It should cancel consecutive cx pairs on same qubits.
"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[0])
self.assertEqual(out_circuit, expected)
def test_pass_cx_cancellation_intermixed_ops(self):
"""Cancellation shouldn't be affected by the order of ops on different qubits."""
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[1])
self.assertEqual(out_circuit, expected)
def test_pass_cx_cancellation_chained_cx(self):
"""Include a test were not all operations can be cancelled."""
# ┌───┐
# q0_0: ┤ H ├──■─────────■───────
# ├───┤┌─┴─┐ ┌─┴─┐
# q0_1: ┤ H ├┤ X ├──■──┤ X ├─────
# └───┘└───┘┌─┴─┐└───┘
# q0_2: ──────────┤ X ├──■────■──
# └───┘┌─┴─┐┌─┴─┐
# q0_3: ───────────────┤ X ├┤ X ├
# └───┘└───┘
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[2], qr[3])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
# ┌───┐
# q0_0: ┤ H ├──■─────────■──
# ├───┤┌─┴─┐ ┌─┴─┐
# q0_1: ┤ H ├┤ X ├──■──┤ X ├
# └───┘└───┘┌─┴─┐└───┘
# q0_2: ──────────┤ X ├─────
# └───┘
# q0_3: ────────────────────
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[1])
expected.cx(qr[0], qr[1])
expected.cx(qr[1], qr[2])
expected.cx(qr[0], qr[1])
self.assertEqual(out_circuit, expected)
def test_swapped_cx(self):
"""Test that CX isn't cancelled if there are intermediary ops."""
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0])
circuit.swap(qr[1], qr[2])
circuit.cx(qr[1], qr[0])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
self.assertEqual(out_circuit, circuit)
def test_inverted_cx(self):
"""Test that CX order dependence is respected."""
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
self.assertEqual(out_circuit, circuit)
def test_if_else(self):
"""Test that the pass recurses in a simple if-else."""
pass_ = CXCancellation()
inner_test = QuantumCircuit(4, 1)
inner_test.cx(0, 1)
inner_test.cx(0, 1)
inner_test.cx(2, 3)
inner_expected = QuantumCircuit(4, 1)
inner_expected.cx(2, 3)
test = QuantumCircuit(4, 1)
test.h(0)
test.measure(0, 0)
test.if_else((0, True), inner_test.copy(), inner_test.copy(), range(4), [0])
expected = QuantumCircuit(4, 1)
expected.h(0)
expected.measure(0, 0)
expected.if_else((0, True), inner_expected, inner_expected, range(4), [0])
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that collection recurses into nested control flow."""
pass_ = CXCancellation()
qubits = [Qubit() for _ in [None] * 4]
clbit = Clbit()
inner_test = QuantumCircuit(qubits, [clbit])
inner_test.cx(0, 1)
inner_test.cx(0, 1)
inner_test.cx(2, 3)
inner_expected = QuantumCircuit(qubits, [clbit])
inner_expected.cx(2, 3)
true_body = QuantumCircuit(qubits, [clbit])
true_body.while_loop((clbit, True), inner_test.copy(), [0, 1, 2, 3], [0])
test = QuantumCircuit(qubits, [clbit])
test.for_loop(range(2), None, inner_test.copy(), [0, 1, 2, 3], [0])
test.if_else((clbit, True), true_body, None, [0, 1, 2, 3], [0])
expected_if_body = QuantumCircuit(qubits, [clbit])
expected_if_body.while_loop((clbit, True), inner_expected, [0, 1, 2, 3], [0])
expected = QuantumCircuit(qubits, [clbit])
expected.for_loop(range(2), None, inner_expected, [0, 1, 2, 3], [0])
expected.if_else((clbit, True), expected_if_body, None, [0, 1, 2, 3], [0])
self.assertEqual(pass_(test), expected)
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
#IBMQ.save_account('TOKEN ID needs to be provided')
#Load the account
IBMQ.load_account()
# Providers available
IBMQ.providers()
ibmq_account = IBMQ.load_account()
backends = ibmq_account.backends()
backends
backend = ibmq_account.get_backend('ibmq_qasm_simulator')
backend
backend.name()
backend=ibmq_account.backend.ibmq_qasm_simulator
backend
backend.name()
ibmq_provider = IBMQ.get_provider(hub='ibm-q')
ibmq_provider.backends()
ibmq_provider.backends(filters=lambda b: b.configuration().n_qubits > 5)
ibmq_provider.backends(n_qubits=5, operational=True)
ibmq_provider.backends(simulator=False, operational=True)
ibmq_provider.backends(simulator=True)
least_busy(ibmq_provider.backends())
backend=least_busy(ibmq_provider.backends())
backend.name()
backend.provider()
backend.configuration()
backend.status()
backend.properties()
backend=ibmq_account.backend.ibmq_qasm_simulator
backend.name()
backend.provider()
backend.configuration()
backend.status()
backend.properties()
backend=ibmq_account.backend.ibmq_bogota
backend.jobs()
backend.jobs()[0]
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 42
from qiskit.circuit import Parameter
from qiskit import QuantumCircuit
params1 = [Parameter("input1"), Parameter("weight1")]
qc1 = QuantumCircuit(1)
qc1.h(0)
qc1.ry(params1[0], 0)
qc1.rx(params1[1], 0)
qc1.draw("mpl")
from qiskit.quantum_info import SparsePauliOp
observable1 = SparsePauliOp.from_list([("Y" * qc1.num_qubits, 1)])
from qiskit_machine_learning.neural_networks import EstimatorQNN
estimator_qnn = EstimatorQNN(
circuit=qc1, observables=observable1, input_params=[params1[0]], weight_params=[params1[1]]
)
estimator_qnn
from qiskit.circuit import ParameterVector
inputs2 = ParameterVector("input", 2)
weights2 = ParameterVector("weight", 4)
print(f"input parameters: {[str(item) for item in inputs2.params]}")
print(f"weight parameters: {[str(item) for item in weights2.params]}")
qc2 = QuantumCircuit(2)
qc2.ry(inputs2[0], 0)
qc2.ry(inputs2[1], 1)
qc2.cx(0, 1)
qc2.ry(weights2[0], 0)
qc2.ry(weights2[1], 1)
qc2.cx(0, 1)
qc2.ry(weights2[2], 0)
qc2.ry(weights2[3], 1)
qc2.draw(output="mpl")
from qiskit_machine_learning.neural_networks import SamplerQNN
sampler_qnn = SamplerQNN(circuit=qc2, input_params=inputs2, weight_params=weights2)
sampler_qnn
estimator_qnn_input = algorithm_globals.random.random(estimator_qnn.num_inputs)
estimator_qnn_weights = algorithm_globals.random.random(estimator_qnn.num_weights)
print(
f"Number of input features for EstimatorQNN: {estimator_qnn.num_inputs} \nInput: {estimator_qnn_input}"
)
print(
f"Number of trainable weights for EstimatorQNN: {estimator_qnn.num_weights} \nWeights: {estimator_qnn_weights}"
)
sampler_qnn_input = algorithm_globals.random.random(sampler_qnn.num_inputs)
sampler_qnn_weights = algorithm_globals.random.random(sampler_qnn.num_weights)
print(
f"Number of input features for SamplerQNN: {sampler_qnn.num_inputs} \nInput: {sampler_qnn_input}"
)
print(
f"Number of trainable weights for SamplerQNN: {sampler_qnn.num_weights} \nWeights: {sampler_qnn_weights}"
)
estimator_qnn_forward = estimator_qnn.forward(estimator_qnn_input, estimator_qnn_weights)
print(
f"Forward pass result for EstimatorQNN: {estimator_qnn_forward}. \nShape: {estimator_qnn_forward.shape}"
)
sampler_qnn_forward = sampler_qnn.forward(sampler_qnn_input, sampler_qnn_weights)
print(
f"Forward pass result for SamplerQNN: {sampler_qnn_forward}. \nShape: {sampler_qnn_forward.shape}"
)
estimator_qnn_forward_batched = estimator_qnn.forward(
[estimator_qnn_input, estimator_qnn_input], estimator_qnn_weights
)
print(
f"Forward pass result for EstimatorQNN: {estimator_qnn_forward_batched}. \nShape: {estimator_qnn_forward_batched.shape}"
)
sampler_qnn_forward_batched = sampler_qnn.forward(
[sampler_qnn_input, sampler_qnn_input], sampler_qnn_weights
)
print(
f"Forward pass result for SamplerQNN: {sampler_qnn_forward_batched}. \nShape: {sampler_qnn_forward_batched.shape}"
)
estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward(
estimator_qnn_input, estimator_qnn_weights
)
print(
f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad}"
)
print(
f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}"
)
sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward(
sampler_qnn_input, sampler_qnn_weights
)
print(
f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad}"
)
print(
f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}"
)
estimator_qnn.input_gradients = True
sampler_qnn.input_gradients = True
estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward(
estimator_qnn_input, estimator_qnn_weights
)
print(
f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad.shape}"
)
print(
f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}"
)
sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward(
sampler_qnn_input, sampler_qnn_weights
)
print(
f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad.shape}"
)
print(
f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}"
)
observable2 = SparsePauliOp.from_list([("Z" * qc1.num_qubits, 1)])
estimator_qnn2 = EstimatorQNN(
circuit=qc1,
observables=[observable1, observable2],
input_params=[params1[0]],
weight_params=[params1[1]],
)
estimator_qnn_forward2 = estimator_qnn2.forward(estimator_qnn_input, estimator_qnn_weights)
estimator_qnn_input_grad2, estimator_qnn_weight_grad2 = estimator_qnn2.backward(
estimator_qnn_input, estimator_qnn_weights
)
print(f"Forward output for EstimatorQNN1: {estimator_qnn_forward.shape}")
print(f"Forward output for EstimatorQNN2: {estimator_qnn_forward2.shape}")
print(f"Backward output for EstimatorQNN1: {estimator_qnn_weight_grad.shape}")
print(f"Backward output for EstimatorQNN2: {estimator_qnn_weight_grad2.shape}")
parity = lambda x: "{:b}".format(x).count("1") % 2
output_shape = 2 # parity = 0, 1
sampler_qnn2 = SamplerQNN(
circuit=qc2,
input_params=inputs2,
weight_params=weights2,
interpret=parity,
output_shape=output_shape,
)
sampler_qnn_forward2 = sampler_qnn2.forward(sampler_qnn_input, sampler_qnn_weights)
sampler_qnn_input_grad2, sampler_qnn_weight_grad2 = sampler_qnn2.backward(
sampler_qnn_input, sampler_qnn_weights
)
print(f"Forward output for SamplerQNN1: {sampler_qnn_forward.shape}")
print(f"Forward output for SamplerQNN2: {sampler_qnn_forward2.shape}")
print(f"Backward output for SamplerQNN1: {sampler_qnn_weight_grad.shape}")
print(f"Backward output for SamplerQNN2: {sampler_qnn_weight_grad2.shape}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
#
# OUR SOLUTION
#
# initial condition:
# Asja will start with one euro,
# and so, we assume that the probability of having head is 1 at the beginning.
prob_head = 1
prob_tail = 0
#
# first coin-flip
#
# the new probability of head is calculated by using the first row of table
new_prob_head = prob_head * 0.6 + prob_tail * 0.3
# the new probability of tail is calculated by using the second row of the table
new_prob_tail = prob_head * 0.4 + prob_tail * 0.7
# update the probabilities for the second round
prob_head = new_prob_head
prob_tail = new_prob_tail
#
# second coin-flip
#
# we do the same calculations
new_prob_head = prob_head * 0.6 + prob_tail * 0.3
new_prob_tail = prob_head * 0.4 + prob_tail * 0.7
prob_head = new_prob_head
prob_tail = new_prob_tail
#
# third coin-flip
#
# we do the same calculations
new_prob_head = prob_head * 0.6 + prob_tail * 0.3
new_prob_tail = prob_head * 0.4 + prob_tail * 0.7
prob_head = new_prob_head
prob_tail = new_prob_tail
# print prob_head and prob_tail
print("the probability of getting head after 3 coin tosses is",prob_head)
print("the probability of getting tail after 3 coin tosses is",prob_tail)
#
# your solution is here
#
#
# We copy and paste the previous code
#
# initial condition:
# Asja will start with one euro,
# and so, we assume that the probability of having head is 1 at the beginning.
prob_head = 1
prob_tail = 0
number_of_iterations = 10
for i in range(number_of_iterations):
# the new probability of head is calculated by using the first row of table
new_prob_head = prob_head * 0.6 + prob_tail * 0.3
# the new probability of tail is calculated by using the second row of table
new_prob_tail = prob_head * 0.4 + prob_tail * 0.7
# update the probabilities
prob_head = new_prob_head
prob_tail = new_prob_tail
# print prob_head and prob_tail
print("the probability of getting head after",number_of_iterations,"coin tosses is",prob_head)
print("the probability of getting tail after",number_of_iterations,"coin tosses is",prob_tail)
#
# your solution is here
#
# define iterations as a list
iterations = [20,30,50]
for iteration in iterations:
# initial probabilites
prob_head = 1
prob_tail = 0
print("the number of iterations is",iteration)
for i in range(iteration):
# the new probability of head is calculated by using the first row of table
new_prob_head = prob_head * 0.6 + prob_tail * 0.3
# the new probability of tail is calculated by using the second row of table
new_prob_tail = prob_head * 0.4 + prob_tail * 0.7
# update the probabilities
prob_head = new_prob_head
prob_tail = new_prob_tail
# print prob_head and prob_tail
print("the probability of getting head after",iteration,"coin tosses is",prob_head)
print("the probability of getting tail after",iteration,"coin tosses is",prob_tail)
print()
#
# your solution is here
#
# define iterations as a list
iterations = [20,30,50]
# define initial probability pairs as a double list
initial_probabilities =[
[1/2,1/2],
[0,1]
]
for initial_probability_pair in initial_probabilities:
print("probability of head is",initial_probability_pair[0])
print("probability of tail is",initial_probability_pair[1])
print()
for iteration in iterations:
# initial probabilites
[prob_head,prob_tail] = initial_probability_pair
print("the number of iterations is",iteration)
for i in range(iteration):
# the new probability of head is calculated by using the first row of table
new_prob_head = prob_head * 0.6 + prob_tail * 0.3
# the new probability of tail is calculated by using the second row of table
new_prob_tail = prob_head * 0.4 + prob_tail * 0.7
# update the probabilities
prob_head = new_prob_head
prob_tail = new_prob_tail
# print prob_head and prob_tail
print("the probability of getting head after",iteration,"coin tosses is",prob_head)
print("the probability of getting tail after",iteration,"coin tosses is",prob_tail)
print()
print()
#
# your solution is here
#
#
# your solution is here
#
#
# your solution is here
#
#
# your solution is here
#
|
https://github.com/jacobwatkins1/rodeo-algorithm
|
jacobwatkins1
|
# Import statements
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit import Parameter, Gate
import matplotlib.pyplot as plt
#from qiskit.opflow import I, X, Y, Z, PauliOp, MatrixEvolution, MatrixOp
#from qiskit.quantum_info import Operator
def zsum(t: Parameter, nqubits, coeffs):
""" Creates time evolution operator for non-interacting qubits. Default is Z.
"""
circ = QuantumCircuit(nqubits)
for q in range(nqubits):
circ.rz(2 * t*coeffs[q], q)
return circ.to_gate(label = r'$\otimes R_z$')
def rodeo_cycle(U, t:Parameter, targ:Parameter, sysqubits:int, coeffs):
"""Prepares a unitary quantum gate for a single cycle of the rodeo algorithm
without measurements. Contains the parameters t and targ.
"""
# Prepare registers
aux = QuantumRegister(1,'a')
sys = QuantumRegister(sysqubits, 's')
circuit = QuantumCircuit(aux, sys)
# Add Hadamard test gates
circuit.h(aux)
circuit.append(U(t, sysqubits, coeffs).control(1), range(1+sysqubits))
circuit.p(targ * t,aux)
circuit.h(aux)
return circuit.to_gate(label=r'$RA_{cyc}$')
def extract_rodeo_success(probs):
"""Given a dictionary of distributions, extracts the values of the distributions at zero counts"""
zero_probs = len(probs)*[0]
for i, dist in enumerate(probs):
try:
zero_probs[i] = dist[0]
except Exception:
pass
return zero_probs
# General parameters
cycles = 6
sys_size = 3
# Circuit parameters
targ = Parameter(r'$E_\odot$')
t = [Parameter(fr'$t_{i}$') for i in range(cycles)]
# Hamiltonian parameters
ham_params = [1]*sys_size
# Create registers and initialize circuit
cbits = ClassicalRegister(cycles, 'c')
aux = QuantumRegister(1, 'a')
sys = QuantumRegister(sys_size, 's')
circ = QuantumCircuit(cbits, aux, sys)
# State prep
circ.h(sys)
# Iteratively construct full rodeo circuit
for cyc in range(cycles):
circ.append(rodeo_cycle(zsum, t[cyc], targ, sys_size, ham_params), range(1 + sys_size))
circ.measure(aux, cbits[cyc])
circ.draw(output= 'mpl')
# Import noise model
from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,
pauli_error, depolarizing_error, thermal_relaxation_error)
from qiskit_ibm_runtime import Sampler, QiskitRuntimeService, Session, Options
# Construct Sampler
service = QiskitRuntimeService(channel="ibm_quantum")
backend = "ibmq_qasm_simulator"
session = Session(service = service, backend = backend)
# Enumerate scan energies
energymin = -5
energymax = 5
stepsize = .1
targetenergies = np.linspace(energymin, energymax, int((energymax-energymin)/stepsize))
targetenergynum = len(targetenergies)
print("Number of target energies:", targetenergynum)
# Energy window, which should to be slightly larger than stepsize in scan
# Is inverse of sigma parameter
gamma = 10 * stepsize
# Amount of "scrambling" of t per target energy. The more random the t the better.
timeresamples = 10 # Resampling of times for given target energy
shots_per_same_time = 100
# Package parameters into runs of rodeo circuit
params = []
for i, energy in enumerate(targetenergies):
for j in range(timeresamples):
tsamples = (1/gamma * np.random.randn(cycles)).tolist() # Choose random t samples
params = params + [[targetenergies[i]] + tsamples] # Append parameters to params list
runs = len(params)
print("Parameter list generated! Number of unique circuits:", runs)
# List of noise model parameters
depolarize_probs = [0.0, 0.01, 0.02, 0.03, 0.04, 0.05]
data = []
for p in depolarize_probs:
# Initialize noise model
noise_model = NoiseModel()
error = depolarizing_error(p, 1)
noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3'])
options = Options()
options.simulator = {"noise_model": noise_model}
sampler = Sampler(session=session, options = options)
# Execute circuit with bound parameters
print("Executing with noise parameter ", p)
job = sampler.run([circ]*runs, params, shots = shots_per_same_time)
result = job.result()
probs = result.quasi_dists
allzeroprob = extract_rodeo_success(probs)
allzeroprob = np.array(allzeroprob).reshape((targetenergynum, timeresamples)).sum(axis=1)/timeresamples
data += [allzeroprob]
print("Data acquired!")
# Plot results
for i, p in enumerate(depolarize_probs):
plt.plot(targetenergies, data[i], linestyle = 'None', marker = 'o')
plt.plot([-3,-1,1,3],[.125,.375,.375,.125],linestyle = 'None', marker = 'x')
plt.ylabel("Normalized counts")
plt.xlabel(r"Energy ($\hbar = 1$)")
plt.legend([0.0, 0.01, 0.02, 0.03, 0.04, 0.05, "Exact"])
plt.title("Depolarization Noise on Rodeo Algorithm")
fig = plt.gcf()
plt.show()
fig.savefig("RodeoScanDepolarization.png")
noise_model = NoiseModel()
error = depolarizing_error(p, 1)
noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3'])
sampler.options.simulator = {"noise_model": noise_model}
sampler.options.optimization_level = 2
sampler.options.optimization_level
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
%%capture
%pip install qiskit
%pip install qiskit_ibm_provider
%pip install qiskit-aer
# Importing standard Qiskit libraries
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QuantumCircuit, transpile, Aer
from qiskit_ibm_provider import IBMProvider
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.circuit.library import C3XGate
# Importing matplotlib
import matplotlib.pyplot as plt
# Importing Numpy, Cmath and math
import numpy as np
import os, math, cmath
from numpy import pi
# Other imports
from IPython.display import display, Math, Latex
# Specify the path to your env file
env_file_path = 'config.env'
# Load environment variables from the file
os.environ.update(line.strip().split('=', 1) for line in open(env_file_path) if '=' in line and not line.startswith('#'))
# Load IBM Provider API KEY
IBMP_API_KEY = os.environ.get('IBMP_API_KEY')
# Loading your IBM Quantum account(s)
IBMProvider.save_account(IBMP_API_KEY, overwrite=True)
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
qc_b1 = QuantumCircuit(2, 2)
qc_b1.h(0)
qc_b1.cx(0, 1)
qc_b1.draw(output='mpl', style="iqp")
sv = backend.run(qc_b1).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^+\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.x(0)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.z(0)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.x(1)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.x(0)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.x(0)
qc_b4.h(0)
qc_b4.x(1)
qc_b4.cx(0, 1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.h(0)
qc_b4.cx(0, 1)
qc_b4.x(0)
qc_b4.z(1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
def sv_latex_from_qc(qc, backend):
sv = backend.run(qc).result().get_statevector()
return sv.draw(output='latex')
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(3)
sv_latex_from_qc(qc_ej2, backend)
def circuit_adder (num):
if num<1 or num>8:
raise ValueError("Out of range") ## El enunciado limita el sumador a los valores entre 1 y 8. Quitar esta restricción sería directo.
# Definición del circuito base que vamos a construir
qreg_q = QuantumRegister(4, 'q')
creg_c = ClassicalRegister(1, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
qbit_position = 0
for element in reversed(np.binary_repr(num)):
if (element=='1'):
circuit.barrier()
match qbit_position:
case 0: # +1
circuit.append(C3XGate(), [qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3]])
circuit.ccx(qreg_q[0], qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
circuit.x(qreg_q[0])
case 1: # +2
circuit.ccx(qreg_q[1], qreg_q[2], qreg_q[3])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.x(qreg_q[1])
case 2: # +4
circuit.cx(qreg_q[2], qreg_q[3])
circuit.x(qreg_q[2])
case 3: # +8
circuit.x(qreg_q[3])
qbit_position+=1
return circuit
add_3 = circuit_adder(3)
add_3.draw(output='mpl', style="iqp")
qc_test_2 = QuantumCircuit(4, 4)
qc_test_2.x(1)
qc_test_2_plus_3 = qc_test_2.compose(add_3)
qc_test_2_plus_3.draw(output='mpl', style="iqp")
sv_latex_from_qc(qc_test_2_plus_3, backend)
qc_test_7 = QuantumCircuit(4, 4)
qc_test_7.x(0)
qc_test_7.x(1)
qc_test_7.x(2)
qc_test_7_plus_8 = qc_test_7.compose(circuit_adder(8))
sv_latex_from_qc(qc_test_7_plus_8, backend)
#qc_test_7_plus_8.draw()
theta = 6.544985
phi = 2.338741
lmbda = 0
alice_1 = 0
alice_2 = 1
bob_1 = 2
qr_alice = QuantumRegister(2, 'Alice')
qr_bob = QuantumRegister(1, 'Bob')
cr = ClassicalRegister(3, 'c')
qc_ej3 = QuantumCircuit(qr_alice, qr_bob, cr)
qc_ej3.barrier(label='1')
qc_ej3.u(theta, phi, lmbda, alice_1);
qc_ej3.barrier(label='2')
qc_ej3.h(alice_2)
qc_ej3.cx(alice_2, bob_1);
qc_ej3.barrier(label='3')
qc_ej3.cx(alice_1, alice_2)
qc_ej3.h(alice_1);
qc_ej3.barrier(label='4')
qc_ej3.measure([alice_1, alice_2], [alice_1, alice_2]);
qc_ej3.barrier(label='5')
qc_ej3.x(bob_1).c_if(alice_2, 1)
qc_ej3.z(bob_1).c_if(alice_1, 1)
qc_ej3.measure(bob_1, bob_1);
qc_ej3.draw(output='mpl', style="iqp")
result = backend.run(qc_ej3, shots=1024).result()
counts = result.get_counts()
plot_histogram(counts)
sv_0 = np.array([1, 0])
sv_1 = np.array([0, 1])
def find_symbolic_representation(value, symbolic_constants={1/np.sqrt(2): '1/√2'}, tolerance=1e-10):
"""
Check if the given numerical value corresponds to a symbolic constant within a specified tolerance.
Parameters:
- value (float): The numerical value to check.
- symbolic_constants (dict): A dictionary mapping numerical values to their symbolic representations.
Defaults to {1/np.sqrt(2): '1/√2'}.
- tolerance (float): Tolerance for comparing values with symbolic constants. Defaults to 1e-10.
Returns:
str or float: If a match is found, returns the symbolic representation as a string
(prefixed with '-' if the value is negative); otherwise, returns the original value.
"""
for constant, symbol in symbolic_constants.items():
if np.isclose(abs(value), constant, atol=tolerance):
return symbol if value >= 0 else '-' + symbol
return value
def array_to_dirac_notation(array, tolerance=1e-10):
"""
Convert a complex-valued array representing a quantum state in superposition
to Dirac notation.
Parameters:
- array (numpy.ndarray): The complex-valued array representing
the quantum state in superposition.
- tolerance (float): Tolerance for considering amplitudes as negligible.
Returns:
str: The Dirac notation representation of the quantum state.
"""
# Ensure the statevector is normalized
array = array / np.linalg.norm(array)
# Get the number of qubits
num_qubits = int(np.log2(len(array)))
# Find indices where amplitude is not negligible
non_zero_indices = np.where(np.abs(array) > tolerance)[0]
# Generate Dirac notation terms
terms = [
(find_symbolic_representation(array[i]), format(i, f"0{num_qubits}b"))
for i in non_zero_indices
]
# Format Dirac notation
dirac_notation = " + ".join([f"{amplitude}|{binary_rep}⟩" for amplitude, binary_rep in terms])
return dirac_notation
def array_to_matrix_representation(array):
"""
Convert a one-dimensional array to a column matrix representation.
Parameters:
- array (numpy.ndarray): The one-dimensional array to be converted.
Returns:
numpy.ndarray: The column matrix representation of the input array.
"""
# Replace symbolic constants with their representations
matrix_representation = np.array([find_symbolic_representation(value) or value for value in array])
# Return the column matrix representation
return matrix_representation.reshape((len(matrix_representation), 1))
def array_to_dirac_and_matrix_latex(array):
"""
Generate LaTeX code for displaying both the matrix representation and Dirac notation
of a quantum state.
Parameters:
- array (numpy.ndarray): The complex-valued array representing the quantum state.
Returns:
Latex: A Latex object containing LaTeX code for displaying both representations.
"""
matrix_representation = array_to_matrix_representation(array)
latex = "Matrix representation\n\\begin{bmatrix}\n" + \
"\\\\\n".join(map(str, matrix_representation.flatten())) + \
"\n\\end{bmatrix}\n"
latex += f'Dirac Notation:\n{array_to_dirac_notation(array)}'
return Latex(latex)
sv_b1 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b2 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) - np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b3 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) + np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b4 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
This module contains the definition of a base class for quantum fourier transforms.
"""
from abc import abstractmethod
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua import Pluggable, AquaError
class QFT(Pluggable):
"""Base class for QFT.
This method should initialize the module and its configuration, and
use an exception if a component of the module is
available.
Args:
configuration (dict): configuration dictionary
"""
@abstractmethod
def __init__(self, *args, **kwargs):
super().__init__()
@classmethod
def init_params(cls, params):
qft_params = params.get(Pluggable.SECTION_KEY_QFT)
kwargs = {k: v for k, v in qft_params.items() if k != 'name'}
return cls(**kwargs)
@abstractmethod
def _build_matrix(self):
raise NotImplementedError
@abstractmethod
def _build_circuit(self, qubits=None, circuit=None, do_swaps=True):
raise NotImplementedError
def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True):
"""Construct the circuit.
Args:
mode (str): 'matrix' or 'circuit'
qubits (QuantumRegister or qubits): register or qubits to build the circuit on.
circuit (QuantumCircuit): circuit for construction.
do_swaps (bool): include the swaps.
Returns:
The matrix or circuit depending on the specified mode.
"""
if mode == 'circuit':
return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps)
elif mode == 'matrix':
return self._build_matrix()
else:
raise AquaError('Unrecognized mode: {}.'.format(mode))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_circuit_layout
from qiskit.tools.monitor import job_monitor
from qiskit.providers.fake_provider import FakeVigoV2
import matplotlib.pyplot as plt
ghz = QuantumCircuit(3, 3)
ghz.h(0)
for idx in range(1,3):
ghz.cx(0,idx)
ghz.measure(range(3), range(3))
backend = FakeVigoV2()
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/JayRGopal/Quantum-Error-Correction
|
JayRGopal
|
!pip install qiskit -q
!pip install qiskit-machine-learning -q
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal, ZZFeatureMap
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.algorithms import VQC
from qiskit_machine_learning.datasets import ad_hoc_data
from matplotlib import pyplot as plt
import numpy as np
!pip install pylatexenc -q
import json
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit import ParameterVector
from qiskit.circuit.library import ZFeatureMap
from qiskit.quantum_info import SparsePauliOp
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier
from qiskit_machine_learning.neural_networks import EstimatorQNN
from sklearn.model_selection import train_test_split
algorithm_globals.random_seed = 12345
seed = 1376
algorithm_globals.random_seed = seed
# Use ad hoc data set for training and test data
feature_dim = 2 # dimension of each data point
training_size = 20
test_size = 10
# training features, training labels, test features, test labels as np.ndarray,
# one hot encoding for labels
training_features, training_labels, test_features, test_labels = ad_hoc_data(
training_size=training_size, test_size=test_size, n=feature_dim, gap=0.3
)
# Visualizing Ad Hoc Data
plt.scatter(np.array(training_features)[:, 0], np.array(training_features)[:, 1],
c=np.argmax(np.array(training_labels), axis=1), cmap='copper')
plt.title("2D Ad Hoc Data")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
# ZZFeatureMap creates a quantum circuit out of the classical data
feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2, entanglement="linear")
print(feature_map.decompose().draw())
# TwoLocal circuit
'''
From Qiskit Documentation:
The two-local circuit is a parameterized circuit consisting of alternating rotation layers
and entanglement layers. The rotation layers are single qubit gates applied on all qubits.
The entanglement layer uses two-qubit gates to entangle the qubits according to a strategy
set using entanglement. Both the rotation and entanglement gates can be specified as string
(e.g. 'ry' or 'cx'), as gate-type (e.g. RYGate or CXGate) or as QuantumCircuit
(e.g. a 1-qubit circuit or 2-qubit circuit).
'''
# We assume that the solution takes the form of the 'ansatz'
ansatz = TwoLocal(feature_map.num_qubits, ["ry", "rz"], "cz", reps=3)
print(ansatz.decompose().draw())
# COBYLA = Constrained Optimization By Linear Approximation optimizer.
# COBYLA assumes the derivative of the objective function isn't known
# VQC = Variational Quantum Classifier
# 1 - Feature Map - Load data into quantum system
# 2 - Ansatz - Variational quantum circuit - a quantum circuit that needs certain parameters (trained via ML)
# 3 - Measure an n (classical) bit output, and convert to a label (e.g. binary)
# 4 - Optimization (may not always be gradient-based). In this case, COBYLA
vqc = VQC(
feature_map=feature_map,
ansatz=ansatz,
optimizer=COBYLA(maxiter=100),
)
vqc.fit(training_features, training_labels)
score = vqc.score(test_features, test_labels)
print(f"Testing accuracy: {score:0.2f}")
# Ad Hoc Data doesn't support feature dims > 3
feature_dim = 3 # dimension of each data point
training_size = 100
test_size = 50
# training features, training labels, test features, test labels as np.ndarray,
# one hot encoding for labels
training_features, training_labels, test_features, test_labels = ad_hoc_data(
training_size=training_size, test_size=test_size, n=feature_dim, gap=0.3
)
feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2, entanglement="linear")
ansatz = TwoLocal(feature_map.num_qubits, ["ry", "rz"], "cz", reps=3)
vqc = VQC(
feature_map=feature_map,
ansatz=ansatz,
optimizer=COBYLA(maxiter=100),
)
vqc.fit(training_features, training_labels)
score = vqc.score(test_features, test_labels)
print(f"Testing accuracy: {score:0.2f}")
def generate_dataset(num_images):
images = []
labels = []
hor_array = np.zeros((6, 8))
ver_array = np.zeros((4, 8))
j = 0
for i in range(0, 7):
if i != 3:
hor_array[j][i] = np.pi / 2
hor_array[j][i + 1] = np.pi / 2
j += 1
j = 0
for i in range(0, 4):
ver_array[j][i] = np.pi / 2
ver_array[j][i + 4] = np.pi / 2
j += 1
for n in range(num_images):
rng = algorithm_globals.random.integers(0, 2)
if rng == 0:
labels.append(-1)
random_image = algorithm_globals.random.integers(0, 6)
images.append(np.array(hor_array[random_image]))
elif rng == 1:
labels.append(1)
random_image = algorithm_globals.random.integers(0, 4)
images.append(np.array(ver_array[random_image]))
# Create noise
for i in range(8):
if images[-1][i] == 0:
images[-1][i] = algorithm_globals.random.uniform(0, np.pi / 4)
return images, labels
images, labels = generate_dataset(50)
train_images, test_images, train_labels, test_labels = train_test_split(
images, labels, test_size=0.3
)
fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []})
for i in range(4):
ax[i // 2, i % 2].imshow(
train_images[i].reshape(2, 4), # Change back to 2 by 4
aspect="equal",
)
plt.subplots_adjust(wspace=0.1, hspace=0.025)
# Steps
# 1 - Feature Map - Load data into quantum system
# 2 - Ansatz - Variational quantum circuit - a quantum circuit that needs certain parameters (trained via ML)
# 3 - Measure an n (classical) bit output, and convert to a label (e.g. binary)
# 4 - Optimization (may not always be gradient-based). In this case, COBYLA
# COBYLA = Constrained Optimization By Linear Approximation optimizer.
# COBYLA assumes the derivative of the objective function isn't known
# We now define a two qubit unitary as defined in [3]
def conv_circuit(params):
target = QuantumCircuit(2)
target.rz(-np.pi / 2, 1)
target.cx(1, 0)
target.rz(params[0], 0)
target.ry(params[1], 1)
target.cx(0, 1)
target.ry(params[2], 1)
target.cx(1, 0)
target.rz(np.pi / 2, 0)
return target
# Let's draw this circuit and see what it looks like
params = ParameterVector("θ", length=3)
circuit = conv_circuit(params)
circuit.draw("mpl")
def conv_layer(num_qubits, param_prefix):
qc = QuantumCircuit(num_qubits, name="Convolutional Layer")
qubits = list(range(num_qubits))
param_index = 0
params = ParameterVector(param_prefix, length=num_qubits * 3)
for q1, q2 in zip(qubits[0::2], qubits[1::2]):
qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2])
qc.barrier()
param_index += 3
for q1, q2 in zip(qubits[1::2], qubits[2::2] + [0]):
qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2])
qc.barrier()
param_index += 3
qc_inst = qc.to_instruction()
qc = QuantumCircuit(num_qubits)
qc.append(qc_inst, qubits)
return qc
circuit = conv_layer(4, "θ")
circuit.decompose().draw("mpl")
def pool_circuit(params):
target = QuantumCircuit(2)
target.rz(-np.pi / 2, 1)
target.cx(1, 0)
target.rz(params[0], 0)
target.ry(params[1], 1)
target.cx(0, 1)
target.ry(params[2], 1)
return target
params = ParameterVector("θ", length=3)
circuit = pool_circuit(params)
circuit.draw("mpl")
def pool_layer(sources, sinks, param_prefix):
num_qubits = len(sources) + len(sinks)
qc = QuantumCircuit(num_qubits, name="Pooling Layer")
param_index = 0
params = ParameterVector(param_prefix, length=num_qubits // 2 * 3)
for source, sink in zip(sources, sinks):
qc = qc.compose(pool_circuit(params[param_index : (param_index + 3)]), [source, sink])
qc.barrier()
param_index += 3
qc_inst = qc.to_instruction()
qc = QuantumCircuit(num_qubits)
qc.append(qc_inst, range(num_qubits))
return qc
sources = [0, 1]
sinks = [2, 3]
circuit = pool_layer(sources, sinks, "θ")
circuit.decompose().draw("mpl")
feature_map = ZFeatureMap(8)
feature_map.decompose().draw("mpl")
feature_map = ZFeatureMap(8)
ansatz = QuantumCircuit(8, name="Ansatz")
# First Convolutional Layer
ansatz.compose(conv_layer(8, "с1"), list(range(8)), inplace=True)
# First Pooling Layer
ansatz.compose(pool_layer([0, 1, 2, 3], [4, 5, 6, 7], "p1"), list(range(8)), inplace=True)
# Second Convolutional Layer
ansatz.compose(conv_layer(4, "c2"), list(range(4, 8)), inplace=True)
# Second Pooling Layer
ansatz.compose(pool_layer([0, 1], [2, 3], "p2"), list(range(4, 8)), inplace=True)
# Third Convolutional Layer
ansatz.compose(conv_layer(2, "c3"), list(range(6, 8)), inplace=True)
# Third Pooling Layer
ansatz.compose(pool_layer([0], [1], "p3"), list(range(6, 8)), inplace=True)
# Combining the feature map and ansatz
circuit = QuantumCircuit(8)
circuit.compose(feature_map, range(8), inplace=True)
circuit.compose(ansatz, range(8), inplace=True)
observable = SparsePauliOp.from_list([("Z" + "I" * 7, 1)])
# we decompose the circuit for the QNN to avoid additional data copying
qnn = EstimatorQNN(
circuit=circuit.decompose(),
observables=observable,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
)
circuit.draw("mpl")
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
from google.colab import drive
drive.mount('/content/drive', force_remount=True)
!cp '/content/drive/MyDrive/Quantum Computing/11_qcnn_initial_point.json' ./
with open("11_qcnn_initial_point.json", "r") as f:
initial_point = json.load(f)
classifier = NeuralNetworkClassifier(
qnn,
optimizer=COBYLA(maxiter=200), # Set max iterations here
callback=callback_graph,
initial_point=initial_point,
)
x = np.asarray(train_images)
y = np.asarray(train_labels)
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
classifier.fit(x, y)
# score classifier
print(f"Accuracy from the train data : {np.round(100 * classifier.score(x, y), 2)}%")
y_predict = classifier.predict(test_images)
x = np.asarray(test_images)
y = np.asarray(test_labels)
print(f"Accuracy from the test data : {np.round(100 * classifier.score(x, y), 2)}%")
# Let's see some examples in our dataset
fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []})
for i in range(0, 4):
ax[i // 2, i % 2].imshow(test_images[i].reshape(2, 4), aspect="equal")
if y_predict[i] == -1:
ax[i // 2, i % 2].set_title("The QCNN predicts this is a Horizontal Line")
if y_predict[i] == +1:
ax[i // 2, i % 2].set_title("The QCNN predicts this is a Vertical Line")
plt.subplots_adjust(wspace=0.1, hspace=0.5)
figure, axes = plt.subplots()
draw1 = plt.Circle((0.5, 0.5), 0.2, color='b')
draw2 = plt.Circle((0.5, 0.5), 0.1, color='r')
axes.set_aspect(1)
axes.add_artist(draw1)
axes.add_artist(draw2)
plt.title('2 Circles')
plt.show()
print('Can be mapped into a 1D space (x^2 + y^2) via a kernel for a simple decision boundary')
|
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))
# Virtual -> physical
# 0 -> 3
# 1 -> 4
# 2 -> 2
my_ghz = transpile(ghz, backend, initial_layout=[3, 4, 2])
plot_circuit_layout(my_ghz, backend)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import random
from qiskit.quantum_info import Statevector
secret = random.randint(0,7) # the owner is randomly picked
secret_string = format(secret, '03b') # format the owner in 3-bit string
oracle = Statevector.from_label(secret_string) # let the oracle know the owner
from qiskit.algorithms import AmplificationProblem
problem = AmplificationProblem(oracle, is_good_state=secret_string)
from qiskit.algorithms import Grover
grover_circuits = []
for iteration in range(1,3):
grover = Grover(iterations=iteration)
circuit = grover.construct_circuit(problem)
circuit.measure_all()
grover_circuits.append(circuit)
# Grover's circuit with 1 iteration
grover_circuits[0].draw()
# Grover's circuit with 2 iterations
grover_circuits[1].draw()
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):
sampler = Sampler()
job = sampler.run(circuits=grover_circuits, shots=1000)
result = job.result()
print(result)
from qiskit.tools.visualization import plot_histogram
# Extract bit string with highest probability from results as the answer
result_dict = result.quasi_dists[1].binary_probabilities()
answer = max(result_dict, key=result_dict.get)
print(f"As you can see, the quantum computer returned '{answer}' as the answer with highest probability.\n"
"And the results with 2 iterations have higher probability than the results with 1 iteration."
)
# Plot the results
plot_histogram(result.quasi_dists, legend=['1 iteration', '2 iterations'])
# Print the results and the correct answer.
print(f"Quantum answer: {answer}")
print(f"Correct answer: {secret_string}")
print('Success!' if answer == secret_string else 'Failure!')
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
X = np.array([[0, 1], [1, 0]])
print("XX^dagger")
print(X.dot(X.T.conj()))
print("X^daggerX")
print(X.T.conj().dot(X))
print("The norm of the state |0> before applying X")
zero_ket = np.array([[1], [0]])
print(np.linalg.norm(zero_ket))
print("The norm of the state after applying X")
print(np.linalg.norm(X.dot(zero_ket)))
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit import BasicAer
from qiskit.tools.visualization import circuit_drawer
np.set_printoptions(precision=3, suppress=True)
backend_statevector = BasicAer.get_backend('statevector_simulator')
q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
circuit.x(q[0])
circuit.x(q[0])
job = execute(circuit, backend_statevector)
print(job.result().get_statevector(circuit))
def mixed_state(pure_state, visibility):
density_matrix = pure_state.dot(pure_state.T.conj())
maximally_mixed_state = np.eye(4)/2**2
return visibility*density_matrix + (1-visibility)*maximally_mixed_state
ϕ = np.array([[1],[0],[0],[1]])/np.sqrt(2)
print("Maximum visibility is a pure state:")
print(mixed_state(ϕ, 1.0))
print("The state is still entangled with visibility 0.8:")
print(mixed_state(ϕ, 0.8))
print("Entanglement is lost by 0.6:")
print(mixed_state(ϕ, 0.6))
print("Barely any coherence remains by 0.2:")
print(mixed_state(ϕ, 0.2))
import matplotlib.pyplot as plt
temperatures = [.5, 5, 2000]
energies = np.linspace(0, 20, 100)
fig, ax = plt.subplots()
for i, T in enumerate(temperatures):
probabilities = np.exp(-energies/T)
Z = probabilities.sum()
probabilities /= Z
ax.plot(energies, probabilities, linewidth=3, label = "$T_" + str(i+1)+"$")
ax.set_xlim(0, 20)
ax.set_ylim(0, 1.2*probabilities.max())
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlabel('Energy')
ax.set_ylabel('Probability')
ax.legend()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
depths = []
for _ in range(100):
depths.append(
transpile(
ghz,
backend,
layout_method='trivial' # Fixed layout mapped in circuit order
).depth()
)
plt.figure(figsize=(8, 6))
plt.hist(depths, align='left', color='#AC557C')
plt.xlabel('Depth', fontsize=14)
plt.ylabel('Counts', fontsize=14);
|
https://github.com/JayRGopal/Quantum-Error-Correction
|
JayRGopal
|
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SEED = 10
SHOTS = 10000
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
# function f costo
def f(theta):
beta = theta[:p]
gamma = theta[p:]
# Anzats
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
return mean
return f
def crear_grafo(cantidad_ciudades):
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
return G, mejor_costo, mejor_camino
def run_QAOA(p,ciudades, grafo):
if grafo == None:
G, mejor_costo, mejor_camino = crear_grafo(ciudades)
print("Mejor Costo")
print(mejor_costo)
print("Mejor Camino")
print(mejor_camino)
print("Bordes del grafo")
print(G.edges())
print("Nodos")
print(G.nodes())
print("Pesos")
labels = nx.get_edge_attributes(G,'weight')
print(labels)
else:
G = grafo
intial_random = []
# beta, mixer Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,np.pi))
# gamma, cost Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
if __name__ == '__main__':
# Run QAOA parametros: profundidad p, numero d ciudades,
run_QAOA(5, 3, None)
|
https://github.com/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# 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.
"""IBM Quantum experiment service."""
import logging
import json
import copy
from typing import Optional, List, Dict, Union, Tuple, Any, Type
from datetime import datetime
from collections import defaultdict
from qiskit.providers.ibmq import accountprovider # pylint: disable=unused-import
from qiskit.providers.exceptions import QiskitBackendNotFoundError
from .constants import (ExperimentShareLevel, ResultQuality,
RESULT_QUALITY_FROM_API, RESULT_QUALITY_TO_API)
from .utils import map_api_error
from .device_component import DeviceComponent
from ..utils.converters import local_to_utc_str, utc_to_local
from ..api.clients.experiment import ExperimentClient
from ..api.exceptions import RequestsApiError
from ..ibmqbackend import IBMQRetiredBackend
from ..exceptions import IBMQApiError
from ..credentials import store_preferences
logger = logging.getLogger(__name__)
class IBMExperimentService:
"""Provides experiment related services.
This class is the main interface to invoke IBM Quantum
experiment service, which allows you to create, delete, update, query, and
retrieve experiments, experiment figures, and analysis results. The
``experiment`` attribute of
:class:`~qiskit.providers.ibmq.accountprovider.AccountProvider` is an
instance of this class, and the main syntax for using the service is
``provider.experiment.<action>``. For example::
from qiskit import IBMQ
provider = IBMQ.load_account()
# Retrieve all experiments.
experiments = provider.experiment.experiments()
# Retrieve experiments with filtering.
experiment_filtered = provider.experiment.experiments(backend_name='ibmq_athens')
# Retrieve a specific experiment using its ID.
experiment = provider.experiment.experiment(EXPERIMENT_ID)
# Upload a new experiment.
new_experiment_id = provider.experiment.create_experiment(
experiment_type="T1",
backend_name="ibmq_athens",
metadata={"qubits": 5}
)
# Update an experiment.
provider.experiment.update_experiment(
experiment_id=EXPERIMENT_ID,
share_level="Group"
)
# Delete an experiment.
provider.experiment.delete_experiment(EXPERIMENT_ID)
Similar syntax applies to analysis results and experiment figures.
"""
_default_preferences = {"auto_save": False}
def __init__(
self,
provider: 'accountprovider.AccountProvider'
) -> None:
"""IBMExperimentService constructor.
Args:
provider: IBM Quantum Experience account provider.
"""
super().__init__()
self._provider = provider
self._api_client = ExperimentClient(provider.credentials)
self._preferences = copy.deepcopy(self._default_preferences)
self._preferences.update(provider.credentials.preferences.get('experiments', {}))
def backends(self) -> List[Dict]:
"""Return a list of backends that can be used for experiments.
Returns:
A list of backends.
"""
return self._api_client.experiment_devices()
def create_experiment(
self,
experiment_type: str,
backend_name: str,
metadata: Optional[Dict] = None,
experiment_id: Optional[str] = None,
parent_id: Optional[str] = None,
job_ids: Optional[List[str]] = None,
tags: Optional[List[str]] = None,
notes: Optional[str] = None,
share_level: Optional[Union[str, ExperimentShareLevel]] = None,
start_datetime: Optional[Union[str, datetime]] = None,
json_encoder: Type[json.JSONEncoder] = json.JSONEncoder,
**kwargs: Any
) -> str:
"""Create a new experiment in the database.
Args:
experiment_type: Experiment type.
backend_name: Name of the backend the experiment ran on.
metadata: Experiment metadata.
experiment_id: Experiment ID. It must be in the ``uuid4`` format.
One will be generated if not supplied.
parent_id: The experiment ID of the parent experiment.
The parent experiment must exist, must be on the same backend as the child,
and an experiment cannot be its own parent.
job_ids: IDs of experiment jobs.
tags: Tags to be associated with the experiment.
notes: Freeform notes about the experiment.
share_level: The level at which the experiment is shared. This determines who can
view the experiment (but not update it). This defaults to "private"
for new experiments. Possible values include:
- private: The experiment is only visible to its owner (default)
- project: The experiment is shared within its project
- group: The experiment is shared within its group
- hub: The experiment is shared within its hub
- public: The experiment is shared publicly regardless of provider
start_datetime: Timestamp when the experiment started, in local time zone.
json_encoder: Custom JSON encoder to use to encode the experiment.
kwargs: Additional experiment attributes that are not supported and will be ignored.
Returns:
Experiment ID.
Raises:
IBMExperimentEntryExists: If the experiment already exits.
IBMQApiError: If the request to the server failed.
"""
# pylint: disable=arguments-differ
if kwargs:
logger.info("Keywords %s are not supported by IBM Quantum experiment service "
"and will be ignored.",
kwargs.keys())
data = {
'type': experiment_type,
'device_name': backend_name,
'hub_id': self._provider.credentials.hub,
'group_id': self._provider.credentials.group,
'project_id': self._provider.credentials.project
}
data.update(self._experiment_data_to_api(metadata=metadata,
experiment_id=experiment_id,
parent_id=parent_id,
job_ids=job_ids,
tags=tags,
notes=notes,
share_level=share_level,
start_dt=start_datetime))
with map_api_error(f"Experiment {experiment_id} already exists."):
response_data = self._api_client.experiment_upload(json.dumps(data, cls=json_encoder))
return response_data['uuid']
def update_experiment(
self,
experiment_id: str,
metadata: Optional[Dict] = None,
job_ids: Optional[List[str]] = None,
notes: Optional[str] = None,
tags: Optional[List[str]] = None,
share_level: Optional[Union[str, ExperimentShareLevel]] = None,
end_datetime: Optional[Union[str, datetime]] = None,
json_encoder: Type[json.JSONEncoder] = json.JSONEncoder,
**kwargs: Any,
) -> None:
"""Update an existing experiment.
Args:
experiment_id: Experiment ID.
metadata: Experiment metadata.
job_ids: IDs of experiment jobs.
notes: Freeform notes about the experiment.
tags: Tags to be associated with the experiment.
share_level: The level at which the experiment is shared. This determines who can
view the experiment (but not update it). This defaults to "private"
for new experiments. Possible values include:
- private: The experiment is only visible to its owner (default)
- project: The experiment is shared within its project
- group: The experiment is shared within its group
- hub: The experiment is shared within its hub
- public: The experiment is shared publicly regardless of provider
end_datetime: Timestamp for when the experiment ended, in local time.
json_encoder: Custom JSON encoder to use to encode the experiment.
kwargs: Additional experiment attributes that are not supported and will be ignored.
Raises:
IBMExperimentEntryNotFound: If the experiment does not exist.
IBMQApiError: If the request to the server failed.
"""
# pylint: disable=arguments-differ
if kwargs:
logger.info("Keywords %s are not supported by IBM Quantum experiment service "
"and will be ignored.",
kwargs.keys())
data = self._experiment_data_to_api(metadata=metadata,
job_ids=job_ids,
tags=tags,
notes=notes,
share_level=share_level,
end_dt=end_datetime)
if not data:
logger.warning("update_experiment() called with nothing to update.")
return
with map_api_error(f"Experiment {experiment_id} not found."):
self._api_client.experiment_update(experiment_id, json.dumps(data, cls=json_encoder))
def _experiment_data_to_api(
self,
metadata: Optional[Dict] = None,
experiment_id: Optional[str] = None,
parent_id: Optional[str] = None,
job_ids: Optional[List[str]] = None,
tags: Optional[List[str]] = None,
notes: Optional[str] = None,
share_level: Optional[Union[str, ExperimentShareLevel]] = None,
start_dt: Optional[Union[str, datetime]] = None,
end_dt: Optional[Union[str, datetime]] = None,
) -> Dict:
"""Convert experiment data to API request data.
Args:
metadata: Experiment metadata.
experiment_id: Experiment ID.
parent_id: Parent experiment ID
job_ids: IDs of experiment jobs.
tags: Tags to be associated with the experiment.
notes: Freeform notes about the experiment.
share_level: The level at which the experiment is shared.
start_dt: Experiment start time.
end_dt: Experiment end time.
Returns:
API request data.
"""
data = {} # type: Dict[str, Any]
if metadata:
data['extra'] = metadata
if experiment_id:
data['uuid'] = experiment_id
if parent_id:
data['parent_experiment_uuid'] = parent_id
if share_level:
if isinstance(share_level, str):
share_level = ExperimentShareLevel(share_level.lower())
data['visibility'] = share_level.value
if tags:
data['tags'] = tags
if job_ids:
data['jobs'] = job_ids
if notes:
data['notes'] = notes
if start_dt:
data['start_time'] = local_to_utc_str(start_dt)
if end_dt:
data['end_time'] = local_to_utc_str(end_dt)
return data
def experiment(
self,
experiment_id: str,
json_decoder: Type[json.JSONDecoder] = json.JSONDecoder
) -> Dict:
"""Retrieve a previously stored experiment.
Args:
experiment_id: Experiment ID.
json_decoder: Custom JSON decoder to use to decode the retrieved experiment.
Returns:
Retrieved experiment data.
Raises:
IBMExperimentEntryNotFound: If the experiment does not exist.
IBMQApiError: If the request to the server failed.
"""
with map_api_error(f"Experiment {experiment_id} not found."):
raw_data = self._api_client.experiment_get(experiment_id)
return self._api_to_experiment_data(json.loads(raw_data, cls=json_decoder))
def experiments(
self,
limit: Optional[int] = 10,
json_decoder: Type[json.JSONDecoder] = json.JSONDecoder,
device_components: Optional[List[Union[str, DeviceComponent]]] = None,
device_components_operator: Optional[str] = None,
experiment_type: Optional[str] = None,
experiment_type_operator: Optional[str] = None,
backend_name: Optional[str] = None,
tags: Optional[List[str]] = None,
tags_operator: Optional[str] = "OR",
start_datetime_after: Optional[datetime] = None,
start_datetime_before: Optional[datetime] = None,
hub: Optional[str] = None,
group: Optional[str] = None,
project: Optional[str] = None,
exclude_public: Optional[bool] = False,
public_only: Optional[bool] = False,
exclude_mine: Optional[bool] = False,
mine_only: Optional[bool] = False,
parent_id: Optional[str] = None,
sort_by: Optional[Union[str, List[str]]] = None,
**filters: Any
) -> List[Dict]:
"""Retrieve all experiments, with optional filtering.
By default, results returned are as inclusive as possible. For example,
if you don't specify any filters, all experiments visible to you
are returned. This includes your own experiments as well as
those shared with you, from all providers you have access to
(not just from the provider you used to invoke this experiment service).
Args:
limit: Number of experiments to retrieve. ``None`` indicates no limit.
json_decoder: Custom JSON decoder to use to decode the retrieved experiments.
device_components: Filter by device components.
device_components_operator: Operator used when filtering by device components.
Valid values are ``None`` and "contains":
* If ``None``, an analysis result's device components must match
exactly for it to be included.
* If "contains" is specified, an analysis result's device components
must contain at least the values specified by the `device_components`
filter.
experiment_type: Experiment type used for filtering.
experiment_type_operator: Operator used when filtering by experiment type.
Valid values are ``None`` and "like":
* If ``None`` is specified, an experiment's type value must
match exactly for it to be included.
* If "like" is specified, an experiment's type value must
contain the value specified by `experiment_type`. For example,
``experiment_type="foo", experiment_type_operator="like"`` will match
both ``foo1`` and ``1foo``.
backend_name: Backend name used for filtering.
tags: Filter by tags assigned to experiments.
tags_operator: Logical operator to use when filtering by job tags. Valid
values are "AND" and "OR":
* If "AND" is specified, then an experiment must have all of the tags
specified in `tags` to be included.
* If "OR" is specified, then an experiment only needs to have any
of the tags specified in `tags` to be included.
start_datetime_after: Filter by the given start timestamp, in local time.
This is used to find experiments whose start date/time is after
(greater than or equal to) this local timestamp.
start_datetime_before: Filter by the given start timestamp, in local time.
This is used to find experiments whose start date/time is before
(less than or equal to) this local timestamp.
hub: Filter by hub.
group: Filter by hub and group. `hub` must also be specified if `group` is.
project: Filter by hub, group, and project. `hub` and `group` must also be
specified if `project` is.
exclude_public: If ``True``, experiments with ``share_level=public``
(that is, experiments visible to all users) will not be returned.
Cannot be ``True`` if `public_only` is ``True``.
public_only: If ``True``, only experiments with ``share_level=public``
(that is, experiments visible to all users) will be returned.
Cannot be ``True`` if `exclude_public` is ``True``.
exclude_mine: If ``True``, experiments where I am the owner will not be returned.
Cannot be ``True`` if `mine_only` is ``True``.
mine_only: If ``True``, only experiments where I am the owner will be returned.
Cannot be ``True`` if `exclude_mine` is ``True``.
parent_id: Filter experiments by this parent experiment ID.
sort_by: Specifies how the output should be sorted. This can be a single sorting
option or a list of options. Each option should contain a sort key
and a direction, separated by a semicolon. Valid sort keys are
"start_datetime" and "experiment_type".
Valid directions are "asc" for ascending or "desc" for descending.
For example, ``sort_by=["experiment_type:asc", "start_datetime:desc"]`` will
return an output list that is first sorted by experiment type in
ascending order, then by start datetime by descending order.
By default, experiments are sorted by ``start_datetime``
descending and ``experiment_id`` ascending.
**filters: Additional filtering keywords that are not supported and will be ignored.
Returns:
A list of experiments. Each experiment is a dictionary containing the
retrieved experiment data.
Raises:
ValueError: If an invalid parameter value is specified.
IBMQApiError: If the request to the server failed.
"""
# pylint: disable=arguments-differ
if filters:
logger.info("Keywords %s are not supported by IBM Quantum experiment service "
"and will be ignored.",
filters.keys())
if limit is not None and (not isinstance(limit, int) or limit <= 0): # type: ignore
raise ValueError(f"{limit} is not a valid `limit`, which has to be a positive integer.")
pgh_text = ['project', 'group', 'hub']
pgh_val = [project, group, hub]
for idx, val in enumerate(pgh_val):
if val is not None and None in pgh_val[idx+1:]:
raise ValueError(f"If {pgh_text[idx]} is specified, "
f"{' and '.join(pgh_text[idx+1:])} must also be specified.")
start_time_filters = []
if start_datetime_after:
st_filter = 'ge:{}'.format(local_to_utc_str(start_datetime_after))
start_time_filters.append(st_filter)
if start_datetime_before:
st_filter = 'le:{}'.format(local_to_utc_str(start_datetime_before))
start_time_filters.append(st_filter)
if exclude_public and public_only:
raise ValueError('exclude_public and public_only cannot both be True')
if exclude_mine and mine_only:
raise ValueError('exclude_mine and mine_only cannot both be True')
converted = self._filtering_to_api(
tags=tags,
tags_operator=tags_operator,
sort_by=sort_by,
sort_map={"start_datetime": "start_time",
"experiment_type": "type"},
device_components=device_components,
device_components_operator=device_components_operator,
item_type=experiment_type,
item_type_operator=experiment_type_operator
)
experiments = []
marker = None
while limit is None or limit > 0:
with map_api_error(f"Request failed."):
response = self._api_client.experiments(
limit=limit,
marker=marker,
backend_name=backend_name,
experiment_type=converted["type"],
start_time=start_time_filters,
device_components=converted["device_components"],
tags=converted["tags"],
hub=hub, group=group, project=project,
exclude_public=exclude_public,
public_only=public_only,
exclude_mine=exclude_mine,
mine_only=mine_only,
parent_id=parent_id,
sort_by=converted["sort_by"])
raw_data = json.loads(response, cls=json_decoder)
marker = raw_data.get('marker')
for exp in raw_data['experiments']:
experiments.append(self._api_to_experiment_data(exp))
if limit:
limit -= len(raw_data['experiments'])
if not marker: # No more experiments to return.
break
return experiments
def _api_to_experiment_data(
self,
raw_data: Dict,
) -> Dict:
"""Convert API response to experiment data.
Args:
raw_data: API response
Returns:
Converted experiment data.
"""
backend_name = raw_data['device_name']
try:
backend = self._provider.get_backend(backend_name)
except QiskitBackendNotFoundError:
backend = IBMQRetiredBackend.from_name(backend_name=backend_name,
provider=self._provider,
credentials=self._provider.credentials,
api=None)
extra_data: Dict[str, Any] = {}
self._convert_dt(raw_data.get('created_at', None), extra_data, 'creation_datetime')
self._convert_dt(raw_data.get('start_time', None), extra_data, 'start_datetime')
self._convert_dt(raw_data.get('end_time', None), extra_data, 'end_datetime')
self._convert_dt(raw_data.get('updated_at', None), extra_data, 'updated_datetime')
out_dict = {
"experiment_type": raw_data['type'],
"backend": backend,
"experiment_id": raw_data['uuid'],
"parent_id": raw_data.get('parent_experiment_uuid', None),
"tags": raw_data.get("tags", None),
"job_ids": raw_data['jobs'],
"share_level": raw_data.get("visibility", None),
"metadata": raw_data.get("extra", None),
"figure_names": raw_data.get("plot_names", None),
"notes": raw_data.get("notes", ""),
"hub": raw_data.get("hub_id", ""),
"group": raw_data.get("group_id", ""),
"project": raw_data.get("project_id", ""),
"owner": raw_data.get("owner", ""),
**extra_data
}
return out_dict
def _convert_dt(
self,
timestamp: Optional[str],
data: Dict,
field_name: str
) -> None:
"""Convert input timestamp.
Args:
timestamp: Timestamp to be converted.
data: Data used to stored the converted timestamp.
field_name: Name used to store the converted timestamp.
"""
if not timestamp:
return
data[field_name] = utc_to_local(timestamp)
def delete_experiment(self, experiment_id: str) -> None:
"""Delete an experiment.
Args:
experiment_id: Experiment ID.
Note:
This method prompts for confirmation and requires a response before proceeding.
Raises:
IBMQApiError: If the request to the server failed.
"""
confirmation = input('\nAre you sure you want to delete the experiment? '
'Results and plots for the experiment will also be deleted. [y/N]: ')
if confirmation not in ('y', 'Y'):
return
try:
self._api_client.experiment_delete(experiment_id)
except RequestsApiError as api_err:
if api_err.status_code == 404:
logger.warning("Experiment %s not found.", experiment_id)
else:
raise IBMQApiError(f"Failed to process the request: {api_err}") from None
def create_analysis_result(
self,
experiment_id: str,
result_data: Dict,
result_type: str,
device_components: Optional[Union[List[Union[str, DeviceComponent]],
str, DeviceComponent]] = None,
tags: Optional[List[str]] = None,
quality: Union[ResultQuality, str] = ResultQuality.UNKNOWN,
verified: bool = False,
result_id: Optional[str] = None,
chisq: Optional[float] = None,
json_encoder: Type[json.JSONEncoder] = json.JSONEncoder,
**kwargs: Any,
) -> str:
"""Create a new analysis result in the database.
Args:
experiment_id: ID of the experiment this result is for.
result_data: Result data to be stored.
result_type: Analysis result type.
device_components: Target device components, such as qubits.
tags: Tags to be associated with the analysis result.
quality: Quality of this analysis.
verified: Whether the result quality has been verified.
result_id: Analysis result ID. It must be in the ``uuid4`` format.
One will be generated if not supplied.
chisq: chi^2 decimal value of the fit.
json_encoder: Custom JSON encoder to use to encode the analysis result.
kwargs: Additional analysis result attributes that are not supported
and will be ignored.
Returns:
Analysis result ID.
Raises:
IBMExperimentEntryExists: If the analysis result already exits.
IBMQApiError: If the request to the server failed.
"""
# pylint: disable=arguments-differ
if kwargs:
logger.info("Keywords %s are not supported by IBM Quantum experiment service "
"and will be ignored.",
kwargs.keys())
components = []
if device_components:
if not isinstance(device_components, list):
device_components = [device_components]
for comp in device_components:
components.append(str(comp))
if isinstance(quality, str):
quality = ResultQuality(quality.upper())
request = self._analysis_result_to_api(
experiment_id=experiment_id,
device_components=components,
data=result_data,
result_type=result_type,
tags=tags,
quality=quality,
verified=verified,
result_id=result_id,
chisq=chisq
)
with map_api_error(f"Analysis result {result_id} already exists."):
response = self._api_client.analysis_result_upload(
json.dumps(request, cls=json_encoder))
return response['uuid']
def update_analysis_result(
self,
result_id: str,
result_data: Optional[Dict] = None,
tags: Optional[List[str]] = None,
quality: Union[ResultQuality, str] = None,
verified: bool = None,
chisq: Optional[float] = None,
json_encoder: Type[json.JSONEncoder] = json.JSONEncoder,
**kwargs: Any,
) -> None:
"""Update an existing analysis result.
Args:
result_id: Analysis result ID.
result_data: Result data to be stored.
quality: Quality of this analysis.
verified: Whether the result quality has been verified.
tags: Tags to be associated with the analysis result.
chisq: chi^2 decimal value of the fit.
json_encoder: Custom JSON encoder to use to encode the analysis result.
kwargs: Additional analysis result attributes that are not supported
and will be ignored.
Raises:
IBMExperimentEntryNotFound: If the analysis result does not exist.
IBMQApiError: If the request to the server failed.
"""
# pylint: disable=arguments-differ
if kwargs:
logger.info("Keywords %s are not supported by IBM Quantum experiment service "
"and will be ignored.",
kwargs.keys())
if isinstance(quality, str):
quality = ResultQuality(quality.upper())
request = self._analysis_result_to_api(data=result_data,
tags=tags,
quality=quality,
verified=verified,
chisq=chisq)
with map_api_error(f"Analysis result {result_id} not found."):
self._api_client.analysis_result_update(
result_id, json.dumps(request, cls=json_encoder))
def _analysis_result_to_api(
self,
experiment_id: Optional[str] = None,
device_components: Optional[List[str]] = None,
data: Optional[Dict] = None,
result_type: Optional[str] = None,
tags: Optional[List[str]] = None,
quality: Optional[ResultQuality] = None,
verified: Optional[bool] = None,
result_id: Optional[str] = None,
chisq: Optional[float] = None,
) -> Dict:
"""Convert analysis result fields to server format.
Args:
experiment_id: ID of the experiment this result is for.
data: Result data to be stored.
result_type: Analysis result type.
device_components: Target device components, such as qubits.
tags: Tags to be associated with the analysis result.
quality: Quality of this analysis.
verified: Whether the result quality has been verified.
result_id: Analysis result ID. It must be in the ``uuid4`` format.
One will be generated if not supplied.
chisq: chi^2 decimal value of the fit.
Returns:
API request data.
"""
out = {} # type: Dict[str, Any]
if experiment_id:
out["experiment_uuid"] = experiment_id
if device_components:
out["device_components"] = device_components
if data:
out["fit"] = data
if result_type:
out["type"] = result_type
if tags:
out["tags"] = tags
if quality:
out["quality"] = RESULT_QUALITY_TO_API[quality]
if verified is not None:
out["verified"] = verified
if result_id:
out["uuid"] = result_id
if chisq:
out["chisq"] = chisq
return out
def analysis_result(
self,
result_id: str,
json_decoder: Type[json.JSONDecoder] = json.JSONDecoder
) -> Dict:
"""Retrieve a previously stored experiment.
Args:
result_id: Analysis result ID.
json_decoder: Custom JSON decoder to use to decode the retrieved analysis result.
Returns:
Retrieved analysis result.
Raises:
IBMExperimentEntryNotFound: If the analysis result does not exist.
IBMQApiError: If the request to the server failed.
"""
with map_api_error(f"Analysis result {result_id} not found."):
raw_data = self._api_client.analysis_result_get(result_id)
return self._api_to_analysis_result(json.loads(raw_data, cls=json_decoder))
def analysis_results(
self,
limit: Optional[int] = 10,
json_decoder: Type[json.JSONDecoder] = json.JSONDecoder,
device_components: Optional[List[Union[str, DeviceComponent]]] = None,
device_components_operator: Optional[str] = None,
experiment_id: Optional[str] = None,
result_type: Optional[str] = None,
result_type_operator: Optional[str] = None,
backend_name: Optional[str] = None,
quality: Optional[Union[List[Union[ResultQuality, str]], ResultQuality, str]] = None,
verified: Optional[bool] = None,
tags: Optional[List[str]] = None,
tags_operator: Optional[str] = "OR",
sort_by: Optional[Union[str, List[str]]] = None,
**filters: Any
) -> List[Dict]:
"""Retrieve all analysis results, with optional filtering.
Args:
limit: Number of analysis results to retrieve.
json_decoder: Custom JSON decoder to use to decode the retrieved analysis results.
device_components: Filter by device components.
device_components_operator: Operator used when filtering by device components.
Valid values are ``None`` and "contains":
* If ``None``, an analysis result's device components must match
exactly for it to be included.
* If "contains" is specified, an analysis result's device components
must contain at least the values specified by the `device_components`
filter.
experiment_id: Experiment ID used for filtering.
result_type: Analysis result type used for filtering.
result_type_operator: Operator used when filtering by result type.
Valid values are ``None`` and "like":
* If ``None`` is specified, an analysis result's type value must
match exactly for it to be included.
* If "like" is specified, an analysis result's type value must
contain the value specified by `result_type`. For example,
``result_type="foo", result_type_operator="like"`` will match
both ``foo1`` and ``1foo``.
backend_name: Backend name used for filtering.
quality: Quality value used for filtering. If a list is given, analysis results
whose quality value is in the list will be included.
verified: Indicates whether this result has been verified..
tags: Filter by tags assigned to analysis results. This can be used
with `tags_operator` for granular filtering.
tags_operator: Logical operator to use when filtering by tags. Valid
values are "AND" and "OR":
* If "AND" is specified, then an analysis result must have all of the tags
specified in `tags` to be included.
* If "OR" is specified, then an analysis result only needs to have any
of the tags specified in `tags` to be included.
sort_by: Specifies how the output should be sorted. This can be a single sorting
option or a list of options. Each option should contain a sort key
and a direction. Valid sort keys are "creation_datetime", "device_components",
and "result_type". Valid directions are "asc" for ascending or "desc" for
descending.
For example, ``sort_by=["result_type: asc", "creation_datetime:desc"]`` will
return an output list that is first sorted by result type in
ascending order, then by creation datetime by descending order.
By default, analysis results are sorted by ``creation_datetime``
descending and ``result_id`` ascending.
**filters: Additional filtering keywords that are not supported and will be ignored.
Returns:
A list of analysis results. Each analysis result is a dictionary
containing the retrieved analysis result.
Raises:
ValueError: If an invalid parameter value is specified.
IBMQApiError: If the request to the server failed.
"""
# pylint: disable=arguments-differ
if filters:
logger.info("Keywords %s are not supported by IBM Quantum experiment service "
"and will be ignored.",
filters.keys())
if limit is not None and (not isinstance(limit, int) or limit <= 0): # type: ignore
raise ValueError(f"{limit} is not a valid `limit`, which has to be a positive integer.")
quality = self._quality_filter_to_api(quality)
converted = self._filtering_to_api(
tags=tags,
tags_operator=tags_operator,
sort_by=sort_by,
sort_map={"creation_datetime": "created_at",
"device_components": "device_components",
"result_type": "type"},
device_components=device_components,
device_components_operator=device_components_operator,
item_type=result_type,
item_type_operator=result_type_operator
)
results = []
marker = None
while limit is None or limit > 0:
with map_api_error("Request failed."):
response = self._api_client.analysis_results(
limit=limit,
marker=marker,
backend_name=backend_name,
device_components=converted["device_components"],
experiment_uuid=experiment_id,
result_type=converted["type"],
quality=quality,
verified=verified,
tags=converted["tags"],
sort_by=converted["sort_by"]
)
raw_data = json.loads(response, cls=json_decoder)
marker = raw_data.get('marker')
for result in raw_data['analysis_results']:
results.append(self._api_to_analysis_result(result))
if limit:
limit -= len(raw_data['analysis_results'])
if not marker: # No more experiments to return.
break
return results
def _quality_filter_to_api(
self,
quality: Optional[Union[List[Union[ResultQuality, str]], ResultQuality, str]] = None,
) -> Optional[Union[str, List[str]]]:
"""Convert quality filter to server format."""
if not quality:
return None
if not isinstance(quality, list):
quality = [quality]
api_quals = []
for qual in quality:
if isinstance(qual, str):
qual = ResultQuality(qual.upper())
api_qual = RESULT_QUALITY_TO_API[qual]
if api_qual not in api_quals:
api_quals.append(api_qual)
if len(api_quals) == 1:
return api_quals[0]
if len(api_quals) == len(ResultQuality):
return None
return "in:" + ",".join(api_quals)
def _filtering_to_api(
self,
tags: Optional[List[str]] = None,
tags_operator: Optional[str] = "OR",
sort_by: Optional[Union[str, List[str]]] = None,
sort_map: Optional[Dict] = None,
device_components: Optional[List[Union[str, DeviceComponent]]] = None,
device_components_operator: Optional[str] = None,
item_type: Optional[str] = None,
item_type_operator: Optional[str] = None,
) -> Dict:
"""Convert filtering inputs to server format.
Args:
tags: Filtering by tags.
tags_operator: Tags operator.
sort_by: Specifies how the output should be sorted.
sort_map: Sort key to API key mapping.
device_components: Filter by device components.
device_components_operator: Device component operator.
item_type: Item type used for filtering.
item_type_operator: Operator used when filtering by type.
Returns:
A dictionary of mapped filters.
Raises:
ValueError: If an input key is invalid.
"""
tags_filter = None
if tags:
if tags_operator.upper() == 'OR':
tags_filter = 'any:' + ','.join(tags)
elif tags_operator.upper() == 'AND':
tags_filter = 'contains:' + ','.join(tags)
else:
raise ValueError('{} is not a valid `tags_operator`. Valid values are '
'"AND" and "OR".'.format(tags_operator))
sort_list = []
if sort_by:
if not isinstance(sort_by, list):
sort_by = [sort_by]
for sorter in sort_by:
key, direction = sorter.split(":")
key = key.lower()
if key not in sort_map:
raise ValueError(f'"{key}" is not a valid sort key. '
f'Valid sort keys are {sort_map.keys()}')
key = sort_map[key]
if direction not in ["asc", "desc"]:
raise ValueError(f'"{direction}" is not a valid sorting direction.'
f'Valid directions are "asc" and "desc".')
sort_list.append(f"{key}:{direction}")
sort_by = ",".join(sort_list)
if device_components:
device_components = [str(comp) for comp in device_components]
if device_components_operator:
if device_components_operator != "contains":
raise ValueError(f'{device_components_operator} is not a valid '
f'device_components_operator value. Valid values '
f'are ``None`` and "contains"')
device_components = \
"contains:" + ','.join(device_components) # type: ignore
if item_type and item_type_operator:
if item_type_operator != "like":
raise ValueError(f'"{item_type_operator}" is not a valid type operator value. '
f'Valid values are ``None`` and "like".')
item_type = "like:" + item_type
return {"tags": tags_filter,
"sort_by": sort_by,
"device_components": device_components,
"type": item_type}
def _api_to_analysis_result(
self,
raw_data: Dict,
) -> Dict:
"""Map API response to an AnalysisResult instance.
Args:
raw_data: API response data.
Returns:
Converted analysis result data.
"""
extra_data = {}
chisq = raw_data.get('chisq', None)
if chisq:
extra_data['chisq'] = chisq
backend_name = raw_data['device_name']
if backend_name:
extra_data['backend_name'] = backend_name
quality = raw_data.get('quality', None)
if quality:
quality = RESULT_QUALITY_FROM_API[quality]
self._convert_dt(raw_data.get('created_at', None), extra_data, 'creation_datetime')
self._convert_dt(raw_data.get('updated_at', None), extra_data, 'updated_datetime')
out_dict = {
"result_data": raw_data.get('fit', {}),
"result_type": raw_data.get('type', None),
"device_components": raw_data.get('device_components', []),
"experiment_id": raw_data.get('experiment_uuid'),
"result_id": raw_data.get('uuid', None),
"quality": quality,
"verified": raw_data.get('verified', False),
"tags": raw_data.get('tags', []),
"service": self,
**extra_data
}
return out_dict
def delete_analysis_result(
self,
result_id: str
) -> None:
"""Delete an analysis result.
Args:
result_id: Analysis result ID.
Note:
This method prompts for confirmation and requires a response before proceeding.
Raises:
IBMQApiError: If the request to the server failed.
"""
confirmation = input('\nAre you sure you want to delete the analysis result? [y/N]: ')
if confirmation not in ('y', 'Y'):
return
try:
self._api_client.analysis_result_delete(result_id)
except RequestsApiError as api_err:
if api_err.status_code == 404:
logger.warning("Analysis result %s not found.", result_id)
else:
raise IBMQApiError(f"Failed to process the request: {api_err}") from None
def create_figure(
self,
experiment_id: str,
figure: Union[str, bytes],
figure_name: Optional[str] = None,
sync_upload: bool = True
) -> Tuple[str, int]:
"""Store a new figure in the database.
Note:
Currently only SVG figures are supported.
Args:
experiment_id: ID of the experiment this figure is for.
figure: Name of the figure file or figure data to store.
figure_name: Name of the figure. If ``None``, the figure file name, if
given, or a generated name is used.
sync_upload: If ``True``, the plot will be uploaded synchronously.
Otherwise the upload will be asynchronous.
Returns:
A tuple of the name and size of the saved figure.
Raises:
IBMExperimentEntryExists: If the figure already exits.
IBMQApiError: If the request to the server failed.
"""
if figure_name is None:
if isinstance(figure, str):
figure_name = figure
else:
figure_name = "figure_{}.svg".format(datetime.now().isoformat())
if not figure_name.endswith(".svg"):
figure_name += ".svg"
with map_api_error(f"Figure {figure_name} already exists."):
response = self._api_client.experiment_plot_upload(experiment_id, figure, figure_name,
sync_upload=sync_upload)
return response['name'], response['size']
def update_figure(
self,
experiment_id: str,
figure: Union[str, bytes],
figure_name: str,
sync_upload: bool = True
) -> Tuple[str, int]:
"""Update an existing figure.
Args:
experiment_id: Experiment ID.
figure: Name of the figure file or figure data to store.
figure_name: Name of the figure.
sync_upload: If ``True``, the plot will be uploaded synchronously.
Otherwise the upload will be asynchronous.
Returns:
A tuple of the name and size of the saved figure.
Raises:
IBMExperimentEntryNotFound: If the figure does not exist.
IBMQApiError: If the request to the server failed.
"""
with map_api_error(f"Figure {figure_name} not found."):
response = self._api_client.experiment_plot_update(experiment_id, figure, figure_name,
sync_upload=sync_upload)
return response['name'], response['size']
def figure(
self,
experiment_id: str,
figure_name: str,
file_name: Optional[str] = None
) -> Union[int, bytes]:
"""Retrieve an existing figure.
Args:
experiment_id: Experiment ID.
figure_name: Name of the figure.
file_name: Name of the local file to save the figure to. If ``None``,
the content of the figure is returned instead.
Returns:
The size of the figure if `file_name` is specified. Otherwise the
content of the figure in bytes.
Raises:
IBMExperimentEntryNotFound: If the figure does not exist.
IBMQApiError: If the request to the server failed.
"""
with map_api_error(f"Figure {figure_name} not found."):
data = self._api_client.experiment_plot_get(experiment_id, figure_name)
if file_name:
with open(file_name, 'wb') as file:
num_bytes = file.write(data)
return num_bytes
return data
def delete_figure(
self,
experiment_id: str,
figure_name: str
) -> None:
"""Delete an experiment plot.
Note:
This method prompts for confirmation and requires a response before proceeding.
Args:
experiment_id: Experiment ID.
figure_name: Name of the figure.
Raises:
IBMQApiError: If the request to the server failed.
"""
confirmation = input('\nAre you sure you want to delete the experiment plot? [y/N]: ')
if confirmation not in ('y', 'Y'):
return
try:
self._api_client.experiment_plot_delete(experiment_id, figure_name)
except RequestsApiError as api_err:
if api_err.status_code == 404:
logger.warning("Figure %s not found.", figure_name)
else:
raise IBMQApiError(f"Failed to process the request: {api_err}") from None
def device_components(
self,
backend_name: Optional[str] = None
) -> Union[Dict[str, List], List]:
"""Return the device components.
Args:
backend_name: Name of the backend whose components are to be retrieved.
Returns:
A list of device components if `backend_name` is specified. Otherwise
a dictionary whose keys are backend names the values
are lists of device components for the backends.
Raises:
IBMQApiError: If the request to the server failed.
"""
with map_api_error(f"No device components found for backend {backend_name}"):
raw_data = self._api_client.device_components(backend_name)
components = defaultdict(list)
for data in raw_data:
components[data['device_name']].append(data['type'])
if backend_name:
return components[backend_name]
return dict(components)
@property
def preferences(self) -> Dict:
"""Return saved experiment preferences.
Note:
These are preferences passed to the applications that use this service
and have no effect on the service itself. It is up to the application,
such as ``qiskit-experiments`` to implement the preferences.
Returns:
Dict: The experiment preferences.
"""
return self._preferences
def save_preferences(self, auto_save: bool = None) -> None:
"""Stores experiment preferences on disk.
Note:
These are preferences passed to the applications that use this service
and have no effect on the service itself.
For example, if ``auto_save`` is set to ``True``, it tells the application,
such as ``qiskit-experiments``, that you prefer changes to be
automatically saved. It is up to the application to implement the preferences.
Args:
auto_save: Automatically save the experiment.
"""
update_cred = False
if auto_save is not None and auto_save != self._preferences["auto_save"]:
self._preferences['auto_save'] = auto_save
update_cred = True
if update_cred:
store_preferences(
{self._provider.credentials.unique_id(): {'experiment': self.preferences}})
|
https://github.com/0tt3r/QuaC-qiskit
|
0tt3r
|
# -*- coding: utf-8 -*-
"""This module contains test cases for ensuring gate addition and functionality is working properly
in the library.
"""
import unittest
from qiskit import execute, Aer
from qiskit.circuit.random import random_circuit
from quac_qiskit import Quac
from quac_qiskit.format import *
from quac_qiskit.models import QuacNoiseModel
from quac_qiskit.stat import *
class GateAdditionTestCase(unittest.TestCase):
"""Tests gate functionality
"""
def setUp(self):
# Set up QuaC simulator and QASM simulator
self.quac_simulator = Quac.get_backend("fake_yorktown_density_simulator")
self.qasm_simulator = Aer.get_backend("statevector_simulator")
def test_hadamard_gate(self):
test_circuit = QuantumCircuit(1)
test_circuit.h(0)
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLessEqual(get_vec_angle(outcome_list, [0.5, 0.5]), 5)
def test_id_gate(self):
test_circuit = QuantumCircuit(1)
test_circuit.id(0)
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLessEqual(get_vec_angle(outcome_list, [1, 0]), 5)
def test_x_gate(self):
test_circuit = QuantumCircuit(1)
test_circuit.x(0)
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLessEqual(get_vec_angle(outcome_list, [0, 1]), 5)
def test_y_gate(self):
test_circuit = QuantumCircuit(1)
test_circuit.y(0)
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLessEqual(get_vec_angle(outcome_list, [0, 1]), 5)
test_circuit = QuantumCircuit(1)
test_circuit.x(0)
test_circuit.y(0)
test_circuit.y(0)
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLessEqual(get_vec_angle(outcome_list, [0, 1]), 5)
def test_z_gate(self):
test_circuit = QuantumCircuit(1)
test_circuit.z(0)
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLessEqual(get_vec_angle(outcome_list, [1, 0]), 5)
def test_rx_gate(self):
test_circuit = QuantumCircuit(1)
test_circuit.rx(np.pi, 0)
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLessEqual(get_vec_angle(outcome_list, [0, 1]), 5)
test_circuit = QuantumCircuit(1)
test_circuit.rx(np.pi / 2, 0) # Hadamard gate equivalent
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLessEqual(get_vec_angle(outcome_list, [0.5, 0.5]), 5)
def test_ry_gate(self):
test_circuit = QuantumCircuit(1)
test_circuit.ry(np.pi, 0)
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLessEqual(get_vec_angle(outcome_list, [0, 1]), 5)
test_circuit = QuantumCircuit(1)
test_circuit.ry(np.pi / 2, 0) # Hadamard gate equivalent
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLessEqual(get_vec_angle(outcome_list, [0.5, 0.5]), 5)
def test_rz_gate(self):
test_circuit = QuantumCircuit(1)
test_circuit.rz(np.pi, 0)
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLess(get_vec_angle(outcome_list, [1, 0]), 5) # should leave state alone
test_circuit = QuantumCircuit(1)
test_circuit.h(0)
test_circuit.rz(np.pi, 0) # should not affect probabilities
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLess(get_vec_angle(outcome_list, [0.5, 0.5]), 5)
def test_u1_gate(self):
test_circuit = QuantumCircuit(1)
test_circuit.u1(math.pi, 0) # same as Z gate
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLessEqual(get_vec_angle(outcome_list, [1, 0]), 5)
def test_u2_gate(self):
test_circuit = QuantumCircuit(1)
test_circuit.u2(0, np.pi, 0) # behaves like a Hadamard gate
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLess(get_vec_angle(outcome_list, [0.5, 0.5]), 5)
def test_u3_gate(self):
test_circuit = QuantumCircuit(1)
test_circuit.u3(np.pi / 2, 0, np.pi, 0) # behaves like a Hadamard gate
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLess(get_vec_angle(outcome_list, [0.5, 0.5]), 5)
def test_cnot_gate(self):
test_circuit = QuantumCircuit(2)
test_circuit.h(0)
test_circuit.cx(0, 1)
test_circuit.measure_all()
outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000)
outcome_list = counts_to_list(outcome_dist.result().get_counts())
self.assertLess(get_vec_angle(outcome_list, [0.5, 0, 0, 0.5]), 5)
def test_random_circuits(self):
for circuit_index in range(1000):
num_qubits = random.randrange(1, 6)
# Generate random circuit and transpile it to run on specific hardware
random_circ = transpile(random_circuit(num_qubits, 5, measure=False), self.quac_simulator)
random_circ.measure_all()
# Get QuaC-calculated probabilities in a list
plugin_probs = counts_to_dist(
execute(random_circ, self.quac_simulator, shots=1, optimization_level=0,
quac_noise_model=QuacNoiseModel.get_noiseless_model(5)).result().get_counts()
)
# Get Qiskit-calculated probabilities in a list
random_circ.remove_final_measurements() # avoid collapsing state vector
qiskit_sv = execute(random_circ, self.qasm_simulator, shots=8000,
optimization_level=0,
).result().get_statevector(random_circ)
# qiskit_probs = qiskit_statevector_to_probabilities(qiskit_sv, 5)
qiskit_probs = statevector_to_probabilities(qiskit_sv)
# Calculate divergence of Qiskit and QuaC predictions
difference_angle = get_vec_angle(qiskit_probs, plugin_probs)
self.assertLess(difference_angle, 1e-5)
if __name__ == '__main__':
unittest.main()
|
https://github.com/abbarreto/qiskit3
|
abbarreto
| |
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from IPython.display import Image
Image(filename="error_correction_files/error_correction_1_0.png", width=450, height=300)
Image(filename="error_correction_files/error_correction_3_0.png", width=450, height=300)
Image(filename="error_correction_files/error_correction_5_0.png", width=450, height=300)
Image(filename="error_correction_files/error_correction_7_0.png", width=450, height=300)
import sys
if sys.version_info < (3,5):
raise Exception('Please use Python version 3.5 or greater.')
from qiskit import QuantumProgram
#import Qconfig
# Needed to visualize quantum circuits
import os
import shutil
from qiskit.tools.visualization import latex_drawer
import pdf2image
from IPython.display import Image
# Initialize quantum program
qp = QuantumProgram()
#qp.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url
# Circuit requires 5 qubits and 5 classical bits
qr = qp.create_quantum_register('qr', 5)
cr = qp.create_classical_register('cr',5)
qc = qp.create_circuit('Circuit', [qr], [cr])
circuit = qp.get_circuit('Circuit')
# get the Quantum Register by Name
quantum_r = qp.get_quantum_register('qr')
# get the Classical Register by Name
classical_r = qp.get_classical_register('cr')
def circuitImage(circuit, filename, basis="u1,u2,u3,cx"):
"""
Obtain the circuit in image format
Note: Requires pdflatex installed (to compile Latex)
Note: Required pdf2image Python package (to display pdf as image)
"""
tmpdir='tmp/'
if not os.path.exists(tmpdir):
os.makedirs(tmpdir)
latex_drawer(circuit, tmpdir+filename+".tex", basis=basis)
os.system("pdflatex -output-directory {} {}".format(tmpdir, filename+".tex"))
images = pdf2image.convert_from_path(tmpdir+filename+".pdf")
shutil.rmtree(tmpdir)
return images[0]
def toffoli(circuit,quantum_r,a,b,c):
"""
Creates toffoli gate in existing circuit with a and b
as the test points and c as the affected point
"""
circuit.iden(quantum_r[c])
circuit.h(quantum_r[c])
circuit.cx(quantum_r[b],quantum_r[c])
circuit.tdg(quantum_r[c])
circuit.cx(quantum_r[a],quantum_r[c])
circuit.t(quantum_r[c])
circuit.cx(quantum_r[b],quantum_r[c])
circuit.tdg(quantum_r[c])
circuit.cx(quantum_r[a],quantum_r[c])
circuit.t(quantum_r[c])
circuit.t(quantum_r[b])
circuit.h(quantum_r[c])
circuit.cx(quantum_r[b],quantum_r[c])
circuit.h(quantum_r[c])
circuit.h(quantum_r[b])
circuit.cx(quantum_r[b],quantum_r[c])
circuit.h(quantum_r[c])
circuit.h(quantum_r[b])
circuit.cx(quantum_r[b],quantum_r[c])
circuit.cx(quantum_r[a],quantum_r[c])
circuit.t(quantum_r[a])
circuit.tdg(quantum_r[c])
circuit.cx(quantum_r[a],quantum_r[c])
circuit.cx(quantum_r[b],quantum_r[c])
circuit.cx(quantum_r[c],quantum_r[b])
circuit.cx(quantum_r[b],quantum_r[c])
#circuit.x(quantum_r[2])
circuit.x(quantum_r[3])
circuit.x(quantum_r[4])
circuit.cx(quantum_r[2],quantum_r[0])
circuit.cx(quantum_r[3],quantum_r[0])
circuit.cx(quantum_r[3],quantum_r[1])
circuit.cx(quantum_r[4],quantum_r[1])
circuit.cx(quantum_r[0],quantum_r[2])
circuit.cx(quantum_r[1],quantum_r[4])
toffoli(circuit,quantum_r,0,1,2)
toffoli(circuit,quantum_r,0,1,3)
toffoli(circuit,quantum_r,0,1,4)
circuit.measure(quantum_r[0], classical_r[0])
circuit.measure(quantum_r[1], classical_r[1])
circuit.measure(quantum_r[2], classical_r[2])
circuit.measure(quantum_r[3], classical_r[3])
circuit.measure(quantum_r[4], classical_r[4])
"""
Image of the final circuit. Becuase it contains three Toffoli gates where
each gate is made up of many basis gates, this circuit is unfortunately
very hard to visualize.
"""
basis="u1,u2,u3,cx,x,y,z,h,s,t,rx,ry,rz"
circuitImage(circuit,'circuit',basis)
#!!! for better visibility plot using the now built-in code
from qiskit.tools.visualization import circuit_drawer
circuit_drawer(circuit)
"""
Results of the computation. Note that the states of the five qubits
from up to down in the circuit are shown from right to left in the result.
"""
backend = 'ibmqx_qasm_simulator'
circuits = ['Circuit'] # Group of circuits to execute
qobj=qp.compile(circuits, backend, shots=1024, max_credits=3)
result = qp.run(qobj, wait=2, timeout=240)
print(result.get_counts('Circuit'))
Image(filename="error_correction_files/error_correction_27_0.png", width=250, height=300)
Image(filename="error_correction_files/error_correction_30_0.png", width=450, height=300)
Image(filename="error_correction_files/error_correction_33_0.png", width=450, height=300)
Image(filename="error_correction_files/error_correction_36_0.png", width=450, height=300)
Image(filename="error_correction_files/error_correction_39_0.png", width=900, height=600)
Image(filename="error_correction_files/error_correction_40_0.png", width=900, height=600)
Image(filename="error_correction_files/error_correction_43_0.png", width=900, height=450)
|
https://github.com/GlazeDonuts/Variational-Quantum-Classifier
|
GlazeDonuts
|
# Installing a few dependencies
!pip install --upgrade seaborn==0.10.1
!pip install --upgrade scikit-learn==0.23.1
!pip install --upgrade matplotlib==3.2.0
!pip install --upgrade pandas==1.0.4
!pip install --upgrade qiskit==0.19.6
!pip install --upgrade plotly==4.9.0
!pip install qiskit-qcgpu-provider
# The output will be cleared after installation
from IPython.display import clear_output
clear_output()
# we have imported a few libraries we think might be useful
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer
from qiskit import *
import numpy as np
from qiskit.visualization import plot_bloch_multivector, plot_histogram
%matplotlib inline
import matplotlib.pyplot as plt
import time
from qiskit.circuit.library import ZZFeatureMap, ZFeatureMap, PauliFeatureMap, RealAmplitudes, EfficientSU2
from qiskit.aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import VQC
from qiskit.aqua.components.optimizers import COBYLA
# The the write_and_run() magic function creates a file with the content inside the cell that it is run.
from IPython.core.magic import register_cell_magic
@register_cell_magic
def write_and_run(line, cell):
argz = line.split()
file = argz[-1]
mode = 'w'
with open(file, mode) as f:
f.write(cell)
get_ipython().run_cell(cell)
!wget -O "dataset_4_9.csv" https://gitlab.com/GlazeDonuts/vqc-datasets/-/raw/master/datasets/dataset_4_9.csv
data = np.loadtxt("dataset_4_9.csv", delimiter=",")
# extracting the first column which contains the labels
data_labels = data[:, :1].reshape(data.shape[0],)
# extracting all the columns but the first which are our features
data_features = data[:, 1:]
import plotly.express as px
import pandas as pd
# Creating a dataframe using pandas only for the purpose fo plotting
df = pd.DataFrame({'Component 0':data_features[:,0], 'Component 1':data_features[:,1],
'Component 2':data_features[:,2], 'label':data_labels})
fig = px.scatter_3d(df, x='Component 0', y='Component 1', z='Component 2', color='label')
fig.show()
### WRITE YOUR CODE BETWEEN THESE LINES - START
# Percentage of corpus considered for training
corp_perc = 4
# Calculating the total number of samples
corp_split = int(corp_perc * data.shape[0] // 100)
# Choosing random samples from data points corresponind to four and nine
four_indices = np.random.choice(np.arange(data.shape[0]//2), corp_split//2, replace=False)
nine_indices = np.random.choice(np.arange(data.shape[0]//2, data.shape[0]), corp_split//2, replace=False)
my_data_four = np.copy(data[four_indices])
my_data_nine = np.copy(data[nine_indices])
# Forming data set with samples of fours and nines
my_data = np.concatenate((my_data_four, my_data_nine))
test_perc = 5
semi_split = int(test_perc*my_data.shape[0]//200)
# Creating training and testing input dictionaries
training_input = {'A': my_data_four[:-semi_split, 1:], 'B': my_data_nine[:-semi_split, 1:]}
test_input = {'A': my_data_four[-semi_split:, 1:], 'B': my_data_nine[-semi_split:, 1:]}
testing_input = np.concatenate((my_data_four[-semi_split:, 1:], my_data_nine[-semi_split:, 1:]))
testing_labels = np.concatenate((my_data_four[-semi_split:, :1], my_data_nine[-semi_split:, :1]))
### WRITE YOUR CODE BETWEEN THESE LINES - END
%%write_and_run feature_map.py
# The write_and_run function writes the content in this cell into the file "feature_map.py"
### WRITE YOUR CODE BETWEEN THESE LINES - START
# Import libraries that are used in the function below.
from qiskit import QuantumCircuit
from qiskit.circuit import ParameterVector
from qiskit.circuit.library import ZZFeatureMap, ZFeatureMap, PauliFeatureMap
### WRITE YOUR CODE BETWEEN THESE LINES - END
def feature_map():
# BUILD FEATURE MAP HERE - START
# Import required qiskit libraries if additional libraries are required
# Build the feature map
reps = 3
num_qubits = 3
feature_map = QuantumCircuit(num_qubits)
x = ParameterVector('x', length=num_qubits)
# EXPERIMENT 1 : 64
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.rx(x[i], i)
# for i in range(num_qubits):
# for j in range(i + 1, num_qubits):
# feature_map.cx(i, j)
# feature_map.u1(x[i] * x[j], j)
# feature_map.cx(i, j)
# EXPERIMENT 2: 63.5
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.h(i)
# for i in range(num_qubits - 1):
# feature_map.cz(i, i+1)
# for i in range(num_qubits):
# feature_map.rx(x[i], i)
# for i in range(num_qubits-1, 0, -1):
# feature_map.cz(i, i-1)
# for i in range(num_qubits):
# feature_map.h(i)
# #EXPERIMENT 3: 72.9
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.rx(x[i], i)
# feature_map.rz(x[i], i)
# for i in range(num_qubits-1, 0, -1):
# feature_map.cx(i, i-1)
#EXPERIMENT 4: 71.2
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.rx(x[i], i)
# feature_map.rz(x[i], i)
# for i in range(num_qubits-1, 0, -1):
# feature_map.cz(i, i-1)
# EXPERIMENT 5: 75.6
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.rx(x[i], i)
# feature_map.rz(x[i], i)
# for i in range(num_qubits-1, 0, -1):
# feature_map.rz(x[i-1], i-1)
# feature_map.cx(i, i-1)
# feature_map.rz(x[i-1], i-1)
# EXPERIMENT 6: 75.7
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.rx(x[i], i)
# feature_map.rz(x[i], i)
# for i in range(num_qubits-1, 0, -1):
# feature_map.rx(x[i-1], i-1)
# feature_map.cx(i, i-1)
# feature_map.rx(x[i-1], i-1)
# Experiment 7: 76.8 with 2 reps and 4 vqc
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.rx(x[i], i)
# feature_map.rz(x[i], i)
# for control in range(num_qubits-1, -1, -1):
# for target in range(num_qubits-1, -1, -1):
# if control != target:
# feature_map.rz(x[target], target)
# feature_map.cx(control, target)
# feature_map.rz(x[target], target)
# Experiment 8: 75.2
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.rx(x[i], i)
# feature_map.rz(x[i], i)
# for control in range(num_qubits-1, -1, -1):
# for target in range(num_qubits-1, -1, -1):
# if control != target:
# feature_map.rx(x[target], target)
# feature_map.cx(control, target)
# feature_map.rx(x[target], target)
# Experiment 9: 77.6
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.rx(x[i], i)
# feature_map.rz(x[i], i)
# for control in range(num_qubits-1, 0, -1):
# target = control - 1
# feature_map.rz(x[target], target)
# feature_map.cx(control, target)
# feature_map.rz(x[target], target) # | Upto this plus Experiment 10 (both 1 rep each), gave 79 with 4 reps of VQC
# for i in range(num_qubits): # Reduced to 75.7
# feature_map.rx(x[i], i)
# feature_map.rz(x[i], i)
# feature_map.rz(x[1], 1) # Reduced to 70.5
# feature_map.cx(2, 1)
# feature_map.rz(x[1], 1)
# Experiment 10: 77.8
for _ in range(reps):
for i in range(num_qubits):
feature_map.rx(x[i], i)
feature_map.rz(x[i], i)
feature_map.barrier()
for control in range(num_qubits-1, 0, -1):
target = control - 1
feature_map.rx(x[target], target)
feature_map.cx(control, target)
feature_map.rx(x[target], target)
feature_map.barrier()
for i in range(num_qubits):
feature_map.rx(x[i], i)
feature_map.rz(x[i], i)
feature_map.barrier()
# Experiment 11: 65.4 with 2 vqc reps | 71.1 with 3 reps of vqc
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.h(i)
# for i in range(num_qubits - 1):
# feature_map.cz(i, i+1)
# for i in range(num_qubits):
# feature_map.rx(x[i], i)
# Experiment 12: 76.4
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.ry(x[i], i)
# for i in range(num_qubits - 1, 0, -1):
# feature_map.cz(i, i-1)
# feature_map.cz(num_qubits-1, 0)
# for i in range(num_qubits):
# feature_map.ry(x[i], i)
# Experiment 13: 70.1
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.ry(x[i], i)
# feature_map.rz(x[i], i)
# for i in range(num_qubits - 1, 0, -1):
# feature_map.cx(i, i-1)
# Experiment 14: 75.2
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.ry(x[i], i)
# feature_map.rz(x[i], i)
# for i in range(num_qubits - 1, 0, -1):
# feature_map.cx(i, i-1)
# feature_map.ry(x[1], 1)
# feature_map.rz(x[1], 1)
# Experiment 15: 77.3
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.ry(x[i], i)
# feature_map.rz(x[i], i)
# for i in range(num_qubits - 1, 0, -1):
# feature_map.cz(i, i-1)
# feature_map.ry(x[1], 1)
# feature_map.rz(x[1], 1)
# Experiment 16: 73.1
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.rx(x[i], i)
# feature_map.rz(x[i], i)
# feature_map.rx(x[0], 0)
# feature_map.cx(num_qubits - 1, 0)
# feature_map.rx(x[0], 0)
# for i in range(num_qubits-2, -1, -1):
# feature_map.rx(x[i+1], i+1)
# feature_map.cx(i, i+1)
# feature_map.rx(x[i+1], i+1)
# Experiment 17: 77.0
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.rx(x[i], i)
# feature_map.rz(x[i], i)
# feature_map.rz(x[0], 0)
# feature_map.cx(num_qubits - 1, 0)
# feature_map.rz(x[0], 0)
# for i in range(num_qubits-2, -1, -1):
# feature_map.rz(x[i+1], i+1)
# feature_map.cx(i, i+1)
# feature_map.rz(x[i+1], i+1)
# Experiment 18: 73.8
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.rx(x[i], i)
# feature_map.rz(x[i], i)
# for control in range(num_qubits - 1, 0, -1):
# target = control - 1
# feature_map.rx(x[target], target)
# feature_map.cx(control, target)
# feature_map.rx(x[target], target)
# Experiment 19: 78.7 2 reps 2 su2 | Gave 52 with RealAmp 4 reps | 68 with 2 reps and SU2 4 reps | 61.4 with 3 reps and su2 4 reps
# for _ in range(2):
# for i in range(num_qubits):
# feature_map.ry(x[i], i)
# feature_map.cx(num_qubits-1, 0)
# for i in range(num_qubits-1):
# feature_map.cx(i, i+1)
# for i in range(num_qubits):
# feature_map.ry(x[i], i)
# feature_map.cx(num_qubits - 1, num_qubits - 2)
# feature_map.cx(0, num_qubits - 1)
# for i in range(1, num_qubits - 1):
# feature_map.cx(i, i-1)
# Experiment 19: 79.9 on 3 reps and 4 vqc and 10 perc data. This is almost same as experiment 10, but only the last two gates are reversed in order
# for _ in range(reps):
# for i in range(num_qubits):
# feature_map.rx(x[i], i)
# feature_map.rz(x[i], i)
# for control in range(num_qubits-1, 0, -1):
# target = control - 1
# feature_map.rx(x[target], target)
# feature_map.cx(control, target)
# feature_map.rx(x[target], target)
# for i in range(num_qubits):
# feature_map.rz(x[i], i)
# feature_map.rx(x[i], i)
# Experiment 20: 78.5 | Same as exp 10 just starting 2 and ending 2 xz swapped
# 79.6 with 3 and 4 vqc 2perc data | 79.0 with 10 perc
# for _ in range(reps): # Exp 20
# for i in range(num_qubits):
# feature_map.rz(x[i], i)
# feature_map.rx(x[i], i)
# for control in range(num_qubits-1, 0, -1):
# target = control - 1
# feature_map.rx(x[target], target)
# feature_map.cx(control, target)
# feature_map.rx(x[target], target)
# for i in range(num_qubits):
# feature_map.rz(x[i], i)
# feature_map.rx(x[i], i)
# ALL SCORES ARE WITH 2 REPS OF SU2 LINEARLY ENTAGLED BY DEFAULT UNLESS MENTIONED OTHERWISE
# BUILD FEATURE MAP HERE - END
#return the feature map which is either a FeatureMap or QuantumCircuit object
return feature_map
fmap = feature_map()
fmap.draw(output='mpl', filename='final_fmap.jpg')
%%write_and_run variational_circuit.py
# the write_and_run function writes the content in this cell into the file "variational_circuit.py"
### WRITE YOUR CODE BETWEEN THESE LINES - START
# import libraries that are used in the function below.
from qiskit import QuantumCircuit
from qiskit.circuit import ParameterVector
from qiskit.circuit.library import RealAmplitudes, EfficientSU2, TwoLocal, NLocal
### WRITE YOUR CODE BETWEEN THESE LINES - END
def variational_circuit():
# BUILD VARIATIONAL CIRCUIT HERE - START
# import required qiskit libraries if additional libraries are required
# build the variational circuit
# var_circuit = EfficientSU2(3, entanglement='linear', reps=2, insert_barriers=True)
var_circuit = TwoLocal(3, ['ry', 'rz'], ['cx'], entanglement='linear', reps=4, insert_barriers=True)
# BUILD VARIATIONAL CIRCUIT HERE - END
# return the variational circuit which is either a VaritionalForm or QuantumCircuit object
return var_circuit
var_circ = variational_circuit()
var_circ.draw(output='mpl', filename='final_var_circ.jpg')
def classical_optimizer():
# CHOOSE AND RETURN CLASSICAL OPTIMIZER OBJECT - START
# import the required clasical optimizer from qiskit.aqua.optimizers
from qiskit.aqua.components.optimizers import ADAM, SPSA, COBYLA
# create an optimizer object
# cls_opt = ADAM(maxiter=250, lr=1e-2, beta_1=0.9, beta_2=0.9, tol=1e-6)
cls_opt = COBYLA(maxiter=100, disp=True, tol=1e-6)
# cls_opt = SPSA(maxiter=250)
# CHOOSE AND RETURN CLASSICAL OPTIMIZER OBJECT - END
return cls_opt
def call_back_vqc(eval_count, var_params, eval_val, index):
print("eval_count: {}".format(eval_count))
print("var_params: {}".format(var_params))
print("eval_val: {}".format(eval_val))
print("index: {}".format(index))
# A fixed seed so that we get the same answer when the same input is given.
seed = 10598
# Setting our backend to qasm_simulator with the "statevector" method on. This particular setup is given as it was
# Found to perform better than most. Feel free to play around with different backend options.
backend = Aer.get_backend('qasm_simulator')
backend_options = {"method": "statevector"}
# Creating a quantum instance using the backend and backend options taken before
quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed,
backend_options=backend_options)
# Creating a VQC instance which you will be used for training. Make sure you input the correct training_dataset and
# Testing_dataset as defined in your program.
vqc = VQC(optimizer=classical_optimizer(),
feature_map=feature_map(),
var_form=variational_circuit(),
callback=call_back_vqc,
training_dataset=training_input, # Training_input must be initialized with your training dataset
test_dataset=test_input) # Testing_input must be initialized with your testing dataset
start = time.process_time()
result = vqc.run(quantum_instance)
print("time taken: ")
print(time.process_time() - start)
print("testing success ratio: {}".format(result['testing_accuracy']))
print(repr(vqc.optimal_params))
%%write_and_run optimal_params.py
# The write_and_run function writes the content in this cell into the file "optimal_params.py"
### WRITE YOUR CODE BETWEEN THESE LINES - START
# import libraries that are used in the function below.
import numpy as np
### WRITE YOUR CODE BETWEEN THESE LINES - END
def return_optimal_params():
# STORE THE OPTIMAL PARAMETERS AS AN ARRAY IN THE VARIABLE optimal_parameters
optimal_parameters = np.array([-0.82871645, -0.50819365, -0.83197798, 3.64408214, 0.99032149,
-1.72461303, -1.8798925 , 0.22324836, 0.7469075 , -0.29177951,
1.18396727, -0.8831999 , -0.20987174, 0.1609452 , 0.72160706,
-0.59644311, -1.46078401, -1.12552463, 1.34940875, -0.40489246,
-1.20122758, 0.10007856, -0.95181456, -1.6608501 , 0.70347488,
-0.37977302, -0.26907574, -0.08800676, -0.56356505, 1.85327073])
# STORE THE OPTIMAL PARAMETERS AS AN ARRAY IN THE VARIABLE optimal_parameters
return np.array(optimal_parameters)
solution = ['feature_map.py','variational_circuit.py','optimal_params.py']
file = open("summary.py","w")
file.truncate(0)
for i in solution:
with open(i) as f:
with open("summary.py", "a") as f1:
for line in f:
f1.write(line)
file.close()
#imports required for the grading function
from qiskit import *
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import VQC
from qiskit.aqua.components.feature_maps import FeatureMap
from qiskit.aqua.components.variational_forms import VariationalForm
import numpy as np
def grade(test_data, test_labels, feature_map, variational_form, optimal_params, find_circuit_cost=True, verbose=True):
seed = 10598
model_accuracy = None
circuit_cost=None
ans = None
unrolled_circuit = None
result_msg=''
data_dim = np.array(test_data).shape[1]
dataset_size = np.array(test_data).shape[0]
dummy_training_dataset=training_input = {'A':np.ones((2,data_dim)), 'B':np.ones((2, data_dim))}
# converting 4's to 0's and 9's to 1's for checking
test_labels_transformed = np.where(test_labels==4, 0., 1.)
max_qubit_count = 6
max_circuit_cost = 2000
# Section 1
if feature_map is None:
result_msg += 'feature_map variable is None. Please submit a valid entry' if verbose else ''
elif variational_form is None:
result_msg += 'variational_form variable is None. Please submit a valid entry' if verbose else ''
elif optimal_params is None:
result_msg += 'optimal_params variable is None. Please submit a valid entry' if verbose else ''
elif test_data is None:
result_msg += 'test_data variable is None. Please submit a valid entry' if verbose else ''
elif test_labels is None:
result_msg += 'test_labels variable is None. Please submit a valid entry' if verbose else ''
elif not isinstance(feature_map, (QuantumCircuit, FeatureMap)):
result_msg += 'feature_map variable should be a QuantumCircuit or a FeatureMap not (%s)' % \
type(feature_map) if verbose else ''
elif not isinstance(variational_form, (QuantumCircuit, VariationalForm)):
result_msg += 'variational_form variable should be a QuantumCircuit or a VariationalForm not (%s)' % \
type(variational_form) if verbose else ''
elif not isinstance(test_data, np.ndarray):
result_msg += 'test_data variable should be a numpy.ndarray not (%s)' % \
type(test_data) if verbose else ''
elif not isinstance(test_labels, np.ndarray):
result_msg += 'test_labels variable should be a numpy.ndarray not (%s)' % \
type(test_labels) if verbose else ''
elif not isinstance(optimal_params, np.ndarray):
result_msg += 'optimal_params variable should be a numpy.ndarray not (%s)' % \
type(optimal_params) if verbose else ''
elif not dataset_size == test_labels_transformed.shape[0]:
result_msg += 'Dataset size and label array size must be equal'
# Section 2
else:
# setting up COBYLA optimizer as a dummy optimizer
from qiskit.aqua.components.optimizers import COBYLA
dummy_optimizer = COBYLA()
# setting up the backend and creating a quantum instance
backend = Aer.get_backend('qasm_simulator')
backend_options = {"method": "statevector"}
quantum_instance = QuantumInstance(backend,
shots=2000,
seed_simulator=seed,
seed_transpiler=seed,
backend_options=backend_options)
# creating a VQC instance and running the VQC.predict method to get the accuracy of the model
vqc = VQC(optimizer=dummy_optimizer,
feature_map=feature_map,
var_form=variational_form,
training_dataset=dummy_training_dataset)
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
pass_ = Unroller(['u3', 'cx'])
pm = PassManager(pass_)
# construct circuit with first datapoint
circuit = vqc.construct_circuit(data[0], optimal_params)
unrolled_circuit = pm.run(circuit)
gates = unrolled_circuit.count_ops()
if 'u3' in gates:
circuit_cost = gates['u3']
if 'cx' in gates:
circuit_cost+= 10*gates['cx']
if circuit.num_qubits > max_qubit_count:
result_msg += 'Your quantum circuit is using more than 6 qubits. Reduce the number of qubits used and try again.'
elif circuit_cost > max_circuit_cost:
result_msg += 'The cost of your circuit is exceeding the maximum accpetable cost of 2000. Reduce the circuit cost and try again.'
else:
ans = vqc.predict(test_data, quantum_instance=quantum_instance, params=np.array(optimal_params))
model_accuracy = np.sum(np.equal(test_labels_transformed, ans[1]))/len(ans[1])
result_msg += 'Accuracy of the model is {}'.format(model_accuracy) if verbose else ''
result_msg += ' and circuit cost is {}'.format(circuit_cost) if verbose else ''
return model_accuracy, circuit_cost, ans, result_msg, unrolled_circuit
grading_dataset_size=2000 # this value is not per digit but in total
grading_features = data_features[-grading_dataset_size:]
grading_labels = data_labels[-grading_dataset_size:]
start = time.process_time()
accuracy, circuit_cost, ans, result_msg, full_circuit = grade(test_data=grading_features,
test_labels=grading_labels,
feature_map=feature_map(),
variational_form=variational_circuit(),
optimal_params=return_optimal_params())
print("time taken: {} seconds".format(time.process_time() - start))
print(result_msg)
print("Accuracy of the model: {}".format(accuracy))
print("Circuit Cost: {}".format(circuit_cost))
print("The complete unrolled circuit: ")
full_circuit.draw()
|
https://github.com/henryliao85/GroverFor3SAT
|
henryliao85
|
# importing Qiskit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import plot_histogram
from qiskit_ibm_provider import IBMProvider
def threeSAT_oracle(circuit, f_in, f_out, aux, n, expression):
num_clauses = len(expression)
for k, clause in enumerate(expression):
# This loop ensures aux[k] is 1 if an odd number of literals
# are true
for literal in clause:
if literal > 0:
circuit.cx(f_in[literal-1], aux[k])
else:
circuit.x(f_in[-literal-1])
circuit.cx(f_in[-literal-1], aux[k])
# Flip aux[k] if 2 literals are true
for literal_1 in clause:
if literal_1 > 0:
l1 = literal_1
else:
l1 = -literal_1
for literal_2 in clause:
if literal_1 >= literal_2:
continue
if literal_2 > 0:
l2 = literal_2
else:
l2 = -literal_2
circuit.ccx(f_in[l1-1], f_in[l2-1], aux[k])
# Flip aux[k] if all literals are true, using auxiliary qubit
# (ancilla) aux[num_clauses]
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
circuit.ccx(f_in[2], aux[num_clauses], aux[k])
# Flip back to reverse state of negative literals and ancilla
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
for literal in clause:
if literal < 0:
circuit.x(f_in[-literal-1])
# The formula is satisfied if and only if all auxiliary qubits
# except aux[num_clauses] are 1
if (num_clauses == 1):
circuit.cx(aux[0], f_out[0])
elif (num_clauses == 2):
circuit.ccx(aux[0], aux[1], f_out[0])
else:
circuit.ccx(aux[0], aux[1], aux[num_clauses])
for i in range(2, num_clauses-1):
circuit.ccx(aux[i], aux[num_clauses+i-2], aux[num_clauses+i-1])
circuit.ccx(aux[num_clauses-1], aux[2*num_clauses-3], f_out[0])
for i in range(num_clauses-2, 1, -1):
circuit.ccx(aux[i], aux[num_clauses+i-2], aux[num_clauses+i-1])
circuit.ccx(aux[0], aux[1], aux[num_clauses])
# Flip back any auxiliary qubits to make sure state is consistent
# for future executions of this routine; same loop as above.
for k, clause in enumerate(expression):
for literal in clause:
if literal > 0:
circuit.cx(f_in[literal-1], aux[k])
else:
circuit.x(f_in[-literal-1])
circuit.cx(f_in[-literal-1], aux[k])
for literal_1 in clause:
if literal_1 > 0:
l1 = literal_1
else:
l1 = -literal_1
for literal_2 in clause:
if literal_1 >= literal_2:
continue
if literal_2 > 0:
l2 = literal_2
else:
l2 = -literal_2
circuit.ccx(f_in[l1-1], f_in[l2-1], aux[k])
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
circuit.ccx(f_in[2], aux[num_clauses], aux[k])
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
for literal in clause:
if literal < 0:
circuit.x(f_in[-literal-1])
def exactly1_threeSAT_oracle(circuit, f_in, f_out, aux, n, expression):
num_clauses = len(expression)
for k, clause in enumerate(expression):
for literal in clause:
if literal > 0:
circuit.cx(f_in[literal-1], aux[k])
else:
circuit.x(f_in[-literal-1])
circuit.cx(f_in[-literal-1], aux[k])
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
circuit.ccx(f_in[2], aux[num_clauses], aux[k])
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
for literal in clause:
if literal < 0:
circuit.x(f_in[-literal-1])
if num_clauses == 1:
circuit.cx(aux[0], f_out[0])
elif num_clauses == 2:
circuit.ccx(aux[0], aux[1], f_out[0])
else:
circuit.ccx(aux[0], aux[1], aux[num_clauses])
for i in range(2, num_clauses-1):
circuit.ccx(aux[i], aux[num_clauses+i-2], aux[num_clauses+i-1])
circuit.ccx(aux[num_clauses-1], aux[2*num_clauses-3], f_out[0])
for i in range(num_clauses-2, 1, -1):
circuit.ccx(aux[i], aux[num_clauses+i-2], aux[num_clauses+i-1])
circuit.ccx(aux[0], aux[1], aux[num_clauses])
for k, clause in enumerate(expression):
for literal in clause:
if literal > 0:
circuit.cx(f_in[literal-1], aux[k])
else:
circuit.x(f_in[-literal-1])
circuit.cx(f_in[-literal-1], aux[k])
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
circuit.ccx(f_in[2], aux[num_clauses], aux[k])
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
for literal in clause:
if literal < 0:
circuit.x(f_in[-literal-1])
def n_controlled_Z(qc, controls, target, aux):
n = len(controls)
qc.h(target)
if (n == 1):
qc.cx(controls[0], target)
elif (n == 2):
qc.ccx(controls[0], controls[1], target)
else:
qc.ccx(controls[0], controls[1], aux[0])
for i in range(2, n-1):
qc.ccx(controls[i], aux[i-2], aux[i-1])
qc.ccx(controls[n-1], aux[n-3], target)
for i in range(n-2, 1, -1):
qc.ccx(controls[i], aux[i-2], aux[i-1])
qc.ccx(controls[0], controls[1], aux[0])
qc.h(target)
def reflect_around_psi(qc, qr1, aux, n=3):
for j in range(n):
qc.h(qr1[j])
qc.x(qr1[j])
n_controlled_Z(qc, qr1[:-1], qr1[-1], aux)
for j in range(n):
qc.x(qr1[j])
qc.h(qr1[j])
def input_state(qc, qr1, qr2, n=3):
for j in range(n):
qc.h(qr1[j])
qc.x(qr2)
qc.h(qr2)
qc.barrier()
# Make a quantum program for the n-bit Grover search.
n = 4
expression = [[1, 2, 3], [-1, 3, 4], [1,2,-4], [-2,3,-4], [-2,-3,4]]
# n = 3
# expression = [[1, 2, -3], [-1, -2, -3], [-1, 2, 3]]
num_run = 4
grovers=[]
for num_grover in range(1,num_run+1):
var = QuantumRegister(n)
res = QuantumRegister(1)
aux = QuantumRegister(2*len(expression)-2)
ans = ClassicalRegister(n)
grover = QuantumCircuit()
grover.add_register(var)
grover.add_register(res)
grover.add_register(aux)
grover.add_register(ans)
input_state(grover, var, res, n)
for _ in range(num_grover):
threeSAT_oracle(grover, var, res, aux, n, expression)
# exactly1_threeSAT_oracle(grover, var, res, aux, n, expression)
grover.barrier()
reflect_around_psi(grover, var, aux, n)
grover.barrier()
for j in range(n):
grover.measure(var[j], ans[j])
grovers.append(grover)
grovers[0].draw(output='mpl')
TOKEN = ''
provider = IBMProvider(token=TOKEN)
# display current supported backends
# print(provider.backends())
# get IBM's simulator backend
backend = provider.get_backend('ibmq_qasm_simulator')
results=[]
histos=[]
for grover in grovers:
# Execute circuit
job = execute(grover, backend=backend)
result = job.result()
counts = result.get_counts(grover)
results.append(result)
histos.append(plot_histogram(counts))
len(histos)
histos[0]
histos[1]
histos[2]
histos[3]
histos[4]
|
https://github.com/JayRGopal/Quantum-Error-Correction
|
JayRGopal
|
from qiskit import *
from qiskit.tools.monitor import job_monitor
from qiskit.providers.ibmq import least_busy
import random
from oracle_generation import validate_oracle
def run_on_simulator(circuit, expected):
simulator = Aer.get_backend('qasm_simulator')
COUNT = 1024
results = execute(circuit, backend = simulator, shots=COUNT).result()
validate_oracle(results,expected,COUNT)
return results
def run_on_QC(circuits, secrets, qubit_cnt, ibm_computer = ""):
COUNT = 10000
if not account_loaded:
load_account()
provider = IBMQ.get_provider(hub = 'ibm-q')
# print(provider.backends())
small_devices = provider.backends(filters=lambda x: x.configuration().n_qubits == qubit_cnt
and not x.configuration().simulator)
device = least_busy(small_devices)
if ibm_computer != "":
device = provider.get_backend(ibm_computer)
current_jobs = device.active_jobs()
job_cnt = len(current_jobs)
# print(job_cnt)
# print(device.remaining_jobs_count())
print("running %d jobs..."%(len(circuits)))
if (len(circuits) > device.remaining_jobs_count()):
print("Too many jobs to handle (limit of %d)... Getting status of older jobs"%(device.remaining_jobs_count()))
print("%d of the inputted circuits will not be run until older jobs are finished"%(len(circuits) - device.remaining_jobs_count()))
while len(circuits) > 0:
# load up to limit of jobs
if (device.remaining_jobs_count() == 0): break
circuit = circuits.pop(0)
secret_key = secrets.pop(0)
# print(secret_key)
cur_job = execute(circuit,backend = device,shots = COUNT)
cur_job.update_tags(replacement_tags=[secret_key])
job_cnt+=1
current_jobs = device.active_jobs()
current_jobs.reverse()
res = []
for i in range(job_cnt):
print("JOB %d"%(i))
cur_job = current_jobs[i]
job_monitor(cur_job)
results = cur_job
res.append(results)
if len(circuits) > 0:
circuit = circuits.pop(0)
secret_key = secrets.pop(0)
extra_job = execute(circuit,backend = device,shots = COUNT)
extra_job.update_tags(replacement_tags=[secret_key])
current_jobs.append(extra_job)
job_cnt+=1
return res
|
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.
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
# Since the import is nearly entirely delegated to an external package, most of the testing is done
# there. Here we need to test our wrapping behaviour for base functionality and exceptions. We
# don't want to get into a situation where updates to `qiskit_qasm3_import` breaks Terra's test
# suite due to too specific tests on the Terra side.
import os
import tempfile
import unittest
from qiskit import qasm3
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.test import QiskitTestCase
from qiskit.utils import optionals
class TestQASM3Import(QiskitTestCase):
@unittest.skipUnless(
optionals.HAS_QASM3_IMPORT, "need qiskit-qasm3-import for OpenQASM 3 imports"
)
def test_import_errors_converted(self):
with self.assertRaises(qasm3.QASM3ImporterError):
qasm3.loads("OPENQASM 3.0; qubit[2.5] q;")
@unittest.skipUnless(
optionals.HAS_QASM3_IMPORT, "need qiskit-qasm3-import for OpenQASM 3 imports"
)
def test_loads_can_succeed(self):
program = """
OPENQASM 3.0;
include "stdgates.inc";
qubit[2] qr;
bit[2] cr;
h qr[0];
cx qr[0], qr[1];
cr[0] = measure qr[0];
cr[1] = measure qr[1];
"""
parsed = qasm3.loads(program)
expected = QuantumCircuit(QuantumRegister(2, "qr"), ClassicalRegister(2, "cr"))
expected.h(0)
expected.cx(0, 1)
expected.measure(0, 0)
expected.measure(1, 1)
self.assertEqual(parsed, expected)
@unittest.skipUnless(
optionals.HAS_QASM3_IMPORT, "need qiskit-qasm3-import for OpenQASM 3 imports"
)
def test_load_can_succeed(self):
program = """
OPENQASM 3.0;
include "stdgates.inc";
qubit[2] qr;
bit[2] cr;
h qr[0];
cx qr[0], qr[1];
cr[0] = measure qr[0];
cr[1] = measure qr[1];
"""
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = os.path.join(tmp_dir, "bell.qasm")
with open(tmp_path, "w") as fptr:
fptr.write(program)
parsed = qasm3.load(tmp_path)
expected = QuantumCircuit(QuantumRegister(2, "qr"), ClassicalRegister(2, "cr"))
expected.h(0)
expected.cx(0, 1)
expected.measure(0, 0)
expected.measure(1, 1)
self.assertEqual(parsed, expected)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This is a implementation of the quantum teleportation algorithm
'''
from qiskit import *
from qiskit.visualization import plot_histogram
import os, shutil, numpy
from matplotlib.pyplot import plot, draw, show
LaTex_folder_Quantum_Teleportation = str(os.getcwd())+'/Latex_quantum_gates/Quantum_Teleportation/'
if not os.path.exists(LaTex_folder_Quantum_Teleportation):
os.makedirs(LaTex_folder_Quantum_Teleportation)
else:
shutil.rmtree(LaTex_folder_Quantum_Teleportation)
os.makedirs(LaTex_folder_Quantum_Teleportation)
qc = QuantumCircuit(3,3)
## prepare the state to be teleported
phi = 0*numpy.pi
theta= 0.5*numpy.pi
lam = 0*numpy.pi
qc.u(phi=phi, theta=theta,lam=lam,qubit=0)
## teleport the state
qc.barrier()
qc.h(1)
qc.cx(1,2)
qc.cz(0,1)
qc.h(0)
qc.h(1)
qc.barrier()
qc.measure([0,1],[0,1])
qc.barrier()
qc.x(2).c_if(0,1)
qc.z(2).c_if(1,1)
qc.h(2)
qc.measure(2,2)
LaTex_code = qc.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'quantum_teleportation.tex'
with open(LaTex_folder_Quantum_Teleportation+f_name, 'w') as f:
f.write(LaTex_code)
# simulation
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend=simulator, shots=100000).result()
counts = {'0':0,
'1': 0}
print(result.get_counts().keys())
for key, value in result.get_counts().items():
if(key[0] == '0'):
counts['0'] += value
else:
counts['1'] += value
print(counts)
plt = plot_histogram(counts)
draw()
show(block=True)
|
https://github.com/Qottmann/Quantum-anomaly-detection
|
Qottmann
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Utils for using with Qiskit unit tests."""
import logging
import os
import unittest
from enum import Enum
from qiskit import __path__ as qiskit_path
class Path(Enum):
"""Helper with paths commonly used during the tests."""
# Main SDK path: qiskit/
SDK = qiskit_path[0]
# test.python path: qiskit/test/python/
TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python'))
# Examples path: examples/
EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples'))
# Schemas path: qiskit/schemas
SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas'))
# VCR cassettes path: qiskit/test/cassettes/
CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes'))
# Sample QASMs path: qiskit/test/python/qasm
QASMS = os.path.normpath(os.path.join(TEST, 'qasm'))
def setup_test_logging(logger, log_level, filename):
"""Set logging to file and stdout for a logger.
Args:
logger (Logger): logger object to be updated.
log_level (str): logging level.
filename (str): name of the output file.
"""
# Set up formatter.
log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
' %(message)s'.format(logger.name))
formatter = logging.Formatter(log_fmt)
# Set up the file handler.
file_handler = logging.FileHandler(filename)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Set the logging level from the environment variable, defaulting
# to INFO if it is not a valid level.
level = logging._nameToLevel.get(log_level, logging.INFO)
logger.setLevel(level)
class _AssertNoLogsContext(unittest.case._AssertLogsContext):
"""A context manager used to implement TestCase.assertNoLogs()."""
# pylint: disable=inconsistent-return-statements
def __exit__(self, exc_type, exc_value, tb):
"""
This is a modified version of TestCase._AssertLogsContext.__exit__(...)
"""
self.logger.handlers = self.old_handlers
self.logger.propagate = self.old_propagate
self.logger.setLevel(self.old_level)
if exc_type is not None:
# let unexpected exceptions pass through
return False
if self.watcher.records:
msg = 'logs of level {} or higher triggered on {}:\n'.format(
logging.getLevelName(self.level), self.logger.name)
for record in self.watcher.records:
msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname,
record.lineno,
record.getMessage())
self._raiseFailure(msg)
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
print(qiskit.__version__)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
circuit = QuantumCircuit(3,3)
circuit
# qiskit.__dir__()
circuit.draw(output='mpl')
circuit.x(0)
circuit.barrier()
circuit.draw(output='mpl')
circuit.h(1)
circuit.cx(1,2)
circuit.draw(output='mpl')
circuit.barrier()
circuit.cx(0,1)
circuit.h(0)
circuit.draw(output='mpl')
circuit.barrier()
circuit.measure([0,1],[0,1])
circuit.draw(output='mpl')
circuit.barrier()
circuit.cx(1,2)
circuit.cx(0,2)
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend=simulator,shots=1024)
result = job.result()
counts=result.get_counts()
print(counts)
plot_histogram(counts)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test QASM3 exporter."""
# We can't really help how long the lines output by the exporter are in some cases.
# pylint: disable=line-too-long
from io import StringIO
from math import pi
import re
import unittest
from ddt import ddt, data
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile
from qiskit.circuit import Parameter, Qubit, Clbit, Instruction, Gate, Delay, Barrier
from qiskit.circuit.classical import expr
from qiskit.circuit.controlflow import CASE_DEFAULT
from qiskit.test import QiskitTestCase
from qiskit.qasm3 import Exporter, dumps, dump, QASM3ExporterError, ExperimentalFeatures
from qiskit.qasm3.exporter import QASM3Builder
from qiskit.qasm3.printer import BasicPrinter
# Tests marked with this decorator should be restored after gate definition with parameters is fixed
# properly, and the dummy tests after them should be deleted. See gh-7335.
requires_fixed_parameterisation = unittest.expectedFailure
class TestQASM3Functions(QiskitTestCase):
"""QASM3 module - high level functions"""
def setUp(self):
self.circuit = QuantumCircuit(2)
self.circuit.u(2 * pi, 3 * pi, -5 * pi, 0)
self.expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"qubit[2] q;",
"U(2*pi, 3*pi, -5*pi) q[0];",
"",
]
)
super().setUp()
def test_dumps(self):
"""Test dumps."""
result = dumps(self.circuit)
self.assertEqual(result, self.expected_qasm)
def test_dump(self):
"""Test dump into an IO stream."""
io = StringIO()
dump(self.circuit, io)
result = io.getvalue()
self.assertEqual(result, self.expected_qasm)
@ddt
class TestCircuitQASM3(QiskitTestCase):
"""QASM3 exporter."""
maxDiff = 1_000_000
@classmethod
def setUpClass(cls):
# These regexes are not perfect by any means, but sufficient for simple tests on controlled
# input circuits. They can allow false negatives (in which case, update the regex), but to
# be useful for the tests must _never_ have false positive matches. We use an explicit
# space (`\s`) or semicolon rather than the end-of-word `\b` because we want to ensure that
# the exporter isn't putting out invalid characters as part of the identifiers.
cls.register_regex = re.compile(
r"^\s*(let|(qu)?bit(\[\d+\])?)\s+(?P<name>\w+)[\s;]", re.U | re.M
)
scalar_type_names = {
"angle",
"duration",
"float",
"int",
"stretch",
"uint",
}
cls.scalar_parameter_regex = re.compile(
r"^\s*((input|output|const)\s+)?" # Modifier
rf"({'|'.join(scalar_type_names)})\s*(\[[^\]]+\])?\s+" # Type name and designator
r"(?P<name>\w+)[\s;]", # Parameter name
re.U | re.M,
)
super().setUpClass()
def test_regs_conds_qasm(self):
"""Test with registers and conditionals."""
qr1 = QuantumRegister(1, "qr1")
qr2 = QuantumRegister(2, "qr2")
cr = ClassicalRegister(3, "cr")
qc = QuantumCircuit(qr1, qr2, cr)
qc.measure(qr1[0], cr[0])
qc.measure(qr2[0], cr[1])
qc.measure(qr2[1], cr[2])
qc.x(qr2[1]).c_if(cr, 0)
qc.y(qr1[0]).c_if(cr, 1)
qc.z(qr1[0]).c_if(cr, 2)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[3] cr;",
"qubit[1] qr1;",
"qubit[2] qr2;",
"cr[0] = measure qr1[0];",
"cr[1] = measure qr2[0];",
"cr[2] = measure qr2[1];",
"if (cr == 0) {",
" x qr2[1];",
"}",
"if (cr == 1) {",
" y qr1[0];",
"}",
"if (cr == 2) {",
" z qr1[0];",
"}",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_registers_as_aliases(self):
"""Test that different types of alias creation and concatenation work."""
qubits = [Qubit() for _ in [None] * 10]
first_four = QuantumRegister(name="first_four", bits=qubits[:4])
last_five = QuantumRegister(name="last_five", bits=qubits[5:])
alternate = QuantumRegister(name="alternate", bits=qubits[::2])
sporadic = QuantumRegister(name="sporadic", bits=[qubits[4], qubits[2], qubits[9]])
qc = QuantumCircuit(qubits, first_four, last_five, alternate, sporadic)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"qubit _qubit0;",
"qubit _qubit1;",
"qubit _qubit2;",
"qubit _qubit3;",
"qubit _qubit4;",
"qubit _qubit5;",
"qubit _qubit6;",
"qubit _qubit7;",
"qubit _qubit8;",
"qubit _qubit9;",
"let first_four = {_qubit0, _qubit1, _qubit2, _qubit3};",
"let last_five = {_qubit5, _qubit6, _qubit7, _qubit8, _qubit9};",
"let alternate = {first_four[0], first_four[2], _qubit4, last_five[1], last_five[3]};",
"let sporadic = {alternate[2], alternate[1], last_five[4]};",
"",
]
)
self.assertEqual(Exporter(allow_aliasing=True).dumps(qc), expected_qasm)
def test_composite_circuit(self):
"""Test with a composite circuit instruction and barriers"""
composite_circ_qreg = QuantumRegister(2)
composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ")
composite_circ.h(0)
composite_circ.x(1)
composite_circ.cx(0, 1)
composite_circ_instr = composite_circ.to_gate()
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.cx(0, 1)
qc.barrier()
qc.append(composite_circ_instr, [0, 1])
qc.measure([0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate composite_circ _gate_q_0, _gate_q_1 {",
" h _gate_q_0;",
" x _gate_q_1;",
" cx _gate_q_0, _gate_q_1;",
"}",
"bit[2] cr;",
"qubit[2] qr;",
"h qr[0];",
"cx qr[0], qr[1];",
"barrier qr[0], qr[1];",
"composite_circ qr[0], qr[1];",
"cr[0] = measure qr[0];",
"cr[1] = measure qr[1];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_custom_gate(self):
"""Test custom gates (via to_gate)."""
composite_circ_qreg = QuantumRegister(2)
composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ")
composite_circ.h(0)
composite_circ.x(1)
composite_circ.cx(0, 1)
composite_circ_instr = composite_circ.to_gate()
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.cx(0, 1)
qc.barrier()
qc.append(composite_circ_instr, [0, 1])
qc.measure([0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate composite_circ _gate_q_0, _gate_q_1 {",
" h _gate_q_0;",
" x _gate_q_1;",
" cx _gate_q_0, _gate_q_1;",
"}",
"bit[2] cr;",
"qubit[2] qr;",
"h qr[0];",
"cx qr[0], qr[1];",
"barrier qr[0], qr[1];",
"composite_circ qr[0], qr[1];",
"cr[0] = measure qr[0];",
"cr[1] = measure qr[1];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_same_composite_circuits(self):
"""Test when a composite circuit is added to the circuit multiple times."""
composite_circ_qreg = QuantumRegister(2)
composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ")
composite_circ.h(0)
composite_circ.x(1)
composite_circ.cx(0, 1)
composite_circ_instr = composite_circ.to_gate()
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.cx(0, 1)
qc.barrier()
qc.append(composite_circ_instr, [0, 1])
qc.append(composite_circ_instr, [0, 1])
qc.measure([0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate composite_circ _gate_q_0, _gate_q_1 {",
" h _gate_q_0;",
" x _gate_q_1;",
" cx _gate_q_0, _gate_q_1;",
"}",
"bit[2] cr;",
"qubit[2] qr;",
"h qr[0];",
"cx qr[0], qr[1];",
"barrier qr[0], qr[1];",
"composite_circ qr[0], qr[1];",
"composite_circ qr[0], qr[1];",
"cr[0] = measure qr[0];",
"cr[1] = measure qr[1];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_composite_circuits_with_same_name(self):
"""Test when multiple composite circuit instructions same name and different
implementation."""
my_gate = QuantumCircuit(1, name="my_gate")
my_gate.h(0)
my_gate_inst1 = my_gate.to_gate()
my_gate = QuantumCircuit(1, name="my_gate")
my_gate.x(0)
my_gate_inst2 = my_gate.to_gate()
my_gate = QuantumCircuit(1, name="my_gate")
my_gate.x(0)
my_gate_inst3 = my_gate.to_gate()
qr = QuantumRegister(1, name="qr")
circuit = QuantumCircuit(qr, name="circuit")
circuit.append(my_gate_inst1, [qr[0]])
circuit.append(my_gate_inst2, [qr[0]])
my_gate_inst2_id = id(circuit.data[-1].operation)
circuit.append(my_gate_inst3, [qr[0]])
my_gate_inst3_id = id(circuit.data[-1].operation)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate my_gate _gate_q_0 {",
" h _gate_q_0;",
"}",
f"gate my_gate_{my_gate_inst2_id} _gate_q_0 {{",
" x _gate_q_0;",
"}",
f"gate my_gate_{my_gate_inst3_id} _gate_q_0 {{",
" x _gate_q_0;",
"}",
"qubit[1] qr;",
"my_gate qr[0];",
f"my_gate_{my_gate_inst2_id} qr[0];",
f"my_gate_{my_gate_inst3_id} qr[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
def test_pi_disable_constants_false(self):
"""Test pi constant (disable_constants=False)"""
circuit = QuantumCircuit(2)
circuit.u(2 * pi, 3 * pi, -5 * pi, 0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"qubit[2] q;",
"U(2*pi, 3*pi, -5*pi) q[0];",
"",
]
)
self.assertEqual(Exporter(disable_constants=False).dumps(circuit), expected_qasm)
def test_pi_disable_constants_true(self):
"""Test pi constant (disable_constants=True)"""
circuit = QuantumCircuit(2)
circuit.u(2 * pi, 3 * pi, -5 * pi, 0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"qubit[2] q;",
"U(6.283185307179586, 9.42477796076938, -15.707963267948966) q[0];",
"",
]
)
self.assertEqual(Exporter(disable_constants=True).dumps(circuit), expected_qasm)
def test_custom_gate_with_unbound_parameter(self):
"""Test custom gate with unbound parameter."""
parameter_a = Parameter("a")
custom = QuantumCircuit(1, name="custom")
custom.rx(parameter_a, 0)
circuit = QuantumCircuit(1)
circuit.append(custom.to_gate(), [0])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"input float[64] a;",
"gate custom(a) _gate_q_0 {",
" rx(a) _gate_q_0;",
"}",
"qubit[1] q;",
"custom(a) q[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
def test_custom_gate_with_bound_parameter(self):
"""Test custom gate with bound parameter."""
parameter_a = Parameter("a")
custom = QuantumCircuit(1)
custom.rx(parameter_a, 0)
custom_gate = custom.bind_parameters({parameter_a: 0.5}).to_gate()
custom_gate.name = "custom"
circuit = QuantumCircuit(1)
circuit.append(custom_gate, [0])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate custom _gate_q_0 {",
" rx(0.5) _gate_q_0;",
"}",
"qubit[1] q;",
"custom q[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
@requires_fixed_parameterisation
def test_custom_gate_with_params_bound_main_call(self):
"""Custom gate with unbound parameters that are bound in the main circuit"""
parameter0 = Parameter("p0")
parameter1 = Parameter("p1")
custom = QuantumCircuit(2, name="custom")
custom.rz(parameter0, 0)
custom.rz(parameter1 / 2, 1)
qr_all_qubits = QuantumRegister(3, "q")
qr_r = QuantumRegister(3, "r")
circuit = QuantumCircuit(qr_all_qubits, qr_r)
circuit.append(custom.to_gate(), [qr_all_qubits[0], qr_r[0]])
circuit.assign_parameters({parameter0: pi, parameter1: pi / 2}, inplace=True)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate custom(_gate_p_0, _gate_p_0) _gate_q_0, _gate_q_1 {",
" rz(pi) _gate_q_0;",
" rz(pi/4) _gate_q_1;",
"}",
"qubit[3] q;",
"qubit[3] r;",
"custom(pi, pi/2) q[0], r[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
def test_reused_custom_parameter(self):
"""Test reused custom gate with parameter."""
parameter_a = Parameter("a")
custom = QuantumCircuit(1)
custom.rx(parameter_a, 0)
circuit = QuantumCircuit(1)
circuit.append(custom.bind_parameters({parameter_a: 0.5}).to_gate(), [0])
circuit.append(custom.bind_parameters({parameter_a: 1}).to_gate(), [0])
circuit_name_0 = circuit.data[0].operation.definition.name
circuit_name_1 = circuit.data[1].operation.definition.name
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"gate {circuit_name_0} _gate_q_0 {{",
" rx(0.5) _gate_q_0;",
"}",
f"gate {circuit_name_1} _gate_q_0 {{",
" rx(1.0) _gate_q_0;",
"}",
"qubit[1] q;",
f"{circuit_name_0} q[0];",
f"{circuit_name_1} q[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
def test_unbound_circuit(self):
"""Test with unbound parameters (turning them into inputs)."""
qc = QuantumCircuit(1)
theta = Parameter("θ")
qc.rz(theta, 0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"input float[64] θ;",
"qubit[1] q;",
"rz(θ) q[0];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_unknown_parameterized_gate_called_multiple_times(self):
"""Test that a parameterised gate is called correctly if the first instance of it is
generic."""
x, y = Parameter("x"), Parameter("y")
qc = QuantumCircuit(2)
qc.rzx(x, 0, 1)
qc.rzx(y, 0, 1)
qc.rzx(0.5, 0, 1)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"input float[64] x;",
"input float[64] y;",
"gate rzx(x) _gate_q_0, _gate_q_1 {",
" h _gate_q_1;",
" cx _gate_q_0, _gate_q_1;",
" rz(x) _gate_q_1;",
" cx _gate_q_0, _gate_q_1;",
" h _gate_q_1;",
"}",
"qubit[2] q;",
"rzx(x) q[0], q[1];",
"rzx(y) q[0], q[1];",
"rzx(0.5) q[0], q[1];",
"",
]
)
# Set the includes and basis gates to ensure that this gate is unknown.
exporter = Exporter(includes=[], basis_gates=("rz", "h", "cx"))
self.assertEqual(exporter.dumps(qc), expected_qasm)
def test_gate_qasm_with_ctrl_state(self):
"""Test with open controlled gate that has ctrl_state"""
qc = QuantumCircuit(2)
qc.ch(0, 1, ctrl_state=0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate ch_o0 _gate_q_0, _gate_q_1 {",
" x _gate_q_0;",
" ch _gate_q_0, _gate_q_1;",
" x _gate_q_0;",
"}",
"qubit[2] q;",
"ch_o0 q[0], q[1];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_custom_gate_collision_with_stdlib(self):
"""Test a custom gate with name collision with the standard library."""
custom = QuantumCircuit(2, name="cx")
custom.cx(0, 1)
custom_gate = custom.to_gate()
qc = QuantumCircuit(2)
qc.append(custom_gate, [0, 1])
custom_gate_id = id(qc.data[-1].operation)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"gate cx_{custom_gate_id} _gate_q_0, _gate_q_1 {{",
" cx _gate_q_0, _gate_q_1;",
"}",
"qubit[2] q;",
f"cx_{custom_gate_id} q[0], q[1];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
@requires_fixed_parameterisation
def test_no_include(self):
"""Test explicit gate declaration (no include)"""
q = QuantumRegister(2, "q")
circuit = QuantumCircuit(q)
circuit.rz(pi / 2, 0)
circuit.sx(0)
circuit.cx(0, 1)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {",
" U(0, 0, pi/2) _gate_q_0;",
"}",
"gate u1(_gate_p_0) _gate_q_0 {",
" u3(0, 0, pi/2) _gate_q_0;",
"}",
"gate rz(_gate_p_0) _gate_q_0 {",
" u1(pi/2) _gate_q_0;",
"}",
"gate sdg _gate_q_0 {",
" u1(-pi/2) _gate_q_0;",
"}",
"gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {",
" u3(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
" u2(0, pi) _gate_q_0;",
"}",
"gate sx _gate_q_0 {",
" sdg _gate_q_0;",
" h _gate_q_0;",
" sdg _gate_q_0;",
"}",
"gate cx c, t {",
" ctrl @ U(pi, 0, pi) c, t;",
"}",
"qubit[2] q;",
"rz(pi/2) q[0];",
"sx q[0];",
"cx q[0], q[1];",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(circuit), expected_qasm)
@requires_fixed_parameterisation
def test_teleportation(self):
"""Teleportation with physical qubits"""
qc = QuantumCircuit(3, 2)
qc.h(1)
qc.cx(1, 2)
qc.barrier()
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.barrier()
qc.x(2).c_if(qc.clbits[1], 1)
qc.z(2).c_if(qc.clbits[0], 1)
transpiled = transpile(qc, initial_layout=[0, 1, 2])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {",
" U(pi/2, 0, pi) _gate_q_0;",
"}",
"gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {",
" u3(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
" u2(0, pi) _gate_q_0;",
"}",
"gate cx c, t {",
" ctrl @ U(pi, 0, pi) c, t;",
"}",
"gate x _gate_q_0 {",
" u3(pi, 0, pi) _gate_q_0;",
"}",
"gate u1(_gate_p_0) _gate_q_0 {",
" u3(0, 0, pi) _gate_q_0;",
"}",
"gate z _gate_q_0 {",
" u1(pi) _gate_q_0;",
"}",
"bit[2] c;",
"h $1;",
"cx $1, $2;",
"barrier $0, $1, $2;",
"cx $0, $1;",
"h $0;",
"barrier $0, $1, $2;",
"c[0] = measure $0;",
"c[1] = measure $1;",
"barrier $0, $1, $2;",
"if (c[1]) {",
" x $2;",
"}",
"if (c[0]) {",
" z $2;",
"}",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(transpiled), expected_qasm)
@requires_fixed_parameterisation
def test_basis_gates(self):
"""Teleportation with physical qubits"""
qc = QuantumCircuit(3, 2)
qc.h(1)
qc.cx(1, 2)
qc.barrier()
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.barrier()
qc.x(2).c_if(qc.clbits[1], 1)
qc.z(2).c_if(qc.clbits[0], 1)
transpiled = transpile(qc, initial_layout=[0, 1, 2])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {",
" U(pi/2, 0, pi) _gate_q_0;",
"}",
"gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {",
" u3(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
" u2(0, pi) _gate_q_0;",
"}",
"gate x _gate_q_0 {",
" u3(pi, 0, pi) _gate_q_0;",
"}",
"bit[2] c;",
"h $1;",
"cx $1, $2;",
"barrier $0, $1, $2;",
"cx $0, $1;",
"h $0;",
"barrier $0, $1, $2;",
"c[0] = measure $0;",
"c[1] = measure $1;",
"barrier $0, $1, $2;",
"if (c[1]) {",
" x $2;",
"}",
"if (c[0]) {",
" z $2;",
"}",
"",
]
)
self.assertEqual(
Exporter(includes=[], basis_gates=["cx", "z", "U"]).dumps(transpiled),
expected_qasm,
)
def test_opaque_instruction_in_basis_gates(self):
"""Test that an instruction that is set in the basis gates is output verbatim with no
definition."""
qc = QuantumCircuit(1)
qc.x(0)
qc.append(Gate("my_gate", 1, []), [0], [])
basis_gates = ["my_gate", "x"]
transpiled = transpile(qc, initial_layout=[0])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"x $0;",
"my_gate $0;",
"",
]
)
self.assertEqual(
Exporter(includes=[], basis_gates=basis_gates).dumps(transpiled), expected_qasm
)
def test_reset_statement(self):
"""Test that a reset statement gets output into valid QASM 3. This includes tests of reset
operations on single qubits and in nested scopes."""
qreg = QuantumRegister(2, "qr")
qc = QuantumCircuit(qreg)
qc.reset(0)
qc.reset([0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"qubit[2] qr;",
"reset qr[0];",
"reset qr[0];",
"reset qr[1];",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(qc), expected_qasm)
def test_delay_statement(self):
"""Test that delay operations get output into valid QASM 3."""
qreg = QuantumRegister(2, "qr")
qc = QuantumCircuit(qreg)
qc.delay(100, qreg[0], unit="ms")
qc.delay(2, qreg[1], unit="ps") # "ps" is not a valid unit in OQ3, so we need to convert.
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"qubit[2] qr;",
"delay[100ms] qr[0];",
"delay[2000ns] qr[1];",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(qc), expected_qasm)
def test_loose_qubits(self):
"""Test that qubits that are not in any register can be used without issue."""
bits = [Qubit(), Qubit()]
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(bits, qr, cr)
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit _qubit0;",
"qubit _qubit1;",
"qubit[2] qr;",
"h _qubit0;",
"h _qubit1;",
"h qr[0];",
"h qr[1];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_loose_clbits(self):
"""Test that clbits that are not in any register can be used without issue."""
qreg = QuantumRegister(1, name="qr")
bits = [Clbit() for _ in [None] * 7]
cr1 = ClassicalRegister(name="cr1", bits=bits[1:3])
cr2 = ClassicalRegister(name="cr2", bits=bits[4:6])
qc = QuantumCircuit(bits, qreg, cr1, cr2)
qc.measure(0, 0)
qc.measure(0, 1)
qc.measure(0, 2)
qc.measure(0, 3)
qc.measure(0, 4)
qc.measure(0, 5)
qc.measure(0, 6)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit _bit0;",
"bit _bit3;",
"bit _bit6;",
"bit[2] cr1;",
"bit[2] cr2;",
"qubit[1] qr;",
"_bit0 = measure qr[0];",
"cr1[0] = measure qr[0];",
"cr1[1] = measure qr[0];",
"_bit3 = measure qr[0];",
"cr2[0] = measure qr[0];",
"cr2[1] = measure qr[0];",
"_bit6 = measure qr[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_classical_register_aliasing(self):
"""Test that clbits that are not in any register can be used without issue."""
qreg = QuantumRegister(1, name="qr")
bits = [Clbit() for _ in [None] * 7]
cr1 = ClassicalRegister(name="cr1", bits=bits[1:3])
cr2 = ClassicalRegister(name="cr2", bits=bits[4:6])
# cr3 overlaps cr2, but this should be allowed in this alias form.
cr3 = ClassicalRegister(name="cr3", bits=bits[5:])
qc = QuantumCircuit(bits, qreg, cr1, cr2, cr3)
qc.measure(0, 0)
qc.measure(0, 1)
qc.measure(0, 2)
qc.measure(0, 3)
qc.measure(0, 4)
qc.measure(0, 5)
qc.measure(0, 6)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit _bit0;",
"bit _bit1;",
"bit _bit2;",
"bit _bit3;",
"bit _bit4;",
"bit _bit5;",
"bit _bit6;",
"let cr1 = {_bit1, _bit2};",
"let cr2 = {_bit4, _bit5};",
"let cr3 = {cr2[1], _bit6};",
"qubit[1] qr;",
"_bit0 = measure qr[0];",
"cr1[0] = measure qr[0];",
"cr1[1] = measure qr[0];",
"_bit3 = measure qr[0];",
"cr2[0] = measure qr[0];",
"cr3[0] = measure qr[0];",
"cr3[1] = measure qr[0];",
"",
]
)
self.assertEqual(dumps(qc, allow_aliasing=True), expected_qasm)
def test_old_alias_classical_registers_option(self):
"""Test that the ``alias_classical_registers`` option still functions during its changeover
period."""
qreg = QuantumRegister(1, name="qr")
bits = [Clbit() for _ in [None] * 7]
cr1 = ClassicalRegister(name="cr1", bits=bits[1:3])
cr2 = ClassicalRegister(name="cr2", bits=bits[4:6])
# cr3 overlaps cr2, but this should be allowed in this alias form.
cr3 = ClassicalRegister(name="cr3", bits=bits[5:])
qc = QuantumCircuit(bits, qreg, cr1, cr2, cr3)
qc.measure(0, 0)
qc.measure(0, 1)
qc.measure(0, 2)
qc.measure(0, 3)
qc.measure(0, 4)
qc.measure(0, 5)
qc.measure(0, 6)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit _bit0;",
"bit _bit1;",
"bit _bit2;",
"bit _bit3;",
"bit _bit4;",
"bit _bit5;",
"bit _bit6;",
"let cr1 = {_bit1, _bit2};",
"let cr2 = {_bit4, _bit5};",
"let cr3 = {cr2[1], _bit6};",
"qubit[1] qr;",
"_bit0 = measure qr[0];",
"cr1[0] = measure qr[0];",
"cr1[1] = measure qr[0];",
"_bit3 = measure qr[0];",
"cr2[0] = measure qr[0];",
"cr3[0] = measure qr[0];",
"cr3[1] = measure qr[0];",
"",
]
)
self.assertEqual(dumps(qc, alias_classical_registers=True), expected_qasm)
def test_simple_for_loop(self):
"""Test that a simple for loop outputs the expected result."""
parameter = Parameter("x")
loop_body = QuantumCircuit(1)
loop_body.rx(parameter, 0)
loop_body.break_loop()
loop_body.continue_loop()
qc = QuantumCircuit(2)
qc.for_loop([0, 3, 4], parameter, loop_body, [1], [])
qc.x(0)
qr_name = qc.qregs[0].name
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"qubit[2] {qr_name};",
f"for {parameter.name} in {{0, 3, 4}} {{",
f" rx({parameter.name}) {qr_name}[1];",
" break;",
" continue;",
"}",
f"x {qr_name}[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_nested_for_loop(self):
"""Test that a for loop nested inside another outputs the expected result."""
inner_parameter = Parameter("x")
outer_parameter = Parameter("y")
inner_body = QuantumCircuit(2)
inner_body.rz(inner_parameter, 0)
inner_body.rz(outer_parameter, 1)
inner_body.break_loop()
outer_body = QuantumCircuit(2)
outer_body.h(0)
outer_body.rz(outer_parameter, 1)
# Note we reverse the order of the bits here to test that this is traced.
outer_body.for_loop(range(1, 5, 2), inner_parameter, inner_body, [1, 0], [])
outer_body.continue_loop()
qc = QuantumCircuit(2)
qc.for_loop(range(4), outer_parameter, outer_body, [0, 1], [])
qc.x(0)
qr_name = qc.qregs[0].name
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"qubit[2] {qr_name};",
f"for {outer_parameter.name} in [0:3] {{",
f" h {qr_name}[0];",
f" rz({outer_parameter.name}) {qr_name}[1];",
f" for {inner_parameter.name} in [1:2:4] {{",
# Note the reversed bit order.
f" rz({inner_parameter.name}) {qr_name}[1];",
f" rz({outer_parameter.name}) {qr_name}[0];",
" break;",
" }",
" continue;",
"}",
f"x {qr_name}[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_regular_parameter_in_nested_for_loop(self):
"""Test that a for loop nested inside another outputs the expected result, including
defining parameters that are used in nested loop scopes."""
inner_parameter = Parameter("x")
outer_parameter = Parameter("y")
regular_parameter = Parameter("t")
inner_body = QuantumCircuit(2)
inner_body.h(0)
inner_body.rx(regular_parameter, 1)
inner_body.break_loop()
outer_body = QuantumCircuit(2)
outer_body.h(0)
outer_body.h(1)
# Note we reverse the order of the bits here to test that this is traced.
outer_body.for_loop(range(1, 5, 2), inner_parameter, inner_body, [1, 0], [])
outer_body.continue_loop()
qc = QuantumCircuit(2)
qc.for_loop(range(4), outer_parameter, outer_body, [0, 1], [])
qc.x(0)
qr_name = qc.qregs[0].name
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
# This next line will be missing until gh-7280 is fixed.
f"input float[64] {regular_parameter.name};",
f"qubit[2] {qr_name};",
f"for {outer_parameter.name} in [0:3] {{",
f" h {qr_name}[0];",
f" h {qr_name}[1];",
f" for {inner_parameter.name} in [1:2:4] {{",
# Note the reversed bit order.
f" h {qr_name}[1];",
f" rx({regular_parameter.name}) {qr_name}[0];",
" break;",
" }",
" continue;",
"}",
f"x {qr_name}[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_for_loop_with_no_parameter(self):
"""Test that a for loop with the parameter set to ``None`` outputs the expected result."""
loop_body = QuantumCircuit(1)
loop_body.h(0)
qc = QuantumCircuit(2)
qc.for_loop([0, 3, 4], None, loop_body, [1], [])
qr_name = qc.qregs[0].name
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"qubit[2] {qr_name};",
"for _ in {0, 3, 4} {",
f" h {qr_name}[1];",
"}",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_simple_while_loop(self):
"""Test that a simple while loop works correctly."""
loop_body = QuantumCircuit(1)
loop_body.h(0)
loop_body.break_loop()
loop_body.continue_loop()
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.while_loop((cr, 0), loop_body, [1], [])
qc.x(0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"while (cr == 0) {",
" h qr[1];",
" break;",
" continue;",
"}",
"x qr[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_nested_while_loop(self):
"""Test that a while loop nested inside another outputs the expected result."""
inner_body = QuantumCircuit(2, 2)
inner_body.measure(0, 0)
inner_body.measure(1, 1)
inner_body.break_loop()
outer_body = QuantumCircuit(2, 2)
outer_body.measure(0, 0)
outer_body.measure(1, 1)
# We reverse the order of the bits here to test this works, and test a single-bit condition.
outer_body.while_loop((outer_body.clbits[0], 0), inner_body, [1, 0], [1, 0])
outer_body.continue_loop()
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.while_loop((cr, 0), outer_body, [0, 1], [0, 1])
qc.x(0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"while (cr == 0) {",
" cr[0] = measure qr[0];",
" cr[1] = measure qr[1];",
# Note the reversed bits in the body.
" while (!cr[0]) {",
" cr[1] = measure qr[1];",
" cr[0] = measure qr[0];",
" break;",
" }",
" continue;",
"}",
"x qr[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_simple_if_statement(self):
"""Test that a simple if statement with no else works correctly."""
true_body = QuantumCircuit(1)
true_body.h(0)
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.if_test((cr, 0), true_body, [1], [])
qc.x(0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"if (cr == 0) {",
" h qr[1];",
"}",
"x qr[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_simple_if_else_statement(self):
"""Test that a simple if statement with an else branch works correctly."""
true_body = QuantumCircuit(1)
true_body.h(0)
false_body = QuantumCircuit(1)
false_body.z(0)
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.if_else((cr, 0), true_body, false_body, [1], [])
qc.x(0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"if (cr == 0) {",
" h qr[1];",
"} else {",
" z qr[1];",
"}",
"x qr[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_nested_if_else_statement(self):
"""Test that a nested if/else statement works correctly."""
inner_true_body = QuantumCircuit(2, 2)
inner_true_body.measure(0, 0)
inner_false_body = QuantumCircuit(2, 2)
inner_false_body.measure(1, 1)
outer_true_body = QuantumCircuit(2, 2)
outer_true_body.if_else(
(outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1]
)
outer_false_body = QuantumCircuit(2, 2)
# Note the flipped bits here.
outer_false_body.if_else(
(outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0]
)
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"if (cr == 0) {",
" if (!cr[0]) {",
" cr[0] = measure qr[0];",
" } else {",
" cr[1] = measure qr[1];",
" }",
"} else {",
" if (cr[0]) {",
" cr[1] = measure qr[1];",
" } else {",
" cr[0] = measure qr[0];",
" }",
"}",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_chain_else_if(self):
"""Test the basic 'else/if' chaining logic for flattening the else scope if its content is a
single if/else statement."""
inner_true_body = QuantumCircuit(2, 2)
inner_true_body.measure(0, 0)
inner_false_body = QuantumCircuit(2, 2)
inner_false_body.measure(1, 1)
outer_true_body = QuantumCircuit(2, 2)
outer_true_body.if_else(
(outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1]
)
outer_false_body = QuantumCircuit(2, 2)
# Note the flipped bits here.
outer_false_body.if_else(
(outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0]
)
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"if (cr == 0) {",
" if (!cr[0]) {",
" cr[0] = measure qr[0];",
" } else {",
" cr[1] = measure qr[1];",
" }",
"} else if (cr[0]) {",
" cr[1] = measure qr[1];",
"} else {",
" cr[0] = measure qr[0];",
"}",
"",
]
)
# This is not the default behaviour, and it's pretty buried how you'd access it.
builder = QASM3Builder(
qc,
includeslist=("stdgates.inc",),
basis_gates=("U",),
disable_constants=False,
allow_aliasing=False,
)
stream = StringIO()
BasicPrinter(stream, indent=" ", chain_else_if=True).visit(builder.build_program())
self.assertEqual(stream.getvalue(), expected_qasm)
def test_chain_else_if_does_not_chain_if_extra_instructions(self):
"""Test the basic 'else/if' chaining logic for flattening the else scope if its content is a
single if/else statement does not cause a flattening if the 'else' block is not a single
if/else."""
inner_true_body = QuantumCircuit(2, 2)
inner_true_body.measure(0, 0)
inner_false_body = QuantumCircuit(2, 2)
inner_false_body.measure(1, 1)
outer_true_body = QuantumCircuit(2, 2)
outer_true_body.if_else(
(outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1]
)
outer_false_body = QuantumCircuit(2, 2)
# Note the flipped bits here.
outer_false_body.if_else(
(outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0]
)
outer_false_body.h(0)
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"if (cr == 0) {",
" if (!cr[0]) {",
" cr[0] = measure qr[0];",
" } else {",
" cr[1] = measure qr[1];",
" }",
"} else {",
" if (cr[0]) {",
" cr[1] = measure qr[1];",
" } else {",
" cr[0] = measure qr[0];",
" }",
" h qr[0];",
"}",
"",
]
)
# This is not the default behaviour, and it's pretty buried how you'd access it.
builder = QASM3Builder(
qc,
includeslist=("stdgates.inc",),
basis_gates=("U",),
disable_constants=False,
allow_aliasing=False,
)
stream = StringIO()
BasicPrinter(stream, indent=" ", chain_else_if=True).visit(builder.build_program())
self.assertEqual(stream.getvalue(), expected_qasm)
def test_custom_gate_used_in_loop_scope(self):
"""Test that a custom gate only used within a loop scope still gets a definition at the top
level."""
parameter_a = Parameter("a")
parameter_b = Parameter("b")
custom = QuantumCircuit(1)
custom.rx(parameter_a, 0)
custom_gate = custom.bind_parameters({parameter_a: 0.5}).to_gate()
custom_gate.name = "custom"
loop_body = QuantumCircuit(1)
loop_body.append(custom_gate, [0])
qc = QuantumCircuit(1)
qc.for_loop(range(2), parameter_b, loop_body, [0], [])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate custom _gate_q_0 {",
" rx(0.5) _gate_q_0;",
"}",
"qubit[1] q;",
"for b in [0:1] {",
" custom q[0];",
"}",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_registers_have_escaped_names(self):
"""Test that both types of register are emitted with safely escaped names if they begin with
invalid names. Regression test of gh-9658."""
qc = QuantumCircuit(
QuantumRegister(2, name="q_{reg}"), ClassicalRegister(2, name="c_{reg}")
)
qc.measure([0, 1], [0, 1])
out_qasm = dumps(qc)
matches = {match_["name"] for match_ in self.register_regex.finditer(out_qasm)}
self.assertEqual(len(matches), 2, msg=f"Observed OQ3 output:\n{out_qasm}")
def test_parameters_have_escaped_names(self):
"""Test that parameters are emitted with safely escaped names if they begin with invalid
names. Regression test of gh-9658."""
qc = QuantumCircuit(1)
qc.u(Parameter("p_{0}"), 2 * Parameter("p_?0!"), 0, 0)
out_qasm = dumps(qc)
matches = {match_["name"] for match_ in self.scalar_parameter_regex.finditer(out_qasm)}
self.assertEqual(len(matches), 2, msg=f"Observed OQ3 output:\n{out_qasm}")
def test_parameter_expression_after_naming_escape(self):
"""Test that :class:`.Parameter` instances are correctly renamed when they are used with
:class:`.ParameterExpression` blocks, even if they have names that needed to be escaped."""
param = Parameter("measure") # an invalid name
qc = QuantumCircuit(1)
qc.u(2 * param, 0, 0, 0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"input float[64] _measure;",
"qubit[1] q;",
"U(2*_measure, 0, 0) q[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_parameters_and_registers_cannot_have_naming_clashes(self):
"""Test that parameters and registers are considered part of the same symbol table for the
purposes of avoiding clashes."""
qreg = QuantumRegister(1, "clash")
param = Parameter("clash")
qc = QuantumCircuit(qreg)
qc.u(param, 0, 0, 0)
out_qasm = dumps(qc)
register_name = self.register_regex.search(out_qasm)
parameter_name = self.scalar_parameter_regex.search(out_qasm)
self.assertTrue(register_name)
self.assertTrue(parameter_name)
self.assertIn("clash", register_name["name"])
self.assertIn("clash", parameter_name["name"])
self.assertNotEqual(register_name["name"], parameter_name["name"])
# Not necessarily all the reserved keywords, just a sensibly-sized subset.
@data("bit", "const", "def", "defcal", "float", "gate", "include", "int", "let", "measure")
def test_reserved_keywords_as_names_are_escaped(self, keyword):
"""Test that reserved keywords used to name registers and parameters are escaped into
another form when output, and the escaping cannot introduce new conflicts."""
with self.subTest("register"):
qreg = QuantumRegister(1, keyword)
qc = QuantumCircuit(qreg)
out_qasm = dumps(qc)
register_name = self.register_regex.search(out_qasm)
self.assertTrue(register_name, msg=f"Observed OQ3:\n{out_qasm}")
self.assertNotEqual(keyword, register_name["name"])
with self.subTest("parameter"):
qc = QuantumCircuit(1)
param = Parameter(keyword)
qc.u(param, 0, 0, 0)
out_qasm = dumps(qc)
parameter_name = self.scalar_parameter_regex.search(out_qasm)
self.assertTrue(parameter_name, msg=f"Observed OQ3:\n{out_qasm}")
self.assertNotEqual(keyword, parameter_name["name"])
def test_expr_condition(self):
"""Simple test that the conditions of `if`s and `while`s can be `Expr` nodes."""
bits = [Qubit(), Clbit()]
cr = ClassicalRegister(2, "cr")
if_body = QuantumCircuit(1)
if_body.x(0)
while_body = QuantumCircuit(1)
while_body.x(0)
qc = QuantumCircuit(bits, cr)
qc.if_test(expr.logic_not(qc.clbits[0]), if_body, [0], [])
qc.while_loop(expr.equal(cr, 3), while_body, [0], [])
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit _bit0;
bit[2] cr;
qubit _qubit0;
if (!_bit0) {
x _qubit0;
}
while (cr == 3) {
x _qubit0;
}
"""
self.assertEqual(dumps(qc), expected)
def test_expr_nested_condition(self):
"""Simple test that the conditions of `if`s and `while`s can be `Expr` nodes when nested,
and the mapping of inner bits to outer bits is correct."""
bits = [Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
inner_if_body = QuantumCircuit(1)
inner_if_body.x(0)
outer_if_body = QuantumCircuit(1, 1)
outer_if_body.if_test(expr.lift(outer_if_body.clbits[0]), inner_if_body, [0], [])
inner_while_body = QuantumCircuit(1)
inner_while_body.x(0)
outer_while_body = QuantumCircuit([Qubit()], cr)
outer_while_body.while_loop(expr.equal(expr.bit_and(cr, 3), 3), inner_while_body, [0], [])
qc = QuantumCircuit(bits, cr)
qc.if_test(expr.logic_not(qc.clbits[0]), outer_if_body, [0], [1])
qc.while_loop(expr.equal(cr, 3), outer_while_body, [0], cr)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit _bit0;
bit _bit1;
bit[2] cr;
qubit _qubit0;
if (!_bit0) {
if (_bit1) {
x _qubit0;
}
}
while (cr == 3) {
while ((cr & 3) == 3) {
x _qubit0;
}
}
"""
self.assertEqual(dumps(qc), expected)
def test_expr_associativity_left(self):
"""Test that operations that are in the expression tree in a left-associative form are
output to OQ3 correctly."""
body = QuantumCircuit()
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
cr3 = ClassicalRegister(3, "cr3")
qc = QuantumCircuit(cr1, cr2, cr3)
qc.if_test(expr.equal(expr.bit_and(expr.bit_and(cr1, cr2), cr3), 7), body.copy(), [], [])
qc.if_test(expr.equal(expr.bit_or(expr.bit_or(cr1, cr2), cr3), 7), body.copy(), [], [])
qc.if_test(expr.equal(expr.bit_xor(expr.bit_xor(cr1, cr2), cr3), 7), body.copy(), [], [])
qc.if_test(expr.logic_and(expr.logic_and(cr1[0], cr1[1]), cr1[2]), body.copy(), [], [])
qc.if_test(expr.logic_or(expr.logic_or(cr1[0], cr1[1]), cr1[2]), body.copy(), [], [])
# Note that bitwise operations have lower priority than `==` so there's extra parentheses.
# All these operators are left-associative in OQ3.
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[3] cr1;
bit[3] cr2;
bit[3] cr3;
if ((cr1 & cr2 & cr3) == 7) {
}
if ((cr1 | cr2 | cr3) == 7) {
}
if ((cr1 ^ cr2 ^ cr3) == 7) {
}
if (cr1[0] && cr1[1] && cr1[2]) {
}
if (cr1[0] || cr1[1] || cr1[2]) {
}
"""
self.assertEqual(dumps(qc), expected)
def test_expr_associativity_right(self):
"""Test that operations that are in the expression tree in a right-associative form are
output to OQ3 correctly."""
body = QuantumCircuit()
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
cr3 = ClassicalRegister(3, "cr3")
qc = QuantumCircuit(cr1, cr2, cr3)
qc.if_test(expr.equal(expr.bit_and(cr1, expr.bit_and(cr2, cr3)), 7), body.copy(), [], [])
qc.if_test(expr.equal(expr.bit_or(cr1, expr.bit_or(cr2, cr3)), 7), body.copy(), [], [])
qc.if_test(expr.equal(expr.bit_xor(cr1, expr.bit_xor(cr2, cr3)), 7), body.copy(), [], [])
qc.if_test(expr.logic_and(cr1[0], expr.logic_and(cr1[1], cr1[2])), body.copy(), [], [])
qc.if_test(expr.logic_or(cr1[0], expr.logic_or(cr1[1], cr1[2])), body.copy(), [], [])
# Note that bitwise operations have lower priority than `==` so there's extra parentheses.
# All these operators are left-associative in OQ3, so we need parentheses for them to be
# parsed correctly. Mathematically, they're all actually associative in general, so the
# order doesn't _technically_ matter.
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[3] cr1;
bit[3] cr2;
bit[3] cr3;
if ((cr1 & (cr2 & cr3)) == 7) {
}
if ((cr1 | (cr2 | cr3)) == 7) {
}
if ((cr1 ^ (cr2 ^ cr3)) == 7) {
}
if (cr1[0] && (cr1[1] && cr1[2])) {
}
if (cr1[0] || (cr1[1] || cr1[2])) {
}
"""
self.assertEqual(dumps(qc), expected)
def test_expr_binding_unary(self):
"""Test that nested unary operators don't insert unnecessary brackets."""
body = QuantumCircuit()
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(cr)
qc.if_test(expr.equal(expr.bit_not(expr.bit_not(cr)), 3), body.copy(), [], [])
qc.if_test(expr.logic_not(expr.logic_not(cr[0])), body.copy(), [], [])
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] cr;
if (~~cr == 3) {
}
if (!!cr[0]) {
}
"""
self.assertEqual(dumps(qc), expected)
def test_expr_precedence(self):
"""Test that the precedence properties of operators are correctly output."""
body = QuantumCircuit()
cr = ClassicalRegister(2, "cr")
# This tree is _completely_ inside out, so there's brackets needed round every operand.
inside_out = expr.logic_not(
expr.less(
expr.bit_and(
expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)),
expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)),
),
expr.bit_and(
expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)),
expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)),
),
)
)
# This one is the other way round - the tightest-binding operations are on the inside, so no
# brackets should be needed at all except to put in a comparison to a bitwise binary
# operation, since those bind less tightly than anything that can cast them to a bool.
outside_in = expr.logic_or(
expr.logic_and(
expr.equal(expr.bit_or(cr, cr), expr.bit_and(cr, cr)),
expr.equal(expr.bit_and(cr, cr), expr.bit_or(cr, cr)),
),
expr.logic_and(
expr.greater(expr.bit_or(cr, cr), expr.bit_xor(cr, cr)),
expr.less_equal(expr.bit_xor(cr, cr), expr.bit_or(cr, cr)),
),
)
# And an extra test of the logical operator order.
logics = expr.logic_or(
expr.logic_and(
expr.logic_or(expr.logic_not(cr[0]), expr.logic_not(cr[0])),
expr.logic_not(expr.logic_and(cr[0], cr[0])),
),
expr.logic_and(
expr.logic_not(expr.logic_and(cr[0], cr[0])),
expr.logic_or(expr.logic_not(cr[0]), expr.logic_not(cr[0])),
),
)
qc = QuantumCircuit(cr)
qc.if_test(inside_out, body.copy(), [], [])
qc.if_test(outside_in, body.copy(), [], [])
qc.if_test(logics, body.copy(), [], [])
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] cr;
if (!((((cr | cr) ^ (cr | cr)) & ((cr | cr) ^ (cr | cr)))\
< (((cr | cr) ^ (cr | cr)) & ((cr | cr) ^ (cr | cr))))) {
}
if ((cr | cr) == (cr & cr) && (cr & cr) == (cr | cr)\
|| (cr | cr) > (cr ^ cr) && (cr ^ cr) <= (cr | cr)) {
}
if ((!cr[0] || !cr[0]) && !(cr[0] && cr[0]) || !(cr[0] && cr[0]) && (!cr[0] || !cr[0])) {
}
"""
self.assertEqual(dumps(qc), expected)
def test_no_unnecessary_cast(self):
"""This is a bit of a cross `Expr`-constructor / OQ3-exporter test. It doesn't really
matter whether or not the `Expr` constructor functions insert cast nodes into their output
for the literals (at the time of writing [commit 2616602], they don't because they do some
type inference) but the OQ3 export definitely shouldn't have them."""
cr = ClassicalRegister(8, "cr")
qc = QuantumCircuit(cr)
# Note that the integer '1' has a minimum bit-width of 1, whereas the register has a width
# of 8. We're testing to make sure that there's no spurious cast up from `bit[1]` to
# `bit[8]`, or anything like that, _whether or not_ the `Expr` node includes one.
qc.if_test(expr.equal(cr, 1), QuantumCircuit(), [], [])
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[8] cr;
if (cr == 1) {
}
"""
self.assertEqual(dumps(qc), expected)
class TestCircuitQASM3ExporterTemporaryCasesWithBadParameterisation(QiskitTestCase):
"""Test functionality that is not what we _want_, but is what we need to do while the definition
of custom gates with parameterisation does not work correctly.
These tests are modified versions of those marked with the `requires_fixed_parameterisation`
decorator, and this whole class can be deleted once those are fixed. See gh-7335.
"""
maxDiff = 1_000_000
def test_basis_gates(self):
"""Teleportation with physical qubits"""
qc = QuantumCircuit(3, 2)
first_h = qc.h(1)[0].operation
qc.cx(1, 2)
qc.barrier()
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.barrier()
first_x = qc.x(2).c_if(qc.clbits[1], 1)[0].operation
qc.z(2).c_if(qc.clbits[0], 1)
u2 = first_h.definition.data[0].operation
u3_1 = u2.definition.data[0].operation
u3_2 = first_x.definition.data[0].operation
expected_qasm = "\n".join(
[
"OPENQASM 3;",
f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(pi/2, 0, pi) _gate_q_0;",
"}",
f"gate u2_{id(u2)}(_gate_p_0, _gate_p_1) _gate_q_0 {{",
f" u3_{id(u3_1)}(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
f" u2_{id(u2)}(0, pi) _gate_q_0;",
"}",
f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(pi, 0, pi) _gate_q_0;",
"}",
"gate x _gate_q_0 {",
f" u3_{id(u3_2)}(pi, 0, pi) _gate_q_0;",
"}",
"bit[2] c;",
"qubit[3] q;",
"h q[1];",
"cx q[1], q[2];",
"barrier q[0], q[1], q[2];",
"cx q[0], q[1];",
"h q[0];",
"barrier q[0], q[1], q[2];",
"c[0] = measure q[0];",
"c[1] = measure q[1];",
"barrier q[0], q[1], q[2];",
"if (c[1]) {",
" x q[2];",
"}",
"if (c[0]) {",
" z q[2];",
"}",
"",
]
)
self.assertEqual(
Exporter(includes=[], basis_gates=["cx", "z", "U"]).dumps(qc),
expected_qasm,
)
def test_teleportation(self):
"""Teleportation with physical qubits"""
qc = QuantumCircuit(3, 2)
qc.h(1)
qc.cx(1, 2)
qc.barrier()
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.barrier()
qc.x(2).c_if(qc.clbits[1], 1)
qc.z(2).c_if(qc.clbits[0], 1)
transpiled = transpile(qc, initial_layout=[0, 1, 2])
first_h = transpiled.data[0].operation
u2 = first_h.definition.data[0].operation
u3_1 = u2.definition.data[0].operation
first_x = transpiled.data[-2].operation
u3_2 = first_x.definition.data[0].operation
first_z = transpiled.data[-1].operation
u1 = first_z.definition.data[0].operation
u3_3 = u1.definition.data[0].operation
expected_qasm = "\n".join(
[
"OPENQASM 3;",
f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(pi/2, 0, pi) _gate_q_0;",
"}",
f"gate u2_{id(u2)}(_gate_p_0, _gate_p_1) _gate_q_0 {{",
f" u3_{id(u3_1)}(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
f" u2_{id(u2)}(0, pi) _gate_q_0;",
"}",
"gate cx c, t {",
" ctrl @ U(pi, 0, pi) c, t;",
"}",
f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(pi, 0, pi) _gate_q_0;",
"}",
"gate x _gate_q_0 {",
f" u3_{id(u3_2)}(pi, 0, pi) _gate_q_0;",
"}",
f"gate u3_{id(u3_3)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(0, 0, pi) _gate_q_0;",
"}",
f"gate u1_{id(u1)}(_gate_p_0) _gate_q_0 {{",
f" u3_{id(u3_3)}(0, 0, pi) _gate_q_0;",
"}",
"gate z _gate_q_0 {",
f" u1_{id(u1)}(pi) _gate_q_0;",
"}",
"bit[2] c;",
"h $1;",
"cx $1, $2;",
"barrier $0, $1, $2;",
"cx $0, $1;",
"h $0;",
"barrier $0, $1, $2;",
"c[0] = measure $0;",
"c[1] = measure $1;",
"barrier $0, $1, $2;",
"if (c[1]) {",
" x $2;",
"}",
"if (c[0]) {",
" z $2;",
"}",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(transpiled), expected_qasm)
def test_custom_gate_with_params_bound_main_call(self):
"""Custom gate with unbound parameters that are bound in the main circuit"""
parameter0 = Parameter("p0")
parameter1 = Parameter("p1")
custom = QuantumCircuit(2, name="custom")
custom.rz(parameter0, 0)
custom.rz(parameter1 / 2, 1)
qr_all_qubits = QuantumRegister(3, "q")
qr_r = QuantumRegister(3, "r")
circuit = QuantumCircuit(qr_all_qubits, qr_r)
circuit.append(custom.to_gate(), [qr_all_qubits[0], qr_r[0]])
circuit.assign_parameters({parameter0: pi, parameter1: pi / 2}, inplace=True)
custom_id = id(circuit.data[0].operation)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"gate custom_{custom_id}(_gate_p_0, _gate_p_1) _gate_q_0, _gate_q_1 {{",
" rz(pi) _gate_q_0;",
" rz(pi/4) _gate_q_1;",
"}",
"qubit[3] q;",
"qubit[3] r;",
f"custom_{custom_id}(pi, pi/2) q[0], r[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
def test_no_include(self):
"""Test explicit gate declaration (no include)"""
q = QuantumRegister(2, "q")
circuit = QuantumCircuit(q)
circuit.rz(pi / 2, 0)
circuit.sx(0)
circuit.cx(0, 1)
rz = circuit.data[0].operation
u1_1 = rz.definition.data[0].operation
u3_1 = u1_1.definition.data[0].operation
sx = circuit.data[1].operation
sdg = sx.definition.data[0].operation
u1_2 = sdg.definition.data[0].operation
u3_2 = u1_2.definition.data[0].operation
h_ = sx.definition.data[1].operation
u2_1 = h_.definition.data[0].operation
u3_3 = u2_1.definition.data[0].operation
expected_qasm = "\n".join(
[
"OPENQASM 3;",
f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(0, 0, pi/2) _gate_q_0;",
"}",
f"gate u1_{id(u1_1)}(_gate_p_0) _gate_q_0 {{",
f" u3_{id(u3_1)}(0, 0, pi/2) _gate_q_0;",
"}",
f"gate rz_{id(rz)}(_gate_p_0) _gate_q_0 {{",
f" u1_{id(u1_1)}(pi/2) _gate_q_0;",
"}",
f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(0, 0, -pi/2) _gate_q_0;",
"}",
f"gate u1_{id(u1_2)}(_gate_p_0) _gate_q_0 {{",
f" u3_{id(u3_2)}(0, 0, -pi/2) _gate_q_0;",
"}",
"gate sdg _gate_q_0 {",
f" u1_{id(u1_2)}(-pi/2) _gate_q_0;",
"}",
f"gate u3_{id(u3_3)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(pi/2, 0, pi) _gate_q_0;",
"}",
f"gate u2_{id(u2_1)}(_gate_p_0, _gate_p_1) _gate_q_0 {{",
f" u3_{id(u3_3)}(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
f" u2_{id(u2_1)}(0, pi) _gate_q_0;",
"}",
"gate sx _gate_q_0 {",
" sdg _gate_q_0;",
" h _gate_q_0;",
" sdg _gate_q_0;",
"}",
"gate cx c, t {",
" ctrl @ U(pi, 0, pi) c, t;",
"}",
"qubit[2] q;",
f"rz_{id(rz)}(pi/2) q[0];",
"sx q[0];",
"cx q[0], q[1];",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(circuit), expected_qasm)
def test_unusual_conditions(self):
"""Test that special QASM constructs such as ``measure`` are correctly handled when the
Terra instructions have old-style conditions."""
qc = QuantumCircuit(3, 2)
qc.h(0)
qc.measure(0, 0)
qc.measure(1, 1).c_if(0, True)
qc.reset([0, 1]).c_if(0, True)
with qc.while_loop((qc.clbits[0], True)):
qc.break_loop().c_if(0, True)
qc.continue_loop().c_if(0, True)
# Terra forbids delay and barrier from being conditioned through `c_if`, but in theory they
# should work fine in a dynamic-circuits sense (although what a conditional barrier _means_
# is a whole other kettle of fish).
delay = Delay(16, "dt")
delay.condition = (qc.clbits[0], True)
qc.append(delay, [0], [])
barrier = Barrier(2)
barrier.condition = (qc.clbits[0], True)
qc.append(barrier, [0, 1], [])
expected = """
OPENQASM 3;
include "stdgates.inc";
bit[2] c;
qubit[3] q;
h q[0];
c[0] = measure q[0];
if (c[0]) {
c[1] = measure q[1];
}
if (c[0]) {
reset q[0];
}
if (c[0]) {
reset q[1];
}
while (c[0]) {
if (c[0]) {
break;
}
if (c[0]) {
continue;
}
}
if (c[0]) {
delay[16dt] q[0];
}
if (c[0]) {
barrier q[0], q[1];
}"""
self.assertEqual(dumps(qc).strip(), expected.strip())
class TestExperimentalFeatures(QiskitTestCase):
"""Tests of features that are hidden behind experimental flags."""
maxDiff = None
def test_switch_forbidden_without_flag(self):
"""Omitting the feature flag should raise an error."""
case = QuantumCircuit(1)
circuit = QuantumCircuit(1, 1)
circuit.switch(circuit.clbits[0], [((True, False), case)], [0], [])
with self.assertRaisesRegex(QASM3ExporterError, "'switch' statements are not stabilized"):
dumps(circuit)
def test_switch_clbit(self):
"""Test that a switch statement can be constructed with a bit as a condition."""
qubit = Qubit()
clbit = Clbit()
case1 = QuantumCircuit([qubit, clbit])
case1.x(0)
case2 = QuantumCircuit([qubit, clbit])
case2.z(0)
circuit = QuantumCircuit([qubit, clbit])
circuit.switch(clbit, [(True, case1), (False, case2)], [0], [0])
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit _bit0;
int switch_dummy;
qubit _qubit0;
switch_dummy = _bit0;
switch (switch_dummy) {
case 1: {
x _qubit0;
}
break;
case 0: {
z _qubit0;
}
break;
}
"""
self.assertEqual(test, expected)
def test_switch_register(self):
"""Test that a switch statement can be constructed with a register as a condition."""
qubit = Qubit()
creg = ClassicalRegister(2, "c")
case1 = QuantumCircuit([qubit], creg)
case1.x(0)
case2 = QuantumCircuit([qubit], creg)
case2.y(0)
case3 = QuantumCircuit([qubit], creg)
case3.z(0)
circuit = QuantumCircuit([qubit], creg)
circuit.switch(creg, [(0, case1), (1, case2), (2, case3)], [0], circuit.clbits)
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] c;
int switch_dummy;
qubit _qubit0;
switch_dummy = c;
switch (switch_dummy) {
case 0: {
x _qubit0;
}
break;
case 1: {
y _qubit0;
}
break;
case 2: {
z _qubit0;
}
break;
}
"""
self.assertEqual(test, expected)
def test_switch_with_default(self):
"""Test that a switch statement can be constructed with a default case at the end."""
qubit = Qubit()
creg = ClassicalRegister(2, "c")
case1 = QuantumCircuit([qubit], creg)
case1.x(0)
case2 = QuantumCircuit([qubit], creg)
case2.y(0)
case3 = QuantumCircuit([qubit], creg)
case3.z(0)
circuit = QuantumCircuit([qubit], creg)
circuit.switch(creg, [(0, case1), (1, case2), (CASE_DEFAULT, case3)], [0], circuit.clbits)
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] c;
int switch_dummy;
qubit _qubit0;
switch_dummy = c;
switch (switch_dummy) {
case 0: {
x _qubit0;
}
break;
case 1: {
y _qubit0;
}
break;
default: {
z _qubit0;
}
break;
}
"""
self.assertEqual(test, expected)
def test_switch_multiple_cases_to_same_block(self):
"""Test that it is possible to add multiple cases that apply to the same block, if they are
given as a compound value. This is an allowed special case of block fall-through."""
qubit = Qubit()
creg = ClassicalRegister(2, "c")
case1 = QuantumCircuit([qubit], creg)
case1.x(0)
case2 = QuantumCircuit([qubit], creg)
case2.y(0)
circuit = QuantumCircuit([qubit], creg)
circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits)
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] c;
int switch_dummy;
qubit _qubit0;
switch_dummy = c;
switch (switch_dummy) {
case 0: {
x _qubit0;
}
break;
case 1:
case 2: {
y _qubit0;
}
break;
}
"""
self.assertEqual(test, expected)
def test_multiple_switches_dont_clash_on_dummy(self):
"""Test that having more than one switch statement in the circuit doesn't cause naming
clashes in the dummy integer value used."""
qubit = Qubit()
creg = ClassicalRegister(2, "switch_dummy")
case1 = QuantumCircuit([qubit], creg)
case1.x(0)
case2 = QuantumCircuit([qubit], creg)
case2.y(0)
circuit = QuantumCircuit([qubit], creg)
circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits)
circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits)
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] switch_dummy;
int switch_dummy__generated0;
int switch_dummy__generated1;
qubit _qubit0;
switch_dummy__generated0 = switch_dummy;
switch (switch_dummy__generated0) {
case 0: {
x _qubit0;
}
break;
case 1:
case 2: {
y _qubit0;
}
break;
}
switch_dummy__generated1 = switch_dummy;
switch (switch_dummy__generated1) {
case 0: {
x _qubit0;
}
break;
case 1:
case 2: {
y _qubit0;
}
break;
}
"""
self.assertEqual(test, expected)
def test_switch_nested_in_if(self):
"""Test that the switch statement works when in a nested scope, including the dummy
classical variable being declared globally. This isn't necessary in the OQ3 language, but
it is universally valid and the IBM QSS stack prefers that. They're our primary consumers
of OQ3 strings, so it's best to play nicely with them."""
qubit = Qubit()
creg = ClassicalRegister(2, "c")
case1 = QuantumCircuit([qubit], creg)
case1.x(0)
case2 = QuantumCircuit([qubit], creg)
case2.y(0)
body = QuantumCircuit([qubit], creg)
body.switch(creg, [(0, case1), ((1, 2), case2)], [0], body.clbits)
circuit = QuantumCircuit([qubit], creg)
circuit.if_else((creg, 1), body.copy(), body, [0], body.clbits)
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] c;
int switch_dummy;
int switch_dummy__generated0;
qubit _qubit0;
if (c == 1) {
switch_dummy = c;
switch (switch_dummy) {
case 0: {
x _qubit0;
}
break;
case 1:
case 2: {
y _qubit0;
}
break;
}
} else {
switch_dummy__generated0 = c;
switch (switch_dummy__generated0) {
case 0: {
x _qubit0;
}
break;
case 1:
case 2: {
y _qubit0;
}
break;
}
}
"""
self.assertEqual(test, expected)
def test_expr_target(self):
"""Simple test that the target of `switch` can be `Expr` nodes."""
bits = [Qubit(), Clbit()]
cr = ClassicalRegister(2, "cr")
case0 = QuantumCircuit(1)
case0.x(0)
case1 = QuantumCircuit(1)
case1.x(0)
qc = QuantumCircuit(bits, cr)
qc.switch(expr.logic_not(bits[1]), [(False, case0)], [0], [])
qc.switch(expr.bit_and(cr, 3), [(3, case1)], [0], [])
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit _bit0;
bit[2] cr;
int switch_dummy;
int switch_dummy__generated0;
qubit _qubit0;
switch_dummy = !_bit0;
switch (switch_dummy) {
case 0: {
x _qubit0;
}
break;
}
switch_dummy__generated0 = cr & 3;
switch (switch_dummy__generated0) {
case 3: {
x _qubit0;
}
break;
}
"""
test = dumps(qc, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
self.assertEqual(test, expected)
@ddt
class TestQASM3ExporterFailurePaths(QiskitTestCase):
"""Tests of the failure paths for the exporter."""
def test_disallow_overlapping_classical_registers_if_no_aliasing(self):
"""Test that the exporter rejects circuits with a classical bit in more than one register if
the ``alias_classical_registers`` option is set false."""
qubits = [Qubit() for _ in [None] * 3]
clbits = [Clbit() for _ in [None] * 5]
registers = [ClassicalRegister(bits=clbits[:4]), ClassicalRegister(bits=clbits[1:])]
qc = QuantumCircuit(qubits, *registers)
exporter = Exporter(alias_classical_registers=False)
with self.assertRaisesRegex(QASM3ExporterError, r"classical registers .* overlap"):
exporter.dumps(qc)
@data([1, 2, 1.1], [1j, 2])
def test_disallow_for_loops_with_non_integers(self, indices):
"""Test that the exporter rejects ``for`` loops that include non-integer values in their
index sets."""
loop_body = QuantumCircuit()
qc = QuantumCircuit(2, 2)
qc.for_loop(indices, None, loop_body, [], [])
exporter = Exporter()
with self.assertRaisesRegex(
QASM3ExporterError, r"The values in QASM 3 'for' loops must all be integers.*"
):
exporter.dumps(qc)
def test_disallow_custom_subroutine_with_parameters(self):
"""Test that the exporter throws an error instead of trying to export a subroutine with
parameters, while this is not supported."""
subroutine = QuantumCircuit(1)
subroutine.rx(Parameter("x"), 0)
qc = QuantumCircuit(1)
qc.append(subroutine.to_instruction(), [0], [])
exporter = Exporter()
with self.assertRaisesRegex(
QASM3ExporterError, "Exporting non-unitary instructions is not yet supported"
):
exporter.dumps(qc)
def test_disallow_opaque_instruction(self):
"""Test that the exporter throws an error instead of trying to export something into a
``defcal`` block, while this is not supported."""
qc = QuantumCircuit(1)
qc.append(Instruction("opaque", 1, 0, []), [0], [])
exporter = Exporter()
with self.assertRaisesRegex(
QASM3ExporterError, "Exporting opaque instructions .* is not yet supported"
):
exporter.dumps(qc)
|
https://github.com/daniel-molina23/basic-quantum-algorithms
|
daniel-molina23
|
%%capture
%pip install qiskit
%pip install qiskit_ibm_provider
%pip install qiskit-aer
# Importing standard Qiskit libraries
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QuantumCircuit, transpile, Aer
from qiskit_ibm_provider import IBMProvider
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.circuit.library import C3XGate
# Importing matplotlib
import matplotlib.pyplot as plt
# Importing Numpy, Cmath and math
import numpy as np
import os, math, cmath
from numpy import pi
# Other imports
from IPython.display import display, Math, Latex
# Specify the path to your env file
env_file_path = 'config.env'
# Load environment variables from the file
os.environ.update(line.strip().split('=', 1) for line in open(env_file_path) if '=' in line and not line.startswith('#'))
# Load IBM Provider API KEY
IBMP_API_KEY = os.environ.get('IBMP_API_KEY')
# Loading your IBM Quantum account(s)
IBMProvider.save_account(IBMP_API_KEY, overwrite=True)
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
qc_b1 = QuantumCircuit(2, 2)
qc_b1.h(0)
qc_b1.cx(0, 1)
qc_b1.draw(output='mpl', style="iqp")
sv = backend.run(qc_b1).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^+\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.x(0)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.z(0)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.x(1)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.x(0)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.x(0)
qc_b4.h(0)
qc_b4.x(1)
qc_b4.cx(0, 1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.h(0)
qc_b4.cx(0, 1)
qc_b4.x(0)
qc_b4.z(1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
def sv_latex_from_qc(qc, backend):
sv = backend.run(qc).result().get_statevector()
return sv.draw(output='latex')
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(3)
sv_latex_from_qc(qc_ej2, backend)
def circuit_adder (num):
if num<1 or num>8:
raise ValueError("Out of range") ## El enunciado limita el sumador a los valores entre 1 y 8. Quitar esta restricción sería directo.
# Definición del circuito base que vamos a construir
qreg_q = QuantumRegister(4, 'q')
creg_c = ClassicalRegister(1, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
qbit_position = 0
for element in reversed(np.binary_repr(num)):
if (element=='1'):
circuit.barrier()
match qbit_position:
case 0: # +1
circuit.append(C3XGate(), [qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3]])
circuit.ccx(qreg_q[0], qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
circuit.x(qreg_q[0])
case 1: # +2
circuit.ccx(qreg_q[1], qreg_q[2], qreg_q[3])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.x(qreg_q[1])
case 2: # +4
circuit.cx(qreg_q[2], qreg_q[3])
circuit.x(qreg_q[2])
case 3: # +8
circuit.x(qreg_q[3])
qbit_position+=1
return circuit
add_3 = circuit_adder(3)
add_3.draw(output='mpl', style="iqp")
qc_test_2 = QuantumCircuit(4, 4)
qc_test_2.x(1)
qc_test_2_plus_3 = qc_test_2.compose(add_3)
qc_test_2_plus_3.draw(output='mpl', style="iqp")
sv_latex_from_qc(qc_test_2_plus_3, backend)
qc_test_7 = QuantumCircuit(4, 4)
qc_test_7.x(0)
qc_test_7.x(1)
qc_test_7.x(2)
qc_test_7_plus_8 = qc_test_7.compose(circuit_adder(8))
sv_latex_from_qc(qc_test_7_plus_8, backend)
#qc_test_7_plus_8.draw()
theta = 6.544985
phi = 2.338741
lmbda = 0
alice_1 = 0
alice_2 = 1
bob_1 = 2
qr_alice = QuantumRegister(2, 'Alice')
qr_bob = QuantumRegister(1, 'Bob')
cr = ClassicalRegister(3, 'c')
qc_ej3 = QuantumCircuit(qr_alice, qr_bob, cr)
qc_ej3.barrier(label='1')
qc_ej3.u(theta, phi, lmbda, alice_1);
qc_ej3.barrier(label='2')
qc_ej3.h(alice_2)
qc_ej3.cx(alice_2, bob_1);
qc_ej3.barrier(label='3')
qc_ej3.cx(alice_1, alice_2)
qc_ej3.h(alice_1);
qc_ej3.barrier(label='4')
qc_ej3.measure([alice_1, alice_2], [alice_1, alice_2]);
qc_ej3.barrier(label='5')
qc_ej3.x(bob_1).c_if(alice_2, 1)
qc_ej3.z(bob_1).c_if(alice_1, 1)
qc_ej3.measure(bob_1, bob_1);
qc_ej3.draw(output='mpl', style="iqp")
result = backend.run(qc_ej3, shots=1024).result()
counts = result.get_counts()
plot_histogram(counts)
sv_0 = np.array([1, 0])
sv_1 = np.array([0, 1])
def find_symbolic_representation(value, symbolic_constants={1/np.sqrt(2): '1/√2'}, tolerance=1e-10):
"""
Check if the given numerical value corresponds to a symbolic constant within a specified tolerance.
Parameters:
- value (float): The numerical value to check.
- symbolic_constants (dict): A dictionary mapping numerical values to their symbolic representations.
Defaults to {1/np.sqrt(2): '1/√2'}.
- tolerance (float): Tolerance for comparing values with symbolic constants. Defaults to 1e-10.
Returns:
str or float: If a match is found, returns the symbolic representation as a string
(prefixed with '-' if the value is negative); otherwise, returns the original value.
"""
for constant, symbol in symbolic_constants.items():
if np.isclose(abs(value), constant, atol=tolerance):
return symbol if value >= 0 else '-' + symbol
return value
def array_to_dirac_notation(array, tolerance=1e-10):
"""
Convert a complex-valued array representing a quantum state in superposition
to Dirac notation.
Parameters:
- array (numpy.ndarray): The complex-valued array representing
the quantum state in superposition.
- tolerance (float): Tolerance for considering amplitudes as negligible.
Returns:
str: The Dirac notation representation of the quantum state.
"""
# Ensure the statevector is normalized
array = array / np.linalg.norm(array)
# Get the number of qubits
num_qubits = int(np.log2(len(array)))
# Find indices where amplitude is not negligible
non_zero_indices = np.where(np.abs(array) > tolerance)[0]
# Generate Dirac notation terms
terms = [
(find_symbolic_representation(array[i]), format(i, f"0{num_qubits}b"))
for i in non_zero_indices
]
# Format Dirac notation
dirac_notation = " + ".join([f"{amplitude}|{binary_rep}⟩" for amplitude, binary_rep in terms])
return dirac_notation
def array_to_matrix_representation(array):
"""
Convert a one-dimensional array to a column matrix representation.
Parameters:
- array (numpy.ndarray): The one-dimensional array to be converted.
Returns:
numpy.ndarray: The column matrix representation of the input array.
"""
# Replace symbolic constants with their representations
matrix_representation = np.array([find_symbolic_representation(value) or value for value in array])
# Return the column matrix representation
return matrix_representation.reshape((len(matrix_representation), 1))
def array_to_dirac_and_matrix_latex(array):
"""
Generate LaTeX code for displaying both the matrix representation and Dirac notation
of a quantum state.
Parameters:
- array (numpy.ndarray): The complex-valued array representing the quantum state.
Returns:
Latex: A Latex object containing LaTeX code for displaying both representations.
"""
matrix_representation = array_to_matrix_representation(array)
latex = "Matrix representation\n\\begin{bmatrix}\n" + \
"\\\\\n".join(map(str, matrix_representation.flatten())) + \
"\n\\end{bmatrix}\n"
latex += f'Dirac Notation:\n{array_to_dirac_notation(array)}'
return Latex(latex)
sv_b1 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b2 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) - np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b3 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) + np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b4 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import (
ElectronicStructureDriverType,
ElectronicStructureMoleculeDriver,
PySCFDriver,
)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
from qiskit_nature.settings import settings
settings.dict_aux_operators = True
molecule = Molecule(
geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1
)
driver = ElectronicStructureMoleculeDriver(
molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF
)
# or equivalently:
driver = PySCFDriver.from_molecule(molecule, basis="sto3g")
transformer = FreezeCoreTransformer()
problem = ElectronicStructureProblem(driver, transformers=[transformer])
# Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so:
second_q_ops = problem.second_q_ops()
hamiltonian = second_q_ops["ElectronicEnergy"]
print(hamiltonian)
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1)
driver = PySCFDriver.from_molecule(molecule, basis="sto3g")
# this is now done explicitly
problem = driver.run()
transformer = FreezeCoreTransformer()
# and you also apply transformers explicitly
problem = transformer.transform(problem)
hamiltonian = problem.hamiltonian.second_q_op()
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import PySCFDriver
molecule = Molecule(
geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1
)
driver = PySCFDriver.from_molecule(molecule)
result = driver.run()
print(type(result))
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo
molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1)
driver = PySCFDriver.from_molecule(molecule, basis="sto3g")
result = driver.run()
print(type(result))
from qiskit_nature.drivers.second_quantization import FCIDumpDriver
path_to_fcidump = "aux_files/h2.fcidump"
driver = FCIDumpDriver(path_to_fcidump)
result = driver.run()
print(type(result))
from qiskit_nature.second_q.formats.fcidump import FCIDump
path_to_fcidump = "aux_files/h2.fcidump"
fcidump = FCIDump.from_file(path_to_fcidump)
print(type(fcidump))
from qiskit_nature.second_q.formats.fcidump_translator import fcidump_to_problem
problem = fcidump_to_problem(fcidump)
print(type(problem))
from qiskit_nature.drivers.second_quantization import PySCFDriver
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
transformer = FreezeCoreTransformer()
driver = PySCFDriver()
transformed_result = transformer.transform(driver.run())
print(type(transformed_result))
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
transformer = FreezeCoreTransformer()
driver = PySCFDriver()
transformed_result = transformer.transform(driver.run())
print(type(transformed_result))
from qiskit_nature.drivers.second_quantization import PySCFDriver
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
driver = PySCFDriver()
transformer = FreezeCoreTransformer()
problem = ElectronicStructureProblem(driver, transformers=[transformer])
# we trigger driver.run() implicitly like so:
second_q_ops = problem.second_q_ops()
hamiltonian_op = second_q_ops.pop("ElectronicEnergy")
aux_ops = second_q_ops
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
driver = PySCFDriver()
problem = driver.run()
transformer = FreezeCoreTransformer()
problem = transformer.transform(problem)
hamiltonian_op, aux_ops = problem.second_q_ops()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
# Apply h gate to the control qubit
qc.h(0)
# apply pauli x gate to the target qubit
qc.x(1)
# Apply h gate to the target qubit
qc.h(1)
#Applying the CNOT gate
qc.cx(0,1)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
pip install git+https://github.com/qiskit-community/qiskit-textbook.git#subdirectory=qiskit-textbook-src
conda install git
|
https://github.com/SammithSB/virat-and-toss
|
SammithSB
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
### Creating 3 qubit and 2 classical bits in each separate register
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(1)
teleportation_circuit = QuantumCircuit(qr, crz, crx)
### A third party eve helps to create an entangled state
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a, b)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, a, b):
qc.cx(a, b)
qc.h(a)
teleportation_circuit.barrier()
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
teleportation_circuit.barrier()
measure_and_send(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1)
qc.z(qubit).c_if(crz, 1)
teleportation_circuit.barrier()
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
from qiskit.extensions import Initialize
import math
qc = QuantumCircuit(1)
initial_state = [0,1]
init_gate = Initialize(initial_state)
# qc.append(initialize_qubit, [0])
qr = QuantumRegister(3) # Protocol uses 3 qubits
crz = ClassicalRegister(1) # and 2 classical registers
crx = ClassicalRegister(1)
qc = QuantumCircuit(qr, crz, crx)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
qc.draw()
backend = BasicAer.get_backend('statevector_simulator')
out_vector = execute(qc, backend).result().get_statevector()
plot_bloch_multivector(out_vector)
inverse_init_gate = init_gate.gates_to_uncompute()
qc.append(inverse_init_gate, [2])
qc.draw()
cr_result = ClassicalRegister(1)
qc.add_register(cr_result)
qc.measure(2,2)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1024).result().get_counts()
plot_histogram(counts)
def bob_gates(qc, a, b, c):
qc.cz(a, c)
qc.cx(b, c)
qc = QuantumCircuit(3,1)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
qc.barrier()
# Alice sends classical bits to Bob
bob_gates(qc, 0, 1, 2)
# We undo the initialisation process
qc.append(inverse_init_gate, [2])
# See the results, we only care about the state of qubit 2
qc.measure(2,0)
# View the results:
qc.draw()
from qiskit import IBMQ
IBMQ.save_account('### IMB TOKEN ')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and
not b.configuration().simulator and b.status().operational==True))
job_exp = execute(qc, backend=backend, shots=8192)
exp_result = job_exp.result()
exp_measurement_result = exp_result.get_counts(qc)
print(exp_measurement_result)
plot_histogram(exp_measurement_result)
error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \
* 100./ sum(list(exp_measurement_result.values()))
print("The experimental error rate : ", error_rate_percent, "%")
|
https://github.com/veenaiyuri/qiskit-education
|
veenaiyuri
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer, assemble, transpile
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.providers.ibmq import least_busy
# import basic plot tools
from qiskit.visualization import plot_histogram
n = 2
grover_circuit = QuantumCircuit(n)
def initialize_s(qc, qubits):
"""Apply a H-gate to 'qubits' in qc"""
for q in qubits:
qc.h(q)
return qc
def diffuser(nqubits):
qc = QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qc.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qc.x(qubit)
# Do multi-controlled-Z gate
qc.h(nqubits-1)
qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qc.h(nqubits-1)
# Apply transformation |11..1> -> |00..0>
for qubit in range(nqubits):
qc.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(nqubits):
qc.h(qubit)
# We will return the diffuser as a gate
U_s = qc.to_gate()
U_s.name = "U$_s$"
return U_s
grover_circuit = initialize_s(grover_circuit, [0,1])
grover_circuit.draw(output="mpl")
grover_circuit.cz(0,1) # Oracle
grover_circuit.draw(output="mpl")
# Diffusion operator (U_s)
grover_circuit.append(diffuser(n),[0,1])
grover_circuit.draw(output="mpl")
sim = Aer.get_backend('aer_simulator')
# we need to make a copy of the circuit with the 'save_statevector'
# instruction to run on the Aer simulator
grover_circuit_sim = grover_circuit.copy()
grover_circuit_sim.save_statevector()
qobj = assemble(grover_circuit_sim)
result = sim.run(qobj).result()
statevec = result.get_statevector()
from qiskit_textbook.tools import vector2latex
vector2latex(statevec, pretext="|\\psi\\rangle =")
grover_circuit.measure_all()
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(grover_circuit)
result = aer_sim.run(qobj).result()
counts = result.get_counts()
plot_histogram(counts)
nqubits = 4
qc = QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qc.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qc.x(qubit)
qc.barrier()
# Do multi-controlled-Z gate
qc.h(nqubits-1)
qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qc.h(nqubits-1)
qc.barrier()
# Apply transformation |11..1> -> |00..0>
for qubit in range(nqubits):
qc.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(nqubits):
qc.h(qubit)
qc.draw(output="mpl")
from qiskit.circuit import classical_function, Int1
# define a classical function f(x): this returns 1 for the solutions of the problem
# in this case, the solutions are 1010 and 1100
@classical_function
def f(x1: Int1, x2: Int1, x3: Int1, x4: Int1) -> Int1:
return (x1 and not x2 and x3 and not x4) or (x1 and x2 and not x3 and not x4)
nqubits = 4
Uf = f.synth() # turn it into a circuit
oracle = QuantumCircuit(nqubits+1)
oracle.compose(Uf, inplace=True)
oracle.draw(output="mpl")
# We will return the diffuser as a gate
#U_f = oracle.to_gate()
# U_f.name = "U$_f$"
# return U_f
|
https://github.com/ubsuny/QiskitNature_EnergyLevels
|
ubsuny
|
import sys, time
sys.path.append("../")
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
print('Qconfig loaded from %s.' % Qconfig.__file__)
# Imports
import qiskit as qk
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import available_backends, execute, register, least_busy
from qiskit.tools.visualization import plot_histogram
from qiskit import IBMQ
from qiskit import Aer
from math import pi
print(qk.__version__)
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr,cr)
# circuit construction
# preparing the wavefunction
qc.h(qr[0])
qc.barrier()
qc.cx(qr[0], qr[1])
qc.barrier()
qc.u3(1.2309,0,0,qr[0])
qc.barrier()
# if we apply phase shift gate
qc.u1((2.0/3)*pi,qr[0])
qc.u1((2.0/3)*pi,qr[1])
qc.barrier()
# rotating the axis for measurement
#qc.cx(qr[0],qr[1]) # THE IMPLEMENTATION PROVIDED BY THE AUTHORS SKIPS THIS CNOT APPLICATION!!! it shouldn't be
# it shouldn't be there. Improves accuracy
#qc.barrier()
qc.u3(2.1862,6.5449,pi,qr[0])
qc.u3(0.9553,2*pi,pi,qr[1])
qc.barrier()
qc.measure(qr,cr)
# Running locally IBM backends respond too slowly
print(Aer.backends())
backend = Aer.get_backend('qasm_simulator')
job = execute(qc,backend)
job.status
result = job.result()
counts = result.get_counts(qc)
print(counts)
plot_histogram(counts)
performance = {
'success':(counts['01']+counts['10'])/1024,
'failure':1 - (counts['01']+counts['10'])/1024
}
plot_histogram(performance)
IBMQ.load_accounts()
# checking the backends
large_enough_devices = IBMQ.backends(filters=lambda x: x.configuration()['n_qubits'] > 1 and not x.configuration()['simulator'])
print(large_enough_devices)
backend = IBMQ.get_backend('ibmqx4')
job = execute(qc,backend,max_credits=3)
job.status
result = job.result()
counts = result.get_counts(qc)
print(counts)
plot_histogram(counts)
performance = {
'success':(counts['01']+counts['10'])/1024,
'failure':(counts['00']+counts['11'])/1024
}
plot_histogram(performance)
sqr = QuantumRegister(1)
scr = ClassicalRegister(1)
sqc = QuantumCircuit(sqr,scr)
# constructing the circuit
sqc.u3(1.1503,6.4850,2.2555,sqr[0])
sqc.barrier()
# unidentified gate -- now assumed to be R2pi3. if identity then use qc.u1(0,q[0])
sqc.u1((2.0/3)*pi,sqr[0])
sqc.barrier()
sqc.u3(1.231,0,0,sqr[0]) # X
sqc.barrier()
sqc.u1((2.0/3)*pi,sqr[0]) # U (unidentified gate)
sqc.barrier()
# measurement
sqc.u3(0.7854,6.0214,6.1913,sqr[0])
sqc.barrier()
sqc.measure(sqr,scr)
# Running on local simulator
backend = Aer.get_backend('qasm_simulator')
job = execute(sqc,backend)
result = job.result()
counts = result.get_counts(sqc)
print(counts)
plot_histogram(counts)
# Running on IBM
backend = IBMQ.get_backend('ibmqx4')
job = execute(sqc,backend,max_credits=3)
result = job.result()
counts = result.get_counts(sqc)
print(counts)
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
state = Statevector(qc)
plot_bloch_multivector(state)
|
https://github.com/IceKhan13/purplecaffeine
|
IceKhan13
|
import numpy as np
import random
from qiskit.circuit.random import random_circuit
from purplecaffeine.core import BaseStorage, LocalStorage, Trial
from purplecaffeine.widget import Widget
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info.random import random_pauli
from qiskit.primitives import Estimator
local_storage = LocalStorage("./trials/")
n_qubits = 4
depth = 10
shots = 2000
for i in range(0, 3):
with Trial("Example trial " + str(i), storage=local_storage) as trial:
# track parameter
trial.add_parameter("estimator", "qiskit.primitives.Estimator")
trial.add_parameter("depth", depth)
trial.add_parameter("n_qubits", n_qubits)
trial.add_parameter("shots", shots)
# track circuits
circuit = random_circuit(n_qubits, depth)
trial.add_circuit("circuit", circuit)
trial.add_circuit("another circuit", random_circuit(n_qubits, depth))
# track operators
obs = random_pauli(n_qubits)
trial.add_operator("obs", obs)
for idx in range(5):
trial.add_operator(f"obs {idx}", random_pauli(n_qubits))
# track tags
trial.add_tag(f"tag {i}")
# track texts
trial.add_text("text one", "This text will be displayed in text tab")
trial.add_text("text two", "This text will be displayed in text tab as well")
# run
exp_value = Estimator().run(circuit, obs, shots=shots).result().values.item()
# track history data as metric
for _ in range(100):
trial.add_metric("history", random.randint(0, 10))
# track results as metric
trial.add_metric("exp_value", exp_value)
Widget(local_storage).show()
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
### replaced x gate ###
qc.x(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
### replaced x gate ###
qc.x(1)
return qc
|
https://github.com/parton-quark/RLSB-CongX-Qiskit
|
parton-quark
|
!pip install qiskit
!pip install CongX
from tfc_to_qiskit import tfc_to_qiskit
tfc_to_qiskit('test.tfc.txt')
import RLSBCQ_test
RLSBCQ_test.qc.draw(output='mpl')
from qiskit.compiler import transpile
transpiled = transpile(RLSBCQ_test.qc, backend=None, basis_gates=None, coupling_map=None, backend_properties=None, initial_layout=None, seed_transpiler=None, optimization_level=None, pass_manager=None, callback=None, output_name=None)
transpiled.draw(output='mpl')
|
https://github.com/apcarrik/qiskit-dev
|
apcarrik
|
#------------------------------------------------------------------------------
# Qaoa.py
#
# Implementation of the Quantum Approximate Optimization Algorithm (QAOA) [1],[2]
# specifically tailored for solving the MaxCut problem on graphs [3].
# This class facilitates the creation of QAOA circuits with
# various types of mixer operators and allows execution on a quantum simulator
# backend provided by Qiskit.
#
# The `Qaoa` class provides methods to:
# - Initialize with QAOA parameters, graph instance, mixer type, and backend settings
# - Create cost operator and various mixer operators (x, xx, y, yy, xy)
# - Generate the complete QAOA circuit
#
# Initialization parameters include the number of QAOA layers, angles for the
# mixer and cost operators, and options for setting verbosity, measurement, and
# random seed. The class checks for consistency in the provided parameters and
# supports visualizing the graph and QAOA circuit.
#
# Refs.
# [1] https://arxiv.org/abs/1411.4028
# [2] https://learning.quantum.ibm.com/tutorial/quantum-approximate-optimization-algorithm
# [3] https://en.wikipedia.org/wiki/Maximum_cut
#
# © Leonardo Lavagna 2024
# @ NESYA https://github.com/NesyaLab
#------------------------------------------------------------------------------
import numpy as np
from matplotlib import pyplot as plt
from classes import Problems as P
from functions import qaoa_utilities as utils
from qiskit import QuantumCircuit
from qiskit_aer import Aer
from typing import List, Tuple
from networkx import Graph
from qiskit.circuit import ParameterVector
class Qaoa:
def __init__(self, p: int = 0, G: Graph = None, betas: List[float] = None, gammas: List[float] = None,
mixer: str = "x", backend = Aer.get_backend('qasm_simulator'), measure: bool = True,
seed: int = None, verbose: bool = True):
"""Initialize class QAOA.
Args:
p (int): Positive number of QAOA layers. The default is 0.
G (Graph): A graph created with the Problem class used as MaxCut problem instance. The default is None.
betas (float): Angles for the mixer operator.
gammas (float): Angles for the cost operator.
mixer (str): Type of mixer operator to be used. The default is "x".
backend (Qiskit backend): Qiskit backend to execute the code on a quantum simulator.
The default is Aer.get_backend('qasm_simulator').
measure (bool): If True measure the qaoa circuit. The default is True.
seed (int): Seed for a pseudo-random number generator. The default is None.
verbose (bool): If True enters in debugging mode. The default is True.
"""
# Setup
self.p = p
self.G = G
self.mixer = mixer
self.backend = backend
self.measure = measure
self.verbose = verbose
self.seed = seed
self.problems_class = P.Problems(p_type="custom", G=self.G)
if self.seed is not None:
np.random.seed(self.seed)
if self.G is None:
self.N = 0
self.w = [[]]
self.betas = []
self.gammas = []
if self.G is not None:
self.N = G.get_number_of_nodes()
self.w = G.get_adjacency_matrix()
if betas is None or gammas is None:
self.betas = utils.generate_parameters(n=self.p, k=1)
self.gammas = utils.generate_parameters(n=self.p, k=2)
if betas is not None and gammas is not None:
self.betas = betas
self.gammas = gammas
# Checking...
if self.problems_class.__class__.__name__ != self.G.__class__.__name__ and G is not None:
raise Exception("Invalid parameters. The graph G should be created with the Problems class.")
if (self.p == 0 and self.G is not None) or (self.p > 0 and G is None):
raise ValueError("If G is not the empty graph p should be a strictly positive integer, and viceversa.")
if len(self.betas) != p or len(self.gammas) != p or len(self.betas) != len(self.gammas):
raise ValueError("Invalid angles list. The length of betas and gammas should be equal to p.")
# Initializing...
if self.verbose is True:
print(" --------------------------- ")
print("| Intializing Qaoa class... |".upper())
print(" --------------------------- ")
print("-> Getting problem instance...".upper())
if self.G is not None:
self.G.get_draw()
plt.show()
if self.G is None:
print("\t * G = ø")
if self.betas is None and self.G is not None:
print("-> Beta angles not provided. Generating angles...".upper())
print(f"\t * betas = {self.betas}")
if self.gammas is None and self.G is not None:
print("-> Gamma angles not provided. Generating angles...".upper())
print(f"\t * gammas = {self.gammas}")
print("-> Getting the ansatz...".upper())
if self.G is not None:
print(self.get_circuit())
if self.G is None:
print("\t * Qaoa circuit = ø")
print("-> The Qaoa class was initialized with the following parameters.".upper())
print(f"\t * Number of layers: p = {self.p};")
if self.G is None:
print(f"\t * Graph: G = ø;")
if self.G is not None:
print(f"\t * Graph: G = {self.G.p_type};")
print("\t * Angles:")
print(f"\t\t - betas = {self.betas};")
print(f"\t\t - gammas = {self.gammas};")
print(f"\t * Mixer Hamiltonian type: '{self.mixer}';")
print(f"\t * Random seed: seed = {self.seed};")
print(f"\t * Measurement setting: measure = {self.measure}.")
def cost_operator(self, gamma: float) -> QuantumCircuit:
"""Create an instance of the cost operator with angle 'gamma'.
Args:
gamma (float): Angle for the cost operator.
Returns:
QuantumCircuit: Circuit representing the cost operator.
"""
qc = QuantumCircuit(self.N, self.N)
for i,j in self.G.get_edges():
qc.cx(i, j)
qc.rz(gamma, j)
qc.cx(i, j)
return qc
def x_mixer_operator(self, beta: float) -> QuantumCircuit:
"""Create an instance of the x-mixer operator with angle 'beta'.
Args:
beta (float): Angle for the mixer operator.
Returns:
QuantumCircuit: Circuit representing the mixer operator.
"""
qc = QuantumCircuit(self.N, self.N)
for v in self.G.get_nodes():
qc.rx(beta, v)
return qc
def xx_mixer_operator(self, beta: float) -> QuantumCircuit:
"""Create an instance of the xx-mixer operator with angle 'beta'.
Args:
beta (float): Angle for the mixer operator.
Returns:
QuantumCircuit: Circuit representing the mixer operator.
"""
qc = QuantumCircuit(self.N, self.N)
for i, j in self.G.get_edges():
if self.w[i, j] > 0:
qc.rxx(beta, i, j)
return qc
def y_mixer_operator(self, beta: float) -> QuantumCircuit:
"""Create an instance of the y-mixer operator with angle 'beta'.
Args:
beta (float): Angle for the mixer operator.
Returns:
QuantumCircuit: Circuit representing the mixer operator.
"""
qc = QuantumCircuit(self.N, self.N)
for v in self.G.get_nodes():
qc.ry(2 * beta, v)
return qc
def yy_mixer_operator(self, beta: float) -> QuantumCircuit:
"""Create an instance of the yy-mixer operator with angle 'beta'.
Args:
beta (float): Time-slice angle for the mixer operator.
Returns:
QuantumCircuit: Circuit representing the mixer operator.
"""
qc = QuantumCircuit(self.N, self.N)
for i, j in self.G.get_edges():
if self.w[i, j] > 0:
qc.ryy(beta / 2, i, j)
return qc
def xy_mixer_operator(self, phi: float, psi: float) -> QuantumCircuit:
"""Create an instance of the xy-mixer operator with angle 'beta'.
Args:
beta (float): Angle for the mixer operator.
Returns:
QuantumCircuit: Circuit representing the mixer operator.
"""
qc = QuantumCircuit(self.N, self.N)
# X_iX_j
for i, j in self.G.get_edges():
if self.w[i, j] > 0:
qc.rxx(phi / 2, i, j)
# Y_iY_j
for i, j in self.G.get_edges():
if self.w[i, j] > 0:
qc.ryy(psi / 2, i, j)
return qc
def get_circuit(self) -> QuantumCircuit:
"""Create an instance of the Qaoa circuit with given parameters.
Returns:
QuantumCircuit: Circuit representing the Qaoa.
"""
qc = QuantumCircuit(self.N, self.N)
params = ParameterVector("params", 2 * self.p)
betas = params[0 : self.p]
gammas = params[self.p : 2 * self.p]
qc.h(range(self.N))
qc.barrier(range(self.N))
for i in range(self.p):
qc = qc.compose(self.cost_operator(gammas[i]))
qc.barrier(range(self.N))
if self.mixer == "x":
qc = qc.compose(self.x_mixer_operator(betas[i]))
qc.barrier(range(self.N))
elif self.mixer == "xx":
qc = qc.compose(self.xx_mixer_operator(betas[i]))
qc.barrier(range(self.N))
elif self.mixer == "y":
qc = qc.compose(self.y_mixer_operator(betas[i]))
qc.barrier(range(self.N))
elif self.mixer == "yy":
qc = qc.compose(self.yy_mixer_operator(betas[i]))
qc.barrier(range(self.N))
elif self.mixer == "xy":
qc = qc.compose(self.xy_mixer_operator(betas[i],betas[i]))
qc.barrier(range(self.N))
qc.barrier(range(self.N))
if self.measure:
qc.measure(range(self.N), range(self.N))
return qc
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Stochastic Swap pass"""
import unittest
import numpy.random
from ddt import ddt, data
from qiskit.transpiler.passes import StochasticSwap
from qiskit.transpiler import CouplingMap, PassManager, Layout
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.test._canonical import canonicalize_control_flow
from qiskit.transpiler.passes.utils import CheckMap
from qiskit.circuit.random import random_circuit
from qiskit.providers.fake_provider import FakeMumbai, FakeMumbaiV2
from qiskit.compiler.transpiler import transpile
from qiskit.circuit import ControlFlowOp, Clbit, CASE_DEFAULT
from qiskit.circuit.classical import expr
@ddt
class TestStochasticSwap(QiskitTestCase):
"""
Tests the StochasticSwap pass.
All of the tests use a fixed seed since the results
may depend on it.
"""
def test_trivial_case(self):
"""
q0:--(+)-[H]-(+)-
| |
q1:---.-------|--
|
q2:-----------.--
Coupling map: [1]--[0]--[2]
"""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_trivial_in_same_layer(self):
"""
q0:--(+)--
|
q1:---.---
q2:--(+)--
|
q3:---.---
Coupling map: [0]--[1]--[2]--[3]
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[2], qr[3])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_permute_wires_1(self):
"""
q0:--------
q1:---.----
|
q2:--(+)---
Coupling map: [1]--[0]--[2]
q0:--x-(+)-
| |
q1:--|--.--
|
q2:--x-----
"""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 11)
after = pass_.run(dag)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[2])
expected.cx(qr[1], qr[0])
self.assertEqual(circuit_to_dag(expected), after)
def test_permute_wires_2(self):
"""
qr0:---.---[H]--
|
qr1:---|--------
|
qr2:--(+)-------
Coupling map: [0]--[1]--[2]
qr0:----.---[H]-
|
qr1:-x-(+)------
|
qr2:-x----------
"""
coupling = CouplingMap([[1, 0], [1, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 11)
after = pass_.run(dag)
expected = QuantumCircuit(qr)
expected.swap(qr[1], qr[2])
expected.cx(qr[0], qr[1])
expected.h(qr[0])
self.assertEqual(expected, dag_to_circuit(after))
def test_permute_wires_3(self):
"""
qr0:--(+)---.--
| |
qr1:---|----|--
| |
qr2:---|----|--
| |
qr3:---.---(+)-
Coupling map: [0]--[1]--[2]--[3]
qr0:-x------------
|
qr1:-x--(+)---.---
| |
qr2:-x---.---(+)--
|
qr3:-x------------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[0])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[1])
expected.swap(qr[2], qr[3])
expected.cx(qr[1], qr[2])
expected.cx(qr[2], qr[1])
self.assertEqual(circuit_to_dag(expected), after)
def test_permute_wires_4(self):
"""No qubit label permutation occurs if the first
layer has only single-qubit gates. This is suboptimal
but seems to be the current behavior.
qr0:------(+)--
|
qr1:-------|---
|
qr2:-------|---
|
qr3:--[H]--.---
Coupling map: [0]--[1]--[2]--[3]
qr0:------X---------
|
qr1:------X-(+)-----
|
qr2:------X--.------
|
qr3:-[H]--X---------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr[3])
circuit.cx(qr[3], qr[0])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
expected = QuantumCircuit(qr)
expected.h(qr[3])
expected.swap(qr[2], qr[3])
expected.swap(qr[0], qr[1])
expected.cx(qr[2], qr[1])
self.assertEqual(circuit_to_dag(expected), after)
def test_permute_wires_5(self):
"""This is the same case as permute_wires_4
except the single qubit gate is after the two-qubit
gate, so the layout is adjusted.
qr0:--(+)------
|
qr1:---|-------
|
qr2:---|-------
|
qr3:---.--[H]--
Coupling map: [0]--[1]--[2]--[3]
qr0:-x-----------
|
qr1:-x--(+)------
|
qr2:-x---.--[H]--
|
qr3:-x-----------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[3], qr[0])
circuit.h(qr[3])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[1])
expected.swap(qr[2], qr[3])
expected.cx(qr[2], qr[1])
expected.h(qr[2])
self.assertEqual(circuit_to_dag(expected), after)
def test_all_single_qubit(self):
"""Test all trivial layers."""
coupling = CouplingMap([[0, 1], [1, 2], [1, 3]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circ = QuantumCircuit(qr, cr)
circ.h(qr)
circ.z(qr)
circ.s(qr)
circ.t(qr)
circ.tdg(qr)
circ.measure(qr[0], cr[0]) # intentional duplicate
circ.measure(qr[0], cr[0])
circ.measure(qr[1], cr[1])
circ.measure(qr[2], cr[2])
circ.measure(qr[3], cr[3])
dag = circuit_to_dag(circ)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_overoptimization_case(self):
"""Check mapper overoptimization.
The mapper should not change the semantics of the input.
An overoptimization introduced issue #81:
https://github.com/Qiskit/qiskit-terra/issues/81
"""
coupling = CouplingMap([[0, 2], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.y(qr[1])
circuit.z(qr[2])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
circuit.s(qr[1])
circuit.t(qr[2])
circuit.h(qr[3])
circuit.cx(qr[1], qr[2])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
circuit.measure(qr[2], cr[2])
circuit.measure(qr[3], cr[3])
dag = circuit_to_dag(circuit)
# ┌───┐ ┌─┐
# q_0: | 0 >┤ X ├────────────■───────────────────────────┤M├─────────
# └───┘┌───┐ ┌─┴─┐ ┌───┐ └╥┘┌─┐
# q_1: | 0 >─────┤ Y ├─────┤ X ├─────┤ S ├────────────■───╫─┤M├──────
# └───┘┌───┐└───┘ └───┘┌───┐ ┌─┴─┐ ║ └╥┘┌─┐
# q_2: | 0 >──────────┤ Z ├───────■───────┤ T ├─────┤ X ├─╫──╫─┤M├───
# └───┘ ┌─┴─┐ └───┘┌───┐└───┘ ║ ║ └╥┘┌─┐
# q_3: | 0 >────────────────────┤ X ├──────────┤ H ├──────╫──╫──╫─┤M├
# └───┘ └───┘ ║ ║ ║ └╥┘
# c_0: 0 ══════════════════════════════════════════════╩══╬══╬══╬═
# ║ ║ ║
# c_1: 0 ═════════════════════════════════════════════════╩══╬══╬═
# ║ ║
# c_2: 0 ════════════════════════════════════════════════════╩══╬═
# ║
# c_3: 0 ═══════════════════════════════════════════════════════╩═
#
expected = QuantumCircuit(qr, cr)
expected.z(qr[2])
expected.y(qr[1])
expected.x(qr[0])
expected.swap(qr[0], qr[2])
expected.cx(qr[2], qr[1])
expected.swap(qr[0], qr[2])
expected.cx(qr[2], qr[3])
expected.s(qr[1])
expected.t(qr[2])
expected.h(qr[3])
expected.measure(qr[0], cr[0])
expected.cx(qr[1], qr[2])
expected.measure(qr[3], cr[3])
expected.measure(qr[1], cr[1])
expected.measure(qr[2], cr[2])
expected_dag = circuit_to_dag(expected)
# ┌───┐ ┌─┐
# q_0: ┤ X ├─X───────X──────┤M├────────────────
# ├───┤ │ ┌───┐ │ ┌───┐└╥┘ ┌─┐
# q_1: ┤ Y ├─┼─┤ X ├─┼─┤ S ├─╫────────■──┤M├───
# ├───┤ │ └─┬─┘ │ └───┘ ║ ┌───┐┌─┴─┐└╥┘┌─┐
# q_2: ┤ Z ├─X───■───X───■───╫─┤ T ├┤ X ├─╫─┤M├
# └───┘ ┌─┴─┐ ║ ├───┤└┬─┬┘ ║ └╥┘
# q_3: ────────────────┤ X ├─╫─┤ H ├─┤M├──╫──╫─
# └───┘ ║ └───┘ └╥┘ ║ ║
# c: 4/══════════════════════╩════════╩═══╩══╩═
# 0 3 1 2
#
# Layout --
# {qr[0]: 0,
# qr[1]: 1,
# qr[2]: 2,
# qr[3]: 3}
pass_ = StochasticSwap(coupling, 20, 19)
after = pass_.run(dag)
self.assertEqual(expected_dag, after)
def test_already_mapped(self):
"""Circuit not remapped if matches topology.
See: https://github.com/Qiskit/qiskit-terra/issues/342
"""
coupling = CouplingMap(
[
[1, 0],
[1, 2],
[2, 3],
[3, 4],
[3, 14],
[5, 4],
[6, 5],
[6, 7],
[6, 11],
[7, 10],
[8, 7],
[9, 8],
[9, 10],
[11, 10],
[12, 5],
[12, 11],
[12, 13],
[13, 4],
[13, 14],
[15, 0],
[15, 0],
[15, 2],
[15, 14],
]
)
qr = QuantumRegister(16, "q")
cr = ClassicalRegister(16, "c")
circ = QuantumCircuit(qr, cr)
circ.cx(qr[3], qr[14])
circ.cx(qr[5], qr[4])
circ.h(qr[9])
circ.cx(qr[9], qr[8])
circ.x(qr[11])
circ.cx(qr[3], qr[4])
circ.cx(qr[12], qr[11])
circ.cx(qr[13], qr[4])
for j in range(16):
circ.measure(qr[j], cr[j])
dag = circuit_to_dag(circ)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(circ), after)
def test_congestion(self):
"""Test code path that falls back to serial layers."""
coupling = CouplingMap([[0, 1], [1, 2], [1, 3]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circ = QuantumCircuit(qr, cr)
circ.cx(qr[1], qr[2])
circ.cx(qr[0], qr[3])
circ.measure(qr[0], cr[0])
circ.h(qr)
circ.cx(qr[0], qr[1])
circ.cx(qr[2], qr[3])
circ.measure(qr[0], cr[0])
circ.measure(qr[1], cr[1])
circ.measure(qr[2], cr[2])
circ.measure(qr[3], cr[3])
dag = circuit_to_dag(circ)
# Input:
# ┌─┐┌───┐ ┌─┐
# q_0: |0>─────────────────■──────────────────┤M├┤ H ├──■─────┤M├
# ┌───┐ │ └╥┘└───┘┌─┴─┐┌─┐└╥┘
# q_1: |0>──■───────┤ H ├──┼───────────────────╫──────┤ X ├┤M├─╫─
# ┌─┴─┐┌───┐└───┘ │ ┌─┐ ║ └───┘└╥┘ ║
# q_2: |0>┤ X ├┤ H ├───────┼─────────■─────┤M├─╫────────────╫──╫─
# └───┘└───┘ ┌─┴─┐┌───┐┌─┴─┐┌─┐└╥┘ ║ ║ ║
# q_3: |0>───────────────┤ X ├┤ H ├┤ X ├┤M├─╫──╫────────────╫──╫─
# └───┘└───┘└───┘└╥┘ ║ ║ ║ ║
# c_0: 0 ═══════════════════════════════╬══╬══╩════════════╬══╩═
# ║ ║ ║
# c_1: 0 ═══════════════════════════════╬══╬═══════════════╩════
# ║ ║
# c_2: 0 ═══════════════════════════════╬══╩════════════════════
# ║
# c_3: 0 ═══════════════════════════════╩═══════════════════════
#
# Expected output (with seed 999):
# ┌───┐ ┌─┐
# q_0: ───────X──┤ H ├─────────────────X──────┤M├──────
# │ └───┘ ┌─┐ ┌───┐ │ ┌───┐└╥┘ ┌─┐
# q_1: ──■────X────■───────┤M├─X─┤ X ├─X─┤ X ├─╫────┤M├
# ┌─┴─┐┌───┐ │ └╥┘ │ └─┬─┘┌─┐└─┬─┘ ║ └╥┘
# q_2: ┤ X ├┤ H ├──┼────────╫──┼───■──┤M├──┼───╫─────╫─
# └───┘└───┘┌─┴─┐┌───┐ ║ │ ┌───┐└╥┘ │ ║ ┌─┐ ║
# q_3: ──────────┤ X ├┤ H ├─╫──X─┤ H ├─╫───■───╫─┤M├─╫─
# └───┘└───┘ ║ └───┘ ║ ║ └╥┘ ║
# c: 4/═════════════════════╩══════════╩═══════╩══╩══╩═
# 0 2 3 0 1
#
# Target coupling graph:
# 2
# |
# 0 - 1 - 3
expected = QuantumCircuit(qr, cr)
expected.cx(qr[1], qr[2])
expected.h(qr[2])
expected.swap(qr[0], qr[1])
expected.h(qr[0])
expected.cx(qr[1], qr[3])
expected.h(qr[3])
expected.measure(qr[1], cr[0])
expected.swap(qr[1], qr[3])
expected.cx(qr[2], qr[1])
expected.h(qr[3])
expected.swap(qr[0], qr[1])
expected.measure(qr[2], cr[2])
expected.cx(qr[3], qr[1])
expected.measure(qr[0], cr[3])
expected.measure(qr[3], cr[0])
expected.measure(qr[1], cr[1])
expected_dag = circuit_to_dag(expected)
pass_ = StochasticSwap(coupling, 20, 999)
after = pass_.run(dag)
self.assertEqual(expected_dag, after)
def test_only_output_cx_and_swaps_in_coupling_map(self):
"""Test that output DAG contains only 2q gates from the the coupling map."""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[3])
circuit.measure(qr, cr)
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 5)
after = pass_.run(dag)
valid_couplings = [{qr[a], qr[b]} for (a, b) in coupling.get_edges()]
for _2q_gate in after.two_qubit_ops():
self.assertIn(set(_2q_gate.qargs), valid_couplings)
def test_len_cm_vs_dag(self):
"""Test error if the coupling map is smaller than the dag."""
coupling = CouplingMap([[0, 1], [1, 2]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[3])
circuit.measure(qr, cr)
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling)
with self.assertRaises(TranspilerError):
_ = pass_.run(dag)
def test_single_gates_omitted(self):
"""Test if single qubit gates are omitted."""
coupling_map = [[0, 1], [1, 0], [1, 2], [1, 3], [2, 1], [3, 1], [3, 4], [4, 3]]
# q_0: ──■──────────────────
# │
# q_1: ──┼─────────■────────
# │ ┌─┴─┐
# q_2: ──┼───────┤ X ├──────
# │ ┌────┴───┴─────┐
# q_3: ──┼──┤ U(1,1.5,0.7) ├
# ┌─┴─┐└──────────────┘
# q_4: ┤ X ├────────────────
# └───┘
qr = QuantumRegister(5, "q")
cr = ClassicalRegister(5, "c")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[4])
circuit.cx(qr[1], qr[2])
circuit.u(1, 1.5, 0.7, qr[3])
# q_0: ─────────────────X──────
# │
# q_1: ───────■─────────X───■──
# ┌─┴─┐ │
# q_2: ─────┤ X ├───────────┼──
# ┌────┴───┴─────┐ ┌─┴─┐
# q_3: ┤ U(1,1.5,0.7) ├─X─┤ X ├
# └──────────────┘ │ └───┘
# q_4: ─────────────────X──────
expected = QuantumCircuit(qr, cr)
expected.cx(qr[1], qr[2])
expected.u(1, 1.5, 0.7, qr[3])
expected.swap(qr[0], qr[1])
expected.swap(qr[3], qr[4])
expected.cx(qr[1], qr[3])
expected_dag = circuit_to_dag(expected)
stochastic = StochasticSwap(CouplingMap(coupling_map), seed=0)
after = PassManager(stochastic).run(circuit)
after = circuit_to_dag(after)
self.assertEqual(expected_dag, after)
@ddt
class TestStochasticSwapControlFlow(QiskitTestCase):
"""Tests for control flow in stochastic swap."""
def test_pre_if_else_route(self):
"""test swap with if else controlflow construct"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.measure(2, 2)
true_body = QuantumCircuit(qreg, creg[[2]])
true_body.x(3)
false_body = QuantumCircuit(qreg, creg[[2]])
false_body.x(4)
qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[2]])
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=82).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.swap(0, 1)
expected.cx(1, 2)
expected.measure(2, 2)
etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[2]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[2]])
efalse_body.x(1)
new_order = [1, 0, 2, 3, 4]
expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[2]])
expected.barrier(qreg)
expected.measure(qreg, creg[new_order])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_if_else_route_post_x(self):
"""test swap with if else controlflow construct; pre-cx and post x"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.measure(2, 2)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(3)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.x(4)
qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[0]])
qc.x(1)
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=431).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.swap(1, 2)
expected.cx(0, 1)
expected.measure(1, 2)
new_order = [0, 2, 1, 3, 4]
etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
efalse_body.x(1)
expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]])
expected.x(2)
expected.barrier(qreg)
expected.measure(qreg, creg[new_order])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_post_if_else_route(self):
"""test swap with if else controlflow construct; post cx"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(3)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.x(4)
qc.barrier(qreg)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.barrier(qreg)
qc.cx(0, 2)
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=6508).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
efalse_body.x(1)
expected.barrier(qreg)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]])
expected.barrier(qreg)
expected.swap(0, 1)
expected.cx(1, 2)
expected.barrier(qreg)
expected.measure(qreg, creg[[1, 0, 2, 3, 4]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_if_else2(self):
"""test swap with if else controlflow construct; cx in if statement"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(0)
false_body = QuantumCircuit(qreg, creg[[0]])
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=38).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.swap(0, 1)
expected.cx(1, 2)
expected.measure(1, 0)
etrue_body = QuantumCircuit(qreg[[1]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[1]], creg[[0]])
new_order = [1, 0, 2, 3, 4]
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1]], creg[[0]])
expected.barrier(qreg)
expected.measure(qreg, creg[new_order])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_intra_if_else_route(self):
"""test swap with if else controlflow construct"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.cx(0, 4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=8).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg, creg[[0]])
etrue_body.swap(0, 1)
etrue_body.cx(1, 2)
etrue_body.swap(1, 2)
etrue_body.swap(3, 4)
efalse_body = QuantumCircuit(qreg, creg[[0]])
efalse_body.swap(0, 1)
efalse_body.swap(1, 2)
efalse_body.swap(3, 4)
efalse_body.cx(2, 3)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]])
new_order = [1, 2, 0, 4, 3]
expected.measure(qreg, creg[new_order])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_intra_if_else(self):
"""test swap with if else controlflow construct; cx in if statement"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.cx(0, 4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=2, trials=20).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
etrue_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]])
efalse_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]])
expected.h(0)
expected.x(1)
expected.swap(0, 1)
expected.cx(1, 2)
expected.measure(1, 0)
etrue_body.cx(0, 1)
etrue_body.swap(2, 3)
etrue_body.swap(0, 1)
efalse_body.swap(0, 1)
efalse_body.swap(2, 3)
efalse_body.cx(1, 2)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 2, 3, 4]], creg[[0]])
expected.measure(qreg, creg[[1, 2, 0, 4, 3]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_intra_post_if_else(self):
"""test swap with if else controlflow construct; cx before, in, and after if
statement"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.cx(0, 4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.h(3)
qc.cx(3, 0)
qc.barrier()
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.swap(1, 2)
expected.cx(0, 1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg, creg[[0]])
etrue_body.cx(0, 1)
etrue_body.swap(0, 1)
etrue_body.swap(4, 3)
etrue_body.swap(2, 3)
efalse_body = QuantumCircuit(qreg, creg[[0]])
efalse_body.swap(0, 1)
efalse_body.swap(3, 4)
efalse_body.swap(2, 3)
efalse_body.cx(1, 2)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[0, 1, 2, 3, 4]], creg[[0]])
expected.swap(1, 2)
expected.h(4)
expected.swap(3, 4)
expected.cx(3, 2)
expected.barrier()
expected.measure(qreg, creg[[2, 4, 0, 3, 1]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_if_expr(self):
"""Test simple if conditional with an `Expr` condition."""
coupling = CouplingMap.from_line(4)
body = QuantumCircuit(4)
body.cx(0, 1)
body.cx(0, 2)
body.cx(0, 3)
qc = QuantumCircuit(4, 2)
qc.if_test(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], [])
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=58).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
def test_if_else_expr(self):
"""Test simple if/else conditional with an `Expr` condition."""
coupling = CouplingMap.from_line(4)
true = QuantumCircuit(4)
true.cx(0, 1)
true.cx(0, 2)
true.cx(0, 3)
false = QuantumCircuit(4)
false.cx(3, 0)
false.cx(3, 1)
false.cx(3, 2)
qc = QuantumCircuit(4, 2)
qc.if_else(expr.logic_and(qc.clbits[0], qc.clbits[1]), true, false, [0, 1, 2, 3], [])
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=58).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
def test_no_layout_change(self):
"""test controlflow with no layout change needed"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.x(4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=23).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.swap(1, 2)
expected.cx(0, 1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg[[1, 4]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[1, 4]], creg[[0]])
efalse_body.x(1)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 4]], creg[[0]])
expected.barrier(qreg)
expected.measure(qreg, creg[[0, 2, 1, 3, 4]])
self.assertEqual(dag_to_circuit(cdag), expected)
@data(1, 2, 3)
def test_for_loop(self, nloops):
"""test stochastic swap with for_loop"""
# if the loop has only one iteration it isn't necessary for the pass
# to swap back to the starting layout. This test would check that
# optimization.
num_qubits = 3
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
for_body = QuantumCircuit(qreg)
for_body.cx(0, 2)
loop_parameter = None
qc.for_loop(range(nloops), loop_parameter, for_body, qreg, [])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=687).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
efor_body = QuantumCircuit(qreg)
efor_body.swap(0, 1)
efor_body.cx(1, 2)
efor_body.swap(0, 1)
loop_parameter = None
expected.for_loop(range(nloops), loop_parameter, efor_body, qreg, [])
expected.measure(qreg, creg)
self.assertEqual(dag_to_circuit(cdag), expected)
def test_while_loop(self):
"""test while loop"""
num_qubits = 4
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(len(qreg))
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
while_body = QuantumCircuit(qreg, creg)
while_body.reset(qreg[2:])
while_body.h(qreg[2:])
while_body.cx(0, 3)
while_body.measure(qreg[3], creg[3])
qc.while_loop((creg, 0), while_body, qc.qubits, qc.clbits)
qc.barrier()
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=58).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
ewhile_body = QuantumCircuit(qreg, creg[:])
ewhile_body.reset(qreg[2:])
ewhile_body.h(qreg[2:])
ewhile_body.swap(0, 1)
ewhile_body.swap(2, 3)
ewhile_body.cx(1, 2)
ewhile_body.measure(qreg[2], creg[3])
ewhile_body.swap(1, 0)
ewhile_body.swap(3, 2)
expected.while_loop((creg, 0), ewhile_body, expected.qubits, expected.clbits)
expected.barrier()
expected.measure(qreg, creg)
self.assertEqual(dag_to_circuit(cdag), expected)
def test_while_loop_expr(self):
"""Test simple while loop with an `Expr` condition."""
coupling = CouplingMap.from_line(4)
body = QuantumCircuit(4)
body.cx(0, 1)
body.cx(0, 2)
body.cx(0, 3)
qc = QuantumCircuit(4, 2)
qc.while_loop(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], [])
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=58).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
def test_switch_single_case(self):
"""Test routing of 'switch' with just a single case."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
qc.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = StochasticSwap(coupling, seed=58)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
case0.swap(0, 1)
expected.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg[:])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_switch_nonexhaustive(self):
"""Test routing of 'switch' with several but nonexhaustive cases."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.cx(3, 1)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.cx(4, 2)
qc.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = StochasticSwap(coupling, seed=58)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
case0.swap(0, 1)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.swap(1, 2)
case1.cx(3, 2)
case1.swap(1, 2)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.swap(3, 4)
case2.cx(3, 2)
case2.swap(3, 4)
expected.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
@data((0, 1, 2, 3), (CASE_DEFAULT,))
def test_switch_exhaustive(self, labels):
"""Test routing of 'switch' with exhaustive cases; we should not require restoring the
layout afterwards."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(2, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
qc.switch(creg, [(labels, case0)], qreg[[0, 1, 2]], creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = StochasticSwap(coupling, seed=58)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
expected.switch(creg, [(labels, case0)], qreg[[0, 1, 2]], creg)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_switch_nonexhaustive_expr(self):
"""Test routing of 'switch' with an `Expr` target and several but nonexhaustive cases."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.cx(3, 1)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.cx(4, 2)
qc.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = StochasticSwap(coupling, seed=58)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
case0.swap(0, 1)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.swap(1, 2)
case1.cx(3, 2)
case1.swap(1, 2)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.swap(3, 4)
case2.cx(3, 2)
case2.swap(3, 4)
expected.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
@data((0, 1, 2, 3), (CASE_DEFAULT,))
def test_switch_exhaustive_expr(self, labels):
"""Test routing of 'switch' with exhaustive cases on an `Expr` target; we should not require
restoring the layout afterwards."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(2, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
qc.switch(expr.bit_or(creg, 3), [(labels, case0)], qreg[[0, 1, 2]], creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = StochasticSwap(coupling, seed=58)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
expected.switch(expr.bit_or(creg, 3), [(labels, case0)], qreg[[0, 1, 2]], creg)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_nested_inner_cnot(self):
"""test swap in nested if else controlflow construct; swap in inner"""
seed = 1
num_qubits = 3
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
check_map_pass = CheckMap(coupling)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(0)
for_body = QuantumCircuit(qreg)
for_body.delay(10, 0)
for_body.barrier(qreg)
for_body.cx(0, 2)
loop_parameter = None
true_body.for_loop(range(3), loop_parameter, for_body, qreg, [])
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.y(0)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=seed).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg, creg[[0]])
etrue_body.x(0)
efor_body = QuantumCircuit(qreg)
efor_body.delay(10, 0)
efor_body.barrier(qreg)
efor_body.swap(1, 2)
efor_body.cx(0, 1)
efor_body.swap(1, 2)
etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg, [])
efalse_body = QuantumCircuit(qreg, creg[[0]])
efalse_body.y(0)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]])
expected.measure(qreg, creg)
self.assertEqual(dag_to_circuit(cdag), expected)
def test_nested_outer_cnot(self):
"""test swap with nested if else controlflow construct; swap in outer"""
seed = 200
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
true_body.x(0)
for_body = QuantumCircuit(qreg)
for_body.delay(10, 0)
for_body.barrier(qreg)
for_body.cx(1, 3)
loop_parameter = None
true_body.for_loop(range(3), loop_parameter, for_body, qreg, [])
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.y(0)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=seed).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg, creg[[0]])
etrue_body.swap(1, 2)
etrue_body.cx(0, 1)
etrue_body.x(0)
efor_body = QuantumCircuit(qreg)
efor_body.delay(10, 0)
efor_body.barrier(qreg)
efor_body.cx(2, 3)
etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg[[0, 1, 2, 3, 4]], [])
efalse_body = QuantumCircuit(qreg, creg[[0]])
efalse_body.y(0)
efalse_body.swap(1, 2)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]])
expected.measure(qreg, creg[[0, 2, 1, 3, 4]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_disjoint_looping(self):
"""Test looping controlflow on different qubit register"""
num_qubits = 4
cm = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(num_qubits, "q")
qc = QuantumCircuit(qr)
loop_body = QuantumCircuit(2)
loop_body.cx(0, 1)
qc.for_loop((0,), None, loop_body, [0, 2], [])
cqc = StochasticSwap(cm, seed=0)(qc)
expected = QuantumCircuit(qr)
efor_body = QuantumCircuit(qr[[0, 1, 2]])
efor_body.swap(1, 2)
efor_body.cx(0, 1)
efor_body.swap(1, 2)
expected.for_loop((0,), None, efor_body, [0, 1, 2], [])
self.assertEqual(cqc, expected)
def test_disjoint_multiblock(self):
"""Test looping controlflow on different qubit register"""
num_qubits = 4
cm = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(num_qubits, "q")
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(3, 1)
true_body.cx(0, 1)
false_body = QuantumCircuit(3, 1)
false_body.cx(0, 2)
qc.if_else((cr[0], 1), true_body, false_body, [0, 1, 2], [0])
cqc = StochasticSwap(cm, seed=353)(qc)
expected = QuantumCircuit(qr, cr)
etrue_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]])
etrue_body.cx(0, 1)
etrue_body.swap(0, 1)
efalse_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]])
efalse_body.swap(0, 1)
efalse_body.cx(1, 2)
expected.if_else((cr[0], 1), etrue_body, efalse_body, [0, 1, 2], cr[[0]])
self.assertEqual(cqc, expected)
def test_multiple_ops_per_layer(self):
"""Test circuits with multiple operations per layer"""
num_qubits = 6
coupling = CouplingMap.from_line(num_qubits)
check_map_pass = CheckMap(coupling)
qr = QuantumRegister(num_qubits, "q")
qc = QuantumCircuit(qr)
# This cx and the for_loop are in the same layer.
qc.cx(0, 2)
with qc.for_loop((0,)):
qc.cx(3, 5)
cqc = StochasticSwap(coupling, seed=0)(qc)
check_map_pass(cqc)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qr)
expected.swap(0, 1)
expected.cx(1, 2)
efor_body = QuantumCircuit(qr[[3, 4, 5]])
efor_body.swap(1, 2)
efor_body.cx(0, 1)
efor_body.swap(2, 1)
expected.for_loop((0,), None, efor_body, [3, 4, 5], [])
self.assertEqual(cqc, expected)
def test_if_no_else_restores_layout(self):
"""Test that an if block with no else branch restores the initial layout. If there is an
else branch, we don't need to guarantee this."""
qc = QuantumCircuit(8, 1)
with qc.if_test((qc.clbits[0], False)):
# Just some arbitrary gates with no perfect layout.
qc.cx(3, 5)
qc.cx(4, 6)
qc.cx(1, 4)
qc.cx(7, 4)
qc.cx(0, 5)
qc.cx(7, 3)
qc.cx(1, 3)
qc.cx(5, 2)
qc.cx(6, 7)
qc.cx(3, 2)
qc.cx(6, 2)
qc.cx(2, 0)
qc.cx(7, 6)
coupling = CouplingMap.from_line(8)
pass_ = StochasticSwap(coupling, seed=2022_10_13)
transpiled = pass_(qc)
# Check the pass claims to have done things right.
initial_layout = Layout.generate_trivial_layout(*qc.qubits)
self.assertEqual(initial_layout, pass_.property_set["final_layout"])
# Check that pass really did do it right.
inner_block = transpiled.data[0].operation.blocks[0]
running_layout = initial_layout.copy()
for instruction in inner_block:
if instruction.operation.name == "swap":
running_layout.swap(*instruction.qubits)
self.assertEqual(initial_layout, running_layout)
@ddt
class TestStochasticSwapRandomCircuitValidOutput(QiskitTestCase):
"""Assert the output of a transpilation with stochastic swap is a physical circuit."""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.backend = FakeMumbai()
cls.coupling_edge_set = {tuple(x) for x in cls.backend.configuration().coupling_map}
cls.basis_gates = set(cls.backend.configuration().basis_gates)
cls.basis_gates.update(["for_loop", "while_loop", "if_else"])
def assert_valid_circuit(self, transpiled):
"""Assert circuit complies with constraints of backend."""
self.assertIsInstance(transpiled, QuantumCircuit)
self.assertIsNotNone(getattr(transpiled, "_layout", None))
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name in {"barrier", "measure"}:
continue
self.assertIn(instruction.operation.name, self.basis_gates)
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
if not isinstance(instruction.operation, ControlFlowOp):
if len(qargs) > 2 or len(qargs) < 0:
raise Exception("Invalid number of qargs for instruction")
if len(qargs) == 2:
self.assertIn(qargs, self.coupling_edge_set)
else:
self.assertLessEqual(qargs[0], 26)
else:
for block in instruction.operation.blocks:
self.assertEqual(block.num_qubits, len(instruction.qubits))
self.assertEqual(block.num_clbits, len(instruction.clbits))
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
# Assert routing ran.
_visit_block(
transpiled,
qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)},
)
@data(*range(1, 27))
def test_random_circuit_no_control_flow(self, size):
"""Test that transpiled random circuits without control flow are physical circuits."""
circuit = random_circuit(size, 3, measure=True, seed=12342)
tqc = transpile(
circuit,
self.backend,
routing_method="stochastic",
layout_method="dense",
seed_transpiler=12342,
)
self.assert_valid_circuit(tqc)
@data(*range(1, 27))
def test_random_circuit_no_control_flow_target(self, size):
"""Test that transpiled random circuits without control flow are physical circuits."""
circuit = random_circuit(size, 3, measure=True, seed=12342)
tqc = transpile(
circuit,
routing_method="stochastic",
layout_method="dense",
seed_transpiler=12342,
target=FakeMumbaiV2().target,
)
self.assert_valid_circuit(tqc)
@data(*range(4, 27))
def test_random_circuit_for_loop(self, size):
"""Test that transpiled random circuits with nested for loops are physical circuits."""
circuit = random_circuit(size, 3, measure=False, seed=12342)
for_block = random_circuit(3, 2, measure=False, seed=12342)
inner_for_block = random_circuit(2, 1, measure=False, seed=12342)
with circuit.for_loop((1,)):
with circuit.for_loop((1,)):
circuit.append(inner_for_block, [0, 3])
circuit.append(for_block, [1, 0, 2])
circuit.measure_all()
tqc = transpile(
circuit,
self.backend,
basis_gates=list(self.basis_gates),
routing_method="stochastic",
layout_method="dense",
seed_transpiler=12342,
)
self.assert_valid_circuit(tqc)
@data(*range(6, 27))
def test_random_circuit_if_else(self, size):
"""Test that transpiled random circuits with if else blocks are physical circuits."""
circuit = random_circuit(size, 3, measure=True, seed=12342)
if_block = random_circuit(3, 2, measure=True, seed=12342)
else_block = random_circuit(2, 1, measure=True, seed=12342)
rng = numpy.random.default_rng(seed=12342)
inner_clbit_count = max((if_block.num_clbits, else_block.num_clbits))
if inner_clbit_count > circuit.num_clbits:
circuit.add_bits([Clbit() for _ in [None] * (inner_clbit_count - circuit.num_clbits)])
clbit_indices = list(range(circuit.num_clbits))
rng.shuffle(clbit_indices)
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.append(if_block, [0, 2, 1], clbit_indices[: if_block.num_clbits])
with else_:
circuit.append(else_block, [2, 5], clbit_indices[: else_block.num_clbits])
tqc = transpile(
circuit,
self.backend,
basis_gates=list(self.basis_gates),
routing_method="stochastic",
layout_method="dense",
seed_transpiler=12342,
)
self.assert_valid_circuit(tqc)
if __name__ == "__main__":
unittest.main()
|
https://github.com/erinaldi/bmn2-qiskit
|
erinaldi
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sys
plt.style.use("../figures/paper.mplstyle")
# parameters
def read_data(
optimizer: str,
p: dict,
):
"""Read the VQE convergence data for the mini BMN model from disk
Args:
optimizer (str): The optimizer used.
p (dict): The dictionary with the parameters for the filename.
Returns:
pandas.DataFrame: The dataframe collecting the results of the convergence
"""
filename = f"{p['f']}_l{p['l']}_convergence_{optimizer}_{p['v']}_depth{p['d']}_reps{p['n']}_max{p['m']}.h5"
try:
df = pd.read_hdf(filename, "vqe")
except FileNotFoundError as e:
print(f"{filename} not found. {e}")
sys.exit()
return df[df.counts<=p["s"]*p['m']] # only keep counts less than maxit
# parameters
def read_data_pickle(
optimizer: str,
p: dict,
):
"""Read the VQE convergence data for the mini BMN model from disk
Args:
optimizer (str): The optimizer used.
p (dict): The dictionary with the parameters for the filename.
Returns:
pandas.DataFrame: The dataframe collecting the results of the convergence
"""
filename = f"{p['f']}_l{p['l']}_convergence_{optimizer}_{p['v']}_depth{p['d']}_reps{p['n']}_max{p['m']}.gz"
try:
df = pd.read_pickle(filename)
except FileNotFoundError as e:
print(f"{filename} not found. {e}")
sys.exit()
return df[df.counts<=p["s"]*p['m']] # only keep counts less than maxit
def collect_data(
optimizers: list,
p: dict,
h5: bool = True,
):
"""Read the VQE convergence data for the mini BMN model from disk
Args:
optimizer (str): The optimizer used.
p (dict): The dictionary with the parameters for the filename.
h5 (bool, optional): if the file to collect data from are in HDF5 format. Defaults to true
Returns:
pandas.DataFrame: The dataframe collecting the all the results of the convergence
"""
# concatenate the results from all files
if h5:
frames = [read_data(o, p) for o in optimizers]
else:
frames = [read_data_pickle(o, p) for o in optimizers]
return pd.concat(frames, keys=optimizers, names=["Optimizer"])
depth = 9
g2N = 2.0
varform = ['ry','rz']
nrep = 100
maxit = 10000
datafolder = "../data/miniBMN_L2"
params = dict()
params["l"] = str(g2N).replace(".", "")
params["d"] = depth
params["v"] = "-".join(varform)
params["m"] = maxit
params["n"] = nrep
params["f"] = datafolder
params["s"] = 10.0 # factor to scale up maxit (works for SLSQP which does not care about maxit)
df = read_data_pickle("SLSQP",params)
df.plot.scatter(x='counts',y='energy',marker='.')
# opt_label = ["COBYLA", "L-BFGS-B","SLSQP"]#,"NELDER-MEAD"]
opt_label = ["COBYLA", "L-BFGS-B","SLSQP","NELDER-MEAD"]
# opt_label = ["COBYLA"]
result = collect_data(opt_label,params,h5=False)
result.groupby('rep').apply(lambda x: x.sort_values(by='counts',ascending=False).iloc[:4][['counts','energy']])
result.groupby('Optimizer').apply(min).style.format(precision=5).hide_columns(['counts','casimir']) # change the precision of the output
result.sort_values(by='energy').iloc[0]
gs = dict()
for r in opt_label:
gs[r] = result.loc[r].groupby('rep').apply(min).energy
gsdf = pd.DataFrame.from_dict(gs, dtype=float)
gsdf
gsdf.describe().T[["min","max","mean","std"]].style.format(precision=5) # change the precision of the output
gsdf['SLSQP'].idxmin()
gsdf.sort_values(by=['SLSQP'],ascending=True).plot.hist(y='SLSQP')
result.loc['SLSQP',39].plot(x='counts',y='energy')
ht = 0.003287
# select the best runs for each optimizer
fig, ax = plt.subplots(figsize=(20,8))
for o in opt_label:
result.loc[o,gsdf[o].idxmin()].plot(x='counts',y='energy', xlim=[0,10000],label=o, ax=ax)
ax.axhline(ht,c="k",ls="--", lw="2",label="HT")
ax.set_xlabel("iterations")
ax.set_ylabel("VQE energy")
ax.legend(loc="upper right")
filename = f"../figures/miniBMN_L2_l{params['l']}_convergence_{params['v']}_depth{params['d']}_nr{params['n']}_max{params['m']}"
plt.savefig(f"{filename}.pdf")
plt.savefig(f"{filename}.png")
plt.savefig(f"{filename}.svg")
# select the best runs for each optimizer
fig, ax = plt.subplots(figsize=(20,8))
for o in opt_label:
result.loc[o,gsdf[o].idxmin()].plot(x='counts',y='energy', xlim=[0,50000],label=o, ax=ax)
ax.axhline(ht,c="k",ls="--", lw="2",label="HT")
# inset axes.... bounds are [x0, y0, width, height] for where to put it
axins = ax.inset_axes([0.4, 0.4, 0.3, 0.5])
for o in opt_label:
result.loc[o,gsdf[o].idxmin()].plot(x='counts',y='energy', xlim=[0,12000], legend=False, ax=axins)
axins.axhline(ht,c="k",ls="--", lw="2")
# sub region of the original image
x1, x2, y1, y2 = 0, 12000, 0, 1
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
axins.set_xticklabels('')
axins.set_yticklabels('')
axins.set_ylabel('')
axins.set_xlabel('')
ax.indicate_inset_zoom(axins, edgecolor="black")
ax.set_xlabel("iterations")
ax.set_ylabel("VQE energy")
ax.legend(loc="upper right")
filename = f"../figures/miniBMN_L2_l{params['l']}_convergence_{params['v']}_depth{params['d']}_nr{params['n']}_max{params['m']}_zoom50000"
plt.savefig(f"{filename}.pdf")
plt.savefig(f"{filename}.png")
plt.savefig(f"{filename}.svg")
depths = [1,2,3,4,5,6,7,8,9]
opts = ["COBYLA","L-BFGS-B","SLSQP","NELDER-MEAD"]
# for d in depths:
# params['d'] = d
# print(f"Depth={params['d']} ---------------------")
# res = collect_data(opts,params,h5=False)
# gs = dict()
# for r in opts:
# gs[r] = res.loc[r].groupby('rep').apply(min).energy
# gsdf = pd.DataFrame.from_dict(gs, dtype=float)
# print(gsdf.describe().T[["min","max","mean","std"]])
ds = dict()
for d in depths:
params['d'] = d
res = collect_data(opts,params,h5=False)
ds[d] = res.groupby('Optimizer').apply(min).energy
dfds = pd.DataFrame.from_dict(ds,orient='index',dtype=float).rename_axis("depth")
dfds
ht = 0.00328726
fig, ax = plt.subplots()
dfds.plot(marker="o", ylim=[0,0.2], ax=ax)
ax.axhline(ht,c="k",ls="--",lw="2",label="HT")
ax.set_ylabel("VQE energy")
ax.set_xlabel(r"$R_yR_z$"+" depth")
ax.legend(loc="upper right")
# plt.savefig("../figures/miniBMN_L2_l02_ry-rz_nr100_max10000_depths.pdf")
# plt.savefig("../figures/miniBMN_L2_l02_ry-rz_nr100_max10000_depths.png")
# plt.savefig("../figures/miniBMN_L2_l02_ry-rz_nr100_max10000_depths.svg")
depth = 3
g2N = 2.0
varform = ['ry']
nrep = 100
maxit = 10000
dataprefix = "../data/bosBMN_L2"
params = dict()
params["l"] = str(g2N).replace(".", "")
params["d"] = depth
params["v"] = "-".join(varform)
params["m"] = maxit
params["n"] = nrep
params["f"] = dataprefix
params["s"] = 1.0
opt_label = ["COBYLA","L-BFGS-B","SLSQP","NELDER-MEAD"]
result = collect_data(opt_label,params,False)
result.groupby('Optimizer').apply(min)
gs = dict()
for r in opt_label:
gs[r] = result.loc[r].groupby('rep').apply(min).energy
gsdf = pd.DataFrame.from_dict(gs, dtype=float)
gsdf.describe().T[["min","max","mean","std"]].style.format(precision=5) # change the precision of the output
ht = 3.13406
# select the best runs for each optimizer
fig, ax = plt.subplots(figsize=(20,8))
for o in opt_label:
result.loc[o,gsdf[o].idxmin()].plot(x='counts',y='energy', xlim=[0,10000],label=o, ax=ax)
ax.axhline(ht,c="k",ls="--", lw="2",label="HT")
ax.set_xlabel("iterations")
ax.set_ylabel("VQE energy")
ax.legend(loc="upper right")
# filename = f"../figures/miniBMN_l{params['l']}_convergence_{params['v']}_depth{params['d']}_nr{params['n']}_max{params['m']}"
# plt.savefig(f"{filename}.pdf")
# plt.savefig(f"{filename}.png")
# select the best runs for each optimizer
fig, ax = plt.subplots(figsize=(20,8))
for o in opt_label:
result.loc[o,gsdf[o].idxmin()].plot(x='counts',y='energy', xlim=[0,10000],label=o, ax=ax)
ax.axhline(ht,c="k",ls="--", lw="2",label="HT")
# inset axes.... bounds are [x0, y0, width, height] for where to put it
axins = ax.inset_axes([0.3, 0.4, 0.3, 0.5])
for o in opt_label:
result.loc[o,gsdf[o].idxmin()].plot(x='counts',y='energy', xlim=[0,1000], legend=False, ax=axins)
axins.axhline(ht,c="k",ls="--", lw="2")
# sub region of the original image
x1, x2, y1, y2 = 0, 1000, 3.1, 6
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
axins.set_xticklabels('')
axins.set_yticklabels('')
axins.set_ylabel('')
axins.set_xlabel('')
ax.indicate_inset_zoom(axins, edgecolor="black")
ax.set_xlabel("iterations")
ax.set_ylabel("VQE energy")
ax.legend(loc="upper right")
figprefix = dataprefix.replace("data","figures")
filename = f"{figprefix}_l{params['l']}_convergence_{params['v']}_depth{params['d']}_nr{params['n']}_max{params['m']}_zoom"
plt.savefig(f"{filename}.pdf")
plt.savefig(f"{filename}.png")
plt.savefig(f"{filename}.svg")
# df = pd.read_csv("../data/bosBMN_L2_couplings_ry_depth3_reps100.csv", index_col='l', dtype=float)
df = pd.read_csv("../data/bosBMN_L4_couplings_ry_depth3_reps100.csv", index_col='l', dtype=float)
df
df = df.assign(COBYLA_HT=df['COBYLA']-df['HT'])
df = df.assign(L_BFGS_B_HT=df['L-BFGS-B']-df['HT'])
df = df.assign(SLSQP_HT=df['SLSQP']-df['HT'])
df = df.assign(NELDER_MEAD_HT=df['NELDER-MEAD']-df['HT'])
fig, ax = plt.subplots()
df.plot(y='HT', marker='o', ax=ax)
df.plot(y='COBYLA', marker='o', ax=ax)
ax.set_xlabel(r"$\lambda$")
fig, ax = plt.subplots()
df.plot.bar(y=['COBYLA_HT','L_BFGS_B_HT','SLSQP_HT','NELDER_MEAD_HT'],label=False,ax=ax)
ax.tick_params(axis="x", rotation=0)
ax.set_xlabel(r"$\lambda$")
ax.set_ylabel("Energy difference")
ax.legend(["COBYLA","L-BFGS-B","SLSQP","NELDER-MEAD"])
plt.savefig("../figures/bosBMN_L4_couplings_e-diff_ry_depth3_reps100_max10000.pdf")
plt.savefig("../figures/bosBMN_L4_couplings_e-diff_ry_depth3_reps100_max10000.png")
plt.savefig("../figures/bosBMN_L4_couplings_e-diff_ry_depth3_reps100_max10000.svg")
df = pd.read_csv("../data/times_mini.csv", dtype=float)
df.head()
df.plot.hist()
df['minutes'] = df['seconds']/60.
df['hours'] = df['seconds']/3600.
df.describe().T
df.plot.hist(y='hours')
|
https://github.com/jaykomarraju/Quantum-Optimization-for-Solar-Farm
|
jaykomarraju
|
import numpy as np
import networkx as nx
from qiskit import Aer
from qiskit.algorithms import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.algorithms import MinimumEigenOptimizer
num_time_slots = 24
# Define the QUBO problem
qubo = QuadraticProgram()
# Add binary variables for charging (c) and discharging (d) states
for t in range(num_time_slots):
qubo.binary_var(f'c_{t}')
qubo.binary_var(f'd_{t}')
# Define the objective function
# (In practice, you need to calculate Jij and hi based on the solar farm data)
Jij = np.random.rand(num_time_slots, num_time_slots) * 0.5
hi_c = -1 + np.random.rand(num_time_slots)
hi_d = 1 - np.random.rand(num_time_slots)
# Set linear and quadratic terms of the objective function
linear_terms = {}
quadratic_terms = {}
for t in range(num_time_slots):
linear_terms[f'c_{t}'] = hi_c[t]
linear_terms[f'd_{t}'] = hi_d[t]
for s in range(num_time_slots):
if t != s:
quadratic_terms[(f'c_{t}', f'c_{s}')] = Jij[t, s]
quadratic_terms[(f'd_{t}', f'd_{s}')] = Jij[t, s]
qubo.minimize(linear=linear_terms, quadratic=quadratic_terms)
# Set up the quantum instance
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, seed_simulator=42, seed_transpiler=42, shots=10000)
# Set up the QAOA algorithm and optimizer
optimizer = COBYLA(maxiter=500)
qaoa = QAOA(optimizer=optimizer, reps=5, quantum_instance=quantum_instance)
# Set up the minimum eigen optimizer
min_eig_optimizer = MinimumEigenOptimizer(qaoa)
# Solve the problem
result = min_eig_optimizer.solve(qubo)
print("QAOA result:", result)
# Solve the problem using a classical solver (NumPyMinimumEigensolver)
exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
exact_result = exact_solver.solve(qubo)
print("Classical result:", exact_result)
|
https://github.com/arnavdas88/QuGlassyIsing
|
arnavdas88
|
!pip install qiskit
J = 4.0
B_x = 0.5
B_z = 1.0
import numpy as np
from qiskit.providers.aer import AerSimulator, QasmSimulator
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.aqua.operators import *
from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance
from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, NumPyEigensolver
from qiskit.circuit import QuantumCircuit, ParameterVector
from qiskit.visualization import plot_histogram
Hamiltonian = J * (Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)
- B_z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z )
) - B_x * ( ( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ))
ansatz = TwoLocal(num_qubits=36, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)
print(ansatz)
backend = AerSimulator(method='matrix_product_state')
quantum_instance = QuantumInstance(backend,
shots = 8192,
initial_layout = None,
optimization_level = 3)
optimizer = COBYLA(maxiter=10000, tol=0.000000001)
vqe = VQE(Hamiltonian, ansatz, optimizer, include_custom = False)
print('We are using:', quantum_instance.backend)
vqe_result = vqe.run(quantum_instance)
print(vqe['result'])
plot_histogram(vqe_result['eigenstate'])
import pickle
filename = "2D_Ising_Model_CountsAF2.pkl"
a = {'vqe_result': vqe_result}
#This saves the data
with open(filename, 'wb') as handle:
pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL)
# This loads the data
with open(filename, 'rb') as handle:
b = pickle.load(handle)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a DensityMatrix
state = DensityMatrix(qc)
plot_state_city(state)
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
%reload_ext autoreload
%autoreload 2
import sys
sys.path.append("../..")
from clonk.backend_utils import FakeHatlab
backend_hatlab = FakeHatlab(dimension=1, router_as_qubits=False)
from clonk.utils.transpiler_passes import level_0_pass_manager
pm_hypercube = level_0_pass_manager(
backend_hatlab,
basis_gate="riswap",
routing="basic",
decompose_swaps=False,
decompose_1q=False,
)
from qiskit import QuantumCircuit
circuit = QuantumCircuit(20)
circuit.cx(1, 4)
circuit.cx(3, 2)
circuit.cx(6, 8)
# circuit.draw()
transp = pm_hypercube.run(circuit)
transp.draw(output="mpl")
from qiskit.converters import circuit_to_dag
from qiskit.visualization import dag_drawer
dag = circuit_to_dag(transp)
dag_drawer(dag)
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
from qiskit.circuit import QuantumCircuit
from qiskit.primitives import Estimator, Sampler
from qiskit.quantum_info import SparsePauliOp
from qiskit.visualization import plot_histogram
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('dark_background') # optional
# create excited |1> state
qc_1 = QuantumCircuit(1)
qc_1.x(0)
qc_1.draw('mpl')
# create superposition |+> state
qc_plus = QuantumCircuit(1)
qc_plus.h(0)
qc_plus.draw('mpl')
qc_1.measure_all()
qc_plus.measure_all()
sampler = Sampler()
job_1 = sampler.run(qc_1)
job_plus = sampler.run(qc_plus)
job_1.result().quasi_dists
job_plus.result().quasi_dists
legend = ["Excited State", "Plus State"] # TODO: Excited State does not appear
plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend)
qc_1.remove_final_measurements()
qc_plus.remove_final_measurements()
# rotate into the X-basis
qc_1.h(0)
qc_plus.h(0)
qc_1.measure_all()
qc_plus.measure_all()
sampler = Sampler()
job_1 = sampler.run(qc_1)
job_plus = sampler.run(qc_plus)
plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend)
qc2_1 = QuantumCircuit(1)
qc2_1.x(0)
qc2_plus = QuantumCircuit(1)
qc2_plus.h(0)
obsvs = list(SparsePauliOp(['Z', 'X']))
estimator = Estimator()
job2_1 = estimator.run([qc2_1]*len(obsvs), observables=obsvs)
job2_plus = estimator.run([qc2_plus]*len(obsvs), observables=obsvs)
job2_1.result()
# TODO: make this into module that outputs a nice table
print(f' | <Z> | <X> ')
print(f'----|------------------')
print(f'|1> | {job2_1.result().values[0]} | {job2_1.result().values[1]}')
print(f'|+> | {job2_plus.result().values[0]} | {job2_plus.result().values[1]}')
A, a, B, b = SparsePauliOp(["Z", "X", "Z", "X"])
obsv = A.tensor(B) - A.tensor(b)+ a.tensor(B) + a.tensor(b) # create operator for chsh witness
from qc_grader.challenges.qgss_2023 import grade_lab2_ex1
grade_lab2_ex1(obsv)
from qiskit.circuit import Parameter
theta = Parameter('θ')
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.ry(theta, 0)
qc.draw('mpl')
angles = [[float(v)] for v in np.linspace(0, 2*np.pi, 10).astype(np.float32)]
# create a parameterization of angles that will violate the inequality
estimator = Estimator()
job = estimator.run([qc]*len(angles), observables=[obsv]*len(angles), parameter_values=angles)
exps = job.result().values
plt.plot(angles, exps, marker='x', ls='-', color='green')
plt.plot(angles, [2]*len(angles), ls='--', color='red', label='Classical Bound')
plt.plot(angles, [-2]*len(angles), ls='--', color='red')
plt.xlabel('angle (rad)')
plt.ylabel('CHSH Witness')
plt.legend(loc=4)
from qc_grader.challenges.qgss_2023 import grade_lab2_ex2
grade_lab2_ex2(obsv, angles)
from qiskit.circuit import ClassicalRegister, QuantumRegister
theta = Parameter('θ')
qr = QuantumRegister(1, 'q')
qc = QuantumCircuit(qr)
qc.ry(theta, 0)
qc.draw('mpl')
tele_qc = qc.copy()
bell = QuantumRegister(2, 'Bell')
alice = ClassicalRegister(2, 'Alice')
bob = ClassicalRegister(1, 'Bob')
tele_qc.add_register(bell, alice, bob)
tele_qc.draw('mpl')
# create Bell state with other two qubits
tele_qc.barrier()
tele_qc.h(1)
tele_qc.cx(1, 2)
tele_qc.barrier()
tele_qc.draw('mpl')
# alice operates on her qubits
tele_qc.cx(0, 1)
tele_qc.h(0)
tele_qc.barrier()
tele_qc.draw('mpl')
tele_qc.measure([qr[0], bell[0]], alice)
tele_qc.draw('mpl')
graded_qc = tele_qc.copy()
##############################
# add gates to graded_qc here
with graded_qc.if_test((alice[1], 1)) as _:
graded_qc.x(2)
with graded_qc.if_test((alice[0], 1)) as _:
graded_qc.z(2)
##############################
graded_qc.draw('mpl')
graded_qc.barrier()
graded_qc.measure(bell[1], bob)
graded_qc.draw('mpl')
from qc_grader.challenges.qgss_2023 import grade_lab2_ex3
grade_lab2_ex3(graded_qc, theta, 5*np.pi/7)
from qiskit_aer.primitives import Sampler
angle = 5*np.pi/7
sampler = Sampler()
qc.measure_all()
job_static = sampler.run(qc.bind_parameters({theta: angle}))
job_dynamic = sampler.run(graded_qc.bind_parameters({theta: angle}))
print(f"Original Dists: {job_static.result().quasi_dists[0].binary_probabilities()}")
print(f"Teleported Dists: {job_dynamic.result().quasi_dists[0].binary_probabilities()}")
from qiskit.result import marginal_counts
tele_counts = marginal_counts(
job_dynamic.result().quasi_dists[0].binary_probabilities(),
indices=[2],
) # marginalize counts
legend = ['Original State', 'Teleported State']
plot_histogram([job_static.result().quasi_dists[0].binary_probabilities(), tele_counts], legend=legend)
from qc_grader.challenges.qgss_2023 import grade_lab2_ex4
grade_lab2_ex4(tele_counts, job_dynamic.result())
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/idriss-hamadi/Qiskit-Quantaum-codes-
|
idriss-hamadi
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit_aer import AerSimulator
# qiskit-ibmq-provider has been deprecated.
# Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail.
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# Loading your IBM Quantum account(s)
service = QiskitRuntimeService(channel="ibm_quantum")
# Invoke a primitive inside a session. For more details see https://qiskit.org/documentation/partners/qiskit_ibm_runtime/tutorials.html
# with Session(backend=service.backend("ibmq_qasm_simulator")):
# result = Sampler().run(circuits).result()
from qiskit import * #importing libraries we need
from qiskit.tools.visualization import plot_bloch_multivector
from qiskit.visualization import plot_histogram
%matplotlib inline
import math
Aer.backends() #seeing all the availibe simulators
def run_on_simulators(circuit): #defining a function to run on two simulators
statevector = execute(circuit, backend=Aer.get_backend('statevector_simulator'))
result = statevector.result()
vec = result.get_statevector()
QubitsNumber = circuit.num_qubits
circuit.measure([i for i in range(QubitsNumber)], [i for i in range(QubitsNumber)])
Qass = execute(circuit, backend=Aer.get_backend('qasm_simulator'), shots=1024).result()
count = Qass.get_counts()
return vec, count
circuit = QuantumCircuit(2,2)
statevec, counts = run_on_simulators(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts])
circuit = QuantumCircuit(2,2)
circuit.h(0)
circuit.cx(0,1)
statevec, counts = run_on_simulators(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts])
circuit = QuantumCircuit(2,2)
circuit.rx(math.pi/4, 0)
circuit.rx(math.pi / 2, 1)
statevec, counts = run_on_simulators(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts])
circuit = QuantumCircuit(2,2)
circuit.ry(math.pi/4, 0)
circuit.ry(math.pi / 2, 1)
statevec, counts = run_on_simulators(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts])
circuit.h(0)
statevec, counts = run_on_simulators(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts])
circuit.h(0)
circuit.h(1)
statevec, counts = run_on_simulators(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts])
statevec, counts = run_on_simulators(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts])
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
"""ResourceEstimation pass testing"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import ResourceEstimation
from qiskit.test import QiskitTestCase
class TestResourceEstimationPass(QiskitTestCase):
"""Tests for PropertySet methods."""
def test_empty_dag(self):
"""Empty DAG."""
circuit = QuantumCircuit()
passmanager = PassManager()
passmanager.append(ResourceEstimation())
passmanager.run(circuit)
self.assertEqual(passmanager.property_set["size"], 0)
self.assertEqual(passmanager.property_set["depth"], 0)
self.assertEqual(passmanager.property_set["width"], 0)
self.assertDictEqual(passmanager.property_set["count_ops"], {})
def test_just_qubits(self):
"""A dag with 8 operations and no classic bits"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
passmanager = PassManager()
passmanager.append(ResourceEstimation())
passmanager.run(circuit)
self.assertEqual(passmanager.property_set["size"], 8)
self.assertEqual(passmanager.property_set["depth"], 7)
self.assertEqual(passmanager.property_set["width"], 2)
self.assertDictEqual(passmanager.property_set["count_ops"], {"cx": 6, "h": 2})
if __name__ == "__main__":
unittest.main()
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import QuantumCircuit, Aer
from qiskit.visualization import array_to_latex
sim = Aer.get_backend("aer_simulator")
qc1 = QuantumCircuit(3)
qc1.ccx(0, 1, 2)
display(qc1.draw("mpl"))
qc1.save_unitary()
unitary = sim.run(qc1).result().get_unitary()
display(array_to_latex(unitary, prefix="\\text{CNOT (MSB as Target) = }"))
print('=' * 80)
qc2 = QuantumCircuit(3)
qc2.ccx(2, 1, 0)
display(qc2.draw("mpl"))
qc2.save_unitary()
unitary = sim.run(qc2).result().get_unitary()
display(array_to_latex(unitary, prefix="\\text{CNOT (LSB as Target) = }"))
|
https://github.com/googlercolin/Qiskit-Course
|
googlercolin
|
import numpy as np
import networkx as nx
import timeit
from qiskit import Aer
from qiskit.circuit.library import TwoLocal
from qiskit_optimization.applications import Maxcut
from qiskit.algorithms import VQE, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import SPSA
from qiskit.utils import algorithm_globals, QuantumInstance
from qiskit_optimization.algorithms import MinimumEigenOptimizer
# Generating a graph of 6 nodes
n = 6 # Number of nodes in graph
G = nx.Graph()
G.add_nodes_from(np.arange(0, n, 1))
elist = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0), (1, 3, 1.0), (2, 4, 1.0), (3, 5, 1.0), (4, 5, 1.0)]
# tuple is (i,j,weight) where (i,j) is the edge
G.add_weighted_edges_from(elist)
colors = ["y" for node in G.nodes()]
pos = nx.spring_layout(G)
def draw_graph(G, colors, pos):
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=0.6, ax=default_axes, pos=pos)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
draw_graph(G, colors, pos)
# Computing the weight matrix from the random graph
w = np.zeros([n, n])
for i in range(n):
for j in range(n):
temp = G.get_edge_data(i, j, default=0)
if temp != 0:
w[i, j] = temp["weight"]
print(w)
def brute():
max_cost_brute = 0
for b in range(2**n):
x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))] # create reverse of binary combinations from 0 to 2**n to create every possible set
cost = 0
for i in range(n):
for j in range(n):
cost = cost + w[i, j] * x[i] * (1 - x[j])
if cost > max_cost_brute:
max_cost_brute = cost
xmax_brute = x
max_cost_brute = 0
for b in range(2**n):
x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))] # create reverse of binary combinations from 0 to 2**n to create every possible set
cost = 0
for i in range(n):
for j in range(n):
cost = cost + w[i, j] * x[i] * (1 - x[j])
if cost > max_cost_brute:
max_cost_brute = cost
xmax_brute = x
print("case = " + str(x) + " cost = " + str(cost))
colors = ["m" if xmax_brute[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
print("\nBest solution = " + str(xmax_brute) + " with cost = " + str(max_cost_brute))
time = timeit.timeit(brute, number = 1)
print(f"\nTime taken for brute force: {time}")
max_cut = Maxcut(w)
qp = max_cut.to_quadratic_program()
print(qp.export_as_lp_string())
qubitOp, offset = qp.to_ising()
print("Offset:", offset)
print("Ising Hamiltonian:")
print(str(qubitOp))
# solving Quadratic Program using exact classical eigensolver
exact = MinimumEigenOptimizer(NumPyMinimumEigensolver())
def classical_eigen():
result = exact.solve(qp)
result = exact.solve(qp)
print(result)
time = timeit.timeit(classical_eigen, number = 1)
print(f"\nTime taken for exact classical eigensolver force: {time}")
# Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = NumPyMinimumEigensolver()
result = ee.compute_minimum_eigenvalue(qubitOp)
x = max_cut.sample_most_likely(result.eigenstate)
print("energy:", result.eigenvalue.real)
print("max-cut objective:", result.eigenvalue.real + offset)
print("solution:", x)
print("solution objective:", qp.objective.evaluate(x))
colors = ["m" if x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
algorithm_globals.random_seed = 99
seed = 1010
backend = Aer.get_backend("aer_simulator_statevector")
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)
# construct VQE
spsa = SPSA(maxiter=300)
ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear")
vqe = VQE(ry, optimizer=spsa, quantum_instance=quantum_instance)
# run VQE
# def vqe_solve():
# result = vqe.compute_minimum_eigenvalue(qubitOp)
# time = timeit.timeit(vqe_solve, number = 1)
result = vqe.compute_minimum_eigenvalue(qubitOp)
# print results
x = max_cut.sample_most_likely(result.eigenstate)
print("energy:", result.eigenvalue.real)
print("time:", result.optimizer_time)
print("max-cut objective:", result.eigenvalue.real + offset)
print("solution:", x)
print("solution objective:", qp.objective.evaluate(x))
# print(f"\nTime taken for VQE: {time}")
# plot results
colors = ["m" if x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
# create minimum eigen optimizer based on VQE
vqe_optimizer = MinimumEigenOptimizer(vqe)
# solve quadratic program
result = vqe_optimizer.solve(qp)
print(result)
colors = ["m" if result.x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
|
https://github.com/AnkRaw/Quantum-Convolutional-Neural-Network
|
AnkRaw
|
# Importing Libraries
import torch
from torch import cat, no_grad, manual_seed
from torch.utils.data import DataLoader
from torchvision import transforms
import torch.optim as optim
from torch.nn import (
Module,
Conv2d,
Linear,
Dropout2d,
NLLLoss
)
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from qiskit_machine_learning.neural_networks import EstimatorQNN
from qiskit_machine_learning.connectors import TorchConnector
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit import QuantumCircuit
from qiskit.visualization import circuit_drawer
# Imports for CIFAR-10s
from torchvision.datasets import CIFAR10
from torchvision import transforms
def prepare_data(X, labels_to_keep, batch_size):
# Filtering out labels (originally 0-9), leaving only labels 0 and 1
filtered_indices = [i for i in range(len(X.targets)) if X.targets[i] in labels_to_keep]
X.data = X.data[filtered_indices]
X.targets = [X.targets[i] for i in filtered_indices]
# Defining dataloader with filtered data
loader = DataLoader(X, batch_size=batch_size, shuffle=True)
return loader
# Set seed for reproducibility
manual_seed(42)
# CIFAR-10 data transformation
transform = transforms.Compose([
transforms.ToTensor(), # convert the images to tensors
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # Normalization usign mean and std.
])
labels_to_keep = [0, 1]
batch_size = 1
# Preparing Train Data
X_train = CIFAR10(root="./data", train=True, download=True, transform=transform)
train_loader = prepare_data(X_train, labels_to_keep, batch_size)
# Preparing Test Data
X_test = CIFAR10(root="./data", train=False, download=True, transform=transform)
test_loader = prepare_data(X_test, labels_to_keep, batch_size)
print(f"Training dataset size: {len(train_loader.dataset)}")
print(f"Test dataset size: {len(test_loader.dataset)}")
# Defining and creating QNN
def create_qnn():
feature_map = ZZFeatureMap(2) # ZZFeatureMap with 2 bits, entanglement between qubits based on the pairwise product of input features.
ansatz = RealAmplitudes(2, reps=1) # parameters (angles, in the case of RealAmplitudes) that are adjusted during the training process to optimize the quantum model for a specific task.
qc = QuantumCircuit(2)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
qnn = EstimatorQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
input_gradients=True,
)
return qnn
qnn = create_qnn()
# Visualizing the QNN circuit
circuit_drawer(qnn.circuit, output='mpl')
# Defining torch NN module
class Net(Module):
def __init__(self, qnn):
super().__init__()
self.conv1 = Conv2d(3, 16, kernel_size=3, padding=1)
self.conv2 = Conv2d(16, 32, kernel_size=3, padding=1)
self.dropout = Dropout2d()
self.fc1 = Linear(32 * 8 * 8, 64)
self.fc2 = Linear(64, 2) # 2-dimensional input to QNN
self.qnn = TorchConnector(qnn)
self.fc3 = Linear(1, 1) # 1-dimensional output from QNN
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.qnn(x)
x = self.fc3(x)
return cat((x, 1 - x), -1)
# Creating model
model = Net(qnn)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
# Defining model, optimizer, and loss function
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = NLLLoss()
# Starting training
epochs = 10
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device) # Move data to GPU
optimizer.zero_grad(set_to_none=True)
output = model(data)
loss = loss_func(output, target)
loss.backward()
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss) / len(total_loss))
print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1]))
# Plotting loss convergence
plt.plot(loss_list)
plt.title("Hybrid NN Training Convergence")
plt.xlabel("Training Iterations")
plt.ylabel("Neg. Log Likelihood Loss")
plt.show()
# Saving the model
torch.save( model.state_dict(), "model_cifar10_10EPOCHS.pt")
# Loading the model
qnn_cifar10 = create_qnn()
model_cifar10 = Net(qnn_cifar10)
model_cifar10.load_state_dict(torch.load("model_cifar10.pt"))
correct = 0
total = 0
model_cifar10.eval()
with torch.no_grad():
for data, target in test_loader:
output = model_cifar10(data)
_, predicted = torch.max(output.data, 1)
total += target.size(0)
correct += (predicted == target).sum().item()
# Calculating and print test accuracy
test_accuracy = correct / total * 100
print(f"Test Accuracy: {test_accuracy:.2f}%")
# Plotting predicted labels
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
model_cifar10.eval()
with no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model_cifar10(data)
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(np.transpose(data[0].numpy(), (1, 2, 0)))
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title("Predicted {0}\n Actual {1}".format(pred.item(), target.item()))
count += 1
plt.show()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#
# You may use python for your calculations.
#
all_portions = [7,5,4,2,6,1];
from random import randrange
#
# your solution is here
#
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
import unittest
import cirq
from cirq.ops import H, X, I
import random
import matplotlib.pyplot as plt
from math import gcd
import numpy as np
from numpy.random import randint
#import hypothesis.strategies as st
#from hypothesis import given, settings
from fractions import Fraction
from math import gcd # greatest common divisor
# Specify variables
n_count = 8 # number of counting qubits
a = 7
N = 15
class aMod15Gate(cirq.Gate):
def __init__(self, a, power):
super(aMod15Gate, self)
self.a = a
self.power = power
def _num_qubits_(self):
return 4
def _decompose_(self, qubits):
q0, q1, q2, q3 = qubits
if self.a not in [2,7,8,11,13]:
raise ValueError("'a' must be 2,7,8,11 or 13")
for iteration in range(self.power):
if self.a in [2,13]:
yield cirq.SWAP(q0,q1)
yield cirq.SWAP(q1,q2)
yield cirq.SWAP(q2,q3)
if self.a in [7,8]:
yield cirq.SWAP(q2,q3)
yield cirq.SWAP(q1,q2)
yield cirq.SWAP(q0,q1)
if self.a == 11:
yield cirq.SWAP(q1,q3)
yield cirq.SWAP(q0,q2)
if self.a in [7,11,13]:
yield cirq.X(q0)
yield cirq.X(q1)
yield cirq.X(q2)
yield cirq.X(q3)
def _circuit_diagram_info_(self, args):
return "a mod 15"
def qft_dagger_cirq(qc, qubits, n):
for qubit in range(n//2):
qc.append(cirq.SWAP(qubits[qubit], qubits[n-qubit-1]))
for j in range(n):
for m in range(j):
qc.append((cirq.CZ**(-1/2**(j-m)))(qubits[m],qubits[j]))
qc.append(cirq.H(qubits[j]))
def qpe_amod15(a):
n_count = 8
qubits = cirq.LineQubit.range(4+n_count)
qc = cirq.Circuit()
for q in range(n_count):
#print(q)
qc.append(cirq.H(qubits[q])) # Initialize counting qubits in state |+>
qc.append(cirq.X(qubits[3+n_count])) # And auxiliary register in state |1>
for q in range(n_count): # Do controlled-U operations
qc.append(aMod15Gate(a, 2**q).on(qubits[8],qubits[9],qubits[10],qubits[11]).controlled_by(qubits[q]))
qft_dagger_cirq(qc, qubits[:n_count], n_count) # Do inverse-QF
qc.append(cirq.measure(*qubits[:8], key='m'))
# Simulate Results
simulator = cirq.Simulator()
results = simulator.run(qc , repetitions =1)
readings = np.array2string(results.measurements['m'][0], separator='')[1:-1][::-1]
phase = int(readings,2)/(2**n_count)
return phase
phase = qpe_amod15(a) # Phase = s/r
Fraction(phase).limit_denominator(15)
frac = Fraction(phase).limit_denominator(15)
s, r = frac.numerator, frac.denominator
print(r)
guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)]
print(guesses)
def find_factor(coprime):
a = coprime
attempt = 0
factors = []
for i in range(100):
attempt += 1
#print("\nAttempt %i:" % attempt)
phase = qpe_amod15(a) # Phase = s/r
frac = Fraction(phase).limit_denominator(N) # Denominator should (hopefully!) tell us r
r = frac.denominator
#print("Result: r = %i" % r)
if phase != 0:
# Guesses for factors are gcd(x^{r/2} ±1 , 15)
guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)]
#print("Guessed Factors: %i and %i" % (guesses[0], guesses[1]))
for guess in guesses:
if guess not in [1,N] and (N % guess) == 0: # Check to see if guess is a factor
# print("*** Non-trivial factor found: %i ***" % guess)
factors += [guess]
return factors
find_factor(7)
import fractions
import math
import random
import numpy as np
import sympy
from typing import Callable, List, Optional, Sequence, Union
import cirq
"""Function to compute the elements of Z_n."""
def multiplicative_group(n: int) -> List[int]:
"""Returns the multiplicative group modulo n.
Args:
n: Modulus of the multiplicative group.
"""
print("multiplicative group")
assert n > 1
group = [1]
for x in range(2, n):
if math.gcd(x, n) == 1:
group.append(x)
return group
"""Defines the modular exponential operation used in Shor's algorithm."""
class ModularExp(cirq.ArithmeticOperation):
"""Quantum modular exponentiation.
This class represents the unitary which multiplies base raised to exponent
into the target modulo the given modulus. More precisely, it represents the
unitary V which computes modular exponentiation x**e mod n:
V|y⟩|e⟩ = |y * x**e mod n⟩ |e⟩ 0 <= y < n
V|y⟩|e⟩ = |y⟩ |e⟩ n <= y
where y is the target register, e is the exponent register, x is the base
and n is the modulus. Consequently,
V|y⟩|e⟩ = (U**e|y)|e⟩
where U is the unitary defined as
U|y⟩ = |y * x mod n⟩ 0 <= y < n
U|y⟩ = |y⟩ n <= y
"""
def __init__(
self,
target: Sequence[cirq.Qid],
exponent: Union[int, Sequence[cirq.Qid]],
base: int,
modulus: int
) -> None:
if len(target) < modulus.bit_length():
raise ValueError(f'Register with {len(target)} qubits is too small '
f'for modulus {modulus}')
self.target = target
self.exponent = exponent
self.base = base
self.modulus = modulus
def registers(self) -> Sequence[Union[int, Sequence[cirq.Qid]]]:
return self.target, self.exponent, self.base, self.modulus
def with_registers(
self,
*new_registers: Union[int, Sequence['cirq.Qid']],
) -> cirq.ArithmeticOperation:
if len(new_registers) != 4:
raise ValueError(f'Expected 4 registers (target, exponent, base, '
f'modulus), but got {len(new_registers)}')
target, exponent, base, modulus = new_registers
if not isinstance(target, Sequence):
raise ValueError(
f'Target must be a qubit register, got {type(target)}')
if not isinstance(base, int):
raise ValueError(
f'Base must be a classical constant, got {type(base)}')
if not isinstance(modulus, int):
raise ValueError(
f'Modulus must be a classical constant, got {type(modulus)}')
return ModularExp(target, exponent, base, modulus)
def apply(self, *register_values: int) -> int:
assert len(register_values) == 4
target, exponent, base, modulus = register_values
if target >= modulus:
return target
return (target * base**exponent) % modulus
def _circuit_diagram_info_(
self,
args: cirq.CircuitDiagramInfoArgs,
) -> cirq.CircuitDiagramInfo:
assert args.known_qubits is not None
wire_symbols: List[str] = []
t, e = 0, 0
for qubit in args.known_qubits:
if qubit in self.target:
if t == 0:
if isinstance(self.exponent, Sequence):
e_str = 'e'
else:
e_str = str(self.exponent)
wire_symbols.append(
f'ModularExp(t*{self.base}**{e_str} % {self.modulus})')
else:
wire_symbols.append('t' + str(t))
t += 1
if isinstance(self.exponent, Sequence) and qubit in self.exponent:
wire_symbols.append('e' + str(e))
e += 1
return cirq.CircuitDiagramInfo(wire_symbols=tuple(wire_symbols))
def make_order_finding_circuit(x: int, n: int) -> cirq.Circuit:
"""Returns quantum circuit which computes the order of x modulo n.
The circuit uses Quantum Phase Estimation to compute an eigenvalue of
the unitary
U|y⟩ = |y * x mod n⟩ 0 <= y < n
U|y⟩ = |y⟩ n <= y
Args:
x: positive integer whose order modulo n is to be found
n: modulus relative to which the order of x is to be found
Returns:
Quantum circuit for finding the order of x modulo n
"""
L = n.bit_length()
target = cirq.LineQubit.range(L)
exponent = cirq.LineQubit.range(L, 3 * L + 3)
return cirq.Circuit(
cirq.X(target[L - 1]),
cirq.H.on_each(*exponent),
ModularExp(target, exponent, x, n),
cirq.qft(*exponent, inverse=True),
cirq.measure(*exponent, key='exponent'),
)
def process_measurement(result: cirq.Result, x: int, n: int) -> Optional[int]:
"""Interprets the output of the order finding circuit.
Specifically, it determines s/r such that exp(2πis/r) is an eigenvalue
of the unitary
U|y⟩ = |xy mod n⟩ 0 <= y < n
U|y⟩ = |y⟩ n <= y
then computes r (by continued fractions) if possible, and returns it.
Args:
result: result obtained by sampling the output of the
circuit built by make_order_finding_circuit
Returns:
r, the order of x modulo n or None.
"""
print("process measurement")
# Read the output integer of the exponent register.
exponent_as_integer = result.data["exponent"][0]
exponent_num_bits = result.measurements["exponent"].shape[1]
eigenphase = float(exponent_as_integer / 2**exponent_num_bits)
# Run the continued fractions algorithm to determine f = s / r.
f = fractions.Fraction.from_float(eigenphase).limit_denominator(n)
# If the numerator is zero, the order finder failed.
if f.numerator == 0:
return None
# Else, return the denominator if it is valid.
r = f.denominator
if x**r % n != 1:
return None
return r
def quantum_order_finder(x: int, n: int) -> Optional[int]:
"""Computes smallest positive r such that x**r mod n == 1.
Args:
x: integer whose order is to be computed, must be greater than one
and belong to the multiplicative group of integers modulo n (which
consists of positive integers relatively prime to n),
n: modulus of the multiplicative group.
"""
print("quantum order finder")
# Check that the integer x is a valid element of the multiplicative group
# modulo n.
if x < 2 or n <= x or math.gcd(x, n) > 1:
raise ValueError(f'Invalid x={x} for modulus n={n}.')
# Create the order finding circuit.
circuit = make_order_finding_circuit(x, n)
print(circuit)
# Sample from the order finding circuit.
measurement = cirq.sample(circuit)
# Return the processed measurement result.
return process_measurement(measurement, x, n)
def find_factor_of_prime_power(n: int) -> Optional[int]:
"""Returns non-trivial factor of n if n is a prime power, else None."""
print("factor of prime power")
for k in range(2, math.floor(math.log2(n)) + 1):
c = math.pow(n, 1 / k)
c1 = math.floor(c)
if c1**k == n:
return c1
c2 = math.ceil(c)
if c2**k == n:
return c2
return None
def find_factor(
n: int,
order_finder: Callable[[int, int], Optional[int]] = quantum_order_finder,
max_attempts: int = 30
) -> Optional[int]:
"""Returns a non-trivial factor of composite integer n.
Args:
n: Integer to factor.
order_finder: Function for finding the order of elements of the
multiplicative group of integers modulo n.
max_attempts: number of random x's to try, also an upper limit
on the number of order_finder invocations.
Returns:
Non-trivial factor of n or None if no such factor was found.
Factor k of n is trivial if it is 1 or n.
"""
# If the number is prime, there are no non-trivial factors.
if sympy.isprime(n):
print("n is prime!")
return None
# If the number is even, two is a non-trivial factor.
#if n % 2 == 0:
# return 2
# If n is a prime power, we can find a non-trivial factor efficiently.
#c = find_factor_of_prime_power(n)
#if c is not None:
# return c
print("find factor")
for _ in range(max_attempts):
print("loop")
# Choose a random number between 2 and n - 1.
x = random.randint(2, n - 1)
print("x " + str(x))
# Most likely x and n will be relatively prime.
c = math.gcd(x, n)
print("c " + str(c))
# If x and n are not relatively prime, we got lucky and found
# a non-trivial factor.
if 1 < c < n:
return c
# Compute the order r of x modulo n using the order finder.
r = order_finder(x, n)
print(r)
# If the order finder failed, try again.
if r is None:
continue
# If the order r is even, try again.
if r % 2 != 0:
continue
# Compute the non-trivial factor.
y = x**(r // 2) % n
assert 1 < y < n
c = math.gcd(y - 1, n)
if 1 < c < n:
return c
print(f"Failed to find a non-trivial factor in {max_attempts} attempts.")
return None
find_factor(15)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import logging
import sys
import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.tools import parallel_map
from qiskit.tools.events import TextProgressBar
from qiskit.aqua import aqua_globals
from qiskit.aqua.algorithms import QuantumAlgorithm
from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class
from qiskit.aqua.algorithms.many_sample.qsvm._qsvm_binary import _QSVM_Binary
from qiskit.aqua.algorithms.many_sample.qsvm._qsvm_multiclass import _QSVM_Multiclass
from qiskit.aqua.algorithms.many_sample.qsvm._qsvm_estimator import _QSVM_Estimator
from qiskit.aqua.utils.dataset_helper import get_feature_dimension, get_num_classes
from qiskit.aqua.utils import split_dataset_to_data_and_labels
logger = logging.getLogger(__name__)
class QSVM(QuantumAlgorithm):
"""
Quantum SVM method.
Internally, it will run the binary classification or multiclass classification
based on how many classes the data have.
"""
CONFIGURATION = {
'name': 'QSVM',
'description': 'QSVM Algorithm',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'QSVM_schema',
'type': 'object',
'properties': {
},
'additionalProperties': False
},
'problems': ['classification'],
'depends': [
{'pluggable_type': 'multiclass_extension'},
{'pluggable_type': 'feature_map',
'default': {
'name': 'SecondOrderExpansion',
'depth': 2
}
},
],
}
BATCH_SIZE = 1000
def __init__(self, feature_map, training_dataset, test_dataset=None, datapoints=None,
multiclass_extension=None):
"""Constructor.
Args:
feature_map (FeatureMap): feature map module, used to transform data
training_dataset (dict): training dataset.
test_dataset (Optional[dict]): testing dataset.
datapoints (Optional[numpy.ndarray]): prediction dataset.
multiclass_extension (Optional[MultiExtension]): if number of classes > 2 then
a multiclass scheme is needed.
Raises:
ValueError: if training_dataset is None
AquaError: use binary classifer for classes > 3
"""
super().__init__()
if training_dataset is None:
raise ValueError('Training dataset must be provided')
is_multiclass = get_num_classes(training_dataset) > 2
if is_multiclass:
if multiclass_extension is None:
raise AquaError('Dataset has more than two classes. '
'A multiclass extension must be provided.')
else:
if multiclass_extension is not None:
logger.warning("Dataset has just two classes. "
"Supplied multiclass extension will be ignored")
self.training_dataset, self.class_to_label = split_dataset_to_data_and_labels(
training_dataset)
if test_dataset is not None:
self.test_dataset = split_dataset_to_data_and_labels(test_dataset,
self.class_to_label)
else:
self.test_dataset = None
self.label_to_class = {label: class_name for class_name, label
in self.class_to_label.items()}
self.num_classes = len(list(self.class_to_label.keys()))
if datapoints is not None and not isinstance(datapoints, np.ndarray):
datapoints = np.asarray(datapoints)
self.datapoints = datapoints
self.feature_map = feature_map
self.num_qubits = self.feature_map.num_qubits
if multiclass_extension is None:
qsvm_instance = _QSVM_Binary(self)
else:
qsvm_instance = _QSVM_Multiclass(self, multiclass_extension)
self.instance = qsvm_instance
@classmethod
def init_params(cls, params, algo_input):
"""Constructor from params."""
feature_dimension = get_feature_dimension(algo_input.training_dataset)
fea_map_params = params.get(Pluggable.SECTION_KEY_FEATURE_MAP)
fea_map_params['feature_dimension'] = feature_dimension
feature_map = get_pluggable_class(PluggableType.FEATURE_MAP,
fea_map_params['name']).init_params(params)
multiclass_extension = None
multiclass_extension_params = params.get(Pluggable.SECTION_KEY_MULTICLASS_EXTENSION)
if multiclass_extension_params is not None:
multiclass_extension_params['params'] = [feature_map]
multiclass_extension_params['estimator_cls'] = _QSVM_Estimator
multiclass_extension = get_pluggable_class(PluggableType.MULTICLASS_EXTENSION,
multiclass_extension_params['name']).init_params(params)
logger.info("Multiclass classifier based on {}".format(multiclass_extension_params['name']))
return cls(feature_map, algo_input.training_dataset, algo_input.test_dataset,
algo_input.datapoints, multiclass_extension)
@staticmethod
def _construct_circuit(x, num_qubits, feature_map, measurement):
x1, x2 = x
if x1.shape[0] != x2.shape[0]:
raise ValueError("x1 and x2 must be the same dimension.")
q = QuantumRegister(num_qubits, 'q')
c = ClassicalRegister(num_qubits, 'c')
qc = QuantumCircuit(q, c)
# write input state from sample distribution
qc += feature_map.construct_circuit(x1, q)
qc += feature_map.construct_circuit(x2, q, inverse=True)
if measurement:
qc.barrier(q)
qc.measure(q, c)
return qc
@staticmethod
def _compute_overlap(idx, results, is_statevector_sim, measurement_basis):
if is_statevector_sim:
temp = results.get_statevector(idx)[0]
# |<0|Psi^daggar(y) x Psi(x)|0>|^2,
kernel_value = np.dot(temp.T.conj(), temp).real
else:
result = results.get_counts(idx)
kernel_value = result.get(measurement_basis, 0) / sum(result.values())
return kernel_value
def construct_circuit(self, x1, x2, measurement=False):
"""
Generate inner product of x1 and x2 with the given feature map.
The dimension of x1 and x2 must be the same.
Args:
x1 (numpy.ndarray): data points, 1-D array, dimension is D
x2 (numpy.ndarray): data points, 1-D array, dimension is D
measurement (bool): add measurement gates at the end
"""
return QSVM._construct_circuit((x1, x2), self.num_qubits,
self.feature_map, measurement)
def construct_kernel_matrix(self, x1_vec, x2_vec=None, quantum_instance=None):
"""
Construct kernel matrix, if x2_vec is None, self-innerproduct is conducted.
Args:
x1_vec (numpy.ndarray): data points, 2-D array, N1xD, where N1 is the number of data,
D is the feature dimension
x2_vec (numpy.ndarray): data points, 2-D array, N2xD, where N2 is the number of data,
D is the feature dimension
quantum_instance (QuantumInstance): quantum backend with all setting
Returns:
numpy.ndarray: 2-D matrix, N1xN2
"""
self._quantum_instance = self._quantum_instance \
if quantum_instance is None else quantum_instance
from .qsvm import QSVM
if x2_vec is None:
is_symmetric = True
x2_vec = x1_vec
else:
is_symmetric = False
is_statevector_sim = self.quantum_instance.is_statevector
measurement = not is_statevector_sim
measurement_basis = '0' * self.num_qubits
mat = np.ones((x1_vec.shape[0], x2_vec.shape[0]))
# get all indices
if is_symmetric:
mus, nus = np.triu_indices(x1_vec.shape[0], k=1) # remove diagonal term
else:
mus, nus = np.indices((x1_vec.shape[0], x2_vec.shape[0]))
mus = np.asarray(mus.flat)
nus = np.asarray(nus.flat)
for idx in range(0, len(mus), QSVM.BATCH_SIZE):
to_be_computed_list = []
to_be_computed_index = []
for sub_idx in range(idx, min(idx + QSVM.BATCH_SIZE, len(mus))):
i = mus[sub_idx]
j = nus[sub_idx]
x1 = x1_vec[i]
x2 = x2_vec[j]
if not np.all(x1 == x2):
to_be_computed_list.append((x1, x2))
to_be_computed_index.append((i, j))
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Building circuits:")
TextProgressBar(sys.stderr)
circuits = parallel_map(QSVM._construct_circuit,
to_be_computed_list,
task_args=(self.num_qubits, self.feature_map,
measurement),
num_processes=aqua_globals.num_processes)
results = self.quantum_instance.execute(circuits)
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Calculating overlap:")
TextProgressBar(sys.stderr)
matrix_elements = parallel_map(QSVM._compute_overlap, range(len(circuits)),
task_args=(results, is_statevector_sim, measurement_basis),
num_processes=aqua_globals.num_processes)
for idx in range(len(to_be_computed_index)):
i, j = to_be_computed_index[idx]
mat[i, j] = matrix_elements[idx]
if is_symmetric:
mat[j, i] = mat[i, j]
return mat
def train(self, data, labels, quantum_instance=None):
"""
Train the svm.
Args:
data (numpy.ndarray): NxD array, where N is the number of data,
D is the feature dimension.
labels (numpy.ndarray): Nx1 array, where N is the number of data
quantum_instance (QuantumInstance): quantum backend with all setting
"""
self._quantum_instance = self._quantum_instance \
if quantum_instance is None else quantum_instance
self.instance.train(data, labels)
def test(self, data, labels, quantum_instance=None):
"""
Test the svm.
Args:
data (numpy.ndarray): NxD array, where N is the number of data,
D is the feature dimension.
labels (numpy.ndarray): Nx1 array, where N is the number of data
quantum_instance (QuantumInstance): quantum backend with all setting
Returns:
float: accuracy
"""
self._quantum_instance = self._quantum_instance \
if quantum_instance is None else quantum_instance
return self.instance.test(data, labels)
def predict(self, data, quantum_instance=None):
"""
Predict using the svm.
Args:
data (numpy.ndarray): NxD array, where N is the number of data,
D is the feature dimension.
quantum_instance (QuantumInstance): quantum backend with all setting
Returns:
numpy.ndarray: predicted labels, Nx1 array
"""
self._quantum_instance = self._quantum_instance \
if quantum_instance is None else quantum_instance
return self.instance.predict(data)
def _run(self):
return self.instance.run()
@property
def ret(self):
return self.instance.ret
@ret.setter
def ret(self, new_value):
self.instance.ret = new_value
def load_model(self, file_path):
"""Load a model from a file path.
Args:
file_path (str): tthe path of the saved model.
"""
self.instance.load_model(file_path)
def save_model(self, file_path):
"""Save the model to a file path.
Args:
file_path (str): a path to save the model.
"""
self.instance.save_model(file_path)
|
https://github.com/Qiskit/qiskit-neko
|
Qiskit
|
# 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.
"""Tests for quantum state tomography."""
from qiskit_experiments.library import StateTomography
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix, state_fidelity
from qiskit_neko import decorators
from qiskit_neko.tests import base
class TestQuantumStateTomography(base.BaseTestCase):
"""Tests adapted from circuit basics tutorial."""
@decorators.component_attr("terra", "backend", "experiment")
def test_ghz_circuit_quantum_info(self):
"""Test state tomography of ghz state circuit"""
nq = 3
qc_ghz = QuantumCircuit(nq)
qc_ghz.h(0)
qc_ghz.s(0)
for i in range(1, nq):
qc_ghz.cx(0, i)
qstexp1 = StateTomography(qc_ghz)
qstdata1 = qstexp1.run(self.backend, seed_simulation=42).block_for_results()
state_result = qstdata1.analysis_results("state")
density_matrix = state_result.value
ideal_density_matrix = DensityMatrix(qc_ghz)
fidelity = state_fidelity(density_matrix, ideal_density_matrix)
self.assertGreaterEqual(fidelity, 0.55)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import RemoveBarriers
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.barrier()
circuit.h(0)
circuit = RemoveBarriers()(circuit)
circuit.draw('mpl')
|
https://github.com/VoicuTomut/Qsiris-Quantum-Odyssey-and-Qiskit
|
VoicuTomut
|
import numpy as np
from qiskit import(
QuantumCircuit,
execute,
Aer)
from qiskit.visualization import plot_histogram
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# 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])
# Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(circuit)
print(counts)
# Draw the circuit
circuit.draw()
print(circuit)
|
https://github.com/soccertes123/QiskitGroverDinnerParty
|
soccertes123
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer, assemble, transpile
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.providers.ibmq import least_busy
# import basic plot tools
from qiskit.visualization import plot_histogram
# general diffuser copied from https://qiskit.org/textbook/ch-algorithms/grover.html#2qubits-simulation
def diffuser(nqubits):
qc = QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qc.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qc.x(qubit)
# Do multi-controlled-Z gate
qc.h(nqubits-1)
qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qc.h(nqubits-1)
# Apply transformation |11..1> -> |00..0>
for qubit in range(nqubits):
qc.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(nqubits):
qc.h(qubit)
return qc
# THIS IS THE MAIN IMPORTANT PART OF THE IMPLEMENTATION
# we made lots of stubs for unimportant but time-consuming functions
# After putting around 10-15 hours in to the project, we realized it would take way too much time to hammer in every
# single function.
def oracle(nqubits, expressions):
# iterate over expressions and define circuit
qc = QuantumCircuit(nqubits + len(expressions))
x_reset_target_indices = [] # list of target qubits which have x gates that need to be reversed
for i, exp in enumerate(expressions):
# if OR: apply X gates
if (exp[0] == "OR"):
for variable in exp[1:]:
qubit_index = int(variable[1]) # each variable is in format xi where i is the qubit index
qc.x(qubit_index)
# apply multi qubit toffoli
control_indices = []
x_reset_input_indices = [] # indices to be reset if we apply x gates
for variable in exp[1:]:
if (variable[0] == "x"):
qubit_index = int(variable[1])
control_indices.append(qubit_index)
else:
# variable[0] = "e" -> the qubit index is the target qubit from the prior expression ei
qubit_index = nqubits + int(variable[1]) # this references the target qubit after evaluating expression ei
control_indices.append(qubit_index)
if (variable[len(variable-1)] == "~"):
qc.x(qubit_index)
x_reset_indices.append(qubit_index)
target_index = nqubits + i
qc = multi_qubit_toffoli(qc, control_indices, target_index)
for index in x_reset_input_indices:
# reset the inputs if we applied x gates
qc.x(index)
# if OR: apply X gate on target qubit for logic and X gates on control qubits to reset input
if (exp[0] == "OR"):
qc.x(target_index)
x_reset_target_indices.append(i) # append to this list so that we can reset the circuit at end of oracle
for variable in exp[1:]:
qubit_index = int(variable[1])
qc.x(qubit_index)
for index in x_reset_target_indices:
# reset the rest of the circuit
qc.x(index)
return qc
def multi_qubit_toffoli(qc, control_indices, target_index):
# perform the multi qubit toffoli gate on the quantum circuit and return the circuit
return qc
def init(nqubits):
qc = QuantumCircuit(nqubits)
for i in range(nqubits):
qc.h(i)
return qc
def parse_exp(exp):
# returns something like [e1=["OR", "x0", "x1~"], e2=["AND", "e1", "x2"], e3=[...], ...]
# where each expression ei is connected by a series of ANDs
# make sure that any negations get distributed
# We will write our expressions as ei=["AND", "x0", "x1~"] so that the last character is "~" if the variable has negation
li = []
return li
def check_solution(boolean_list, expression):
# boolean list would represent the variables in the expression by index
return false
expression = "((x0 & x1) & (x1 & ~x2) & x3)"
nqubits = 2
circuit = init(nqubits)
oracle_qc = oracle(nqubits, expression)
diffuser_qc = diffuser(nqubits)
# now join the circuits together
solved = false
boolean_list
while (solved):
# add oracle and diffuser on our circuit
circuit = circuit + oracle_qc + diffuser_qc
# measure result
results = circuit.measure_all().counts()
boolean_list = results
# check solution with expression
solved = checks_solution(boolean_list, expression)
print(boolean_list)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.