repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/carstenblank/dc-qiskit-algorithms
|
carstenblank
|
# -*- 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/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
import sys
sys.path.append("..")
# from benchmark_suite.backend_suite import backends
# from clonk.backend_utils.backend_analysis_pass import TopologyAnalysis
# from qiskit.transpiler.passmanager import PassManager
# from qiskit import QuantumCircuit
# qc = QuantumCircuit(1)
# for backend_label, backend_obj in backends.items():
# print(backend_label)
# pm1 = PassManager(TopologyAnalysis(backend_obj.backend))
# pm1.run(qc)
# #FIXME, just save the property_set dictionary directly
# for key, value in pm1.property_set.items():
# backend_obj.save_data(parameter=key, data=value)
# backend_obj.save_json()
# hypercube analsis
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from clonk.backend_utils.backend_analysis_pass import TopologyAnalysis
qc = QuantumCircuit(1)
import sys
sys.path.append("..")
from clonk.backend_utils.mock_backends import FakeHyperCubeV2, FakeHyperCubeSnail
backend_list = [
FakeHyperCubeSnail(corral_skip_pattern=(0, 0)),
FakeHyperCubeSnail(corral_skip_pattern=(0, 1)),
]
max_connectivity = 0
min_distance = 100
best = None
for i in range(6):
for j in range(6):
backend = FakeHyperCubeSnail(corral_skip_pattern=(i, j))
print(backend.name[:-3])
try:
pm1 = PassManager(TopologyAnalysis(backend))
pm1.run(qc)
except Exception:
continue
# coupling error
# print(f"Num qubits {backend.num_qubits}")
connectivity = pm1.property_set["Avg_Connectivity"]
distance = pm1.property_set["Avg_Distance"]
if distance <= min_distance:
if distance < min_distance or connectivity > max_connectivity:
best = backend.name[:-3]
min_distance = distance
max_connectivity = connectivity
degree = pm1.property_set["Degree"]
diameter = pm1.property_set["Diameter"]
# if connectivity >= max_connectivity:
# if connectivity > max_connectivity or distance < min_distance:
# best = backend.name[:-3]
# min_distance = distance
# max_connectivity = connectivity
print(f"best: {best}")
print(min_distance)
print(max_connectivity)
print(degree)
print(diameter)
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
import sys
sys.path.append("..")
from clonk.backend_utils.backend_analysis_pass import TopologyAnalysis
qc = QuantumCircuit(1)
# from mock_backends.ibm import *
# from mock_backends import *
# backend_list = [PenguinV1(), PenguinV2(), PenguinV3(), PenguinV4(), FakeHeavyHex()] #FalconR4()]
from benchmark_suite.backend_suite_v2 import (
small_motivation_backends,
hpca_modular_backends,
hpca_corral_backends,
)
backend_list = hpca_corral_backends
for backend in backend_list:
print(backend.label)
pm1 = PassManager(TopologyAnalysis(backend.backend))
pm1.run(qc)
print(f"Num qubits {backend.backend.num_qubits}")
# just save the property_set dictionary directly
backend.data.update(dict(pm1.property_set))
backend.save_json()
# then print it
for key, value in pm1.property_set.items():
print(key, str(round(value, 2)))
print()
from clonk.backend_utils.mock_backends import FakeModular
backend_list = [FakeModular(module_size=4, children=4, total_levels=3)]
for backend in backend_list:
print(backend.name)
pm1 = PassManager(TopologyAnalysis(backend))
pm1.run(qc)
print(f"Num qubits {backend.num_qubits}")
# then print it
for key, value in pm1.property_set.items():
print(key, str(round(value, 2)))
print()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
|
https://github.com/sarthag/Quantum-Algos-using-Qiskit
|
sarthag
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
%matplotlib inline
secretnumber = '11100011'
circuit = QuantumCircuit(len(secretnumber)+1,len(secretnumber))
circuit.h(range(len(secretnumber)))
circuit.x(len(secretnumber))
circuit.h(len(secretnumber))
circuit.barrier()
for ii, yesno in enumerate(reversed(secretnumber)):
if yesno == '1':
circuit.cx(ii,len(secretnumber))
circuit.barrier()
circuit.h(range(len(secretnumber)))
circuit.barrier()
circuit.measure(range(len(secretnumber)),range(len(secretnumber)))
circuit.draw(output = 'mpl')
|
https://github.com/WhenTheyCry96/qiskitHackathon2022
|
WhenTheyCry96
|
import warnings
warnings.filterwarnings('ignore')
from qiskit_metal import designs, MetalGUI
design = designs.DesignPlanar()
design.overwrite_enabled = True
design.chips.main.size_x = '12mm'
design.chips.main.size_y = '10mm'
gui = MetalGUI(design)
from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL
design.delete_all_components()
design_span_x = 5
design_span_y = 3
half_chip_width = design_span_x / 2
half_chip_height = design_span_y / 2
connection_pads_options = dict(
a = dict(loc_W=1, loc_H=-1),
b = dict(loc_W=1, loc_H=1),
c = dict(loc_W=-1, loc_H=-1)
)
connection23_pads_options = dict(
a = dict(loc_W=1, loc_H=-1),
c = dict(loc_W=-1, loc_H=-1)
)
transmons = []
transmons.append(TransmonPocketCL(design, 'Q1',
options=dict(pos_x=f'-{half_chip_width}mm',
pos_y=f'{-half_chip_height}mm',
connection_pads=dict(**connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q2',
options=dict(pos_x=f'0mm',
pos_y=f'{half_chip_height}mm',
orientation=-90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q3',
options=dict(pos_x=f'0mm',
pos_y=f'{-half_chip_height}mm',
orientation=90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q4',
options=dict(pos_x=f'{half_chip_width}mm',
pos_y=f'{half_chip_height}mm',
orientation=180,
connection_pads=dict(**connection_pads_options))))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
from qiskit_metal import Dict
fillet='99.99um'
options = Dict(
meander=Dict(
lead_start='0.1mm',
lead_end='0.1mm',
asymmetry='0 um')
)
def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str,
length: str,
asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False):
"""Connect two pins with a CPW."""
myoptions = Dict(
pin_inputs=Dict(
start_pin=Dict(
component=component1,
pin=pin1),
end_pin=Dict(
component=component2,
pin=pin2)),
lead=Dict(
start_straight=start_strght,
end_straight=end_strght
),
total_length=length,
fillet = '99.9um')
myoptions.update(options)
myoptions.meander.asymmetry = asymmetry
myoptions.meander.lead_direction_inverted = 'true' if flip else 'false'
return RouteMeander(design, component_name, myoptions)
asym_h = 100
asym_v = 100
cpw = []
cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled
readouts_lwc = []
control_lwc = []
offset_x = 0
offset_y = 1
#Readouts
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1',
options = dict(
pos_x = '-5mm',
pos_y = f'-{half_chip_height+offset_y}mm',
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2',
options = dict(
pos_x = '-1mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3',
options = dict(
pos_x = '1mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4',
options = dict(
pos_x = '5mm',
pos_y = f'{half_chip_height+offset_y}mm',
orientation = 180,
lead_length = '30um')))
#Controls
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1',
options = dict(
pos_x = '-5mm',
pos_y = '2mm',
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2',
options = dict(
pos_x = '4mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3',
options = dict(
pos_x = '-4mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4',
options = dict(
pos_x = '5mm',
pos_y = '-2mm',
orientation = 180,
lead_length = '30um')))
gui.rebuild()
gui.autoscale()
readout_lines = []
asym_14 = 700
asym_23 = 700
options = Dict(
lead=Dict(
start_straight='330um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um'))
options = Dict(
lead=Dict(
start_straight='430um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um'))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors
from collections import OrderedDict
import numpy as np
control_lines = []
def connectRouteAnchor(name: str,
component1: str, pin1: str, component2: str, pin2: str,
anchor_points: OrderedDict) -> RouteAnchors:
options_line_cl = dict(
pin_inputs = dict(start_pin = dict(component = component1, pin = pin1),
end_pin = dict(component = component2, pin = pin2)),
anchors = anchor_points,
lead = dict(start_straight = '200um',
end_straight = '225um'),
fillet = fillet
)
return RouteAnchors(design, name, options_line_cl)
anchors1c = OrderedDict()
anchors1c[0] = np.array([-4, -1.42])
anchors1c[1] = np.array([-4, 2])
control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c))
anchors2c = OrderedDict()
anchors2c[0] = np.array([0.08, 3.25])
anchors2c[1] = np.array([4, 3.25])
control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c))
anchors3c = OrderedDict()
anchors3c[0] = np.array([-0.08, -3.25])
anchors3c[1] = np.array([-4, -3.25])
control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c))
anchors4c = OrderedDict()
anchors4c[0] = np.array([4, 1.42])
anchors4c[1] = np.array([4, -2])
control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c))
gui.rebuild()
gui.autoscale()
gui.autoscale()
gui.screenshot(name="full_design")
import numpy as np
from scipy.constants import c, h, pi, hbar, e
from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength
# constants:
phi0 = h/(2*e)
varphi0 = phi0/(2*pi)
# project target parameters
f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz
f_rList = f_qList + 1.8 # GHz
L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH
# initial CPW readout lengths
def find_resonator_length(frequency, line_width, line_gap, N):
#frequency in GHz
#line_width/line_gap in um
#N -> 2 for lambda/2, 4 for lambda/4
[lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6,
line_gap*10**-6, 750*10**-6, 200*10**-9)
return str(lambdaG/N*10**3)+" mm"
find_resonator_length(f_rList, 10, 6, 2)
find_resonator_length(np.around(np.linspace(8, 9.2, 4), 2), 10, 6, 2)
transmons[0].options.pad_gap = '40um'
transmons[0].options.pad_width = '550um' # 405
transmons[0].options.pad_height = '120um'
transmons[1].options.pad_gap = '40um'
transmons[1].options.pad_width = '500um' # 405
transmons[1].options.pad_height = '120um'
transmons[2].options.pad_gap = '40um'
transmons[2].options.pad_width = '460um' # 405
transmons[2].options.pad_height = '120um'
transmons[3].options.pad_gap = '40um'
transmons[3].options.pad_width = '440um' # 405
transmons[3].options.pad_height = '120um'
readout_lines[0].options.total_length = '8.63mm'
readout_lines[1].options.total_length = '8.42mm'
readout_lines[2].options.total_length = '8.24mm'
readout_lines[3].options.total_length = '8.06mm'
cpw[0].options.total_length = '7.6mm'
cpw[1].options.total_length = '7.2mm'
cpw[2].options.total_length = '6.9mm'
cpw[3].options.total_length = '6.6mm'
gui.rebuild()
gui.autoscale()
qcomps = design.components # short handle (alias)
qcomps['Q1'].options['hfss_inductance'] = 'Lj1'
qcomps['Q1'].options['hfss_capacitance'] = 'Cj1'
qcomps['Q2'].options['hfss_inductance'] = 'Lj2'
qcomps['Q2'].options['hfss_capacitance'] = 'Cj2'
qcomps['Q3'].options['hfss_inductance'] = 'Lj3'
qcomps['Q3'].options['hfss_capacitance'] = 'Cj3'
qcomps['Q4'].options['hfss_inductance'] = 'Lj4'
qcomps['Q4'].options['hfss_capacitance'] = 'Cj4'
from qiskit_metal.analyses.quantization import EPRanalysis, LOManalysis
c1 = LOManalysis(design, "q3d")
q3d1 = c1.sim.renderer
q3d1.start()
q3d1.activate_ansys_design("full_circuit", 'capacitive')
q3d1.render_design([], [])
q3d1.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5,percent_error=0.05)
q3d1.analyze_setup("Setup")
c1.sim.capacitance_matrix, c1.sim.units = q3d1.get_capacitance_matrix()
c1.sim.capacitance_all_passes, _ = q3d1.get_capacitance_all_passes()
c1.sim.capacitance_matrix
Out[17].to_csv("full_original_design_C.txt")
c1 = LOManalysis(design, "q3d")
q3d1 = c1.sim.renderer
q3d1.start()
q3d1.activate_ansys_design("Q1only_busopen", 'capacitive')
q3d1.render_design(['Q1', 'R1', 'cpw1', 'cpw4', 'ol1', 'line_cl1', 'CL1'], [('cpw1', 'end'),('cpw4', 'start')])
q3d1.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5,percent_error=0.05)
q3d1.analyze_setup("Setup")
c1.sim.capacitance_matrix, c1.sim.units = q3d1.get_capacitance_matrix()
c1.sim.capacitance_all_passes, _ = q3d1.get_capacitance_all_passes()
c1.sim.capacitance_matrix
|
https://github.com/arnavdas88/QuGlassyIsing
|
arnavdas88
|
!pip install qiskit
from qiskit.providers.aer import AerSimulator, QasmSimulator
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
# opflow is Qiskit's module for creating operators like yours
from qiskit import *
from qiskit.opflow import OperatorBase
from qiskit.opflow import Z, X, I # Pauli Z, X matrices and identity
import pylab
import matplotlib.pyplot as plt
import numpy as np
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
def get_gradient(values, counts):
rvalues = []
rcounts = []
for i in range(1, len(values)):
rvalues += [ (values[i - 1] - values[i]) ]
rcounts = [ i for i in range(len(rvalues)) ]
return rvalues, rcounts
def get_absolute(values):
return [ (v if v > 0 else -v) for v in values]
# J = 1.0
counts = []
values = []
H = (504.0 * I^I^I^I^I^I^I^Z) + (1008.0 * I^I^I^I^I^I^Z^I) + (2016.0 * I^I^I^I^I^Z^I^I) + (504.0 * I^I^I^I^Z^I^I^I) + (1143.7999999999997 * I^I^I^Z^I^I^I^I) + (2287.6 * I^I^Z^I^I^I^I^I) + (4575.200000000001 * I^Z^I^I^I^I^I^I) + (1143.7999999999997 * Z^I^I^I^I^I^I^I) + (98.0 * I^I^I^I^I^I^Z^Z) + (196.0 * I^I^I^I^I^Z^I^Z) + (392.0 * I^I^I^I^I^Z^Z^I) + (49.0 * I^I^I^I^Z^I^I^Z) + (98.0 * I^I^I^I^Z^I^Z^I) + (196.0 * I^I^I^I^Z^Z^I^I) + (93.1 * I^I^Z^Z^I^I^I^I) + (186.2 * I^Z^I^Z^I^I^I^I) + (372.4 * I^Z^Z^I^I^I^I^I) + (46.55 * Z^I^I^Z^I^I^I^I) + (93.1 * Z^I^Z^I^I^I^I^I) + (186.2 * Z^Z^I^I^I^I^I^I)
# you can swap this for a real quantum device and keep the rest of the code the same!
# backend = AerSimulator(method='matrix_product_state')
backend = QasmSimulator()
# COBYLA usually works well for small problems like this one
optimizer = COBYLA(maxiter=2000)
# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library
ansatz = TwoLocal(num_qubits=8, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)
# set the algorithm
vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)
#run it with the Hamiltonian we defined above
result = vqe.compute_minimum_eigenvalue(H)
#print the result (it contains lot's of information)
print(result)
v1, c1 = get_gradient(values, counts)
plt.figure(figsize=(15,15))
plt.plot(c1,v1)
plt.xlabel('optimization step')
plt.ylabel('E')
plt.show()
counts = []
values = []
H = (504.0 * I^I^I^I^I^I^I^Z) + (1008.0 * I^I^I^I^I^I^Z^I) + (2016.0 * I^I^I^I^I^Z^I^I) + (504.0 * I^I^I^I^Z^I^I^I) + (1143.7999999999997 * I^I^I^Z^I^I^I^I) + (2287.6 * I^I^Z^I^I^I^I^I) + (4575.200000000001 * I^Z^I^I^I^I^I^I) + (1143.7999999999997 * Z^I^I^I^I^I^I^I) + (98.0 * I^I^I^I^I^I^Z^Z) + (196.0 * I^I^I^I^I^Z^I^Z) + (392.0 * I^I^I^I^I^Z^Z^I) + (49.0 * I^I^I^I^Z^I^I^Z) + (98.0 * I^I^I^I^Z^I^Z^I) + (196.0 * I^I^I^I^Z^Z^I^I) + (93.1 * I^I^Z^Z^I^I^I^I) + (186.2 * I^Z^I^Z^I^I^I^I) + (372.4 * I^Z^Z^I^I^I^I^I) + (46.55 * Z^I^I^Z^I^I^I^I) + (93.1 * Z^I^Z^I^I^I^I^I) + (186.2 * Z^Z^I^I^I^I^I^I)
# you can swap this for a real quantum device and keep the rest of the code the same!
# backend = AerSimulator(method='matrix_product_state')
backend = QasmSimulator()
# COBYLA usually works well for small problems like this one
optimizer = COBYLA(maxiter=2000)
# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library
ansatz = TwoLocal(num_qubits=8, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)
# set the algorithm
vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)
#run it with the Hamiltonian we defined above
result = vqe.compute_minimum_eigenvalue(H)
#print the result (it contains lot's of information)
print(result)
v2, c2 = get_gradient(values, counts)
plt.figure(figsize=(15,15))
plt.plot(c2,v2)
plt.xlabel('optimization step')
plt.ylabel('E')
plt.show()
counts = []
values = []
H = (504.0 * I^I^I^I^I^I^I^Z) + (1008.0 * I^I^I^I^I^I^Z^I) + (2016.0 * I^I^I^I^I^Z^I^I) + (504.0 * I^I^I^I^Z^I^I^I) + (1143.7999999999997 * I^I^I^Z^I^I^I^I) + (2287.6 * I^I^Z^I^I^I^I^I) + (4575.200000000001 * I^Z^I^I^I^I^I^I) + (1143.7999999999997 * Z^I^I^I^I^I^I^I) + (98.0 * I^I^I^I^I^I^Z^Z)+(196.0 * I^I^I^I^I^Z^I^Z) + (392.0 * I^I^I^I^I^Z^Z^I) + (49.0 * I^I^I^I^Z^I^I^Z) + (98.0 * I^I^I^I^Z^I^Z^I) + (196.0 * I^I^I^I^Z^Z^I^I) + (93.1 * I^I^Z^Z^I^I^I^I) + (186.2 * I^Z^I^Z^I^I^I^I)+ (372.4 * I^Z^Z^I^I^I^I^I) + (46.55 * Z^I^I^Z^I^I^I^I) + (93.1 * Z^I^Z^I^I^I^I^I) + (186.2 * Z^Z^I^I^I^I^I^I)
# you can swap this for a real quantum device and keep the rest of the code the same!
# backend = AerSimulator(method='matrix_product_state')
backend = QasmSimulator()
# COBYLA usually works well for small problems like this one
optimizer = COBYLA(maxiter=2000)
# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library
ansatz = TwoLocal(num_qubits=8, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)
# set the algorithm
vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)
#run it with the Hamiltonian we defined above
result = vqe.compute_minimum_eigenvalue(H)
#print the result (it contains lot's of information)
print(result)
v3, c3 = get_gradient(values, counts)
plt.figure(figsize=(15,15))
plt.plot(c3,v3)
plt.xlabel('optimization step')
plt.ylabel('E')
plt.show()
counts = []
values = []
H = (504.0 * I^I^I^I^I^I^I^Z) + (1008.0 * I^I^I^I^I^I^Z^I) + (2016.0 * I^I^I^I^I^Z^I^I) + (504.0 * I^I^I^I^Z^I^I^I) + (1143.7999999999997 * I^I^I^Z^I^I^I^I) + (2287.6 * I^I^Z^I^I^I^I^I) + (4575.200000000001 * I^Z^I^I^I^I^I^I) + (1143.7999999999997 * Z^I^I^I^I^I^I^I)+ (98.0 * I^I^I^I^I^I^Z^Z) + (196.0 * I^I^I^I^I^Z^I^Z) + (392.0 * I^I^I^I^I^Z^Z^I) + (49.0 * I^I^I^I^Z^I^I^Z)+ (98.0 * I^I^I^I^Z^I^Z^I)+ (196.0 * I^I^I^I^Z^Z^I^I) + (93.1 * I^I^Z^Z^I^I^I^I)+ (186.2 * I^Z^I^Z^I^I^I^I)+ (372.4 * I^Z^Z^I^I^I^I^I)+ (46.55 * Z^I^I^Z^I^I^I^I)+ (93.1 * Z^I^Z^I^I^I^I^I)+ (186.2 * Z^Z^I^I^I^I^I^I)
# you can swap this for a real quantum device and keep the rest of the code the same!
# backend = AerSimulator(method='matrix_product_state')
backend = QasmSimulator()
# COBYLA usually works well for small problems like this one
optimizer = COBYLA(maxiter=2000)
# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library
ansatz = TwoLocal(num_qubits=8, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)
# set the algorithm
vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)
#run it with the Hamiltonian we defined above
result = vqe.compute_minimum_eigenvalue(H)
#print the result (it contains lot's of information)
print(result)
v4, c4 = get_gradient(values, counts)
plt.figure(figsize=(15,15))
plt.plot(c4,v4)
plt.xlabel('optimization step')
plt.ylabel('E')
plt.show()
# 2nd Order Der
v1, c1 = get_gradient(v1, c1)
v2, c2 = get_gradient(v2, c2)
v3, c3 = get_gradient(v3, c3)
v4, c4 = get_gradient(v4, c4)
v1 = get_absolute(v1)
v2 = get_absolute(v2)
v3 = get_absolute(v3)
v4 = get_absolute(v4)
plt.figure(figsize=(15,15))
plt.plot(c1,v1, label="R1")
plt.plot(c2,v2, label="R2")
plt.plot(c3,v3, label="R3")
plt.plot(c4,v4, label="R4")
plt.xlabel('comparison optimization step')
plt.ylabel('E')
plt.legend()
plt.show()
plt.figure(figsize=(15,15))
plt.plot(c1[:100],v1[:100], label="R1")
plt.plot(c2[:100],v2[:100], label="R2")
plt.plot(c3[:100],v3[:100], label="R3")
plt.plot(c4[:100],v4[:100], label="R4")
plt.xlabel('comparison optimization step')
plt.ylabel('E')
plt.legend()
plt.show()
|
https://github.com/ionq-samples/qiskit-getting-started
|
ionq-samples
|
# import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.circuit.library import QFT
from qiskit_ionq import IonQProvider
#Call provider and set token value
provider = IonQProvider(token='my token')
# numpy
import numpy as np
# plotting
from matplotlib import pyplot as plt
%matplotlib inline
provider.backends()
# Quantum Fourier transform of |q>, of length n.
def qft(circ, q, n):
# Loop through the target qubits.
for i in range(n,0,-1):
# Apply the H gate to the target.
circ.h(q[i-1])
# Loop through the control qubits.
for j in range(i-1,0,-1):
circ.cp(2*np.pi/2**(i-j+1), q[j-1], q[i-1])
# Inverse Fourier transform of |q>, of length n.
def iqft(circ, q, n):
# Loop through the target qubits.
for i in range(1,n+1):
# Loop through the control qubits.
for j in range(1,i):
# The inverse Fourier transform just uses a negative phase.
circ.cp(-2*np.pi/2**(i-j+1), q[j-1], q[i-1])
# Apply the H gate to the target.
circ.h(q[i-1])
# define the Add function
def Add(circ, a, b, n):
# add 1 to n to account for overflow
n += 1
# take the QFT
qft(circ, b, n)
circ.barrier()
# Compute the controlled phases
# Iterate over targets
for i in range(n, 0, -1):
# Iterate over controls
for j in range(i, 0, -1):
# If the qubit a[j-1] exists run cp, if not assume the qubit is 0 and never existed
if len(a) - 1 >= j - 1:
circ.cp(2*np.pi/2**(i-j+1), a[j-1], b[i-1])
circ.barrier()
# take the inverse QFT
iqft(circ, b, n)
# Registers and circuit.
a = QuantumRegister(2)
b = QuantumRegister(3)
ca = ClassicalRegister(2)
cb = ClassicalRegister(3)
qc = QuantumCircuit(a, b, ca, cb)
# Numbers to add.
qc.x(a[1]) # a = 01110 / a = 10
#qc.x(a[2])
#qc.x(a[3])
qc.x(b[0]) # b = 01011 / b = 001
#qc.x(b[1])
#qc.x(b[3])
qc.barrier()
# Add the numbers, so |a>|b> to |a>|a+b>.
Add(qc, a, b, 2)
qc.barrier()
# Measure the results.
qc.measure(a, ca)
qc.measure(b, cb)
qc.draw(output="mpl")
# simulate the circuit
simulator = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, simulator)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
# run the circuit on a real-device
qpu = provider.get_backend("ionq_qpu")
qpu_job = qpu.run(qc)
from qiskit.providers.jobstatus import JobStatus
import time
# Check if job is done
while qpu_job.status() is not JobStatus.DONE:
print("Job status is", qpu_job.status() )
time.sleep(60)
# grab a coffee! This can take up to a few minutes.
# once we break out of that while loop, we know our job is finished
print("Job status is", qpu_job.status() )
print(qpu_job.get_counts()) # these counts are the “true” counts from the actual QPU Run
result_exp = qpu_job.result()
from qiskit.visualization import plot_histogram
plot_histogram(qpu_job.get_counts())
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This module implements the state preparation proposed by
Bergholm et al (2005) available in:
https://journals.aps.org/pra/abstract/10.1103/PhysRevA.71.052330
"""
import numpy as np
import numpy.linalg as la
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library import UCGate
from qclib.gates.initialize import Initialize
class UCGInitialize(Initialize):
"""
Quantum circuits with uniformly controlled one-qubit gates
https://doi.org/10.48550/arXiv.quant-ph/0410066
"""
def __init__(self, params, label=None, opt_params=None):
self._name = "ucg_initialize"
self._get_num_qubits(params)
self.register = QuantumRegister(self.num_qubits)
self.circuit = QuantumCircuit(self.register)
self.target_state = 0 if opt_params is None else opt_params.get("target_state")
self.str_target = bin(self.target_state)[2:].zfill(self.num_qubits)[::-1]
self.preserve = False if opt_params is None else opt_params.get("preserve_previous")
if label is None:
label = "ucg_initialize"
super().__init__(self._name, self.num_qubits, params, label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
children = self.params
parent = self._update_parent(children)
tree_level = self.num_qubits
r_gate = self.target_state // 2
while tree_level > 0:
bit_target, ucg = self._disentangle_qubit(children, parent, r_gate, tree_level)
children = self._apply_diagonal(bit_target, parent, ucg)
parent = self._update_parent(children)
# prepare next iteration
r_gate = r_gate // 2
tree_level -= 1
return self.circuit.inverse()
def _disentangle_qubit(self, children: 'list[float]',
parent: 'list[float]',
r_gate: int, tree_level: int):
""" Apply UCGate to disentangle qubit target"""
bit_target = self.str_target[self.num_qubits - tree_level]
mult, mult_controls, target = self._define_mult(children, parent, tree_level)
if self.preserve:
self._preserve_previous(mult, mult_controls, r_gate, target)
ucg = self._apply_ucg(mult, mult_controls, target)
return bit_target, ucg
def _define_mult(self, children: 'list[float]', parent: 'list[float]', tree_level: int):
current_level_mux = self._build_multiplexor(parent,
children,
self.str_target)
mult_controls, target = self._get_ctrl_targ(tree_level)
return current_level_mux, mult_controls, target
def _apply_ucg(self, current_level_mux: 'list[np.ndarray]',
mult_controls: 'list[int]',
target: int):
""" Creates and applies multiplexer """
ucg = UCGate(current_level_mux, up_to_diagonal=True)
if len(current_level_mux) != 1:
self.circuit.append(ucg, [target] + mult_controls)
else:
self.circuit.unitary(current_level_mux[0], target) # pylint: disable=maybe-no-member
return ucg
def _preserve_previous(self, mux: 'list[np.ndarray]',
mult_controls: 'list[int]',
r_gate: int, target: int):
"""
Remove one gate from mux and apply separately to avoid changing previous base vectors
"""
out_gate = mux[r_gate]
qc_gate = QuantumCircuit(1)
qc_gate.unitary(out_gate, 0) # pylint: disable=maybe-no-member
mux[r_gate] = np.eye(2)
out_gate_ctrl = list(range(0, target)) + list(range(target + 1, self.num_qubits))
ctrl_state = self.str_target[0:target][::-1]
if len(ctrl_state) < self.num_qubits - 1:
ctrl_state = bin(r_gate)[2:].zfill(len(mult_controls)) + ctrl_state
gate = qc_gate.control(self.num_qubits - 1, ctrl_state=ctrl_state)
self.circuit.compose(gate, out_gate_ctrl + [target], inplace=True)
@staticmethod
def _update_parent(children):
size = len(children) // 2
parent = [la.norm([children[2 * k], children[2 * k + 1]]) for k in range(size)]
return parent
@staticmethod
def _apply_diagonal(bit_target: str, parent: 'list[float]', ucg: UCGate):
children = parent
if bit_target == '1':
diagonal = np.conj(ucg._get_diagonal())[1::2] # pylint: disable=protected-access
else:
diagonal = np.conj(ucg._get_diagonal())[::2] # pylint: disable=protected-access
children = children * diagonal
return children
def _get_ctrl_targ(self, tree_level: int):
controls = list(range(self.num_qubits - tree_level + 1, self.num_qubits))
target = self.num_qubits - tree_level
return controls, target
def _build_multiplexor(self, parent_amplitudes: 'list[float]',
children_amplitudes: 'list[float]', str_target: str):
"""
Infers the unitary to be used in the uniformily controlled multiplexor
defined by Bergholm et al (2005).
Args:
parent_amplitudes: list of amplitudes
children_amplitudes: children of the parent amplitudes
Returns:
list of 2-by-2 numpy arrays with the desired unitaries to be used
in the multiplexor
"""
tree_lvl = int(np.log2(len(children_amplitudes)))
bit_target = str_target[self.num_qubits - tree_lvl]
gates = []
len_pnodes = len(parent_amplitudes)
len_snodes = len(children_amplitudes)
for parent_idx, sibling_idx in zip(range(len_pnodes), range(0, len_snodes, 2)):
if parent_amplitudes[parent_idx] != 0:
amp_ket0 = (children_amplitudes[sibling_idx] / parent_amplitudes[parent_idx])
amp_ket1 = (children_amplitudes[sibling_idx + 1] / parent_amplitudes[parent_idx])
if amp_ket0 != 0:
gates += [self._get_branch_operator(amp_ket0, amp_ket1, bit_target)]
else:
gates += [self._get_diagonal_operator(amp_ket1, bit_target)]
else:
gates += [np.eye(2)]
return gates
@staticmethod
def _get_branch_operator(amplitude_ket0, amplitude_ket1, target='0'):
"""
Returns the matrix operator that is going to split the qubit in to two components
of a superposition
Args:
amplitude_ket0: Complex amplitude of the |0> component of the superpoisition
amplitude_ket1: Complex amplitude of the |1> component of the superpoisition
Returns:
A 2x2 numpy array defining the desired operator inferred from
the amplitude argument
"""
if target == '0':
operator = np.array([[amplitude_ket0, -np.conj(amplitude_ket1)],
[amplitude_ket1, np.conj(amplitude_ket0)]])
else:
operator = np.array([[-np.conj(amplitude_ket1), amplitude_ket0],
[np.conj(amplitude_ket0), amplitude_ket1]])
return np.conj(operator).T
@staticmethod
def initialize(q_circuit, state, qubits=None, opt_params=None):
gate = UCGInitialize(state, opt_params=opt_params)
if qubits is None:
q_circuit.append(gate.definition, q_circuit.qubits)
else:
q_circuit.append(gate.definition, qubits)
@staticmethod
def _get_diagonal_operator(amplitude_ket1, target):
if target == '0':
operator = np.array([[0, 1], [amplitude_ket1, 0]])
else:
operator = np.array([[1, 0], [0, amplitude_ket1]])
return np.conj(operator).T
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
===============================================================================
Qiskit Transpiler Service (:mod:`qiskit_transpiler_service.transpiler_service`)
===============================================================================
.. currentmodule:: qiskit_transpiler_service.transpiler_service
Classes
=======
.. autosummary::
:toctree: ../stubs/
TranspilerService
"""
import logging
from typing import Dict, List, Union, Literal
from qiskit import QuantumCircuit
from .wrappers.transpile import TranspileAPI
logger = logging.getLogger(__name__)
class TranspilerService:
"""Class for using the transpiler service.
:param optimization_level: The optimization level to use during the transpilation. There are 4 optimization levels ranging from 0 to 3, where 0 is intended for not performing any optimizations and 3 spends the most effort to optimize the circuit.
:type optimization_level: int
:param ai: Specifies if the transpilation should use AI or not, defaults to True.
:type ai: str, optional
:param coupling_map: A list of pairs that represents physical links between qubits.
:type coupling_map: list[list[int]], optional
:param backend_name: Name of the backend used for doing the transpilation.
:type backend_name: str, optional
:param qiskit_transpile_options: Other options to transpile with qiskit.
:type qiskit_transpile_options: dict, optional
:param ai_layout_mode: Specifies how to handle the layout selection. There are 3 layout modes: keep (respects the layout set by the previous transpiler passes), improve (uses the layout set by the previous transpiler passes as a starting point) and optimize (ignores previous layout selections).
:type ai_layout_mode: str, optional
"""
def __init__(
self,
optimization_level: int,
ai: Literal["true", "false", "auto"] = "true",
coupling_map: Union[List[List[int]], None] = None,
backend_name: Union[str, None] = None,
qiskit_transpile_options: Dict = None,
ai_layout_mode: str = None,
) -> None:
"""Initializes the instance."""
self.transpiler_service = TranspileAPI()
self.backend_name = backend_name
self.coupling_map = coupling_map
self.optimization_level = optimization_level
self.ai = ai
self.qiskit_transpile_options = qiskit_transpile_options
if ai_layout_mode is not None:
if ai_layout_mode.upper() not in ["KEEP", "OPTIMIZE", "IMPROVE"]:
raise (
f"ERROR. Unknown ai_layout_mode: {ai_layout_mode.upper()}. Valid modes: 'KEEP', 'OPTIMIZE', 'IMPROVE'"
)
self.ai_layout_mode = ai_layout_mode.upper()
else:
self.ai_layout_mode = ai_layout_mode
super().__init__()
def run(
self,
circuits: Union[List[Union[str, QuantumCircuit]], Union[str, QuantumCircuit]],
):
"""Transpile the circuit(s) by calling the service /transpile endpoint.
Args:
circuits: circuit(s) to transpile.
Returns:
The transpiled circuit(s)
"""
logger.info(f"Requesting transpile to the service")
transpile_result = self.transpiler_service.transpile(
circuits=circuits,
backend=self.backend_name,
coupling_map=self.coupling_map,
optimization_level=self.optimization_level,
ai=self.ai,
qiskit_transpile_options=self.qiskit_transpile_options,
)
if transpile_result is None:
logger.warning(
"Qiskit transpiler service couldn't transpile the circuit(s)"
)
return None
logger.info("Qiskit transpiler service returned a result")
return transpile_result
|
https://github.com/pedroripper/qiskit_tutoriais
|
pedroripper
|
from qiskit import *
%matplotlib inline
import numpy as np
# Podemos encontrar o operador de densidade de estados
# Para isso vamos primeiramente usar o statevector_simulator para encontrar o vetor de
# estado desejado
qc = QuantumCircuit(1)
qc.ry(3*np.pi/2,0)
qc.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
job = execute(qc,backend)
result = job.result()
statevector = result.get_statevector(qc, decimals = 3)
# Aqui está o nosso vetor de estado
print(statevector)
# Agora para encontrar o seu operador de densidade
from qiskit.quantum_info import *
op_densidade = DensityMatrix(statevector)
print(op_densidade.data)
# É possível também visualizar a matriz de densidade por meio de um histograma
from qiskit.visualization import plot_state_city
plot_state_city(statevector)
# Também é possivel visualizar as matrizes de Pauli que compõem o seu operador de densidade
from qiskit.tools.visualization import plot_state_paulivec
plot_state_paulivec(statevector)
# Podemos ver o traço do nosso operador
op_densidade.trace()
estado = [np.sqrt(2),np.sqrt(2)]
print(np.inner(np.inner(estado, op_densidade.data), estado))
rho_2 = np.matmul(op_densidade.data,op_densidade.data)
trace = rho_2.trace()
print(trace)
def bloch_vector(op):
pauli_x = [[0,1],[1,0]]
pauli_y = [[0,-1j],[1j,0]]
pauli_z = [[1,0],[0,-1]]
x = np.matmul(op,pauli_x).trace()
y = np.matmul(op,pauli_y).trace()
z = np.matmul(op,pauli_z).trace()
return [np.absolute(x),np.absolute(y),np.absolute(z)]
from qiskit.tools.visualization import plot_bloch_vector
plot_bloch_vector(bloch_vector(op_densidade.data))
# Exemplo de estado misto:
estado_misto = [[0.5, 0.25],[0.25,0.5]]
plot_bloch_vector(bloch_vector(estado_misto))
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2024 Qiskit on IQM developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
"""Testing the new move gate
"""
import pytest
from qiskit import QuantumCircuit
from qiskit.transpiler import TranspilerError
from iqm.qiskit_iqm.iqm_circuit import IQMCircuit
from iqm.qiskit_iqm.move_gate import MoveGate
from tests.utils import describe_instruction, get_transpiled_circuit_json
def test_move_gate_trivial_layout(new_architecture):
"""Tests that a trivial 1-to-1 layout is translated correctly."""
qc = QuantumCircuit(7)
qc.append(MoveGate(), [6, 0])
qc.cz(0, 3)
qc.cz(2, 0)
submitted_circuit = get_transpiled_circuit_json(qc, new_architecture)
assert [describe_instruction(i) for i in submitted_circuit.instructions] == ['move:6,0', 'cz:0,3', 'cz:2,0']
def test_move_gate_nontrivial_layout(new_architecture):
"""
For now only trivial layouts (1-to-1 mapping between virtual and physical qubits) are supported
if there are qubit connections that don't have all operations specified.
"""
qc = QuantumCircuit(7)
qc.append(MoveGate(), [3, 0])
with pytest.raises(TranspilerError):
get_transpiled_circuit_json(qc, new_architecture)
def test_mapped_move_qubit(new_architecture):
"""
Test that other qubit indices can be used if we manually calculate a working
initial layout using the IQMMoveLayout() layout pass.
"""
qc = QuantumCircuit(7)
qc.cz(0, 2)
qc.append(MoveGate(), [3, 0])
submitted_circuit = get_transpiled_circuit_json(qc, new_architecture, create_move_layout=True)
assert [describe_instruction(i) for i in submitted_circuit.instructions] == ['cz:0,2', 'move:6,0']
def test_mapped_move_qubit_and_resonator(new_architecture):
qc = IQMCircuit(7)
# Now resonator is 2, move qubit 5, so need to switch 2<->0, 5<->6
qc.cz(2, 4)
qc.move(5, 2)
qc.cz(2, 1)
qc.cz(2, 0)
qc.move(5, 2)
qc.h(5)
submitted_circuit = get_transpiled_circuit_json(qc, new_architecture, create_move_layout=True)
assert [describe_instruction(i) for i in submitted_circuit.instructions] == [
'cz:0,4',
'move:6,0',
'cz:0,1',
'cz:0,2',
'move:6,0',
'prx:6',
'prx:6',
]
def test_cant_layout_two_resonators(new_architecture):
qc = QuantumCircuit(7)
qc.append(MoveGate(), [0, 6])
qc.append(MoveGate(), [3, 6])
with pytest.raises(TranspilerError):
get_transpiled_circuit_json(qc, new_architecture, create_move_layout=True)
def test_cant_layout_two_move_qubits(new_architecture):
qc = QuantumCircuit(7)
qc.append(MoveGate(), [0, 6])
qc.append(MoveGate(), [0, 4])
with pytest.raises(TranspilerError):
get_transpiled_circuit_json(qc, new_architecture, create_move_layout=True)
def test_transpiled_circuit(new_architecture):
"""
Tests that a circuit with a move operation is transpiled correctly into JSON.
"""
qc = IQMCircuit(7, 2)
qc.move(6, 0)
qc.cz(0, 3)
qc.h(6)
qc.h(4)
qc.cz(4, 0)
qc.barrier()
qc.move(6, 0)
qc.measure(6, 0)
qc.measure(3, 1)
submitted_circuit = get_transpiled_circuit_json(qc, new_architecture, seed_transpiler=1)
assert [describe_instruction(i) for i in submitted_circuit.instructions] == [
# h(4) is moved before the move gate
'prx:4',
'prx:4',
# move(6, 0)
'move:6,0',
# cz(0, 3)
'cz:0,3',
# cz(4, 0) is optimized before h(6)
'cz:4,0',
# h(6)
'prx:6',
'prx:6',
# barrier()
'barrier:0,1,2,3,4,5,6',
# move (6, 0)
'move:6,0',
# measurements
'measure:6',
'measure:3',
]
|
https://github.com/quantum-melbourne/qiskit-challenge-22
|
quantum-melbourne
|
#Let us first import necessary libraries
from qiskit import Aer
from qiskit.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.utils import QuantumInstance
from qiskit_finance.applications.optimization import PortfolioOptimization
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization.applications import OptimizationApplication
from qiskit_optimization.converters import QuadraticProgramToQubo
import numpy as np
import matplotlib.pyplot as plt
import datetime
# set number of assets (= number of qubits)
num_assets = 4
seed = 103
# 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(2021,1,1),
end=datetime.datetime(2022,6,30),
seed=seed)
data.run()
mu = data.get_period_return_mean_vector()
sigma = data.get_period_return_covariance_matrix()
# Let's plot our finanical data
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.xlabel('days')
plt.ylabel('stock value')
plt.show()
# Let's plot our covariance matrix Σ(sigma)
sigma = data.get_period_return_covariance_matrix() #Returns the covariance matrix of the four assets
print(sigma)
fig, ax = plt.subplots(1,1)
im = plt.imshow(sigma, extent=[-1,1,-1,1])
x_label_list = ['stock3', 'stock2', 'stock1', 'stock0']
y_label_list = ['stock3', 'stock2', 'stock1', 'stock0']
ax.set_xticks([-0.75,-0.25,0.25,0.75])
ax.set_yticks([0.75,0.25,-0.25,-0.75])
ax.set_xticklabels(x_label_list)
ax.set_yticklabels(y_label_list)
plt.colorbar()
plt.clim(-0.000002, 0.00001)
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 index_to_selection(i, num_assets):
s = "{0:b}".format(i).rjust(num_assets)
x = np.array([1 if s[i]=='1' else 0 for i in reversed(range(num_assets))])
return x
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
# eigenvector = eigenstate if isinstance(eigenstate, np.ndarray) else eigenstate.to_matrix()
# probabilities = np.abs(eigenvector)**2
# i_sorted = reversed(np.argsort(probabilities))
# print('\n----------------- Full result ---------------------')
# print('selection\tvalue\t\tprobability')
# print('---------------------------------------------------')
# for i in i_sorted:
# x = index_to_selection(i, num_assets)
# value = QuadraticProgramToQubo().convert(qp).objective.evaluate(x)
# #value = portfolio.to_quadratic_program().objective.evaluate(x)
# probability = probabilities[i]
# print('%10s\t%.4f\t\t%.4f' %(x, value, probability))
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
backend = Aer.get_backend('statevector_simulator')
cobyla = COBYLA()
cobyla.set_options(maxiter=500)
ry = TwoLocal(num_assets, 'ry', 'cz', reps=3, entanglement='full')
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
vqe_mes = VQE(ry, optimizer=cobyla, quantum_instance=quantum_instance)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.solve(qp)
print_result(result)
algorithm_globals.random_seed = 1234
backend = Aer.get_backend('statevector_simulator')
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
qaoa_mes = QAOA(optimizer=cobyla, reps=3, quantum_instance=quantum_instance)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qp)
print_result(result)
|
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
|
SaashaJoshi
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
# our backend is the Pulse Simulator
from resources import helper
from qiskit.providers.aer import PulseSimulator
backend_sim = PulseSimulator()
# sample duration for pulse instructions
dt = 1e-9
# create the model
duffing_model = helper.get_transmon(dt)
# get qubit frequency from Duffing model
qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift()
import numpy as np
# visualization tools
import matplotlib.pyplot as plt
plt.style.use('dark_background')
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
kHz = 1.0e3 # kilohertz
us = 1.0e-6 # microseconds
ns = 1.0e-9 # nanoseconds
from qiskit import pulse
from qiskit.pulse import Play, Acquire
from qiskit.pulse.pulse_lib import GaussianSquare
# qubit to be used throughout the notebook
qubit = 0
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
# Construct a measurement schedule and add it to an InstructionScheduleMap
meas_samples = 1200
meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150)
measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit))
inst_map = pulse.InstructionScheduleMap()
inst_map.add('measure', [qubit], measure_sched)
# save the measurement/acquire pulse for later
measure = inst_map.get('measure', qubits=[qubit])
from qiskit.pulse import pulse_lib
def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma):
### create a Rabi schedule (already done)
### create a Gaussian Rabi pulse using pulse_lib
### play Rabi pulse on the Rabi schedule and return
rabi_schedule = pulse.Schedule(name='rabi_experiment')
### WRITE YOUR CODE BETWEEN THESE LINES - START
rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp,
sigma=drive_sigma)
rabi_schedule = pulse.Schedule()
rabi_schedule += Play(rabi_pulse, drive_chan)
### WRITE YOUR CODE BETWEEN THESE LINES - END
# add measurement to rabi_schedule
# << indicates time shift the beginning to the start of the schedule
rabi_schedule += measure << rabi_schedule.duration
return rabi_schedule
# Gaussian pulse parameters, with varying amplitude
drive_duration = 128
num_rabi_points = 41
drive_amps = np.linspace(0, 0.9, num_rabi_points)
drive_sigma = 16
# now vary the amplitude for each drive amp
rabi_schedules = []
for drive_amp in drive_amps:
rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma))
rabi_schedules[-1].draw()
# assemble the schedules into a Qobj
from qiskit import assemble
rabi_qobj = assemble(**helper.get_params('rabi', globals()))
answer1a = rabi_qobj
# run the simulation
rabi_result = backend_sim.run(rabi_qobj, duffing_model).result()
# retrieve the data from the experiment
rabi_values = helper.get_values_from_result(rabi_result, qubit)
fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0])
plt.scatter(drive_amps, rabi_values, color='white')
plt.plot(drive_amps, y_fit, color='red')
drive_period = fit_params[2] # get period of rabi oscillation
plt.axvline(0, color='red', linestyle='--')
plt.axvline(drive_period/2, color='red', linestyle='--')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
print("Pi pulse amplitude is %f"%float(drive_period/2))
# x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees
x90_pulse = pulse_lib.gaussian(duration=drive_duration,
amp=drive_period/4,
sigma=drive_sigma,
name='x90_pulse')
# Ramsey experiment parameters
time_max_us = 0.4
time_step_us = 0.0035
times_us = np.arange(0.1, time_max_us, time_step_us)
# Convert to units of dt
delay_times_dt = times_us * us / dt
def build_ramsey_pulse_schedule(delay):
### create a Ramsey pulse schedule (already done)
### play an x90 pulse on the drive channel
### play another x90 pulse after delay
### add measurement pulse to schedule
ramsey_schedule = pulse.Schedule(name='ramsey_experiment')
### HINT: include delay by adding it to the duration of the schedule
### round delay to nearest integer with int(delay)
### WRITE YOUR CODE BETWEEN THESE LINES - START
ramsey_schedule = pulse.Schedule()
ramsey_schedule += Play(x90_pulse, drive_chan)
ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay)
ramsey_schedule += measure << ramsey_schedule.duration
### WRITE YOUR CODE BETWEEN THESE LINES - END
return ramsey_schedule
# create schedules for Ramsey experiment
ramsey_schedules = []
for delay in delay_times_dt:
ramsey_schedules.append(build_ramsey_pulse_schedule(delay))
ramsey_schedules[-1].draw()
# assemble the schedules into a Qobj
# the helper will drive the pulses off-resonantly by an unknown value
ramsey_qobj = assemble(**helper.get_params('ramsey', globals()))
answer1b = ramsey_qobj
# run the simulation
ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result()
# retrieve the data from the experiment
ramsey_values = helper.get_values_from_result(ramsey_result, qubit)
# off-resonance component
fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25])
_, _, ramsey_period_us, _, = fit_params
del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us
plt.scatter(times_us, np.real(ramsey_values), color='white')
plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz")
plt.xlim(np.min(times_us), np.max(times_us))
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Ramsey Experiment', fontsize=15)
plt.legend(loc=3)
plt.show()
print("Drive is off-resonant by %f MHz"%float(del_f_MHz))
name = 'Saasha Joshi'
email = 'saashajoshi08@gmail.com'
from grading_tools import grade
grade(answer1a, name, email, 'lab6', 'ex1a')
grade(answer1b, name, email, 'lab6', 'ex1b')
from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();'));
from grading_tools import send_code;send_code('ex1.ipynb')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output
from qiskit.primitives import Estimator
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.observables_evaluator import estimate_observables
from qiskit.algorithms.optimizers import COBYLA, SLSQP
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit.circuit.library import TwoLocal
from qiskit.quantum_info import Pauli, SparsePauliOp
from qiskit.utils import algorithm_globals
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_nature.second_q.mappers import JordanWignerMapper
def kronecker_delta_function(n: int, m: int) -> int:
"""An implementation of the Kronecker delta function.
Args:
n (int): The first integer argument.
m (int): The second integer argument.
Returns:
Returns 1 if n = m, else returns 0.
"""
return int(n == m)
def create_deuteron_hamiltonian(
N: int, hbar_omega: float = 7.0, V_0: float = -5.68658111
) -> SparsePauliOp:
"""Creates a version of the Deuteron Hamiltonian as a qubit operator.
Args:
N (int): An integer number that represents the dimension of the
basis.
hbar_omega (float, optional): The value of the product of hbar and omega. Defaults to 7.0.
V_0 (float, optional): The value of the potential energy. Defaults to -5.68658111.
Returns:
SparsePauliOp: The qubit-space Hamiltonian that represents the Deuteron.
"""
hamiltonian_terms = {}
for m in range(N):
for n in range(N):
label = "+_{} -_{}".format(str(n), str(m))
coefficient_kinect = (hbar_omega / 2) * (
(2 * n + 3 / 2) * kronecker_delta_function(n, m)
- np.sqrt(n * (n + (1 / 2))) * kronecker_delta_function(n, m + 1)
- np.sqrt((n + 1) * (n + (3 / 2)) * kronecker_delta_function(n, m - 1))
)
hamiltonian_terms[label] = coefficient_kinect
coefficient_potential = (
V_0 * kronecker_delta_function(n, 0) * kronecker_delta_function(n, m)
)
hamiltonian_terms[label] += coefficient_potential
hamiltonian = FermionicOp(hamiltonian_terms, num_spin_orbitals=N)
mapper = JordanWignerMapper()
qubit_hamiltonian = mapper.map(hamiltonian)
if not isinstance(qubit_hamiltonian, SparsePauliOp):
qubit_hamiltonian = qubit_hamiltonian.primitive
return qubit_hamiltonian
deuteron_hamiltonians = [create_deuteron_hamiltonian(i) for i in range(1, 5)]
for i, hamiltonian in enumerate(deuteron_hamiltonians):
print("Deuteron Hamiltonian: H_{}".format(i + 1))
print(hamiltonian)
print("\n")
theta = Parameter(r"$\theta$")
eta = Parameter(r"$\eta$")
wavefunction = QuantumCircuit(1)
wavefunction.ry(theta, 0)
wavefunction.draw("mpl")
wavefunction2 = QuantumCircuit(2)
wavefunction2.x(0)
wavefunction2.ry(theta, 1)
wavefunction2.cx(1, 0)
wavefunction2.draw("mpl")
wavefunction3 = QuantumCircuit(3)
wavefunction3.x(0)
wavefunction3.ry(eta, 1)
wavefunction3.ry(theta, 2)
wavefunction3.cx(2, 0)
wavefunction3.cx(0, 1)
wavefunction3.ry(-eta, 1)
wavefunction3.cx(0, 1)
wavefunction3.cx(1, 0)
wavefunction3.draw("mpl")
ansatz = [wavefunction, wavefunction2, wavefunction3]
reference_values = []
print("Exact binding energies calculated through numpy.linalg.eigh \n")
for i, hamiltonian in enumerate(deuteron_hamiltonians):
eigenvalues, eigenstates = np.linalg.eigh(hamiltonian.to_matrix())
reference_values.append(eigenvalues[0])
print("Exact binding energy for H_{}: {}".format(i + 1, eigenvalues[0]))
print(
"Results using Estimator for H_1, H_2 and H_3 with the ansatz given in the reference paper \n"
)
for i in range(3):
seed = 42
algorithm_globals.random_seed = seed
vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=SLSQP())
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
binding_energy = vqe_result.optimal_value
print("Binding energy for H_{}: {} MeV".format(i + 1, binding_energy))
def callback(eval_count, parameters, mean, std):
# Overwrites the same line when printing
display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std))
clear_output(wait=True)
counts.append(eval_count)
values.append(mean)
params.append(parameters)
deviation.append(std)
plots = []
for i in range(3):
counts = []
values = []
params = []
deviation = []
seed = 42
algorithm_globals.random_seed = seed
vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=COBYLA(), callback=callback)
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
plots.append([counts, values])
fig, ax = plt.subplots(nrows=3, ncols=1)
fig.set_size_inches((12, 12))
for i, plot in enumerate(plots):
ax[i].plot(plot[0], plot[1], "o-", label="COBYLA")
ax[i].axhline(
y=reference_values[i],
color="k",
linestyle="--",
label=f"Reference Value: {reference_values[i]}",
)
ax[i].legend()
ax[i].set_xlabel("Cost Function Evaluations", fontsize=15)
ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15)
plt.show()
twolocal_ansatzes = []
for i in range(1, 5):
ansatz = TwoLocal(
deuteron_hamiltonians[i - 1].num_qubits,
["rz", "ry"],
"cx",
entanglement="full",
reps=i,
initial_state=None,
)
twolocal_ansatzes.append(ansatz)
print("Results using Estimator for H_1, H_2, H_3 and H_4 with TwoLocal ansatz \n")
seed = 42
algorithm_globals.random_seed = seed
for i in range(4):
vqe = VQE(Estimator(), ansatz=twolocal_ansatzes[i], optimizer=SLSQP())
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
binding_energy = vqe_result.optimal_value
print("Binding energy for H_{}:".format(i + 1), binding_energy, "MeV")
seed = 42
algorithm_globals.random_seed = seed
plots_tl = []
for i in range(4):
counts = []
values = []
params = []
deviation = []
vqe = VQE(
Estimator(),
ansatz=twolocal_ansatzes[i],
optimizer=SLSQP(),
callback=callback,
)
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
plots_tl.append([counts, values])
fig, ax = plt.subplots(nrows=4, ncols=1)
fig.set_size_inches((15, 15))
for i, plot in enumerate(plots_tl):
ax[i].plot(plot[0], plot[1], "o-", label="COBYLA")
ax[i].axhline(
y=reference_values[i],
color="k",
linestyle="--",
label=f"Reference Value: {reference_values[i]}",
)
ax[i].legend()
ax[i].set_xlabel("Cost Function Evaluations", fontsize=15)
ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15)
plt.show()
def calculate_observables_exp_values(
quantum_circuit: QuantumCircuit, observables: list, angles: list
) -> list:
"""Calculate the expectation value of an observable given the quantum
circuit that represents the wavefunction and a list of parameters.
Args:
quantum_circuit (QuantumCircuit): A parameterized quantum circuit
that represents the wavefunction of the system.
observables (list): A list containing the observables that we want
to know the expectation values.
angles (list): A list with the values that will be used in the
'bind_parameters' method.
Returns:
list_exp_values (list): A list containing the expectation values
of the observables given as input.
"""
list_exp_values = []
for observable in observables:
exp_values = []
for angle in angles:
qc = quantum_circuit.bind_parameters({theta: angle})
result = estimate_observables(
Estimator(),
quantum_state=qc,
observables=[observable],
)
exp_values.append(result[0][0])
list_exp_values.append(exp_values)
return list_exp_values
angles = list(np.linspace(-np.pi, np.pi, 100))
observables = [
Pauli("IZ"),
Pauli("ZI"),
Pauli("XX"),
Pauli("YY"),
deuteron_hamiltonians[1],
]
h2_observables_exp_values = calculate_observables_exp_values(wavefunction2, observables, angles)
fig, ax = plt.subplots(nrows=2, ncols=1)
fig.set_size_inches((12, 12))
ax[0].plot(angles, h2_observables_exp_values[0], "o", label=r"$Z_0$")
ax[0].plot(angles, h2_observables_exp_values[1], "o", label=r"$Z_1$")
ax[0].plot(angles, h2_observables_exp_values[2], "o", label=r"$X_0X_1$")
ax[0].plot(angles, h2_observables_exp_values[3], "o", label=r"$Y_0Y_1$")
ax[0].axhline(
y=1,
color="k",
linestyle="--",
)
ax[0].axhline(y=-1, color="k", linestyle="--")
ax[0].legend()
ax[0].set_xlabel(r"Theta - $\theta$", fontsize=15)
ax[0].set_ylabel(r"$\langle O \rangle $ - Operator Expectation Value", fontsize=15)
ax[0].set_xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"],
)
ax[0].set_title(
r"Expectation value of the observables $Z_0$, $Z_1$, $X_0X_1$ and $Y_0Y_1$ when we vary $\theta$ in the ansatz.",
fontsize=15,
)
ax[1].plot(angles, h2_observables_exp_values[4], "o")
ax[1].axhline(
y=reference_values[1],
color="k",
linestyle="--",
label="Binding Energy: {} MeV".format(np.round(reference_values[1], 3)),
)
ax[1].legend()
ax[1].set_xlabel(r"Theta - $\theta$", fontsize=15)
ax[1].set_ylabel(r"$\langle H_2 \rangle $ - Energy (MeV)", fontsize=15)
ax[1].set_xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"],
)
ax[1].set_title(
r"Behavior of the expectation value of $H_2$ when we vary $\theta$ in the ansatz.", fontsize=15
)
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
dc = pulse.DriveChannel
d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4)
with pulse.build(name='pulse_programming_in') as pulse_prog:
pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3)
pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4)
pulse_prog.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate
from qiskit.converters import dag_to_circuit
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
circuit = dag_to_circuit(dag)
circuit.draw('mpl')
|
https://github.com/tstopa/Qiskit_for_high_schools
|
tstopa
|
%matplotlib inline
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, IBMQ
from qiskit.tools.monitor import backend_overview, backend_monitor
from qiskit.compiler import transpile, assemble
from qiskit.visualization import *
from qiskit.transpiler import *
from qiskit.converters import circuit_to_dag
from qiskit.tools.visualization import dag_drawer
import pprint
provider = IBMQ.load_account()
real_backend = provider.get_backend('ibmq_16_melbourne')
plot_error_map(real_backend)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
circuit.measure(qr, cr)
circuit.draw(output='mpl')
compiled_circuit = transpile(circuit, real_backend, optimization_level=0)
compiled_circuit.draw(output='mpl', idle_wires=False)
compiled_circuit = transpile(circuit, real_backend, optimization_level=3)
compiled_circuit.draw(output='mpl', idle_wires=False)
qr2 = QuantumRegister(14)
cr2 = ClassicalRegister(14)
circuit2 = QuantumCircuit(qr2, cr2)
circuit2.h(qr2[0])
circuit2.cx(qr2[0], qr2[6])
circuit2.cx(qr2[6], qr2[13])
circuit2.cx(qr2[13], qr2[7])
circuit2.cx(qr2[7], qr2[0])
circuit2.measure(qr2, cr2)
for level in range(4):
compiled_circuit2 = transpile(circuit2, real_backend, optimization_level=level)
print('---------- Level = ' + str(level) + '----------')
print('gates = ', compiled_circuit2.count_ops())
print('depth = ', compiled_circuit2.depth())
|
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
|
# -*- coding: utf-8 -*-
# Copyright 2018 IBM.
#
# 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.
# =============================================================================
"""
The Fidelity of Quantum Evolution.
This is a simple tutorial example to show how to build an algorithm to extend
Qiskit Aqua library. Algorithms are designed to be dynamically discovered within
Qiskit Aqua. For this the entire parent directory 'evolutionfidelity' should
be moved under the 'qiskit_aqua' directory. The current demonstration notebook
shows how to explicitly register the algorithm and works without re-locating this
code. The former automatic discovery does however allow the algorithm to be found
and seen in the UI browser, and selected from the GUI when choosing an algorithm.
"""
import logging
import numpy as np
from qiskit import QuantumRegister
from qiskit.quantum_info import state_fidelity
from qiskit_aqua.algorithms import QuantumAlgorithm
from qiskit_aqua import AquaError, PluggableType, get_pluggable_class
logger = logging.getLogger(__name__)
class EvolutionFidelity(QuantumAlgorithm):
"""The Tutorial Sample EvolutionFidelity algorithm."""
PROP_EXPANSION_ORDER = 'expansion_order'
"""
A configuration dictionary defines the algorithm to QISKIt Aqua. It can contain
the following though this sample does not have them all.
name: Is the registered name and will be used as the case-sensitive key to load an instance
description: As it implies a brief description of algorithm
classical: True if purely a classical algorithm that does not need a quantum backend
input_schema: A json schema detailing the configuration variables of this entity.
Each variable as a type, and can be given default, minimum etc. This conforms
to JSON Schema which can be consulted for for detail. The existing algorithms
and other pluggable entities may also be helpful to refer to.
problems: A list of problems the algorithm can solve
depends: A list of dependent object types
defaults: A list of configurations for the dependent objects. May just list names if the
dependent's defaults are acceptable
"""
CONFIGURATION = {
'name': 'EvolutionFidelity',
'description': 'Sample Demo EvolutionFidelity Algorithm for Quantum Systems',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'evolution_fidelity_schema',
'type': 'object',
'properties': {
PROP_EXPANSION_ORDER: {
'type': 'integer',
'default': 1,
'minimum': 1
},
},
'additionalProperties': False
},
'problems': ['eoh'],
'depends': ['initial_state'],
'defaults': {
'initial_state': {
'name': 'ZERO'
}
}
}
"""
If directly use these objects programmatically then the constructor is more convenient to call
than init_params. init_params itself uses this to do the actual object initialization.
"""
def __init__(self, operator, initial_state, expansion_order=1):
self.validate(locals())
super().__init__()
self._operator = operator
self._initial_state = initial_state
self._expansion_order = expansion_order
self._ret = {}
"""
init_params is called via run_algorithm. The params contain all the configuration settings
of the objects. algo_input contains data computed from above for the algorithm. A simple
algorithm may have all its data in configuration params such that algo_input is None
"""
@classmethod
def init_params(cls, params, algo_input):
"""
Initialize via parameters dictionary and algorithm input instance.
Args:
params: parameters dictionary
algo_input: EnergyInput instance
"""
if algo_input is None:
raise AquaError("EnergyInput instance is required.")
operator = algo_input.qubit_op
evolution_fidelity_params = params.get(QuantumAlgorithm.SECTION_KEY_ALGORITHM)
expansion_order = evolution_fidelity_params.get(EvolutionFidelity.PROP_EXPANSION_ORDER)
# Set up initial state, we need to add computed num qubits to params
initial_state_params = params.get(QuantumAlgorithm.SECTION_KEY_INITIAL_STATE)
initial_state_params['num_qubits'] = operator.num_qubits
initial_state = get_pluggable_class(PluggableType.INITIAL_STATE,
initial_state_params['name']).init_params(initial_state_params)
return cls(operator, initial_state, expansion_order)
"""
Once the algorithm has been initialized then run is called to carry out the computation
and the result is returned as a dictionary.
E.g., the `_run` method is required to be implemented for an algorithm.
"""
def _run(self):
evo_time = 1
# get the groundtruth via simple matrix * vector
state_out_exact = self._operator.evolve(self._initial_state.construct_circuit('vector'), evo_time, 'matrix', 0)
qr = QuantumRegister(self._operator.num_qubits, name='q')
circuit = self._initial_state.construct_circuit('circuit', qr)
circuit += self._operator.evolve(
None, evo_time, 'circuit', 1,
quantum_registers=qr,
expansion_mode='suzuki',
expansion_order=self._expansion_order
)
result = self._quantum_instance.execute(circuit)
state_out_dynamics = np.asarray(result.get_statevector(circuit))
self._ret['score'] = state_fidelity(state_out_exact, state_out_dynamics)
return self._ret
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
import pylab
from qiskit_chemistry import QiskitChemistry
# Input dictionary to configure Qiskit Chemistry for the chemistry problem.
qiskit_chemistry_dict = {
'problem': {'random_seed': 50},
'driver': {'name': 'PYSCF'},
'PYSCF': {'atom': '', 'basis': 'sto3g'},
'operator': {'name': 'hamiltonian', 'qubit_mapping': '', 'two_qubit_reduction': False},
'algorithm': {'name': ''},
'optimizer': {'name': 'L_BFGS_B', 'maxfun': 2500},
'variational_form': {'name': 'RYRZ', 'depth': 5}
}
molecule = 'H .0 .0 -{0}; H .0 .0 {0}'
algorithms = ['VQE', 'ExactEigensolver']
mappings = ['jordan_wigner', 'parity', 'bravyi_kitaev']
start = 0.5 # Start distance
by = 0.5 # How much to increase distance by
steps = 20 # Number of steps to increase by
energies = np.empty([len(mappings), len(algorithms), steps+1])
hf_energies = np.empty(steps+1)
distances = np.empty(steps+1)
print('Processing step __', end='')
for i in range(steps+1):
print('\b\b{:2d}'.format(i), end='', flush=True)
d = start + i*by/steps
qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2)
for j in range(len(algorithms)):
qiskit_chemistry_dict['algorithm']['name'] = algorithms[j]
for k in range(len(mappings)):
qiskit_chemistry_dict['operator']['qubit_mapping'] = mappings[k]
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict)
energies[k][j][i] = result['energy']
hf_energies[i] = result['hf_energy'] # Independent of algorithm & mapping
distances[i] = d
print(' --- complete')
print('Distances: ', distances)
print('Energies:', energies)
print('Hartree-Fock energies:', hf_energies)
pylab.rcParams['figure.figsize'] = (12, 8)
pylab.ylim(-1.14, -1.04)
pylab.plot(distances, hf_energies, label='Hartree-Fock')
for j in range(len(algorithms)):
for k in range(len(mappings)):
pylab.plot(distances, energies[k][j], label=algorithms[j] + ", " + mappings[k])
pylab.xlabel('Interatomic distance')
pylab.ylabel('Energy')
pylab.title('H2 Ground State Energy in different mappings')
pylab.legend(loc='upper right')
pylab.show()
pylab.rcParams['figure.figsize'] = (6, 4)
for k in range(len(mappings)):
pylab.ylim(-1.14, -1.04)
pylab.plot(distances, hf_energies, label='Hartree-Fock')
for j in range(len(algorithms)):
pylab.plot(distances, energies[k][j], label=algorithms[j])
pylab.xlabel('Interatomic distance')
pylab.ylabel('Energy')
pylab.title('H2 Ground State Energy with {} mapping'.format(mappings[k]))
pylab.legend(loc='upper right')
pylab.show()
#pylab.plot(distances, np.subtract(hf_energies, energies[k][1]), label='Hartree-Fock')
pylab.plot(distances, np.subtract(energies[k][0], energies[k][1]), color=[0.8500, 0.3250, 0.0980], label='VQE')
pylab.xlabel('Interatomic distance')
pylab.ylabel('Energy')
pylab.yscale('log')
pylab.title('Energy difference from ExactEigensolver with {} mapping'.format(mappings[k]))
pylab.legend(loc='upper right')
pylab.show()
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit.circuit import Parameter
from qiskit import pulse
from qiskit.test.mock.backends.almaden import *
phase = Parameter('phase')
with pulse.build(FakeAlmaden()) as phase_test_sched:
pulse.shift_phase(phase, pulse.drive_channel(0))
phase_test_sched.instructions # ()
|
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/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 = True
LaTex_folder_Bell_states = str(os.getcwd())+'/Latex_quantum_gates/Bell_measurement/'
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)
qr = QuantumRegister(2) # initialise a two-bit quantum register
cr = ClassicalRegister(2) # 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
circuit.cx(qr[0],qr[1]) # at a CNOT gate to the second qubit depending on the state of the first one
circuit.h(qr[0]) # add a Hadamard gate to first qubit
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_measurement.tex'
with open(LaTex_folder_Bell_states+f_name, 'w') as f:
f.write(LaTex_code)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# Copyright 2019 Cambridge Quantum Computing
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Methods to allow conversion between Qiskit and pytket circuit classes
"""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Instruction, Measure
from qiskit.extensions.standard import *
from pytket._circuit import Circuit, Op, OpType
from pytket._routing import PhysicalCircuit
from sympy import pi
_known_qiskit_gate = {
IdGate : OpType.noop,
XGate : OpType.X,
YGate : OpType.Y,
ZGate : OpType.Z,
SGate : OpType.S,
SdgGate : OpType.Sdg,
TGate : OpType.T,
TdgGate : OpType.Tdg,
HGate : OpType.H,
RXGate : OpType.Rx,
RYGate : OpType.Ry,
RZGate : OpType.Rz,
U1Gate : OpType.U1,
U2Gate : OpType.U2,
U3Gate : OpType.U3,
CnotGate : OpType.CX,
CyGate : OpType.CY,
CzGate : OpType.CZ,
CHGate : OpType.CH,
SwapGate : OpType.SWAP,
ToffoliGate : OpType.CCX,
FredkinGate : OpType.CSWAP,
CrzGate : OpType.CRz,
Cu1Gate : OpType.CU1,
Cu3Gate : OpType.CU3,
Measure : OpType.Measure
}
_known_qiskit_gate_rev = {v : k for k, v in _known_qiskit_gate.items()}
def qiskit_to_tk(qcirc: QuantumCircuit) -> Circuit :
"""Convert a :py:class:`qiskit.QuantumCircuit` to a :py:class:`Circuit`.
:param qcirc: A circuit to be converted
:type qcirc: QuantumCircuit
:return: The converted circuit
:rtype: Circuit
"""
tkc = Circuit()
qregmap = {}
for reg in qcirc.qregs :
tk_reg = tkc.add_q_register(reg.name, len(reg))
qregmap.update({reg : tk_reg})
cregmap = {}
for reg in qcirc.cregs :
tk_reg = tkc.add_c_register(reg.name, len(reg))
cregmap.update({reg : tk_reg})
for i, qargs, cargs in qcirc.data :
if i.control is not None :
raise NotImplementedError("Cannot convert conditional gates from Qiskit to tket")
optype = _known_qiskit_gate[type(i)]
qubits = [qregmap[r][ind] for r, ind in qargs]
bits = [cregmap[r][ind] for r, ind in cargs]
if optype == OpType.Measure :
tkc.add_measure(*qubits, *bits)
continue
params = [p/pi for p in i.params]
tkc.add_gate(optype, params, qubits, [])
return tkc
def tk_to_qiskit(tkcirc: Circuit) -> QuantumCircuit :
"""Convert back
:param tkcirc: A circuit to be converted
:type tkcirc: Circuit
:return: The converted circuit
:rtype: QuantumCircuit
"""
tkc = tkcirc
if isinstance(tkcirc, PhysicalCircuit) :
tkc = tkcirc._get_circuit()
qcirc = QuantumCircuit()
qregmap = {}
for _, reg in tkc.q_regs.items() :
if reg.size() == 0 :
continue
name = reg.name
if len(name) == 0 :
name = None
qis_reg = QuantumRegister(reg.size(), name)
qregmap.update({reg : qis_reg})
qcirc.add_register(qis_reg)
cregmap = {}
for _, reg in tkc.c_regs.items() :
if reg.size() == 0 :
continue
name = reg.name
if len(name) == 0 :
name = None
qis_reg = ClassicalRegister(reg.size(), name)
cregmap.update({reg : qis_reg})
qcirc.add_register(qis_reg)
tempregmap = {}
for command in tkc :
op = command.op
qubits = command.qubits
qargs = [qregmap[q.reg][q.index] for q in qubits]
if len(command.controls) != 0 :
raise NotImplementedError("Cannot convert conditional gates from tket to Qiskit")
if op.get_type() == OpType.Measure :
bits = [_convert_bit(b, cregmap, qcirc, tempregmap) for b in command.bits]
qcirc.measure(*qargs, *bits)
continue
params = [p * pi for p in op.get_params()]
try :
gatetype = _known_qiskit_gate_rev[op.get_type()]
except KeyError as error :
raise NotImplementedError("Cannot convert tket Op to Qiskit gate: " + op.get_name()) from error
g = gatetype(*params)
qcirc.append(g, qargs=qargs)
return qcirc
def _convert_bit(bit, cregmap, qcirc, tempregmap) :
index = bit.index
if bit.temp :
if bit not in tempregmap :
new_reg = ClassicalRegister(1, "temp"+str(index))
qcirc.add_register(new_reg)
tempregmap.update({bit : new_reg})
return new_reg[0]
return tempregmap[bit][0]
return cregmap[bit.reg][index]
|
https://github.com/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.
# pylint: disable=invalid-name
"""Randomized tests of transpiler circuit equivalence.
This test can be optionally configured (e.g. by CI) via the
following env vars:
QISKIT_RANDOMIZED_TEST_LAYOUT_METHODS
A space-delimited list of layout method names from which the
randomizer should pick the layout method. Defaults to all
available built-in methods if unspecified.
QISKIT_RANDOMIZED_TEST_ROUTING_METHODS
A space-delimited list of routing method names from which the
randomizer should pick the routing method. Defaults to all
available built-in methods if unspecified.
QISKIT_RANDOMIZED_TEST_SCHEDULING_METHODS
A space-delimited list of scheduling method names from which the
randomizer should pick the scheduling method. Defaults to all
available built-in methods if unspecified.
QISKIT_RANDOMIZED_TEST_BACKEND_NEEDS_DURATIONS
A boolean value (e.g. "true", "Y", etc.) which, when true, forces
the randomizer to pick a backend which fully supports scheduling
(i.e. has fully specified duration info). Defaults to False.
QISKIT_RANDOMIZED_TEST_ALLOW_BARRIERS
A boolean value (e.g. "true", "Y", etc.) which, when false,
prevents the randomizer from emitting barrier instructions.
Defaults to True.
"""
import os
from math import pi
from hypothesis import assume, settings, HealthCheck
from hypothesis.stateful import multiple, rule, precondition, invariant
from hypothesis.stateful import Bundle, RuleBasedStateMachine
import hypothesis.strategies as st
from qiskit import transpile, Aer
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit import Measure, Reset, Gate, Barrier
from qiskit.providers.fake_provider import (
FakeProvider,
FakeOpenPulse2Q,
FakeOpenPulse3Q,
FakeYorktown,
FakeTenerife,
FakeOurense,
FakeVigo,
FakeMelbourne,
FakeRueschlikon,
FakeTokyo,
FakePoughkeepsie,
FakeAlmaden,
FakeSingapore,
FakeJohannesburg,
FakeBoeblingen,
FakeRochester,
FakeBurlington,
FakeCambridge,
FakeCambridgeAlternativeBasis,
FakeEssex,
FakeLondon,
FakeQasmSimulator,
FakeArmonk,
FakeRome,
FakeSantiago,
FakeSydney,
FakeToronto,
FakeValencia,
)
from qiskit.test.base import dicts_almost_equal
# pylint: disable=wildcard-import,unused-wildcard-import
from qiskit.circuit.library.standard_gates import *
default_profile = "transpiler_equivalence"
settings.register_profile(
default_profile,
report_multiple_bugs=False,
max_examples=200,
deadline=None,
suppress_health_check=[HealthCheck.filter_too_much],
)
settings.load_profile(os.getenv("HYPOTHESIS_PROFILE", default_profile))
BASE_INSTRUCTIONS = {
# Key is (n_qubits, n_clbits, n_params). All gates here should be directly known by Aer so they
# can be simulated without an initial transpile (whether that's via `execute` or not).
(1, 0, 0): [HGate, IGate, SGate, SdgGate, TGate, TdgGate, XGate, YGate, ZGate, Reset],
(2, 0, 0): [CXGate, CYGate, CZGate, SwapGate],
(3, 0, 0): [CCXGate, CSwapGate],
(1, 0, 1): [PhaseGate, RXGate, RYGate, RZGate],
(1, 0, 3): [UGate],
(2, 0, 1): [RZZGate, CPhaseGate],
(2, 0, 4): [CUGate],
(1, 1, 0): [Measure],
}
variadic_gates = [Barrier]
def _strtobool(s):
return s.lower() in ("y", "yes", "t", "true", "on", "1")
if not _strtobool(os.getenv("QISKIT_RANDOMIZED_TEST_ALLOW_BARRIERS", "True")):
variadic_gates.remove(Barrier)
def _getenv_list(var_name):
value = os.getenv(var_name)
return None if value is None else value.split()
# Note: a value of `None` for any of the following methods means that
# the selected pass manager gets to choose. However, to avoid complexity,
# its not possible to specify `None` when overriding these with environment
# variables. Really, `None` is useful only for testing Terra's pass managers,
# and if you're overriding these, your goal is probably to test a specific
# pass or set of passes instead.
layout_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_LAYOUT_METHODS") or [
None,
"trivial",
"dense",
"noise_adaptive",
"sabre",
]
routing_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_ROUTING_METHODS") or [
None,
"basic",
"stochastic",
"lookahead",
"sabre",
]
scheduling_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_SCHEDULING_METHODS") or [
None,
"alap",
"asap",
]
backend_needs_durations = _strtobool(
os.getenv("QISKIT_RANDOMIZED_TEST_BACKEND_NEEDS_DURATIONS", "False")
)
def _fully_supports_scheduling(backend):
"""Checks if backend is not in the set of backends known not to have specified gate durations."""
return not isinstance(
backend,
(
# no coupling map
FakeArmonk,
# no measure durations
FakeAlmaden,
FakeBurlington,
FakeCambridge,
FakeCambridgeAlternativeBasis,
FakeEssex,
FakeJohannesburg,
FakeLondon,
FakeOpenPulse2Q,
FakeOpenPulse3Q,
FakePoughkeepsie,
FakeQasmSimulator,
FakeRochester,
FakeRueschlikon,
FakeSingapore,
FakeTenerife,
FakeTokyo,
# No reset duration
FakeAlmaden,
FakeArmonk,
FakeBoeblingen,
FakeBurlington,
FakeCambridge,
FakeCambridgeAlternativeBasis,
FakeEssex,
FakeJohannesburg,
FakeLondon,
FakeMelbourne,
FakeOpenPulse2Q,
FakeOpenPulse3Q,
FakeOurense,
FakePoughkeepsie,
FakeQasmSimulator,
FakeRochester,
FakeRome,
FakeRueschlikon,
FakeSantiago,
FakeSingapore,
FakeSydney,
FakeTenerife,
FakeTokyo,
FakeToronto,
FakeValencia,
FakeVigo,
FakeYorktown,
),
)
fake_provider = FakeProvider()
mock_backends = fake_provider.backends()
mock_backends_with_scheduling = [b for b in mock_backends if _fully_supports_scheduling(b)]
@st.composite
def transpiler_conf(draw):
"""Composite search strategy to pick a valid transpiler config."""
all_backends = st.one_of(st.none(), st.sampled_from(mock_backends))
scheduling_backends = st.sampled_from(mock_backends_with_scheduling)
scheduling_method = draw(st.sampled_from(scheduling_methods))
backend = (
draw(scheduling_backends)
if scheduling_method or backend_needs_durations
else draw(all_backends)
)
return {
"backend": backend,
"optimization_level": draw(st.integers(min_value=0, max_value=3)),
"layout_method": draw(st.sampled_from(layout_methods)),
"routing_method": draw(st.sampled_from(routing_methods)),
"scheduling_method": scheduling_method,
"seed_transpiler": draw(st.integers(min_value=0, max_value=1_000_000)),
}
class QCircuitMachine(RuleBasedStateMachine):
"""Build a Hypothesis rule based state machine for constructing, transpiling
and simulating a series of random QuantumCircuits.
Build circuits with up to QISKIT_RANDOM_QUBITS qubits, apply a random
selection of gates from qiskit.circuit.library with randomly selected
qargs, cargs, and parameters. At random intervals, transpile the circuit for
a random backend with a random optimization level and simulate both the
initial and the transpiled circuits to verify that their counts are the
same.
"""
qubits = Bundle("qubits")
clbits = Bundle("clbits")
backend = Aer.get_backend("aer_simulator")
max_qubits = int(backend.configuration().n_qubits / 2)
# Limit reg generation for more interesting circuits
max_qregs = 3
max_cregs = 3
def __init__(self):
super().__init__()
self.qc = QuantumCircuit()
self.enable_variadic = bool(variadic_gates)
@precondition(lambda self: len(self.qc.qubits) < self.max_qubits)
@precondition(lambda self: len(self.qc.qregs) < self.max_qregs)
@rule(target=qubits, n=st.integers(min_value=1, max_value=max_qubits))
def add_qreg(self, n):
"""Adds a new variable sized qreg to the circuit, up to max_qubits."""
n = min(n, self.max_qubits - len(self.qc.qubits))
qreg = QuantumRegister(n)
self.qc.add_register(qreg)
return multiple(*list(qreg))
@precondition(lambda self: len(self.qc.cregs) < self.max_cregs)
@rule(target=clbits, n=st.integers(1, 5))
def add_creg(self, n):
"""Add a new variable sized creg to the circuit."""
creg = ClassicalRegister(n)
self.qc.add_register(creg)
return multiple(*list(creg))
# Gates of various shapes
@precondition(lambda self: self.qc.num_qubits > 0 and self.qc.num_clbits > 0)
@rule(n_arguments=st.sampled_from(sorted(BASE_INSTRUCTIONS.keys())), data=st.data())
def add_gate(self, n_arguments, data):
"""Append a random fixed gate to the circuit."""
n_qubits, n_clbits, n_params = n_arguments
gate_class = data.draw(st.sampled_from(BASE_INSTRUCTIONS[n_qubits, n_clbits, n_params]))
qubits = data.draw(st.lists(self.qubits, min_size=n_qubits, max_size=n_qubits, unique=True))
clbits = data.draw(st.lists(self.clbits, min_size=n_clbits, max_size=n_clbits, unique=True))
params = data.draw(
st.lists(
st.floats(
allow_nan=False, allow_infinity=False, min_value=-10 * pi, max_value=10 * pi
),
min_size=n_params,
max_size=n_params,
)
)
self.qc.append(gate_class(*params), qubits, clbits)
@precondition(lambda self: self.enable_variadic)
@rule(gate=st.sampled_from(variadic_gates), qargs=st.lists(qubits, min_size=1, unique=True))
def add_variQ_gate(self, gate, qargs):
"""Append a gate with a variable number of qargs."""
self.qc.append(gate(len(qargs)), qargs)
@precondition(lambda self: len(self.qc.data) > 0)
@rule(carg=clbits, data=st.data())
def add_c_if_last_gate(self, carg, data):
"""Modify the last gate to be conditional on a classical register."""
creg = self.qc.find_bit(carg).registers[0][0]
val = data.draw(st.integers(min_value=0, max_value=2 ** len(creg) - 1))
last_gate = self.qc.data[-1]
# Conditional instructions are not supported
assume(isinstance(last_gate[0], Gate))
last_gate[0].c_if(creg, val)
# Properties to check
@invariant()
def qasm(self):
"""After each circuit operation, it should be possible to build QASM."""
self.qc.qasm()
@precondition(lambda self: any(isinstance(d[0], Measure) for d in self.qc.data))
@rule(kwargs=transpiler_conf())
def equivalent_transpile(self, kwargs):
"""Simulate, transpile and simulate the present circuit. Verify that the
counts are not significantly different before and after transpilation.
"""
assume(
kwargs["backend"] is None
or kwargs["backend"].configuration().n_qubits >= len(self.qc.qubits)
)
call = (
"transpile(qc, "
+ ", ".join(f"{key:s}={value!r}" for key, value in kwargs.items() if value is not None)
+ ")"
)
print(f"Evaluating {call} for:\n{self.qc.qasm()}")
shots = 4096
# Note that there's no transpilation here, which is why the gates are limited to only ones
# that Aer supports natively.
aer_counts = self.backend.run(self.qc, shots=shots).result().get_counts()
try:
xpiled_qc = transpile(self.qc, **kwargs)
except Exception as e:
failed_qasm = f"Exception caught during transpilation of circuit: \n{self.qc.qasm()}"
raise RuntimeError(failed_qasm) from e
xpiled_aer_counts = self.backend.run(xpiled_qc, shots=shots).result().get_counts()
count_differences = dicts_almost_equal(aer_counts, xpiled_aer_counts, 0.05 * shots)
assert (
count_differences == ""
), "Counts not equivalent: {}\nFailing QASM Input:\n{}\n\nFailing QASM Output:\n{}".format(
count_differences, self.qc.qasm(), xpiled_qc.qasm()
)
TestQuantumCircuit = QCircuitMachine.TestCase
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit, Aer, transpile, assemble, execute
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from numpy.random import randint
import numpy as np
def generate_binary(len):
return randint(2, size=len)
def encode_message(bits, bases, messageLen):
message = []
for i in range(messageLen):
qc = QuantumCircuit(1,1)
if bases[i] == 0: # Prepare qubit in Z-basis
if bits[i] == 0:
pass
else:
qc.x(0)
else: # Prepare qubit in X-basis
if bits[i] == 0:
qc.h(0)
else:
qc.x(0)
qc.h(0)
qc.barrier()
message.append(qc)
return message
def measure_message(message, bases, messageLen):
backend = Aer.get_backend('aer_simulator')
measurements = []
for q in range(messageLen):
if bases[q] == 0: # measuring in Z-basis
message[q].measure(0,0)
if bases[q] == 1: # measuring in X-basis
message[q].h(0)
message[q].measure(0,0)
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(message[q], shots=1, memory=True)
result = aer_sim.run(qobj).result()
measured_bit = int(result.get_memory()[0])
measurements.append(measured_bit)
return measurements
def remove_garbage(a_bases, b_bases, bits, messageLen):
good_bits = []
for q in range(messageLen):
if a_bases[q] == b_bases[q]:
# If both used the same basis, add
# this to the list of 'good' bits
good_bits.append(bits[q])
return good_bits
def sample_bits(bits, selection):
sample = []
for i in selection:
# use np.mod to make sure the
# bit we sample is always in
# the list range
i = np.mod(i, len(bits))
# pop(i) removes the element of the
# list at index 'i'
sample.append(bits.pop(i))
return sample
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
from qiskit import QuantumCircuit
import numpy as np
import random
from qiskit import Aer, execute
import math
circ = QuantumCircuit(4)
simulator = Aer.get_backend('statevector_simulator')
def display(circ,msg=""):
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
qb = int(math.log2(len(statevector)))
print("============ State Vector ============", msg)
s = 0
for i in statevector:
print(' ({:.5f}) |{:0{}b}>'.format(i,s,qb))
s = s+1
print("============..............============")
# circ.initialize([1, 1, 0, 0] / np.sqrt(2), [0, 1])
display(circ,"step 0")
# initialize
a1 = np.pi * random.random()
circ.ry(a1,0)
display(circ,"step 1")
a2 = np.pi * random.random()
circ.ry(a2,1)
display(circ,"step 2")
a3 = np.pi * random.random()
#circ.ry(a3,2)
display(circ,"step 3")
circ.x(0)
circ.toffoli(0,1,3)
circ.x(0)
circ.toffoli(0,2,3)
display(circ,"step 4")
print(circ.draw())
|
https://github.com/ctuning/ck-qiskit
|
ctuning
|
from qiskit import IBMQ
from qiskit import BasicAer as Aer
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import execute
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Rectangle
import copy
from ipywidgets import widgets
from IPython.display import display, clear_output
try:
IBMQ.load_accounts()
except:
pass
class run_game():
# Implements a puzzle, which is defined by the given inputs.
def __init__(self,initialize, success_condition, allowed_gates, vi, qubit_names, eps=0.1, backend=Aer.get_backend('qasm_simulator'), shots=1024,mode='circle',verbose=False):
"""
initialize
List of gates applied to the initial 00 state to get the starting state of the puzzle.
Supported single qubit gates (applied to qubit '0' or '1') are 'x', 'y', 'z', 'h', 'ry(pi/4)'.
Supported two qubit gates are 'cz' and 'cx'. Specify only the target qubit.
success_condition
Values for pauli observables that must be obtained for the puzzle to declare success.
allowed_gates
For each qubit, specify which operations are allowed in this puzzle. 'both' should be used only for operations that don't need a qubit to be specified ('cz' and 'unbloch').
Gates are expressed as a dict with an int as value. If this is non-zero, it specifies the number of times the gate is must be used (no more or less) for the puzzle to be successfully solved. If the value is zero, the player can use the gate any number of times.
vi
Some visualization information as a three element list. These specify:
* which qubits are hidden (empty list if both shown).
* whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles).
* whether the correlation circles (the four in the middle) are shown.
qubit_names
The two qubits are always called '0' and '1' from the programming side. But for the player, we can display different names.
eps=0.1
How close the expectation values need to be to the targets for success to be declared.
backend=Aer.get_backend('qasm_simulator')
Backend to be used by Qiskit to calculate expectation values (defaults to local simulator).
shots=1024
Number of shots used to to calculate expectation values.
mode='circle'
Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line').
verbose=False
"""
def get_total_gate_list():
# Get a text block describing allowed gates.
total_gate_list = ""
for qubit in allowed_gates:
gate_list = ""
for gate in allowed_gates[qubit]:
if required_gates[qubit][gate] > 0 :
gate_list += ' ' + gate+" (use "+str(required_gates[qubit][gate])+" time"+"s"*(required_gates[qubit][gate]>1)+")"
elif allowed_gates[qubit][gate]==0:
gate_list += ' '+gate + ' '
if gate_list!="":
if qubit=="both" :
gate_list = "\nAllowed symmetric operations:" + gate_list
else :
gate_list = "\nAllowed operations for " + qubit_names[qubit] + ":\n" + " "*10 + gate_list
total_gate_list += gate_list +"\n"
return total_gate_list
def get_success(required_gates):
# Determine whether the success conditions are satisfied, both for expectation values, and the number of gates to be used.
success = True
grid.get_rho()
if verbose:
print(grid.rho)
for pauli in success_condition:
success = success and (abs(success_condition[pauli] - grid.rho[pauli])<eps)
for qubit in required_gates:
for gate in required_gates[qubit]:
success = success and (required_gates[qubit][gate]==0)
return success
def get_command(gate,qubit):
# For a given gate and qubit, return the string describing the corresoinding Qiskit string.
if qubit=='both':
qubit = '1'
qubit_name = qubit_names[qubit]
for name in qubit_names.values():
if name!=qubit_name:
other_name = name
# then make the command (both for the grid, and for printing to screen)
if gate in ['x','y','z','h']:
real_command = 'grid.qc.'+gate+'(grid.qr['+qubit+'])'
clean_command = 'qc.'+gate+'('+qubit_name+')'
elif gate in ['ry(pi/4)','ry(-pi/4)']:
real_command = 'grid.qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,grid.qr['+qubit+'])'
clean_command = 'qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,'+qubit_name+')'
elif gate in ['cz','cx','swap']:
real_command = 'grid.qc.'+gate+'(grid.qr['+'0'*(qubit=='1')+'1'*(qubit=='0')+'],grid.qr['+qubit+'])'
clean_command = 'qc.'+gate+'('+other_name+','+qubit_name+')'
return [real_command,clean_command]
clear_output()
bloch = [None]
# set up initial state and figure
grid = pauli_grid(backend=backend,shots=shots,mode=mode)
for gate in initialize:
eval( get_command(gate[0],gate[1])[0] )
required_gates = copy.deepcopy(allowed_gates)
# determine which qubits to show in figure
if allowed_gates['0']=={} : # if no gates are allowed for qubit 0, we know to only show qubit 1
shown_qubit = 1
elif allowed_gates['1']=={} : # and vice versa
shown_qubit = 0
else :
shown_qubit = 2
# show figure
grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list())
description = {'gate':['Choose gate'],'qubit':['Choose '+'qu'*vi[1]+'bit'],'action':['Make it happen!']}
all_allowed_gates_raw = []
for q in ['0','1','both']:
all_allowed_gates_raw += list(allowed_gates[q])
all_allowed_gates_raw = list(set(all_allowed_gates_raw))
all_allowed_gates = []
for g in ['bloch','unbloch']:
if g in all_allowed_gates_raw:
all_allowed_gates.append( g )
for g in ['x','y','z','h','cz','cx']:
if g in all_allowed_gates_raw:
all_allowed_gates.append( g )
for g in all_allowed_gates_raw:
if g not in all_allowed_gates:
all_allowed_gates.append( g )
gate = widgets.ToggleButtons(options=description['gate']+all_allowed_gates)
qubit = widgets.ToggleButtons(options=[''])
action = widgets.ToggleButtons(options=[''])
boxes = widgets.VBox([gate,qubit,action])
display(boxes)
if vi[1]:
print('\nYour quantum program so far\n')
self.program = []
def given_gate(a):
# Action to be taken when gate is chosen. This sets up the system to choose a qubit.
if gate.value:
if gate.value in allowed_gates['both']:
qubit.options = description['qubit'] + ["not required"]
qubit.value = "not required"
else:
allowed_qubits = []
for q in ['0','1']:
if (gate.value in allowed_gates[q]) or (gate.value in allowed_gates['both']):
allowed_qubits.append(q)
allowed_qubit_names = []
for q in allowed_qubits:
allowed_qubit_names += [qubit_names[q]]
qubit.options = description['qubit'] + allowed_qubit_names
def given_qubit(b):
# Action to be taken when qubit is chosen. This sets up the system to choose an action.
if qubit.value not in ['',description['qubit'][0],'Success!']:
action.options = description['action']+['Apply operation']
def given_action(c):
# Action to be taken when user confirms their choice of gate and qubit.
# This applied the command, updates the visualization and checks whether the puzzle is solved.
if action.value not in ['',description['action'][0]]:
# apply operation
if action.value=='Apply operation':
if qubit.value not in ['',description['qubit'][0],'Success!']:
# translate bit gates to qubit gates
if gate.value=='NOT':
q_gate = 'x'
elif gate.value=='CNOT':
q_gate = 'cx'
else:
q_gate = gate.value
if qubit.value=="not required":
q = qubit_names['1']
else:
q = qubit.value
q01 = '0'*(qubit.value==qubit_names['0']) + '1'*(qubit.value==qubit_names['1']) + 'both'*(qubit.value=="not required")
if q_gate in ['bloch','unbloch']:
if q_gate=='bloch':
bloch[0] = q01
else:
bloch[0] = None
else:
command = get_command(q_gate,q01)
eval(command[0])
if vi[1]:
print(command[1])
self.program.append( command[1] )
if required_gates[q01][gate.value]>0:
required_gates[q01][gate.value] -= 1
grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list())
success = get_success(required_gates)
if success:
gate.options = ['Success!']
qubit.options = ['Success!']
action.options = ['Success!']
plt.close(grid.fig)
else:
gate.value = description['gate'][0]
qubit.options = ['']
action.options = ['']
gate.observe(given_gate)
qubit.observe(given_qubit)
action.observe(given_action)
class pauli_grid():
# Allows a quantum circuit to be created, modified and implemented, and visualizes the output in the style of 'Hello Quantum'.
def __init__(self,backend=Aer.get_backend('qasm_simulator'),shots=1024,mode='circle'):
"""
backend=Aer.get_backend('qasm_simulator')
Backend to be used by Qiskit to calculate expectation values (defaults to local simulator).
shots=1024
Number of shots used to to calculate expectation values.
mode='circle'
Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line').
"""
self.backend = backend
self.shots = shots
self.box = {'ZI':(-1, 2),'XI':(-2, 3),'IZ':( 1, 2),'IX':( 2, 3),'ZZ':( 0, 3),'ZX':( 1, 4),'XZ':(-1, 4),'XX':( 0, 5)}
self.rho = {}
for pauli in self.box:
self.rho[pauli] = 0.0
for pauli in ['ZI','IZ','ZZ']:
self.rho[pauli] = 1.0
self.qr = QuantumRegister(2)
self.cr = ClassicalRegister(2)
self.qc = QuantumCircuit(self.qr, self.cr)
self.mode = mode
# colors are background, qubit circles and correlation circles, respectively
if self.mode=='line':
self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)]
else:
self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)]
self.fig = plt.figure(figsize=(5,5),facecolor=self.colors[0])
self.ax = self.fig.add_subplot(111)
plt.axis('off')
self.bottom = self.ax.text(-3,1,"",size=9,va='top',color='w')
self.lines = {}
for pauli in self.box:
w = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(1.0,1.0,1.0), lw=0 )
b = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(0.0,0.0,0.0), lw=0 )
c = {}
c['w'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(0,0,0), zorder=10) )
c['b'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(1,1,1), zorder=10) )
self.lines[pauli] = {'w':w,'b':b,'c':c}
def get_rho(self):
# Runs the circuit specified by self.qc and determines the expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'.
bases = ['ZZ','ZX','XZ','XX']
results = {}
for basis in bases:
temp_qc = copy.deepcopy(self.qc)
for j in range(2):
if basis[j]=='X':
temp_qc.h(self.qr[j])
temp_qc.barrier(self.qr)
temp_qc.measure(self.qr,self.cr)
job = execute(temp_qc, backend=self.backend, shots=self.shots)
results[basis] = job.result().get_counts()
for string in results[basis]:
results[basis][string] = results[basis][string]/self.shots
prob = {}
# prob of expectation value -1 for single qubit observables
for j in range(2):
for p in ['X','Z']:
pauli = {}
for pp in 'IXZ':
pauli[pp] = (j==1)*pp + p + (j==0)*pp
prob[pauli['I']] = 0
for basis in [pauli['X'],pauli['Z']]:
for string in results[basis]:
if string[(j+1)%2]=='1':
prob[pauli['I']] += results[basis][string]/2
# prob of expectation value -1 for two qubit observables
for basis in ['ZZ','ZX','XZ','XX']:
prob[basis] = 0
for string in results[basis]:
if string[0]!=string[1]:
prob[basis] += results[basis][string]
for pauli in prob:
self.rho[pauli] = 1-2*prob[pauli]
def update_grid(self,rho=None,labels=False,bloch=None,hidden=[],qubit=True,corr=True,message=""):
"""
rho = None
Dictionary of expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'. If supplied, this will be visualized instead of the results of running self.qc.
labels = None
Dictionary of strings for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ' that are printed in the corresponding boxes.
bloch = None
If a qubit name is supplied, and if mode='line', Bloch circles are displayed for this qubit
hidden = []
Which qubits have their circles hidden (empty list if both shown).
qubit = True
Whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles).
corr = True
Whether the correlation circles (the four in the middle) are shown.
message
A string of text that is displayed below the grid.
"""
def see_if_unhidden(pauli):
# For a given Pauli, see whether its circle should be shown.
unhidden = True
# first: does it act non-trivially on a qubit in `hidden`
for j in hidden:
unhidden = unhidden and (pauli[j]=='I')
# second: does it contain something other than 'I' or 'Z' when only bits are shown
if qubit==False:
for j in range(2):
unhidden = unhidden and (pauli[j] in ['I','Z'])
# third: is it a correlation pauli when these are not allowed
if corr==False:
unhidden = unhidden and ((pauli[0]=='I') or (pauli[1]=='I'))
return unhidden
def add_line(line,pauli_pos,pauli):
"""
For mode='line', add in the line.
line = the type of line to be drawn (X, Z or the other one)
pauli = the box where the line is to be drawn
expect = the expectation value that determines its length
"""
unhidden = see_if_unhidden(pauli)
coord = None
p = (1-self.rho[pauli])/2 # prob of 1 output
# in the following, white lines goes from a to b, and black from b to c
if unhidden:
if line=='Z':
a = ( self.box[pauli_pos][0], self.box[pauli_pos][1]+l/2 )
c = ( self.box[pauli_pos][0], self.box[pauli_pos][1]-l/2 )
b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] )
lw = 8
coord = (b[1] - (a[1]+c[1])/2)*1.2 + (a[1]+c[1])/2
elif line=='X':
a = ( self.box[pauli_pos][0]+l/2, self.box[pauli_pos][1] )
c = ( self.box[pauli_pos][0]-l/2, self.box[pauli_pos][1] )
b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] )
lw = 9
coord = (b[0] - (a[0]+c[0])/2)*1.1 + (a[0]+c[0])/2
else:
a = ( self.box[pauli_pos][0]+l/(2*np.sqrt(2)), self.box[pauli_pos][1]+l/(2*np.sqrt(2)) )
c = ( self.box[pauli_pos][0]-l/(2*np.sqrt(2)), self.box[pauli_pos][1]-l/(2*np.sqrt(2)) )
b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] )
lw = 9
self.lines[pauli]['w'].pop(0).remove()
self.lines[pauli]['b'].pop(0).remove()
self.lines[pauli]['w'] = plt.plot( [a[0],b[0]], [a[1],b[1]], color=(1.0,1.0,1.0), lw=lw )
self.lines[pauli]['b'] = plt.plot( [b[0],c[0]], [b[1],c[1]], color=(0.0,0.0,0.0), lw=lw )
return coord
l = 0.9 # line length
r = 0.6 # circle radius
L = 0.98*np.sqrt(2) # box height and width
if rho==None:
self.get_rho()
# draw boxes
for pauli in self.box:
if 'I' in pauli:
color = self.colors[1]
else:
color = self.colors[2]
self.ax.add_patch( Rectangle( (self.box[pauli][0],self.box[pauli][1]-1), L, L, angle=45, color=color) )
# draw circles
for pauli in self.box:
unhidden = see_if_unhidden(pauli)
if unhidden:
if self.mode=='line':
self.ax.add_patch( Circle(self.box[pauli], r, color=(0.5,0.5,0.5)) )
else:
prob = (1-self.rho[pauli])/2
self.ax.add_patch( Circle(self.box[pauli], r, color=(prob,prob,prob)) )
# update bars if required
if self.mode=='line':
if bloch in ['0','1']:
for other in 'IXZ':
px = other*(bloch=='1') + 'X' + other*(bloch=='0')
pz = other*(bloch=='1') + 'Z' + other*(bloch=='0')
z_coord = add_line('Z',pz,pz)
x_coord = add_line('X',pz,px)
for j in self.lines[pz]['c']:
self.lines[pz]['c'][j].center = (x_coord,z_coord)
self.lines[pz]['c'][j].radius = (j=='w')*0.05 + (j=='b')*0.04
px = 'I'*(bloch=='0') + 'X' + 'I'*(bloch=='1')
pz = 'I'*(bloch=='0') + 'Z' + 'I'*(bloch=='1')
add_line('Z',pz,pz)
add_line('X',px,px)
else:
for pauli in self.box:
for j in self.lines[pauli]['c']:
self.lines[pauli]['c'][j].radius = 0.0
if pauli in ['ZI','IZ','ZZ']:
add_line('Z',pauli,pauli)
if pauli in ['XI','IX','XX']:
add_line('X',pauli,pauli)
if pauli in ['XZ','ZX']:
add_line('ZX',pauli,pauli)
self.bottom.set_text(message)
if labels:
for pauli in box:
plt.text(self.box[pauli][0]-0.05,self.box[pauli][1]-0.85, pauli)
self.ax.set_xlim([-3,3])
self.ax.set_ylim([0,6])
self.fig.canvas.draw()
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import transpile
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.x(1)
qc.cp(np.pi/4, 0, 1)
qc.h(0)
qc.measure([0], [0])
qc_basis = transpile(qc, backend)
qc_basis.draw(output='mpl')
|
https://github.com/Spintronic6889/Introduction-of-Quantum-walk-its-application-on-search-and-decision-making
|
Spintronic6889
|
!python --version
!pip install qiskit
!pip install pylatexenc
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
from qiskit.visualization import plot_state_city
from random import randrange
from qiskit.tools.monitor import job_monitor
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import random
import math
#discrete time quantum random walk with a hadamard coin
n=2
steps=1
qpos = QuantumRegister(n,'qpos')
qcoin = QuantumRegister(1,'qcoin')
cpos = ClassicalRegister(n,'cr')
QC = QuantumCircuit(qpos, qcoin)
#initialized
#QC.x(qcoin[0])
for i in range(steps):
#coin
QC.h(qcoin[0])
QC.barrier()
#increment gate operator
for i in range(n):
QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
QC.barrier()
#decrement gate operator
QC.x(qcoin[0])
for i in range(n):
if i+1 < n: QC.x(qpos[i+1:])
QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
if i+1 < n: QC.x(qpos[i+1:])
QC.barrier()
a=n/2
p=math.floor(a)
#print(p)
for k in range(n):
if(k<p):
QC.swap(qpos[n-1-k],qpos[k])
#print(a)
display(QC.draw(output="mpl"))
QC.measure_all()
# # Execute the circuit on the qasm simulator
job = execute(QC,Aer.get_backend('aer_simulator'),shots=10000)
counts = job.result().get_counts(QC)
print(counts)
plot_histogram(counts, color='midnightblue', title="New Histogram")
#aer_sim = Aer.get_backend('aer_simulator')
#qobj = assemble(had)
#result = aer_sim.run(qobj).result()
#counts = result.get_counts()
#plot_histogram(counts)
#discrete time quantum random walk with a hadamard coin
n=2
steps=2
qpos = QuantumRegister(n,'qpos')
qcoin = QuantumRegister(1,'qcoin')
cpos = ClassicalRegister(n,'cr')
QC = QuantumCircuit(qpos, qcoin)
#initialized
#QC.x(qcoin[0])
for i in range(steps):
#coin
QC.h(qcoin[0])
QC.barrier()
#increment gate operator
for i in range(n):
QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
QC.barrier()
#decrement gate operator
QC.x(qcoin[0])
for i in range(n):
if i+1 < n: QC.x(qpos[i+1:])
QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
if i+1 < n: QC.x(qpos[i+1:])
QC.barrier()
a=n/2
p=math.floor(a)
#print(p)
for k in range(n):
if(k<p):
QC.swap(qpos[n-1-k],qpos[k])
#print(a)
display(QC.draw(output="mpl"))
QC.measure_all()
# # Execute the circuit on the qasm simulator
job = execute(QC,Aer.get_backend('aer_simulator'),shots=10000)
counts = job.result().get_counts(QC)
print(counts)
plot_histogram(counts, color='midnightblue', title="New Histogram")
#aer_sim = Aer.get_backend('aer_simulator')
#qobj = assemble(had)
#result = aer_sim.run(qobj).result()
#counts = result.get_counts()
#plot_histogram(counts)
#discrete time quantum random walk with a hadamard coin
n=2
steps=3
qpos = QuantumRegister(n,'qpos')
qcoin = QuantumRegister(1,'qcoin')
cpos = ClassicalRegister(n,'cr')
QC = QuantumCircuit(qpos, qcoin)
#initialized
#QC.x(qcoin[0])
for i in range(steps):
#coin
QC.h(qcoin[0])
QC.barrier()
#increment gate operator
for i in range(n):
QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
QC.barrier()
#decrement gate operator
QC.x(qcoin[0])
for i in range(n):
if i+1 < n: QC.x(qpos[i+1:])
QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
if i+1 < n: QC.x(qpos[i+1:])
QC.barrier()
a=n/2
p=math.floor(a)
#print(p)
for k in range(n):
if(k<p):
QC.swap(qpos[n-1-k],qpos[k])
#print(a)
display(QC.draw(output="mpl"))
QC.measure_all()
# # Execute the circuit on the qasm simulator
job = execute(QC,Aer.get_backend('aer_simulator'),shots=10000)
counts = job.result().get_counts(QC)
print(counts)
plot_histogram(counts, color='midnightblue', title="New Histogram")
#aer_sim = Aer.get_backend('aer_simulator')
#qobj = assemble(had)
#result = aer_sim.run(qobj).result()
#counts = result.get_counts()
#plot_histogram(counts)
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
#discrete time quantum random walk with a hadamard coin
n=3
steps=11
qpos = QuantumRegister(n,'qpos')
qcoin = QuantumRegister(1,'qcoin')
cpos = ClassicalRegister(n,'cr')
QC = QuantumCircuit(qpos, qcoin)
#initialized
#QC.x(qcoin[0])
for i in range(steps):
#coin
QC.h(qcoin[0])
QC.barrier()
#increment gate operator
for i in range(n):
QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
QC.barrier()
#decrement gate operator
QC.x(qcoin[0])
for i in range(n):
if i+1 < n: QC.x(qpos[i+1:])
QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
if i+1 < n: QC.x(qpos[i+1:])
QC.barrier()
a=n/2
p=math.floor(a)
#print(p)
for k in range(n):
if(k<p):
QC.swap(qpos[n-1-k],qpos[k])
#print(a)
display(QC.draw(output="mpl"))
state = DensityMatrix.from_instruction(QC)
plot_state_city(state,figsize=(15, 8), color=['midnightblue', 'midnightblue'],
title="New State City")
QC.measure_all()
# # Execute the circuit on the qasm simulator
job = execute(QC,Aer.get_backend('aer_simulator'),shots=10000)
counts = job.result().get_counts(QC)
print(counts)
plot_histogram(counts, figsize=(10, 2), color='midnightblue', title="New Histogram")
#aer_sim = Aer.get_backend('aer_simulator')
#qobj = assemble(had)
#result = aer_sim.run(qobj).result()
#counts = result.get_counts()
#plot_histogram(counts)
# Import Aer
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = execute(QC, backend)
result = job.result()
outputstate = result.get_statevector(QC, decimals=3)
print(outputstate)
#discrete time quantum random walk with a hadamard coin
n=6
steps=11
qpos = QuantumRegister(n,'qpos')
qcoin = QuantumRegister(1,'qcoin')
cpos = ClassicalRegister(n,'cr')
QC = QuantumCircuit(qpos, qcoin)
#initialized coin |0>
#QC.x(qcoin[0])
for i in range(steps):
#coin
QC.h(qcoin[0])
QC.barrier()
#increment gate operator
for i in range(n):
QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
QC.barrier()
#decrement gate operator
QC.x(qcoin[0])
for i in range(n):
if i+1 < n: QC.x(qpos[i+1:])
QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
if i+1 < n: QC.x(qpos[i+1:])
QC.barrier()
a=n/2
p=math.floor(a)
#print(p)
for k in range(n):
if(k<p):
QC.swap(qpos[n-1-k],qpos[k])
#print(a)
display(QC.draw(output="mpl"))
QC.measure_all()
# # Execute the circuit on the qasm simulator
job = execute(QC,Aer.get_backend('aer_simulator'),shots=10000)
counts = job.result().get_counts(QC)
print(counts)
plot_histogram(counts, figsize=(10, 2), color='midnightblue', title="New Histogram")
#aer_sim = Aer.get_backend('aer_simulator')
#qobj = assemble(had)
#result = aer_sim.run(qobj).result()
#counts = result.get_counts()
#plot_histogram(counts)
#discrete time quantum random walk with a hadamard coin
n=6
steps=11
qpos = QuantumRegister(n,'qpos')
qcoin = QuantumRegister(1,'qcoin')
cpos = ClassicalRegister(n,'cr')
QC = QuantumCircuit(qpos, qcoin)
#initialized coin |1>
QC.x(qcoin[0])
for i in range(steps):
#coin
QC.h(qcoin[0])
QC.barrier()
#increment gate operator
for i in range(n):
QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
QC.barrier()
#decrement gate operator
QC.x(qcoin[0])
for i in range(n):
if i+1 < n: QC.x(qpos[i+1:])
QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
if i+1 < n: QC.x(qpos[i+1:])
QC.barrier()
a=n/2
p=math.floor(a)
#print(p)
for k in range(n):
if(k<p):
QC.swap(qpos[n-1-k],qpos[k])
#print(a)
display(QC.draw(output="mpl"))
QC.measure_all()
# # Execute the circuit on the qasm simulator
job = execute(QC,Aer.get_backend('aer_simulator'),shots=10000)
counts = job.result().get_counts(QC)
print(counts)
plot_histogram(counts, figsize=(10, 2), color='midnightblue', title="New Histogram")
#aer_sim = Aer.get_backend('aer_simulator')
#qobj = assemble(had)
#result = aer_sim.run(qobj).result()
#counts = result.get_counts()
#plot_histogram(counts)
from qiskit import *
%matplotlib inline
#discrete time quantum random walk with a hadamard coin
n=6
steps=11
qpos = QuantumRegister(n,'qpos')
qcoin = QuantumRegister(1,'qcoin')
cpos = ClassicalRegister(n,'cr')
QC = QuantumCircuit(qpos, qcoin)
pi=math.pi
#initialized coin Ugate
QC.u(pi/2, 3*pi/2, 0, qcoin[0])
for i in range(steps):
#coin
QC.h(qcoin[0])
QC.barrier()
#increment gate operator
for i in range(n):
QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
QC.barrier()
#decrement gate operator
QC.x(qcoin[0])
for i in range(n):
if i+1 < n: QC.x(qpos[i+1:])
QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
if i+1 < n: QC.x(qpos[i+1:])
QC.barrier()
a=n/2
p=math.floor(a)
#print(p)
for k in range(n):
if(k<p):
QC.swap(qpos[n-1-k],qpos[k])
#print(a)
display(QC.draw(output="mpl"))
QC.measure_all()
# # Execute the circuit on the qasm simulator
job = execute(QC,Aer.get_backend('aer_simulator'),shots=10000)
counts = job.result().get_counts(QC)
print(counts)
plot_histogram(counts, figsize=(10, 2), color='midnightblue', title="New Histogram")
#aer_sim = Aer.get_backend('aer_simulator')
#qobj = assemble(had)
#result = aer_sim.run(qobj).result()
#counts = result.get_counts()
#plot_histogram(counts)
|
https://github.com/HuangJunye/Qiskit-for-GameDev
|
HuangJunye
|
import sys
sys.path.append('/Users/kirais/Documents/GitHub/Qiskit-for-GameDev/pygame/')
from qgame import CircuitGridModel, CircuitGridNode
from qgame import circuit_node_types as node_types
from qiskit import QuantumCircuit
circuit_grid_model = CircuitGridModel(qubit_count=3, circuit_depth=6)
print(circuit_grid_model)
qasm_str = circuit_grid_model.create_qasm_for_circuit()
print(qasm_str)
circuit = QuantumCircuit.from_qasm_str(qasm_str)
circuit.draw()
print(CircuitGridNode(node_types.X))
circuit_grid_model.set_node(qubit_index=1,depth_index=0,circuit_grid_node=CircuitGridNode(node_types.X))
print(circuit_grid_model)
qasm_str = circuit_grid_model.create_qasm_for_circuit()
print(qasm_str)
circuit = QuantumCircuit.from_qasm_str(qasm_str)
circuit.draw()
circuit_grid_model.set_node(0,1,CircuitGridNode(node_types.H))
circuit_grid_model.set_node(2,1,CircuitGridNode(node_types.H))
print(circuit_grid_model)
qasm_str = circuit_grid_model.create_qasm_for_circuit()
print(qasm_str)
circuit = QuantumCircuit.from_qasm_str(qasm_str)
circuit.draw()
from qiskit import BasicAer, execute, ClassicalRegister
def paddle_before_measurement(circuit, qubit_num, shot_num):
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circuit, backend_sv_sim, shots=shot_num)
result_sim = job_sim.result()
state = result_sim.get_statevector(circuit, decimals=3)
probability = (state*state).real
return probability
probability = paddle_before_measurement(circuit, 3, 1000)
print(probability)
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
plt.figure(figsize=(20,1))
ax = plt.gca()
for i in range(8):
ax.add_patch(Rectangle((i/8, 0), 1/8, 1, alpha=probability[i], fc='k', ec='k'))
# add statvector labels
ax.text(0/8+1/40,-1,r"$\left|000\right\rangle$", fontsize=36)
ax.text(1/8+1/40,-1,r"$\left|001\right\rangle$", fontsize=36)
ax.text(2/8+1/40,-1,r"$\left|010\right\rangle$", fontsize=36)
ax.text(3/8+1/40,-1,r"$\left|011\right\rangle$", fontsize=36)
ax.text(4/8+1/40,-1,r"$\left|100\right\rangle$", fontsize=36)
ax.text(5/8+1/40,-1,r"$\left|101\right\rangle$", fontsize=36)
ax.text(6/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36)
ax.text(7/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36)
plt.axis('off')
plt.show()
from copy import deepcopy
def paddle_after_measurement(circuit, qubit_num, shot_num):
backend_sv_sim = BasicAer.get_backend('qasm_simulator')
circuit.measure(circuit.qregs[0], circuit.cregs[0])
job_sim = execute(circuit, backend_sv_sim, shots=shot_num)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
return int(list(counts.keys())[0], 2)
result = paddle_after_measurement(circuit, 3, 100)
print(result)
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
plt.figure(figsize=(20,1))
ax = plt.gca()
for i in range(8):
if i == result:
ax.add_patch(Rectangle((i/8, 0), 1/8, 1, alpha=1, fc='k', ec='k'))
else:
ax.add_patch(Rectangle((i/8, 0), 1/8, 1, alpha=0, fc='k', ec='k'))
# add statvector labels
ax.text(0/8+1/40,-1,r"$\left|000\right\rangle$", fontsize=36)
ax.text(1/8+1/40,-1,r"$\left|001\right\rangle$", fontsize=36)
ax.text(2/8+1/40,-1,r"$\left|010\right\rangle$", fontsize=36)
ax.text(3/8+1/40,-1,r"$\left|011\right\rangle$", fontsize=36)
ax.text(4/8+1/40,-1,r"$\left|100\right\rangle$", fontsize=36)
ax.text(5/8+1/40,-1,r"$\left|101\right\rangle$", fontsize=36)
ax.text(6/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36)
ax.text(7/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36)
plt.axis('off')
plt.show()
|
https://github.com/Qiskit/feedback
|
Qiskit
|
# Cell 1: simple representation
from qiskit import QuantumCircuit
from qiskit.circuit import QuantumRegister, ClassicalRegister, Clbit
from qiskit.circuit.classical import expr
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
expr.equal(expr.bit_and(cr1, cr2), 5)
# Cell 2: where can I use these?
qc1 = QuantumCircuit(QuantumRegister(3), cr1, cr2)
with qc1.if_test((cr1, 5)):
qc1.x(0)
with qc1.if_test(expr.equal(cr1, 5)):
qc1.x(0)
# But we're not limited to equality relations!
with qc1.if_test(expr.less_equal(cr1, 5)):
qc1.z(0)
qc1.data[-1].operation.condition
# Cell 3: where else?
qc2 = QuantumCircuit(QuantumRegister(3), cr1, cr2)
with qc2.while_loop(expr.logic_or(expr.equal(cr1, 5), cr2[0])):
qc2.x(0)
with qc2.switch(expr.bit_and(cr1, cr2)) as case:
with case(0):
qc2.x(0)
with case(1):
qc2.z(0)
with case(2):
qc2.x(1)
with case(case.DEFAULT):
qc2.z(1)
# Cell 4: integration testing
import io
from qiskit import transpile, qasm3, qpy
from qiskit_aer import AerSimulator
backend = AerSimulator(method="statevector")
transpiled = transpile(qc1, backend)
with io.BytesIO() as fptr:
qpy.dump(transpiled, fptr)
fptr.seek(0)
loaded = qpy.load(fptr)[0]
print(qasm3.dumps(loaded))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123456
from sklearn.datasets import make_blobs
features, labels = make_blobs(
n_samples=20,
centers=2,
center_box=(-1, 1),
cluster_std=0.1,
random_state=algorithm_globals.random_seed,
)
from qiskit import BasicAer
from qiskit.utils import QuantumInstance
sv_qi = QuantumInstance(
BasicAer.get_backend("statevector_simulator"),
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed,
)
from qiskit.circuit.library import ZZFeatureMap
from qiskit_machine_learning.kernels import QuantumKernel
feature_map = ZZFeatureMap(2)
previous_kernel = QuantumKernel(feature_map=feature_map, quantum_instance=sv_qi)
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=previous_kernel)
qsvc.fit(features, labels)
qsvc.score(features, labels)
from qiskit.algorithms.state_fidelities import ComputeUncompute
from qiskit.primitives import Sampler
fidelity = ComputeUncompute(sampler=Sampler())
from qiskit_machine_learning.kernels import FidelityQuantumKernel
feature_map = ZZFeatureMap(2)
new_kernel = FidelityQuantumKernel(feature_map=feature_map, fidelity=fidelity)
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=new_kernel)
qsvc.fit(features, labels)
qsvc.score(features, labels)
from qiskit import QuantumCircuit
from qiskit.circuit.library import RealAmplitudes
num_inputs = 2
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs, reps=1)
circuit = QuantumCircuit(num_inputs)
circuit.compose(feature_map, inplace=True)
circuit.compose(ansatz, inplace=True)
def parity(x):
return "{:b}".format(x).count("1") % 2
initial_point = algorithm_globals.random.random(ansatz.num_parameters)
from qiskit_machine_learning.neural_networks import CircuitQNN
circuit_qnn = CircuitQNN(
circuit=circuit,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=2,
quantum_instance=sv_qi,
)
from qiskit.algorithms.optimizers import COBYLA
from qiskit_machine_learning.algorithms import NeuralNetworkClassifier
classifier = NeuralNetworkClassifier(
neural_network=circuit_qnn,
loss="cross_entropy",
one_hot=True,
optimizer=COBYLA(maxiter=40),
initial_point=initial_point,
)
classifier.fit(features, labels)
classifier.score(features, labels)
from qiskit.primitives import Sampler
sampler = Sampler()
from qiskit_machine_learning.neural_networks import SamplerQNN
sampler_qnn = SamplerQNN(
circuit=circuit,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=2,
sampler=sampler,
)
classifier = NeuralNetworkClassifier(
neural_network=sampler_qnn,
loss="cross_entropy",
one_hot=True,
optimizer=COBYLA(maxiter=40),
initial_point=initial_point,
)
classifier.fit(features, labels)
classifier.score(features, labels)
import numpy as np
num_samples = 20
eps = 0.2
lb, ub = -np.pi, np.pi
features = (ub - lb) * np.random.rand(num_samples, 1) + lb
labels = np.sin(features[:, 0]) + eps * (2 * np.random.rand(num_samples) - 1)
from qiskit.circuit import Parameter
num_inputs = 1
feature_map = QuantumCircuit(1)
feature_map.ry(Parameter("input"), 0)
ansatz = QuantumCircuit(1)
ansatz.ry(Parameter("weight"), 0)
circuit = QuantumCircuit(num_inputs)
circuit.compose(feature_map, inplace=True)
circuit.compose(ansatz, inplace=True)
initial_point = algorithm_globals.random.random(ansatz.num_parameters)
from qiskit.opflow import PauliSumOp, StateFn
from qiskit_machine_learning.neural_networks import OpflowQNN
observable = PauliSumOp.from_list([("Z", 1)])
operator = StateFn(observable, is_measurement=True) @ StateFn(circuit)
opflow_qnn = OpflowQNN(
operator=operator,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
quantum_instance=sv_qi,
)
from qiskit.algorithms.optimizers import L_BFGS_B
from qiskit_machine_learning.algorithms import NeuralNetworkRegressor
regressor = NeuralNetworkRegressor(
neural_network=opflow_qnn,
optimizer=L_BFGS_B(maxiter=5),
initial_point=initial_point,
)
regressor.fit(features, labels)
regressor.score(features, labels)
from qiskit.primitives import Estimator
estimator = Estimator()
from qiskit_machine_learning.neural_networks import EstimatorQNN
estimator_qnn = EstimatorQNN(
circuit=circuit,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
estimator=estimator,
)
from qiskit.algorithms.optimizers import L_BFGS_B
from qiskit_machine_learning.algorithms import VQR
regressor = NeuralNetworkRegressor(
neural_network=estimator_qnn,
optimizer=L_BFGS_B(maxiter=5),
initial_point=initial_point,
)
regressor.fit(features, labels)
regressor.score(features, labels)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
|
mnp-club
|
%matplotlib inline
# Importing standard Qiskit libraries
import random
from qiskit import *
from qiskit.tools.jupyter import *
from qiskit.visualization import *
#Get the library to check the answers
%pip install -I git+https://github.com/mnp-club/MnP_QC_Workshop.git
from mnp_qc_workshop_2020.bb84 import *
# Configuring account
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_qasm_simulator') # with this simulator it wouldn't work \
# Initial setup
random.seed(64) # do not change this seed, otherwise you will get a different key
random.seed(64)
# This is your 'random' bit string that determines your bases
numqubits = 16
bob_bases = str('{0:016b}'.format(random.getrandbits(numqubits)))
def bb84():
print('Bob\'s bases:', bob_bases)
# Now Alice will send her bits one by one...
all_qubit_circuits = []
for qubit_index in range(numqubits):
# This is Alice creating the qubit
thisqubit_circuit = alice_prepare_qubit(qubit_index)
# This is Bob finishing the protocol below
bob_measure_qubit(bob_bases, qubit_index, thisqubit_circuit)
# We collect all these circuits and put them in an array
all_qubit_circuits.append(thisqubit_circuit)
# Now execute all the circuits for each qubit
results = execute(all_qubit_circuits, backend=backend, shots=1).result()
# And combine the results
bits = ''
for qubit_index in range(numqubits):
bits += [measurement for measurement in results.get_counts(qubit_index)][0]
return bits
# Here is your task
def bob_measure_qubit(bob_bases, qubit_index, qubit_circuit):
if bob_bases[qubit_index] == '1':
qubit_circuit.h(0)
qubit_circuit.measure(0, 0)
bits = bb84()
print('Bob\'s bits: ', bits)
check_bits(bits)
alice_bases = '0100000101011100' # Alice's bases bits
key = ''
for i in range(16):
if bob_bases[i] == alice_bases[i]:
key += bits[i]
print(key)
check_key(key)
message = get_message()# encrypted message
decrypted = ''
for i in range(len(message)):
x = key[-(i%len(key))-1]
y = message[-i-1]
if x == y:
decrypted = '0' + decrypted
else:
decrypted = '1' + decrypted
print(decrypted)
check_decrypted(decrypted)
decrypted_to_string_ASCII = ''
i = 0
while i < 43:
decrypted_to_string_ASCII += decrypted[]
check_message(decrypted_to_string_ASCII)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test commutation checker class ."""
import unittest
import numpy as np
from qiskit import ClassicalRegister
from qiskit.test import QiskitTestCase
from qiskit.circuit import QuantumRegister, Parameter, Qubit
from qiskit.circuit import CommutationChecker
from qiskit.circuit.library import (
ZGate,
XGate,
CXGate,
CCXGate,
MCXGate,
RZGate,
Measure,
Barrier,
Reset,
LinearFunction,
)
class TestCommutationChecker(QiskitTestCase):
"""Test CommutationChecker class."""
def test_simple_gates(self):
"""Check simple commutation relations between gates, experimenting with
different orders of gates, different orders of qubits, different sets of
qubits over which gates are defined, and so on."""
comm_checker = CommutationChecker()
# should commute
res = comm_checker.commute(ZGate(), [0], [], CXGate(), [0, 1], [])
self.assertTrue(res)
# should not commute
res = comm_checker.commute(ZGate(), [1], [], CXGate(), [0, 1], [])
self.assertFalse(res)
# should not commute
res = comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], [])
self.assertFalse(res)
# should commute
res = comm_checker.commute(XGate(), [1], [], CXGate(), [0, 1], [])
self.assertTrue(res)
# should not commute
res = comm_checker.commute(XGate(), [1], [], CXGate(), [1, 0], [])
self.assertFalse(res)
# should commute
res = comm_checker.commute(XGate(), [0], [], CXGate(), [1, 0], [])
self.assertTrue(res)
# should commute
res = comm_checker.commute(CXGate(), [1, 0], [], XGate(), [0], [])
self.assertTrue(res)
# should not commute
res = comm_checker.commute(CXGate(), [1, 0], [], XGate(), [1], [])
self.assertFalse(res)
# should commute
res = comm_checker.commute(
CXGate(),
[1, 0],
[],
CXGate(),
[1, 0],
[],
)
self.assertTrue(res)
# should not commute
res = comm_checker.commute(
CXGate(),
[1, 0],
[],
CXGate(),
[0, 1],
[],
)
self.assertFalse(res)
# should commute
res = comm_checker.commute(
CXGate(),
[1, 0],
[],
CXGate(),
[1, 2],
[],
)
self.assertTrue(res)
# should not commute
res = comm_checker.commute(
CXGate(),
[1, 0],
[],
CXGate(),
[2, 1],
[],
)
self.assertFalse(res)
# should commute
res = comm_checker.commute(
CXGate(),
[1, 0],
[],
CXGate(),
[2, 3],
[],
)
self.assertTrue(res)
res = comm_checker.commute(XGate(), [2], [], CCXGate(), [0, 1, 2], [])
self.assertTrue(res)
res = comm_checker.commute(CCXGate(), [0, 1, 2], [], CCXGate(), [0, 2, 1], [])
self.assertFalse(res)
def test_passing_quantum_registers(self):
"""Check that passing QuantumRegisters works correctly."""
comm_checker = CommutationChecker()
qr = QuantumRegister(4)
# should commute
res = comm_checker.commute(CXGate(), [qr[1], qr[0]], [], CXGate(), [qr[1], qr[2]], [])
self.assertTrue(res)
# should not commute
res = comm_checker.commute(CXGate(), [qr[0], qr[1]], [], CXGate(), [qr[1], qr[2]], [])
self.assertFalse(res)
def test_caching_positive_results(self):
"""Check that hashing positive results in commutativity checker works as expected."""
comm_checker = CommutationChecker()
res = comm_checker.commute(ZGate(), [0], [], CXGate(), [0, 1], [])
self.assertTrue(res)
self.assertGreater(len(comm_checker.cache), 0)
def test_caching_negative_results(self):
"""Check that hashing negative results in commutativity checker works as expected."""
comm_checker = CommutationChecker()
res = comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], [])
self.assertFalse(res)
self.assertGreater(len(comm_checker.cache), 0)
def test_caching_different_qubit_sets(self):
"""Check that hashing same commutativity results over different qubit sets works as expected."""
comm_checker = CommutationChecker()
# All the following should be cached in the same way
# though each relation gets cached twice: (A, B) and (B, A)
comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], [])
comm_checker.commute(XGate(), [10], [], CXGate(), [10, 20], [])
comm_checker.commute(XGate(), [10], [], CXGate(), [10, 5], [])
comm_checker.commute(XGate(), [5], [], CXGate(), [5, 7], [])
self.assertEqual(len(comm_checker.cache), 2)
def test_gates_with_parameters(self):
"""Check commutativity between (non-parameterized) gates with parameters."""
comm_checker = CommutationChecker()
res = comm_checker.commute(RZGate(0), [0], [], XGate(), [0], [])
self.assertTrue(res)
res = comm_checker.commute(RZGate(np.pi / 2), [0], [], XGate(), [0], [])
self.assertFalse(res)
res = comm_checker.commute(RZGate(np.pi / 2), [0], [], RZGate(0), [0], [])
self.assertTrue(res)
def test_parameterized_gates(self):
"""Check commutativity between parameterized gates, both with free and with
bound parameters."""
comm_checker = CommutationChecker()
# gate that has parameters but is not considered parameterized
rz_gate = RZGate(np.pi / 2)
self.assertEqual(len(rz_gate.params), 1)
self.assertFalse(rz_gate.is_parameterized())
# gate that has parameters and is considered parameterized
rz_gate_theta = RZGate(Parameter("Theta"))
rz_gate_phi = RZGate(Parameter("Phi"))
self.assertEqual(len(rz_gate_theta.params), 1)
self.assertTrue(rz_gate_theta.is_parameterized())
# gate that has no parameters and is not considered parameterized
cx_gate = CXGate()
self.assertEqual(len(cx_gate.params), 0)
self.assertFalse(cx_gate.is_parameterized())
# We should detect that these gates commute
res = comm_checker.commute(rz_gate, [0], [], cx_gate, [0, 1], [])
self.assertTrue(res)
# We should detect that these gates commute
res = comm_checker.commute(rz_gate, [0], [], rz_gate, [0], [])
self.assertTrue(res)
# We should detect that parameterized gates over disjoint qubit subsets commute
res = comm_checker.commute(rz_gate_theta, [0], [], rz_gate_theta, [1], [])
self.assertTrue(res)
# We should detect that parameterized gates over disjoint qubit subsets commute
res = comm_checker.commute(rz_gate_theta, [0], [], rz_gate_phi, [1], [])
self.assertTrue(res)
# We should detect that parameterized gates over disjoint qubit subsets commute
res = comm_checker.commute(rz_gate_theta, [2], [], cx_gate, [1, 3], [])
self.assertTrue(res)
# However, for now commutativity checker should return False when checking
# commutativity between a parameterized gate and some other gate, when
# the two gates are over intersecting qubit subsets.
# This check should be changed if commutativity checker is extended to
# handle parameterized gates better.
res = comm_checker.commute(rz_gate_theta, [0], [], cx_gate, [0, 1], [])
self.assertFalse(res)
res = comm_checker.commute(rz_gate_theta, [0], [], rz_gate, [0], [])
self.assertFalse(res)
def test_measure(self):
"""Check commutativity involving measures."""
comm_checker = CommutationChecker()
# Measure is over qubit 0, while gate is over a disjoint subset of qubits
# We should be able to swap these.
res = comm_checker.commute(Measure(), [0], [0], CXGate(), [1, 2], [])
self.assertTrue(res)
# Measure and gate have intersecting set of qubits
# We should not be able to swap these.
res = comm_checker.commute(Measure(), [0], [0], CXGate(), [0, 2], [])
self.assertFalse(res)
# Measures over different qubits and clbits
res = comm_checker.commute(Measure(), [0], [0], Measure(), [1], [1])
self.assertTrue(res)
# Measures over different qubits but same classical bit
# We should not be able to swap these.
res = comm_checker.commute(Measure(), [0], [0], Measure(), [1], [0])
self.assertFalse(res)
# Measures over same qubits but different classical bit
# ToDo: can we swap these?
# Currently checker takes the safe approach and returns False.
res = comm_checker.commute(Measure(), [0], [0], Measure(), [0], [1])
self.assertFalse(res)
def test_barrier(self):
"""Check commutativity involving barriers."""
comm_checker = CommutationChecker()
# A gate should not commute with a barrier
# (at least if these are over intersecting qubit sets).
res = comm_checker.commute(Barrier(4), [0, 1, 2, 3], [], CXGate(), [1, 2], [])
self.assertFalse(res)
# Does it even make sense to have a barrier over a subset of qubits?
# Though in this case, it probably makes sense to say that barrier and gate can be swapped.
res = comm_checker.commute(Barrier(4), [0, 1, 2, 3], [], CXGate(), [5, 6], [])
self.assertTrue(res)
def test_reset(self):
"""Check commutativity involving resets."""
comm_checker = CommutationChecker()
# A gate should not commute with reset when the qubits intersect.
res = comm_checker.commute(Reset(), [0], [], CXGate(), [0, 2], [])
self.assertFalse(res)
# A gate should commute with reset when the qubits are disjoint.
res = comm_checker.commute(Reset(), [0], [], CXGate(), [1, 2], [])
self.assertTrue(res)
def test_conditional_gates(self):
"""Check commutativity involving conditional gates."""
comm_checker = CommutationChecker()
qr = QuantumRegister(3)
cr = ClassicalRegister(2)
# Currently, in all cases commutativity checker should returns False.
# This is definitely suboptimal.
res = comm_checker.commute(
CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [], XGate(), [qr[2]], []
)
self.assertFalse(res)
res = comm_checker.commute(
CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [], XGate(), [qr[1]], []
)
self.assertFalse(res)
res = comm_checker.commute(
CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [], CXGate().c_if(cr[0], 0), [qr[0], qr[1]], []
)
self.assertFalse(res)
res = comm_checker.commute(
XGate().c_if(cr[0], 0), [qr[0]], [], XGate().c_if(cr[0], 1), [qr[0]], []
)
self.assertFalse(res)
res = comm_checker.commute(XGate().c_if(cr[0], 0), [qr[0]], [], XGate(), [qr[0]], [])
self.assertFalse(res)
def test_complex_gates(self):
"""Check commutativity involving more complex gates."""
comm_checker = CommutationChecker()
lf1 = LinearFunction([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
lf2 = LinearFunction([[1, 0, 0], [0, 0, 1], [0, 1, 0]])
# lf1 is equivalent to swap(0, 1), and lf2 to swap(1, 2).
# These do not commute.
res = comm_checker.commute(lf1, [0, 1, 2], [], lf2, [0, 1, 2], [])
self.assertFalse(res)
lf3 = LinearFunction([[0, 1, 0], [0, 0, 1], [1, 0, 0]])
lf4 = LinearFunction([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
# lf3 is permutation 1->2, 2->3, 3->1.
# lf3 is the inverse permutation 1->3, 2->1, 3->2.
# These commute.
res = comm_checker.commute(lf3, [0, 1, 2], [], lf4, [0, 1, 2], [])
self.assertTrue(res)
def test_c7x_gate(self):
"""Test wide gate works correctly."""
qargs = [Qubit() for _ in [None] * 8]
res = CommutationChecker().commute(XGate(), qargs[:1], [], XGate().control(7), qargs, [])
self.assertFalse(res)
def test_wide_gates_over_nondisjoint_qubits(self):
"""Test that checking wide gates does not lead to memory problems."""
res = CommutationChecker().commute(MCXGate(29), list(range(30)), [], XGate(), [0], [])
self.assertFalse(res)
res = CommutationChecker().commute(XGate(), [0], [], MCXGate(29), list(range(30)), [])
self.assertFalse(res)
def test_wide_gates_over_disjoint_qubits(self):
"""Test that wide gates still commute when they are over disjoint sets of qubits."""
res = CommutationChecker().commute(MCXGate(29), list(range(30)), [], XGate(), [30], [])
self.assertTrue(res)
res = CommutationChecker().commute(XGate(), [30], [], MCXGate(29), list(range(30)), [])
self.assertTrue(res)
if __name__ == "__main__":
unittest.main()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# import common packages
import itertools
import numpy as np
from numpy import array, concatenate, zeros
import qiskit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.quantum_info import Pauli
# lib from Qiskit AQUA Chemistry
from qiskit.chemistry import FermionicOperator
# lib from optimizer and algorithm
from qiskit.aqua.operator import Operator
# lib for driver
from collections import OrderedDict
from abc import ABC, abstractmethod
import time
def _jordan_wigner_mode(n):
"""
Jordan_Wigner mode.
Args:
n (int): number of modes
"""
a = []
for i in range(n):
xv = np.asarray([1] * i + [0] + [0] * (n - i - 1))
xw = np.asarray([0] * i + [1] + [0] * (n - i - 1))
yv = np.asarray([1] * i + [1] + [0] * (n - i - 1))
yw = np.asarray([0] * i + [1] + [0] * (n - i - 1))
a.append((Pauli(xv, xw), Pauli(yv, yw)))
return a
def _one_body_mapping(a_i, a_j, threshold=0.000001):
"""
Subroutine for one body mapping.
Args:
a_i (Pauli): pauli at index i
a_j (Pauli): pauli at index j
threshold: (float): threshold to remove a pauli
Returns:
Operator: Operator for those paulis
"""
pauli_list = []
for alpha in range(2):
for beta in range(2):
pauli_prod = Pauli.sgn_prod(a_i[alpha], a_j[beta])
coeff = 1.0/4 * pauli_prod[1] * np.power(-1j, alpha) * np.power(1j, beta)
pauli_term = [coeff, pauli_prod[0]]
if np.absolute(pauli_term[0]) > threshold:
pauli_list.append(pauli_term)
return Operator(paulis=pauli_list)
class QseMatrices():
def __init__(self, qubit_hamiltonian, n_qubits):
self.qubit_hamiltonian = qubit_hamiltonian
self.n_qubits = n_qubits
self.c_i = None
paulis_test = _jordan_wigner_mode(n_qubits)
excit_operator = []
excit_operator_conjugated = []
#Construct operators C_i C_j^+ and conjugated operators
#C_i : 2nd quantization annihilation operator
#C_i^+ : 2nd quantization creation operator
k = 0
for i, j in itertools.product(range(n_qubits), repeat=2):
second_q_operator = _one_body_mapping(paulis_test[i],paulis_test[j])
excit_operator.append(second_q_operator)
second_q_op_conjugated = _one_body_mapping(paulis_test[j],paulis_test[i])
excit_operator_conjugated.append(second_q_op_conjugated)
k += 1
self.excit_operator = excit_operator
self.excit_operator_conjugated = excit_operator_conjugated
def overlap(self):
return np.outer(self.excit_operator_conjugated, self.excit_operator)
def overlap_term(self, i, j):
return self.excit_operator_conjugated[j]*self.excit_operator[i]
def hamiltonian_term(self, i, j):
return self.excit_operator_conjugated[j]*self.qubit_hamiltonian*self.excit_operator[i]
def unroll_paulis(paulis):
coeffs = np.zeros(len(paulis), dtype=np.complex)
bools = np.zeros((len(paulis), 2*paulis[0][1].numberofqubits), dtype=np.int)
for i, pauli in enumerate(paulis):
coeffs[i] = pauli[0]
bools[i, :4] = pauli[1].v
bools[i, 4:] = pauli[1].w
return coeffs, bools
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
print(problem)
hamiltonian = problem.hamiltonian
coefficients = hamiltonian.electronic_integrals
print(coefficients.alpha)
second_q_op = hamiltonian.second_q_op()
print(second_q_op)
hamiltonian.nuclear_repulsion_energy # NOT included in the second_q_op above
problem.molecule
problem.reference_energy
problem.num_particles
problem.num_spatial_orbitals
problem.basis
problem.properties
problem.properties.particle_number
problem.properties.angular_momentum
problem.properties.magnetization
problem.properties.electronic_dipole_moment
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import JordanWignerMapper
solver = GroundStateEigensolver(
JordanWignerMapper(),
NumPyMinimumEigensolver(),
)
result = solver.solve(problem)
print(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests basic functionality of the transpile function"""
import copy
import io
import math
import os
import sys
import unittest
from logging import StreamHandler, getLogger
from test import combine # pylint: disable=wrong-import-order
from unittest.mock import patch
import numpy as np
import rustworkx as rx
from ddt import data, ddt, unpack
from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister, pulse, qasm3, qpy
from qiskit.circuit import (
Clbit,
ControlFlowOp,
ForLoopOp,
Gate,
IfElseOp,
Parameter,
Qubit,
Reset,
SwitchCaseOp,
WhileLoopOp,
)
from qiskit.circuit.classical import expr
from qiskit.circuit.delay import Delay
from qiskit.circuit.library import (
CXGate,
CZGate,
HGate,
RXGate,
RYGate,
RZGate,
SXGate,
U1Gate,
U2Gate,
UGate,
XGate,
)
from qiskit.circuit.measure import Measure
from qiskit.compiler import transpile
from qiskit.converters import circuit_to_dag
from qiskit.dagcircuit import DAGOpNode, DAGOutNode
from qiskit.exceptions import QiskitError
from qiskit.providers.backend import BackendV2
from qiskit.providers.fake_provider import (
FakeBoeblingen,
FakeMelbourne,
FakeMumbaiV2,
FakeNairobiV2,
FakeRueschlikon,
FakeSherbrooke,
FakeVigo,
)
from qiskit.providers.options import Options
from qiskit.pulse import InstructionScheduleMap
from qiskit.quantum_info import Operator, random_unitary
from qiskit.test import QiskitTestCase, slow_test
from qiskit.tools import parallel
from qiskit.transpiler import CouplingMap, Layout, PassManager, TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements, GateDirection, VF2PostLayout
from qiskit.transpiler.passmanager_config import PassManagerConfig
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager, level_0_pass_manager
from qiskit.transpiler.target import InstructionProperties, Target
class CustomCX(Gate):
"""Custom CX gate representation."""
def __init__(self):
super().__init__("custom_cx", 2, [])
def _define(self):
self._definition = QuantumCircuit(2)
self._definition.cx(0, 1)
def connected_qubits(physical: int, coupling_map: CouplingMap) -> set:
"""Get the physical qubits that have a connection to this one in the coupling map."""
for component in coupling_map.connected_components():
if physical in (qubits := set(component.graph.nodes())):
return qubits
raise ValueError(f"physical qubit {physical} is not in the coupling map")
@ddt
class TestTranspile(QiskitTestCase):
"""Test transpile function."""
def test_empty_transpilation(self):
"""Test that transpiling an empty list is a no-op. Regression test of gh-7287."""
self.assertEqual(transpile([]), [])
def test_pass_manager_none(self):
"""Test passing the default (None) pass manager to the transpiler.
It should perform the default qiskit flow:
unroll, swap_mapper, cx_direction, cx_cancellation, optimize_1q_gates
and should be equivalent to using tools.compile
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
coupling_map = [[1, 0]]
basis_gates = ["u1", "u2", "u3", "cx", "id"]
backend = BasicAer.get_backend("qasm_simulator")
circuit2 = transpile(
circuit,
backend=backend,
coupling_map=coupling_map,
basis_gates=basis_gates,
)
circuit3 = transpile(
circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates
)
self.assertEqual(circuit2, circuit3)
def test_transpile_basis_gates_no_backend_no_coupling_map(self):
"""Verify transpile() works with no coupling_map or backend."""
qr = QuantumRegister(2, "qr")
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])
basis_gates = ["u1", "u2", "u3", "cx", "id"]
circuit2 = transpile(circuit, basis_gates=basis_gates, optimization_level=0)
resources_after = circuit2.count_ops()
self.assertEqual({"u2": 2, "cx": 4}, resources_after)
def test_transpile_non_adjacent_layout(self):
"""Transpile pipeline can handle manual layout on non-adjacent qubits.
circuit:
.. parsed-literal::
┌───┐
qr_0: ┤ H ├──■──────────── -> 1
└───┘┌─┴─┐
qr_1: ─────┤ X ├──■─────── -> 2
└───┘┌─┴─┐
qr_2: ──────────┤ X ├──■── -> 3
└───┘┌─┴─┐
qr_3: ───────────────┤ X ├ -> 5
└───┘
device:
0 - 1 - 2 - 3 - 4 - 5 - 6
| | | | | |
13 - 12 - 11 - 10 - 9 - 8 - 7
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[2], qr[3])
coupling_map = FakeMelbourne().configuration().coupling_map
basis_gates = FakeMelbourne().configuration().basis_gates
initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]]
new_circuit = transpile(
circuit,
basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)}
for instruction in new_circuit.data:
if isinstance(instruction.operation, CXGate):
self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map)
def test_transpile_qft_grid(self):
"""Transpile pipeline can handle 8-qubit QFT on 14-qubit grid."""
qr = QuantumRegister(8)
circuit = QuantumCircuit(qr)
for i, _ in enumerate(qr):
for j in range(i):
circuit.cp(math.pi / float(2 ** (i - j)), qr[i], qr[j])
circuit.h(qr[i])
coupling_map = FakeMelbourne().configuration().coupling_map
basis_gates = FakeMelbourne().configuration().basis_gates
new_circuit = transpile(circuit, basis_gates=basis_gates, coupling_map=coupling_map)
qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)}
for instruction in new_circuit.data:
if isinstance(instruction.operation, CXGate):
self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map)
def test_already_mapped_1(self):
"""Circuit not remapped if matches topology.
See: https://github.com/Qiskit/qiskit-terra/issues/342
"""
backend = FakeRueschlikon()
coupling_map = backend.configuration().coupling_map
basis_gates = backend.configuration().basis_gates
qr = QuantumRegister(16, "qr")
cr = ClassicalRegister(16, "cr")
qc = QuantumCircuit(qr, cr)
qc.cx(qr[3], qr[14])
qc.cx(qr[5], qr[4])
qc.h(qr[9])
qc.cx(qr[9], qr[8])
qc.x(qr[11])
qc.cx(qr[3], qr[4])
qc.cx(qr[12], qr[11])
qc.cx(qr[13], qr[4])
qc.measure(qr, cr)
new_qc = transpile(
qc,
coupling_map=coupling_map,
basis_gates=basis_gates,
initial_layout=Layout.generate_trivial_layout(qr),
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)}
cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"]
cx_qubits_physical = [
[qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits
]
self.assertEqual(
sorted(cx_qubits_physical), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]]
)
def test_already_mapped_via_layout(self):
"""Test that a manual layout that satisfies a coupling map does not get altered.
See: https://github.com/Qiskit/qiskit-terra/issues/2036
circuit:
.. parsed-literal::
┌───┐ ┌───┐ ░ ┌─┐
qn_0: ┤ H ├──■────────────■──┤ H ├─░─┤M├─── -> 9
└───┘ │ │ └───┘ ░ └╥┘
qn_1: ───────┼────────────┼────────░──╫──── -> 6
│ │ ░ ║
qn_2: ───────┼────────────┼────────░──╫──── -> 5
│ │ ░ ║
qn_3: ───────┼────────────┼────────░──╫──── -> 0
│ │ ░ ║
qn_4: ───────┼────────────┼────────░──╫──── -> 1
┌───┐┌─┴─┐┌──────┐┌─┴─┐┌───┐ ░ ║ ┌─┐
qn_5: ┤ H ├┤ X ├┤ P(2) ├┤ X ├┤ H ├─░──╫─┤M├ -> 4
└───┘└───┘└──────┘└───┘└───┘ ░ ║ └╥┘
cn: 2/════════════════════════════════╩══╩═
0 1
device:
0 -- 1 -- 2 -- 3 -- 4
| |
5 -- 6 -- 7 -- 8 -- 9
| |
10 - 11 - 12 - 13 - 14
| |
15 - 16 - 17 - 18 - 19
"""
basis_gates = ["u1", "u2", "u3", "cx", "id"]
coupling_map = [
[0, 1],
[0, 5],
[1, 0],
[1, 2],
[2, 1],
[2, 3],
[3, 2],
[3, 4],
[4, 3],
[4, 9],
[5, 0],
[5, 6],
[5, 10],
[6, 5],
[6, 7],
[7, 6],
[7, 8],
[7, 12],
[8, 7],
[8, 9],
[9, 4],
[9, 8],
[9, 14],
[10, 5],
[10, 11],
[10, 15],
[11, 10],
[11, 12],
[12, 7],
[12, 11],
[12, 13],
[13, 12],
[13, 14],
[14, 9],
[14, 13],
[14, 19],
[15, 10],
[15, 16],
[16, 15],
[16, 17],
[17, 16],
[17, 18],
[18, 17],
[18, 19],
[19, 14],
[19, 18],
]
q = QuantumRegister(6, name="qn")
c = ClassicalRegister(2, name="cn")
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[5])
qc.cx(q[0], q[5])
qc.p(2, q[5])
qc.cx(q[0], q[5])
qc.h(q[0])
qc.h(q[5])
qc.barrier(q)
qc.measure(q[0], c[0])
qc.measure(q[5], c[1])
initial_layout = [
q[3],
q[4],
None,
None,
q[5],
q[2],
q[1],
None,
None,
q[0],
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
]
new_qc = transpile(
qc, coupling_map=coupling_map, basis_gates=basis_gates, initial_layout=initial_layout
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)}
cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"]
cx_qubits_physical = [
[qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits
]
self.assertEqual(sorted(cx_qubits_physical), [[9, 4], [9, 4]])
def test_transpile_bell(self):
"""Test Transpile Bell.
If all correct some should exists.
"""
backend = BasicAer.get_backend("qasm_simulator")
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)
circuits = transpile(qc, backend)
self.assertIsInstance(circuits, QuantumCircuit)
def test_transpile_one(self):
"""Test transpile a single circuit.
Check that the top-level `transpile` function returns
a single circuit."""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2)
clbit_reg = ClassicalRegister(2)
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)
circuit = transpile(qc, backend)
self.assertIsInstance(circuit, QuantumCircuit)
def test_transpile_two(self):
"""Test transpile two circuits.
Check that the transpiler returns a list of two circuits.
"""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2)
clbit_reg = ClassicalRegister(2)
qubit_reg2 = QuantumRegister(2)
clbit_reg2 = ClassicalRegister(2)
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, qubit_reg2, clbit_reg, clbit_reg2, name="extra")
qc_extra.measure(qubit_reg, clbit_reg)
circuits = transpile([qc, qc_extra], backend)
self.assertIsInstance(circuits, list)
self.assertEqual(len(circuits), 2)
for circuit in circuits:
self.assertIsInstance(circuit, QuantumCircuit)
def test_transpile_singleton(self):
"""Test transpile a single-element list with a circuit.
Check that `transpile` returns a single-element list.
See https://github.com/Qiskit/qiskit-terra/issues/5260
"""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2)
clbit_reg = ClassicalRegister(2)
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)
circuits = transpile([qc], backend)
self.assertIsInstance(circuits, list)
self.assertEqual(len(circuits), 1)
self.assertIsInstance(circuits[0], QuantumCircuit)
def test_mapping_correction(self):
"""Test mapping works in previous failed case."""
backend = FakeRueschlikon()
qr = QuantumRegister(name="qr", size=11)
cr = ClassicalRegister(name="qc", size=11)
circuit = QuantumCircuit(qr, cr)
circuit.u(1.564784764685993, -1.2378965763410095, 2.9746763177861713, qr[3])
circuit.u(1.2269835563676523, 1.1932982847014162, -1.5597357740824318, qr[5])
circuit.cx(qr[5], qr[3])
circuit.p(0.856768317675967, qr[3])
circuit.u(-3.3911273825190915, 0.0, 0.0, qr[5])
circuit.cx(qr[3], qr[5])
circuit.u(2.159209321625547, 0.0, 0.0, qr[5])
circuit.cx(qr[5], qr[3])
circuit.u(0.30949966910232335, 1.1706201763833217, 1.738408691990081, qr[3])
circuit.u(1.9630571407274755, -0.6818742967975088, 1.8336534616728195, qr[5])
circuit.u(1.330181833806101, 0.6003162754946363, -3.181264980452862, qr[7])
circuit.u(0.4885914820775024, 3.133297443244865, -2.794457469189904, qr[8])
circuit.cx(qr[8], qr[7])
circuit.p(2.2196187596178616, qr[7])
circuit.u(-3.152367609631023, 0.0, 0.0, qr[8])
circuit.cx(qr[7], qr[8])
circuit.u(1.2646005789809263, 0.0, 0.0, qr[8])
circuit.cx(qr[8], qr[7])
circuit.u(0.7517780502091939, 1.2828514296564781, 1.6781179605443775, qr[7])
circuit.u(0.9267400575390405, 2.0526277839695153, 2.034202361069533, qr[8])
circuit.u(2.550304293455634, 3.8250017126569698, -2.1351609599720054, qr[1])
circuit.u(0.9566260876600556, -1.1147561503064538, 2.0571590492298797, qr[4])
circuit.cx(qr[4], qr[1])
circuit.p(2.1899329069137394, qr[1])
circuit.u(-1.8371715243173294, 0.0, 0.0, qr[4])
circuit.cx(qr[1], qr[4])
circuit.u(0.4717053496327104, 0.0, 0.0, qr[4])
circuit.cx(qr[4], qr[1])
circuit.u(2.3167620677708145, -1.2337330260253256, -0.5671322899563955, qr[1])
circuit.u(1.0468499525240678, 0.8680750644809365, -1.4083720073192485, qr[4])
circuit.u(2.4204244021892807, -2.211701932616922, 3.8297006565735883, qr[10])
circuit.u(0.36660280497727255, 3.273119149343493, -1.8003362351299388, qr[6])
circuit.cx(qr[6], qr[10])
circuit.p(1.067395863586385, qr[10])
circuit.u(-0.7044917541291232, 0.0, 0.0, qr[6])
circuit.cx(qr[10], qr[6])
circuit.u(2.1830003849921527, 0.0, 0.0, qr[6])
circuit.cx(qr[6], qr[10])
circuit.u(2.1538343756723917, 2.2653381826084606, -3.550087952059485, qr[10])
circuit.u(1.307627685019188, -0.44686656993522567, -2.3238098554327418, qr[6])
circuit.u(2.2046797998462906, 0.9732961754855436, 1.8527865921467421, qr[9])
circuit.u(2.1665254613904126, -1.281337664694577, -1.2424905413631209, qr[0])
circuit.cx(qr[0], qr[9])
circuit.p(2.6209599970201007, qr[9])
circuit.u(0.04680566321901303, 0.0, 0.0, qr[0])
circuit.cx(qr[9], qr[0])
circuit.u(1.7728411151289603, 0.0, 0.0, qr[0])
circuit.cx(qr[0], qr[9])
circuit.u(2.4866395967434443, 0.48684511243566697, -3.0069186877854728, qr[9])
circuit.u(1.7369112924273789, -4.239660866163805, 1.0623389015296005, qr[0])
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits = transpile(circuit, backend)
self.assertIsInstance(circuits, QuantumCircuit)
def test_transpiler_layout_from_intlist(self):
"""A list of ints gives layout to correctly map circuit.
virtual physical
q1_0 - 4 ---[H]---
q2_0 - 5
q2_1 - 6 ---[H]---
q3_0 - 8
q3_1 - 9
q3_2 - 10 ---[H]---
"""
qr1 = QuantumRegister(1, "qr1")
qr2 = QuantumRegister(2, "qr2")
qr3 = QuantumRegister(3, "qr3")
qc = QuantumCircuit(qr1, qr2, qr3)
qc.h(qr1[0])
qc.h(qr2[1])
qc.h(qr3[2])
layout = [4, 5, 6, 8, 9, 10]
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],
]
new_circ = transpile(
qc, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_circ.qubits)}
mapped_qubits = []
for instruction in new_circ.data:
mapped_qubits.append(qubit_indices[instruction.qubits[0]])
self.assertEqual(mapped_qubits, [4, 6, 10])
def test_mapping_multi_qreg(self):
"""Test mapping works for multiple qregs."""
backend = FakeRueschlikon()
qr = QuantumRegister(3, name="qr")
qr2 = QuantumRegister(1, name="qr2")
qr3 = QuantumRegister(4, name="qr3")
cr = ClassicalRegister(3, name="cr")
qc = QuantumCircuit(qr, qr2, qr3, cr)
qc.h(qr[0])
qc.cx(qr[0], qr2[0])
qc.cx(qr[1], qr3[2])
qc.measure(qr, cr)
circuits = transpile(qc, backend)
self.assertIsInstance(circuits, QuantumCircuit)
def test_transpile_circuits_diff_registers(self):
"""Transpile list of circuits with different qreg names."""
backend = FakeRueschlikon()
circuits = []
for _ in range(2):
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.measure(qr, cr)
circuits.append(circuit)
circuits = transpile(circuits, backend)
self.assertIsInstance(circuits[0], QuantumCircuit)
def test_wrong_initial_layout(self):
"""Test transpile with a bad initial layout."""
backend = FakeMelbourne()
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)
bad_initial_layout = [
QuantumRegister(3, "q")[0],
QuantumRegister(3, "q")[1],
QuantumRegister(3, "q")[2],
]
with self.assertRaises(TranspilerError):
transpile(qc, backend, initial_layout=bad_initial_layout)
def test_parameterized_circuit_for_simulator(self):
"""Verify that a parameterized circuit can be transpiled for a simulator backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.rz(theta, qr[0])
transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator"))
expected_qc = QuantumCircuit(qr)
expected_qc.append(RZGate(theta), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_parameterized_circuit_for_device(self):
"""Verify that a parameterized circuit can be transpiled for a device backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.rz(theta, qr[0])
transpiled_qc = transpile(
qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr)
)
qr = QuantumRegister(14, "q")
expected_qc = QuantumCircuit(qr, global_phase=-1 * theta / 2.0)
expected_qc.append(U1Gate(theta), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_parameter_expression_circuit_for_simulator(self):
"""Verify that a circuit including expressions of parameters can be
transpiled for a simulator backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
square = theta * theta
qc.rz(square, qr[0])
transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator"))
expected_qc = QuantumCircuit(qr)
expected_qc.append(RZGate(square), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_parameter_expression_circuit_for_device(self):
"""Verify that a circuit including expressions of parameters can be
transpiled for a device backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
square = theta * theta
qc.rz(square, qr[0])
transpiled_qc = transpile(
qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr)
)
qr = QuantumRegister(14, "q")
expected_qc = QuantumCircuit(qr, global_phase=-1 * square / 2.0)
expected_qc.append(U1Gate(square), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_final_measurement_barrier_for_devices(self):
"""Verify BarrierBeforeFinalMeasurements pass is called in default pipeline for devices."""
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, "example.qasm"))
layout = Layout.generate_trivial_layout(*circ.qregs)
orig_pass = BarrierBeforeFinalMeasurements()
with patch.object(BarrierBeforeFinalMeasurements, "run", wraps=orig_pass.run) as mock_pass:
transpile(
circ,
coupling_map=FakeRueschlikon().configuration().coupling_map,
initial_layout=layout,
)
self.assertTrue(mock_pass.called)
def test_do_not_run_gatedirection_with_symmetric_cm(self):
"""When the coupling map is symmetric, do not run GateDirection."""
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, "example.qasm"))
layout = Layout.generate_trivial_layout(*circ.qregs)
coupling_map = []
for node1, node2 in FakeRueschlikon().configuration().coupling_map:
coupling_map.append([node1, node2])
coupling_map.append([node2, node1])
orig_pass = GateDirection(CouplingMap(coupling_map))
with patch.object(GateDirection, "run", wraps=orig_pass.run) as mock_pass:
transpile(circ, coupling_map=coupling_map, initial_layout=layout)
self.assertFalse(mock_pass.called)
def test_optimize_to_nothing(self):
"""Optimize gates up to fixed point in the default pipeline
See https://github.com/Qiskit/qiskit-terra/issues/2035
"""
# ┌───┐ ┌───┐┌───┐┌───┐ ┌───┐
# q0_0: ┤ H ├──■──┤ X ├┤ Y ├┤ Z ├──■──┤ H ├──■────■──
# └───┘┌─┴─┐└───┘└───┘└───┘┌─┴─┐└───┘┌─┴─┐┌─┴─┐
# q0_1: ─────┤ X ├───────────────┤ X ├─────┤ X ├┤ X ├
# └───┘ └───┘ └───┘└───┘
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.x(qr[0])
circ.y(qr[0])
circ.z(qr[0])
circ.cx(qr[0], qr[1])
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.cx(qr[0], qr[1])
after = transpile(circ, coupling_map=[[0, 1], [1, 0]], basis_gates=["u3", "u2", "u1", "cx"])
expected = QuantumCircuit(QuantumRegister(2, "q"), global_phase=-np.pi / 2)
msg = f"after:\n{after}\nexpected:\n{expected}"
self.assertEqual(after, expected, msg=msg)
def test_pass_manager_empty(self):
"""Test passing an empty PassManager() to the transpiler.
It should perform no transformations on the circuit.
"""
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])
resources_before = circuit.count_ops()
pass_manager = PassManager()
out_circuit = pass_manager.run(circuit)
resources_after = out_circuit.count_ops()
self.assertDictEqual(resources_before, resources_after)
def test_move_measurements(self):
"""Measurements applied AFTER swap mapping."""
backend = FakeRueschlikon()
cmap = backend.configuration().coupling_map
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, "move_measurements.qasm"))
lay = [0, 1, 15, 2, 14, 3, 13, 4, 12, 5, 11, 6]
out = transpile(circ, initial_layout=lay, coupling_map=cmap, routing_method="stochastic")
out_dag = circuit_to_dag(out)
meas_nodes = out_dag.named_nodes("measure")
for meas_node in meas_nodes:
is_last_measure = all(
isinstance(after_measure, DAGOutNode)
for after_measure in out_dag.quantum_successors(meas_node)
)
self.assertTrue(is_last_measure)
@data(0, 1, 2, 3)
def test_init_resets_kept_preset_passmanagers(self, optimization_level):
"""Test initial resets kept at all preset transpilation levels"""
num_qubits = 5
qc = QuantumCircuit(num_qubits)
qc.reset(range(num_qubits))
num_resets = transpile(qc, optimization_level=optimization_level).count_ops()["reset"]
self.assertEqual(num_resets, num_qubits)
@data(0, 1, 2, 3)
def test_initialize_reset_is_not_removed(self, optimization_level):
"""The reset in front of initializer should NOT be removed at beginning"""
qr = QuantumRegister(1, "qr")
qc = QuantumCircuit(qr)
qc.initialize([1.0 / math.sqrt(2), 1.0 / math.sqrt(2)], [qr[0]])
qc.initialize([1.0 / math.sqrt(2), -1.0 / math.sqrt(2)], [qr[0]])
after = transpile(qc, basis_gates=["reset", "u3"], optimization_level=optimization_level)
self.assertEqual(after.count_ops()["reset"], 2, msg=f"{after}\n does not have 2 resets.")
def test_initialize_FakeMelbourne(self):
"""Test that the zero-state resets are remove in a device not supporting them."""
desired_vector = [1 / math.sqrt(2), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(2)]
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2]])
out = transpile(qc, backend=FakeMelbourne())
out_dag = circuit_to_dag(out)
reset_nodes = out_dag.named_nodes("reset")
self.assertEqual(len(reset_nodes), 3)
def test_non_standard_basis(self):
"""Test a transpilation with a non-standard basis"""
qr1 = QuantumRegister(1, "q1")
qr2 = QuantumRegister(2, "q2")
qr3 = QuantumRegister(3, "q3")
qc = QuantumCircuit(qr1, qr2, qr3)
qc.h(qr1[0])
qc.h(qr2[1])
qc.h(qr3[2])
layout = [4, 5, 6, 8, 9, 10]
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],
]
circuit = transpile(
qc, backend=None, coupling_map=cmap, basis_gates=["h"], initial_layout=layout
)
dag_circuit = circuit_to_dag(circuit)
resources_after = dag_circuit.count_ops()
self.assertEqual({"h": 3}, resources_after)
def test_hadamard_to_rot_gates(self):
"""Test a transpilation from H to Rx, Ry gates"""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.h(0)
expected = QuantumCircuit(qr, global_phase=np.pi / 2)
expected.append(RYGate(theta=np.pi / 2), [0])
expected.append(RXGate(theta=np.pi), [0])
circuit = transpile(qc, basis_gates=["rx", "ry"], optimization_level=0)
self.assertEqual(circuit, expected)
def test_basis_subset(self):
"""Test a transpilation with a basis subset of the standard basis"""
qr = QuantumRegister(1, "q1")
qc = QuantumCircuit(qr)
qc.h(qr[0])
qc.x(qr[0])
qc.t(qr[0])
layout = [4]
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],
]
circuit = transpile(
qc, backend=None, coupling_map=cmap, basis_gates=["u3"], initial_layout=layout
)
dag_circuit = circuit_to_dag(circuit)
resources_after = dag_circuit.count_ops()
self.assertEqual({"u3": 1}, resources_after)
def test_check_circuit_width(self):
"""Verify transpilation of circuit with virtual qubits greater than
physical qubits raises error"""
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],
]
qc = QuantumCircuit(15, 15)
with self.assertRaises(TranspilerError):
transpile(qc, coupling_map=cmap)
@data(0, 1, 2, 3)
def test_ccx_routing_method_none(self, optimization_level):
"""CCX without routing method."""
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.cx(1, 2)
out = transpile(
qc,
routing_method="none",
basis_gates=["u", "cx"],
initial_layout=[0, 1, 2],
seed_transpiler=0,
coupling_map=[[0, 1], [1, 2]],
optimization_level=optimization_level,
)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_ccx_routing_method_none_failed(self, optimization_level):
"""CCX without routing method cannot be routed."""
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
with self.assertRaises(TranspilerError):
transpile(
qc,
routing_method="none",
basis_gates=["u", "cx"],
initial_layout=[0, 1, 2],
seed_transpiler=0,
coupling_map=[[0, 1], [1, 2]],
optimization_level=optimization_level,
)
@data(0, 1, 2, 3)
def test_ms_unrolls_to_cx(self, optimization_level):
"""Verify a Rx,Ry,Rxx circuit transpile to a U3,CX target."""
qc = QuantumCircuit(2)
qc.rx(math.pi / 2, 0)
qc.ry(math.pi / 4, 1)
qc.rxx(math.pi / 4, 0, 1)
out = transpile(qc, basis_gates=["u3", "cx"], optimization_level=optimization_level)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_ms_can_target_ms(self, optimization_level):
"""Verify a Rx,Ry,Rxx circuit can transpile to an Rx,Ry,Rxx target."""
qc = QuantumCircuit(2)
qc.rx(math.pi / 2, 0)
qc.ry(math.pi / 4, 1)
qc.rxx(math.pi / 4, 0, 1)
out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_cx_can_target_ms(self, optimization_level):
"""Verify a U3,CX circuit can transpiler to a Rx,Ry,Rxx target."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.rz(math.pi / 4, [0, 1])
out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_measure_doesnt_unroll_ms(self, optimization_level):
"""Verify a measure doesn't cause an Rx,Ry,Rxx circuit to unroll to U3,CX."""
qc = QuantumCircuit(2, 2)
qc.rx(math.pi / 2, 0)
qc.ry(math.pi / 4, 1)
qc.rxx(math.pi / 4, 0, 1)
qc.measure([0, 1], [0, 1])
out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level)
self.assertEqual(qc, out)
@data(
["cx", "u3"],
["cz", "u3"],
["cz", "rx", "rz"],
["rxx", "rx", "ry"],
["iswap", "rx", "rz"],
)
def test_block_collection_runs_for_non_cx_bases(self, basis_gates):
"""Verify block collection is run when a single two qubit gate is in the basis."""
twoq_gate, *_ = basis_gates
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.cx(1, 0)
qc.cx(0, 1)
qc.cx(0, 1)
out = transpile(qc, basis_gates=basis_gates, optimization_level=3)
self.assertLessEqual(out.count_ops()[twoq_gate], 2)
@unpack
@data(
(["u3", "cx"], {"u3": 1, "cx": 1}),
(["rx", "rz", "iswap"], {"rx": 6, "rz": 12, "iswap": 2}),
(["rx", "ry", "rxx"], {"rx": 6, "ry": 5, "rxx": 1}),
)
def test_block_collection_reduces_1q_gate(self, basis_gates, gate_counts):
"""For synthesis to non-U3 bases, verify we minimize 1q gates."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
out = transpile(qc, basis_gates=basis_gates, optimization_level=3)
self.assertTrue(Operator(out).equiv(qc))
self.assertTrue(set(out.count_ops()).issubset(basis_gates))
for basis_gate in basis_gates:
self.assertLessEqual(out.count_ops()[basis_gate], gate_counts[basis_gate])
@combine(
optimization_level=[0, 1, 2, 3],
basis_gates=[
["u3", "cx"],
["rx", "rz", "iswap"],
["rx", "ry", "rxx"],
],
)
def test_translation_method_synthesis(self, optimization_level, basis_gates):
"""Verify translation_method='synthesis' gets to the basis."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
out = transpile(
qc,
translation_method="synthesis",
basis_gates=basis_gates,
optimization_level=optimization_level,
)
self.assertTrue(Operator(out).equiv(qc))
self.assertTrue(set(out.count_ops()).issubset(basis_gates))
def test_transpiled_custom_gates_calibration(self):
"""Test if transpiled calibrations is equal to custom gates circuit calibrations."""
custom_180 = Gate("mycustom", 1, [3.14])
custom_90 = Gate("mycustom", 1, [1.57])
circ = QuantumCircuit(2)
circ.append(custom_180, [0])
circ.append(custom_90, [1])
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
with pulse.build() as q1_y90:
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), pulse.DriveChannel(1))
# Add calibration
circ.add_calibration(custom_180, [0], q0_x180)
circ.add_calibration(custom_90, [1], q1_y90)
backend = FakeBoeblingen()
transpiled_circuit = transpile(
circ,
backend=backend,
layout_method="trivial",
)
self.assertEqual(transpiled_circuit.calibrations, circ.calibrations)
self.assertEqual(list(transpiled_circuit.count_ops().keys()), ["mycustom"])
self.assertEqual(list(transpiled_circuit.count_ops().values()), [2])
def test_transpiled_basis_gates_calibrations(self):
"""Test if the transpiled calibrations is equal to basis gates circuit calibrations."""
circ = QuantumCircuit(2)
circ.h(0)
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
# Add calibration
circ.add_calibration("h", [0], q0_x180)
backend = FakeBoeblingen()
transpiled_circuit = transpile(
circ,
backend=backend,
)
self.assertEqual(transpiled_circuit.calibrations, circ.calibrations)
def test_transpile_calibrated_custom_gate_on_diff_qubit(self):
"""Test if the custom, non calibrated gate raises QiskitError."""
custom_180 = Gate("mycustom", 1, [3.14])
circ = QuantumCircuit(2)
circ.append(custom_180, [0])
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
# Add calibration
circ.add_calibration(custom_180, [1], q0_x180)
backend = FakeBoeblingen()
with self.assertRaises(QiskitError):
transpile(circ, backend=backend, layout_method="trivial")
def test_transpile_calibrated_nonbasis_gate_on_diff_qubit(self):
"""Test if the non-basis gates are transpiled if they are on different qubit that
is not calibrated."""
circ = QuantumCircuit(2)
circ.h(0)
circ.h(1)
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
# Add calibration
circ.add_calibration("h", [1], q0_x180)
backend = FakeBoeblingen()
transpiled_circuit = transpile(
circ,
backend=backend,
)
self.assertEqual(transpiled_circuit.calibrations, circ.calibrations)
self.assertEqual(set(transpiled_circuit.count_ops().keys()), {"u2", "h"})
def test_transpile_subset_of_calibrated_gates(self):
"""Test transpiling a circuit with both basis gate (not-calibrated) and
a calibrated gate on different qubits."""
x_180 = Gate("mycustom", 1, [3.14])
circ = QuantumCircuit(2)
circ.h(0)
circ.append(x_180, [0])
circ.h(1)
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
circ.add_calibration(x_180, [0], q0_x180)
circ.add_calibration("h", [1], q0_x180) # 'h' is calibrated on qubit 1
transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial")
self.assertEqual(set(transpiled_circ.count_ops().keys()), {"u2", "mycustom", "h"})
def test_parameterized_calibrations_transpile(self):
"""Check that gates can be matched to their calibrations before and after parameter
assignment."""
tau = Parameter("tau")
circ = QuantumCircuit(3, 3)
circ.append(Gate("rxt", 1, [2 * 3.14 * tau]), [0])
def q0_rxt(tau):
with pulse.build() as q0_rxt:
pulse.play(pulse.library.Gaussian(20, 0.4 * tau, 3.0), pulse.DriveChannel(0))
return q0_rxt
circ.add_calibration("rxt", [0], q0_rxt(tau), [2 * 3.14 * tau])
transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial")
self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"})
circ = circ.assign_parameters({tau: 1})
transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial")
self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"})
def test_inst_durations_from_calibrations(self):
"""Test that circuit calibrations can be used instead of explicitly
supplying inst_durations.
"""
qc = QuantumCircuit(2)
qc.append(Gate("custom", 1, []), [0])
with pulse.build() as cal:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
qc.add_calibration("custom", [0], cal)
out = transpile(qc, scheduling_method="alap")
self.assertEqual(out.duration, cal.duration)
@data(0, 1, 2, 3)
def test_multiqubit_gates_calibrations(self, opt_level):
"""Test multiqubit gate > 2q with calibrations works
Adapted from issue description in https://github.com/Qiskit/qiskit-terra/issues/6572
"""
circ = QuantumCircuit(5)
custom_gate = Gate("my_custom_gate", 5, [])
circ.append(custom_gate, [0, 1, 2, 3, 4])
circ.measure_all()
backend = FakeBoeblingen()
with pulse.build(backend, name="custom") as my_schedule:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(1)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(2)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(3)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(4)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(1)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(2)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(3)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(4)
)
circ.add_calibration("my_custom_gate", [0, 1, 2, 3, 4], my_schedule, [])
trans_circ = transpile(circ, backend, optimization_level=opt_level, layout_method="trivial")
self.assertEqual({"measure": 5, "my_custom_gate": 1, "barrier": 1}, trans_circ.count_ops())
@data(0, 1, 2, 3)
def test_circuit_with_delay(self, optimization_level):
"""Verify a circuit with delay can transpile to a scheduled circuit."""
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(500, 1)
qc.cx(0, 1)
out = transpile(
qc,
scheduling_method="alap",
basis_gates=["h", "cx"],
instruction_durations=[("h", 0, 200), ("cx", [0, 1], 700)],
optimization_level=optimization_level,
)
self.assertEqual(out.duration, 1200)
def test_delay_converts_to_dt(self):
"""Test that a delay instruction is converted to units of dt given a backend."""
qc = QuantumCircuit(2)
qc.delay(1000, [0], unit="us")
backend = FakeRueschlikon()
backend.configuration().dt = 0.5e-6
out = transpile([qc, qc], backend)
self.assertEqual(out[0].data[0].operation.unit, "dt")
self.assertEqual(out[1].data[0].operation.unit, "dt")
out = transpile(qc, dt=1e-9)
self.assertEqual(out.data[0].operation.unit, "dt")
def test_scheduling_backend_v2(self):
"""Test that scheduling method works with Backendv2."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = FakeMumbaiV2()
out = transpile([qc, qc], backend, scheduling_method="alap")
self.assertIn("delay", out[0].count_ops())
self.assertIn("delay", out[1].count_ops())
@data(1, 2, 3)
def test_no_infinite_loop(self, optimization_level):
"""Verify circuit cost always descends and optimization does not flip flop indefinitely."""
qc = QuantumCircuit(1)
qc.ry(0.2, 0)
out = transpile(
qc, basis_gates=["id", "p", "sx", "cx"], optimization_level=optimization_level
)
# Expect a -pi/2 global phase for the U3 to RZ/SX conversion, and
# a -0.5 * theta phase for RZ to P twice, once at theta, and once at 3 pi
# for the second and third RZ gates in the U3 decomposition.
expected = QuantumCircuit(
1, global_phase=-np.pi / 2 - 0.5 * (-0.2 + np.pi) - 0.5 * 3 * np.pi
)
expected.p(-np.pi, 0)
expected.sx(0)
expected.p(np.pi - 0.2, 0)
expected.sx(0)
error_message = (
f"\nOutput circuit:\n{out!s}\n{Operator(out).data}\n"
f"Expected circuit:\n{expected!s}\n{Operator(expected).data}"
)
self.assertEqual(out, expected, error_message)
@data(0, 1, 2, 3)
def test_transpile_preserves_circuit_metadata(self, optimization_level):
"""Verify that transpile preserves circuit metadata in the output."""
circuit = QuantumCircuit(2, metadata={"experiment_id": "1234", "execution_number": 4})
circuit.h(0)
circuit.cx(0, 1)
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],
]
res = transpile(
circuit,
basis_gates=["id", "p", "sx", "cx"],
coupling_map=cmap,
optimization_level=optimization_level,
)
self.assertEqual(circuit.metadata, res.metadata)
@data(0, 1, 2, 3)
def test_transpile_optional_registers(self, optimization_level):
"""Verify transpile accepts circuits without registers end-to-end."""
qubits = [Qubit() for _ in range(3)]
clbits = [Clbit() for _ in range(3)]
qc = QuantumCircuit(qubits, clbits)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 2)
qc.measure(qubits, clbits)
out = transpile(qc, FakeBoeblingen(), optimization_level=optimization_level)
self.assertEqual(len(out.qubits), FakeBoeblingen().configuration().num_qubits)
self.assertEqual(len(out.clbits), len(clbits))
@data(0, 1, 2, 3)
def test_translate_ecr_basis(self, optimization_level):
"""Verify that rewriting in ECR basis is efficient."""
circuit = QuantumCircuit(2)
circuit.append(random_unitary(4, seed=1), [0, 1])
circuit.barrier()
circuit.cx(0, 1)
circuit.barrier()
circuit.swap(0, 1)
circuit.barrier()
circuit.iswap(0, 1)
res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=optimization_level)
self.assertEqual(res.count_ops()["ecr"], 9)
self.assertTrue(Operator(res).equiv(circuit))
def test_optimize_ecr_basis(self):
"""Test highest optimization level can optimize over ECR."""
circuit = QuantumCircuit(2)
circuit.swap(1, 0)
circuit.iswap(0, 1)
res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=3)
self.assertEqual(res.count_ops()["ecr"], 1)
self.assertTrue(Operator(res).equiv(circuit))
def test_approximation_degree_invalid(self):
"""Test invalid approximation degree raises."""
circuit = QuantumCircuit(2)
circuit.swap(0, 1)
with self.assertRaises(QiskitError):
transpile(circuit, basis_gates=["u", "cz"], approximation_degree=1.1)
def test_approximation_degree(self):
"""Test more approximation gives lower-cost circuit."""
circuit = QuantumCircuit(2)
circuit.swap(0, 1)
circuit.h(0)
circ_10 = transpile(
circuit,
basis_gates=["u", "cx"],
translation_method="synthesis",
approximation_degree=0.1,
)
circ_90 = transpile(
circuit,
basis_gates=["u", "cx"],
translation_method="synthesis",
approximation_degree=0.9,
)
self.assertLess(circ_10.depth(), circ_90.depth())
@data(0, 1, 2, 3)
def test_synthesis_translation_method_with_single_qubit_gates(self, optimization_level):
"""Test that synthesis basis translation works for solely 1q circuit"""
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.h(2)
res = transpile(
qc,
basis_gates=["id", "rz", "x", "sx", "cx"],
translation_method="synthesis",
optimization_level=optimization_level,
)
expected = QuantumCircuit(3, global_phase=3 * np.pi / 4)
expected.rz(np.pi / 2, 0)
expected.rz(np.pi / 2, 1)
expected.rz(np.pi / 2, 2)
expected.sx(0)
expected.sx(1)
expected.sx(2)
expected.rz(np.pi / 2, 0)
expected.rz(np.pi / 2, 1)
expected.rz(np.pi / 2, 2)
self.assertEqual(res, expected)
@data(0, 1, 2, 3)
def test_synthesis_translation_method_with_gates_outside_basis(self, optimization_level):
"""Test that synthesis translation works for circuits with single gates outside bassis"""
qc = QuantumCircuit(2)
qc.swap(0, 1)
res = transpile(
qc,
basis_gates=["id", "rz", "x", "sx", "cx"],
translation_method="synthesis",
optimization_level=optimization_level,
)
if optimization_level != 3:
self.assertTrue(Operator(qc).equiv(res))
self.assertNotIn("swap", res.count_ops())
else:
# Optimization level 3 eliminates the pointless swap
self.assertEqual(res, QuantumCircuit(2))
@data(0, 1, 2, 3)
def test_target_ideal_gates(self, opt_level):
"""Test that transpile() with a custom ideal sim target works."""
theta = Parameter("θ")
phi = Parameter("ϕ")
lam = Parameter("λ")
target = Target(num_qubits=2)
target.add_instruction(UGate(theta, phi, lam), {(0,): None, (1,): None})
target.add_instruction(CXGate(), {(0, 1): None})
target.add_instruction(Measure(), {(0,): None, (1,): None})
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])
result = transpile(qc, target=target, optimization_level=opt_level)
self.assertEqual(Operator.from_circuit(result), Operator.from_circuit(qc))
@data(0, 1, 2, 3)
def test_transpile_with_custom_control_flow_target(self, opt_level):
"""Test transpile() with a target and constrol flow ops."""
target = FakeMumbaiV2().target
target.add_instruction(ForLoopOp, name="for_loop")
target.add_instruction(WhileLoopOp, name="while_loop")
target.add_instruction(IfElseOp, name="if_else")
target.add_instruction(SwitchCaseOp, name="switch_case")
circuit = QuantumCircuit(6, 1)
circuit.h(0)
circuit.measure(0, 0)
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with circuit.for_loop((1,)):
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with else_:
circuit.cx(3, 4)
circuit.cz(3, 5)
circuit.append(CustomCX(), [4, 5], [])
with circuit.while_loop((circuit.clbits[0], True)):
circuit.cx(3, 4)
circuit.cz(3, 5)
circuit.append(CustomCX(), [4, 5], [])
with circuit.switch(circuit.cregs[0]) as case_:
with case_(0):
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with case_(1):
circuit.cx(1, 2)
circuit.cz(1, 3)
circuit.append(CustomCX(), [2, 3], [])
transpiled = transpile(
circuit, optimization_level=opt_level, target=target, seed_transpiler=12434
)
# Tests of the complete validity of a circuit are mostly done at the indiviual pass level;
# here we're just checking that various passes do appear to have run.
self.assertIsInstance(transpiled, QuantumCircuit)
# Assert layout ran.
self.assertIsNot(getattr(transpiled, "_layout", None), None)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(target.instruction_supported(instruction.operation.name, qargs))
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
# Assert unrolling ran.
self.assertNotIsInstance(instruction.operation, CustomCX)
# Assert translation ran.
self.assertNotIsInstance(instruction.operation, CZGate)
# Assert routing ran.
_visit_block(
transpiled,
qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)},
)
@data(1, 2, 3)
def test_transpile_identity_circuit_no_target(self, opt_level):
"""Test circuit equivalent to identity is optimized away for all optimization levels >0.
Reproduce taken from https://github.com/Qiskit/qiskit-terra/issues/9217
"""
qr1 = QuantumRegister(3, "state")
qr2 = QuantumRegister(2, "ancilla")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr1, qr2, cr)
qc.h(qr1[0])
qc.cx(qr1[0], qr1[1])
qc.cx(qr1[1], qr1[2])
qc.cx(qr1[1], qr1[2])
qc.cx(qr1[0], qr1[1])
qc.h(qr1[0])
empty_qc = QuantumCircuit(qr1, qr2, cr)
result = transpile(qc, optimization_level=opt_level)
self.assertEqual(empty_qc, result)
@data(0, 1, 2, 3)
def test_initial_layout_with_loose_qubits(self, opt_level):
"""Regression test of gh-10125."""
qc = QuantumCircuit([Qubit(), Qubit()])
qc.cx(0, 1)
transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level)
self.assertIsNotNone(transpiled.layout)
self.assertEqual(
transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]})
)
@data(0, 1, 2, 3)
def test_initial_layout_with_overlapping_qubits(self, opt_level):
"""Regression test of gh-10125."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(bits=qr1[:])
qc = QuantumCircuit(qr1, qr2)
qc.cx(0, 1)
transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level)
self.assertIsNotNone(transpiled.layout)
self.assertEqual(
transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]})
)
@combine(opt_level=[0, 1, 2, 3], basis=[["rz", "x"], ["rx", "z"], ["rz", "y"], ["ry", "x"]])
def test_paulis_to_constrained_1q_basis(self, opt_level, basis):
"""Test that Pauli-gate circuits can be transpiled to constrained 1q bases that do not
contain any root-Pauli gates."""
qc = QuantumCircuit(1)
qc.x(0)
qc.barrier()
qc.y(0)
qc.barrier()
qc.z(0)
transpiled = transpile(qc, basis_gates=basis, optimization_level=opt_level)
self.assertGreaterEqual(set(basis) | {"barrier"}, transpiled.count_ops().keys())
self.assertEqual(Operator(qc), Operator(transpiled))
@ddt
class TestPostTranspileIntegration(QiskitTestCase):
"""Test that the output of `transpile` is usable in various other integration contexts."""
def _regular_circuit(self):
a = Parameter("a")
regs = [
QuantumRegister(2, name="q0"),
QuantumRegister(3, name="q1"),
ClassicalRegister(2, name="c0"),
]
bits = [Qubit(), Qubit(), Clbit()]
base = QuantumCircuit(*regs, bits)
base.h(0)
base.measure(0, 0)
base.cx(0, 1)
base.cz(0, 2)
base.cz(0, 3)
base.cz(1, 4)
base.cx(1, 5)
base.measure(1, 1)
base.append(CustomCX(), [3, 6])
base.append(CustomCX(), [5, 4])
base.append(CustomCX(), [5, 3])
base.append(CustomCX(), [2, 4]).c_if(base.cregs[0], 3)
base.ry(a, 4)
base.measure(4, 2)
return base
def _control_flow_circuit(self):
a = Parameter("a")
regs = [
QuantumRegister(2, name="q0"),
QuantumRegister(3, name="q1"),
ClassicalRegister(2, name="c0"),
]
bits = [Qubit(), Qubit(), Clbit()]
base = QuantumCircuit(*regs, bits)
base.h(0)
base.measure(0, 0)
with base.if_test((base.cregs[0], 1)) as else_:
base.cx(0, 1)
base.cz(0, 2)
base.cz(0, 3)
with else_:
base.cz(1, 4)
with base.for_loop((1, 2)):
base.cx(1, 5)
base.measure(2, 2)
with base.while_loop((2, False)):
base.append(CustomCX(), [3, 6])
base.append(CustomCX(), [5, 4])
base.append(CustomCX(), [5, 3])
base.append(CustomCX(), [2, 4])
base.ry(a, 4)
base.measure(4, 2)
with base.switch(base.cregs[0]) as case_:
with case_(0, 1):
base.cz(3, 5)
with case_(case_.DEFAULT):
base.cz(1, 4)
base.append(CustomCX(), [2, 4])
base.append(CustomCX(), [3, 4])
return base
def _control_flow_expr_circuit(self):
a = Parameter("a")
regs = [
QuantumRegister(2, name="q0"),
QuantumRegister(3, name="q1"),
ClassicalRegister(2, name="c0"),
]
bits = [Qubit(), Qubit(), Clbit()]
base = QuantumCircuit(*regs, bits)
base.h(0)
base.measure(0, 0)
with base.if_test(expr.equal(base.cregs[0], 1)) as else_:
base.cx(0, 1)
base.cz(0, 2)
base.cz(0, 3)
with else_:
base.cz(1, 4)
with base.for_loop((1, 2)):
base.cx(1, 5)
base.measure(2, 2)
with base.while_loop(expr.logic_not(bits[2])):
base.append(CustomCX(), [3, 6])
base.append(CustomCX(), [5, 4])
base.append(CustomCX(), [5, 3])
base.append(CustomCX(), [2, 4])
base.ry(a, 4)
base.measure(4, 2)
with base.switch(expr.bit_and(base.cregs[0], 2)) as case_:
with case_(0, 1):
base.cz(3, 5)
with case_(case_.DEFAULT):
base.cz(1, 4)
base.append(CustomCX(), [2, 4])
base.append(CustomCX(), [3, 4])
return base
@data(0, 1, 2, 3)
def test_qpy_roundtrip(self, optimization_level):
"""Test that the output of a transpiled circuit can be round-tripped through QPY."""
transpiled = transpile(
self._regular_circuit(),
backend=FakeMelbourne(),
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_backendv2(self, optimization_level):
"""Test that the output of a transpiled circuit can be round-tripped through QPY."""
transpiled = transpile(
self._regular_circuit(),
backend=FakeMumbaiV2(),
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow can be round-tripped
through QPY."""
if optimization_level == 3 and sys.platform == "win32":
self.skipTest(
"This test case triggers a bug in the eigensolver routine on windows. "
"See #10345 for more details."
)
backend = FakeMelbourne()
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
basis_gates=backend.configuration().basis_gates
+ ["if_else", "for_loop", "while_loop", "switch_case"],
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow_backendv2(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow can be round-tripped
through QPY."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow_expr(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow including `Expr` nodes can
be round-tripped through QPY."""
if optimization_level == 3 and sys.platform == "win32":
self.skipTest(
"This test case triggers a bug in the eigensolver routine on windows. "
"See #10345 for more details."
)
backend = FakeMelbourne()
transpiled = transpile(
self._control_flow_expr_circuit(),
backend=backend,
basis_gates=backend.configuration().basis_gates
+ ["if_else", "for_loop", "while_loop", "switch_case"],
optimization_level=optimization_level,
seed_transpiler=2023_07_26,
)
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow_expr_backendv2(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow including `Expr` nodes can
be round-tripped through QPY."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2023_07_26,
)
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qasm3_output(self, optimization_level):
"""Test that the output of a transpiled circuit can be dumped into OpenQASM 3."""
transpiled = transpile(
self._regular_circuit(),
backend=FakeMelbourne(),
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# TODO: There's not a huge amount we can sensibly test for the output here until we can
# round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump
# itself doesn't throw an error, though.
self.assertIsInstance(qasm3.dumps(transpiled).strip(), str)
@data(0, 1, 2, 3)
def test_qasm3_output_control_flow(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow can be dumped into
OpenQASM 3."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# TODO: There's not a huge amount we can sensibly test for the output here until we can
# round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump
# itself doesn't throw an error, though.
self.assertIsInstance(
qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(),
str,
)
@data(0, 1, 2, 3)
def test_qasm3_output_control_flow_expr(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow and `Expr` nodes can be
dumped into OpenQASM 3."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2023_07_26,
)
# TODO: There's not a huge amount we can sensibly test for the output here until we can
# round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump
# itself doesn't throw an error, though.
self.assertIsInstance(
qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(),
str,
)
@data(0, 1, 2, 3)
def test_transpile_target_no_measurement_error(self, opt_level):
"""Test that transpile with a target which contains ideal measurement works
Reproduce from https://github.com/Qiskit/qiskit-terra/issues/8969
"""
target = Target()
target.add_instruction(Measure(), {(0,): None})
qc = QuantumCircuit(1, 1)
qc.measure(0, 0)
res = transpile(qc, target=target, optimization_level=opt_level)
self.assertEqual(qc, res)
def test_transpile_final_layout_updated_with_post_layout(self):
"""Test that the final layout is correctly set when vf2postlayout runs.
Reproduce from #10457
"""
def _get_index_layout(transpiled_circuit: QuantumCircuit, num_source_qubits: int):
"""Return the index layout of a transpiled circuit"""
layout = transpiled_circuit.layout
if layout is None:
return list(range(num_source_qubits))
pos_to_virt = {v: k for k, v in layout.input_qubit_mapping.items()}
qubit_indices = []
for index in range(num_source_qubits):
qubit_idx = layout.initial_layout[pos_to_virt[index]]
if layout.final_layout is not None:
qubit_idx = layout.final_layout[transpiled_circuit.qubits[qubit_idx]]
qubit_indices.append(qubit_idx)
return qubit_indices
vf2_post_layout_called = False
def callback(**kwargs):
nonlocal vf2_post_layout_called
if isinstance(kwargs["pass_"], VF2PostLayout):
vf2_post_layout_called = True
self.assertIsNotNone(kwargs["property_set"]["post_layout"])
backend = FakeVigo()
qubits = 3
qc = QuantumCircuit(qubits)
for i in range(5):
qc.cx(i % qubits, int(i + qubits / 2) % qubits)
tqc = transpile(qc, backend=backend, seed_transpiler=4242, callback=callback)
self.assertTrue(vf2_post_layout_called)
self.assertEqual([3, 2, 1], _get_index_layout(tqc, qubits))
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestLogTranspile(QiskitTestCase):
"""Testing the log_transpile option."""
def setUp(self):
super().setUp()
logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)
logger.setLevel("DEBUG")
self.output = io.StringIO()
logger.addHandler(StreamHandlerRaiseException(self.output))
self.circuit = QuantumCircuit(QuantumRegister(1))
def assertTranspileLog(self, log_msg):
"""Runs the transpiler and check for logs containing specified message"""
transpile(self.circuit)
self.output.seek(0)
# Filter unrelated log lines
output_lines = self.output.readlines()
transpile_log_lines = [x for x in output_lines if log_msg in x]
self.assertTrue(len(transpile_log_lines) > 0)
def test_transpile_log_time(self):
"""Check Total Transpile Time is logged"""
self.assertTranspileLog("Total Transpile Time")
class TestTranspileCustomPM(QiskitTestCase):
"""Test transpile function with custom pass manager"""
def test_custom_multiple_circuits(self):
"""Test transpiling with custom pass manager and multiple circuits.
This tests created a deadlock, so it needs to be monitored for timeout.
See: https://github.com/Qiskit/qiskit-terra/issues/3925
"""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
pm_conf = PassManagerConfig(
initial_layout=None,
basis_gates=["u1", "u2", "u3", "cx"],
coupling_map=CouplingMap([[0, 1]]),
backend_properties=None,
seed_transpiler=1,
)
passmanager = level_0_pass_manager(pm_conf)
transpiled = passmanager.run([qc, qc])
expected = QuantumCircuit(QuantumRegister(2, "q"))
expected.append(U2Gate(0, 3.141592653589793), [0])
expected.cx(0, 1)
self.assertEqual(len(transpiled), 2)
self.assertEqual(transpiled[0], expected)
self.assertEqual(transpiled[1], expected)
@ddt
class TestTranspileParallel(QiskitTestCase):
"""Test transpile() in parallel."""
def setUp(self):
super().setUp()
# Force parallel execution to True to test multiprocessing for this class
original_val = parallel.PARALLEL_DEFAULT
def restore_default():
parallel.PARALLEL_DEFAULT = original_val
self.addCleanup(restore_default)
parallel.PARALLEL_DEFAULT = True
@data(0, 1, 2, 3)
def test_parallel_multiprocessing(self, opt_level):
"""Test parallel dispatch works with multiprocessing."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = FakeMumbaiV2()
pm = generate_preset_pass_manager(opt_level, backend)
res = pm.run([qc, qc])
for circ in res:
self.assertIsInstance(circ, QuantumCircuit)
@data(0, 1, 2, 3)
def test_parallel_with_target(self, opt_level):
"""Test that parallel dispatch works with a manual target."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
target = FakeMumbaiV2().target
res = transpile([qc] * 3, target=target, optimization_level=opt_level)
self.assertIsInstance(res, list)
for circ in res:
self.assertIsInstance(circ, QuantumCircuit)
@data(0, 1, 2, 3)
def test_parallel_dispatch(self, opt_level):
"""Test that transpile in parallel works for all optimization levels."""
backend = FakeRueschlikon()
qr = QuantumRegister(16)
cr = ClassicalRegister(16)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
for k in range(1, 15):
qc.cx(qr[0], qr[k])
qc.measure(qr, cr)
qlist = [qc for k in range(15)]
tqc = transpile(
qlist, backend=backend, optimization_level=opt_level, seed_transpiler=424242
)
result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result()
counts = result.get_counts()
for count in counts:
self.assertTrue(math.isclose(count["0000000000000000"], 500, rel_tol=0.1))
self.assertTrue(math.isclose(count["0111111111111111"], 500, rel_tol=0.1))
def test_parallel_dispatch_lazy_cal_loading(self):
"""Test adding calibration by lazy loading in parallel environment."""
class TestAddCalibration(TransformationPass):
"""A fake pass to test lazy pulse qobj loading in parallel environment."""
def __init__(self, target):
"""Instantiate with target."""
super().__init__()
self.target = target
def run(self, dag):
"""Run test pass that adds calibration of SX gate of qubit 0."""
dag.add_calibration(
"sx",
qubits=(0,),
schedule=self.target["sx"][(0,)].calibration, # PulseQobj is parsed here
)
return dag
backend = FakeMumbaiV2()
# This target has PulseQobj entries that provides a serialized schedule data
pass_ = TestAddCalibration(backend.target)
pm = PassManager(passes=[pass_])
self.assertIsNone(backend.target["sx"][(0,)]._calibration._definition)
qc = QuantumCircuit(1)
qc.sx(0)
qc_copied = [qc for _ in range(10)]
qcs_cal_added = pm.run(qc_copied)
ref_cal = backend.target["sx"][(0,)].calibration
for qc_test in qcs_cal_added:
added_cal = qc_test.calibrations["sx"][((0,), ())]
self.assertEqual(added_cal, ref_cal)
@data(0, 1, 2, 3)
def test_backendv2_and_basis_gates(self, opt_level):
"""Test transpile() with BackendV2 and basis_gates set."""
backend = FakeNairobiV2()
qc = QuantumCircuit(5)
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.cz(0, 3)
qc.cz(0, 4)
qc.measure_all()
tqc = transpile(
qc,
backend=backend,
basis_gates=["u", "cz"],
optimization_level=opt_level,
seed_transpiler=12345678942,
)
op_count = set(tqc.count_ops())
self.assertEqual({"u", "cz", "measure", "barrier"}, op_count)
for inst in tqc.data:
if inst.operation.name not in {"u", "cz"}:
continue
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
self.assertIn(qubits, backend.target.qargs)
@data(0, 1, 2, 3)
def test_backendv2_and_coupling_map(self, opt_level):
"""Test transpile() with custom coupling map."""
backend = FakeNairobiV2()
qc = QuantumCircuit(5)
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.cz(0, 3)
qc.cz(0, 4)
qc.measure_all()
cmap = CouplingMap.from_line(5, bidirectional=False)
tqc = transpile(
qc,
backend=backend,
coupling_map=cmap,
optimization_level=opt_level,
seed_transpiler=12345678942,
)
op_count = set(tqc.count_ops())
self.assertTrue({"rz", "sx", "x", "cx", "measure", "barrier"}.issuperset(op_count))
for inst in tqc.data:
if len(inst.qubits) == 2:
qubit_0 = tqc.find_bit(inst.qubits[0]).index
qubit_1 = tqc.find_bit(inst.qubits[1]).index
self.assertEqual(qubit_1, qubit_0 + 1)
def test_transpile_with_multiple_coupling_maps(self):
"""Test passing a different coupling map for every circuit"""
backend = FakeNairobiV2()
qc = QuantumCircuit(3)
qc.cx(0, 2)
# Add a connection between 0 and 2 so that transpile does not change
# the gates
cmap = CouplingMap.from_line(7)
cmap.add_edge(0, 2)
with self.assertRaisesRegex(TranspilerError, "Only a single input coupling"):
# Initial layout needed to prevent transpiler from relabeling
# qubits to avoid doing the swap
transpile(
[qc] * 2,
backend,
coupling_map=[backend.coupling_map, cmap],
initial_layout=(0, 1, 2),
)
@data(0, 1, 2, 3)
def test_backend_and_custom_gate(self, opt_level):
"""Test transpile() with BackendV2, custom basis pulse gate."""
backend = FakeNairobiV2()
inst_map = InstructionScheduleMap()
inst_map.add("newgate", [0, 1], pulse.ScheduleBlock())
newgate = Gate("newgate", 2, [])
circ = QuantumCircuit(2)
circ.append(newgate, [0, 1])
tqc = transpile(
circ, backend, inst_map=inst_map, basis_gates=["newgate"], optimization_level=opt_level
)
self.assertEqual(len(tqc.data), 1)
self.assertEqual(tqc.data[0].operation, newgate)
qubits = tuple(tqc.find_bit(x).index for x in tqc.data[0].qubits)
self.assertIn(qubits, backend.target.qargs)
@ddt
class TestTranspileMultiChipTarget(QiskitTestCase):
"""Test transpile() with a disjoint coupling map."""
def setUp(self):
super().setUp()
class FakeMultiChip(BackendV2):
"""Fake multi chip backend."""
def __init__(self):
super().__init__()
graph = rx.generators.directed_heavy_hex_graph(3)
num_qubits = len(graph) * 3
rng = np.random.default_rng(seed=12345678942)
rz_props = {}
x_props = {}
sx_props = {}
measure_props = {}
delay_props = {}
self._target = Target("Fake multi-chip backend", num_qubits=num_qubits)
for i in range(num_qubits):
qarg = (i,)
rz_props[qarg] = InstructionProperties(error=0.0, duration=0.0)
x_props[qarg] = InstructionProperties(
error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7)
)
sx_props[qarg] = InstructionProperties(
error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7)
)
measure_props[qarg] = InstructionProperties(
error=rng.uniform(1e-3, 1e-1), duration=rng.uniform(1e-8, 9e-7)
)
delay_props[qarg] = None
self._target.add_instruction(XGate(), x_props)
self._target.add_instruction(SXGate(), sx_props)
self._target.add_instruction(RZGate(Parameter("theta")), rz_props)
self._target.add_instruction(Measure(), measure_props)
self._target.add_instruction(Delay(Parameter("t")), delay_props)
cz_props = {}
for i in range(3):
for root_edge in graph.edge_list():
offset = i * len(graph)
edge = (root_edge[0] + offset, root_edge[1] + offset)
cz_props[edge] = InstructionProperties(
error=rng.uniform(1e-5, 5e-3), duration=rng.uniform(1e-8, 9e-7)
)
self._target.add_instruction(CZGate(), cz_props)
@property
def target(self):
return self._target
@property
def max_circuits(self):
return None
@classmethod
def _default_options(cls):
return Options(shots=1024)
def run(self, circuit, **kwargs):
raise NotImplementedError
self.backend = FakeMultiChip()
@data(0, 1, 2, 3)
def test_basic_connected_circuit(self, opt_level):
"""Test basic connected circuit on disjoint backend"""
qc = QuantumCircuit(5)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.measure_all()
tqc = transpile(qc, self.backend, optimization_level=opt_level)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data(0, 1, 2, 3)
def test_triple_circuit(self, opt_level):
"""Test a split circuit with one circuit component per chip."""
qc = QuantumCircuit(30)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.measure_all()
if opt_level == 0:
with self.assertRaises(TranspilerError):
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
return
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
def test_disjoint_control_flow(self):
"""Test control flow circuit on disjoint coupling map."""
qc = QuantumCircuit(6, 1)
qc.h(0)
qc.ecr(0, 1)
qc.cx(0, 2)
qc.measure(0, 0)
with qc.if_test((qc.clbits[0], True)):
qc.reset(0)
qc.cz(1, 0)
qc.h(3)
qc.cz(3, 4)
qc.cz(3, 5)
target = self.backend.target
target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)})
target.add_instruction(IfElseOp, name="if_else")
tqc = transpile(qc, target=target)
edges = set(target.build_coupling_map().graph.edge_list())
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(target.instruction_supported(instruction.operation.name, qargs))
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
elif len(qargs) == 2:
self.assertIn(qargs, edges)
self.assertIn(instruction.operation.name, target)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
def test_disjoint_control_flow_shared_classical(self):
"""Test circuit with classical data dependency between connected components."""
creg = ClassicalRegister(19)
qc = QuantumCircuit(25)
qc.add_register(creg)
qc.h(0)
for i in range(18):
qc.cx(0, i + 1)
for i in range(18):
qc.measure(i, creg[i])
with qc.if_test((creg, 0)):
qc.h(20)
qc.ecr(20, 21)
qc.ecr(20, 22)
qc.ecr(20, 23)
qc.ecr(20, 24)
target = self.backend.target
target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)})
target.add_instruction(IfElseOp, name="if_else")
tqc = transpile(qc, target=target)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(target.instruction_supported(instruction.operation.name, qargs))
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
@slow_test
@data(2, 3)
def test_six_component_circuit(self, opt_level):
"""Test input circuit with more than 1 component per backend component."""
qc = QuantumCircuit(42)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.h(30)
qc.cx(30, 31)
qc.cx(30, 32)
qc.cx(30, 33)
qc.h(34)
qc.cx(34, 35)
qc.cx(34, 36)
qc.cx(34, 37)
qc.h(38)
qc.cx(38, 39)
qc.cx(39, 40)
qc.cx(39, 41)
qc.measure_all()
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
def test_six_component_circuit_level_1(self):
"""Test input circuit with more than 1 component per backend component."""
opt_level = 1
qc = QuantumCircuit(42)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.h(30)
qc.cx(30, 31)
qc.cx(30, 32)
qc.cx(30, 33)
qc.h(34)
qc.cx(34, 35)
qc.cx(34, 36)
qc.cx(34, 37)
qc.h(38)
qc.cx(38, 39)
qc.cx(39, 40)
qc.cx(39, 41)
qc.measure_all()
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data(0, 1, 2, 3)
def test_shared_classical_between_components_condition(self, opt_level):
"""Test a condition sharing classical bits between components."""
creg = ClassicalRegister(19)
qc = QuantumCircuit(25)
qc.add_register(creg)
qc.h(0)
for i in range(18):
qc.cx(0, i + 1)
for i in range(18):
qc.measure(i, creg[i])
qc.ecr(20, 21).c_if(creg, 0)
tqc = transpile(qc, self.backend, optimization_level=opt_level)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
@data(0, 1, 2, 3)
def test_shared_classical_between_components_condition_large_to_small(self, opt_level):
"""Test a condition sharing classical bits between components."""
creg = ClassicalRegister(2)
qc = QuantumCircuit(25)
qc.add_register(creg)
# Component 0
qc.h(24)
qc.cx(24, 23)
qc.measure(24, creg[0])
qc.measure(23, creg[1])
# Component 1
qc.h(0).c_if(creg, 0)
for i in range(18):
qc.ecr(0, i + 1).c_if(creg, 0)
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=123456789)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
# Check that virtual qubits that interact with each other via quantum links are placed into
# the same component of the coupling map.
initial_layout = tqc.layout.initial_layout
coupling_map = self.backend.target.build_coupling_map()
components = [
connected_qubits(initial_layout[qc.qubits[23]], coupling_map),
connected_qubits(initial_layout[qc.qubits[0]], coupling_map),
]
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in [23, 24]}, components[0])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(19)}, components[1])
# Check clbits are in order.
# Traverse the output dag over the sole clbit, checking that the qubits of the ops
# go in order between the components. This is a sanity check to ensure that routing
# doesn't reorder a classical data dependency between components. Inside a component
# we have the dag ordering so nothing should be out of order within a component.
tqc_dag = circuit_to_dag(tqc)
qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)}
input_node = tqc_dag.input_map[tqc_dag.clbits[0]]
first_meas_node = tqc_dag._multi_graph.find_successors_by_edge(
input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
# The first node should be a measurement
self.assertIsInstance(first_meas_node.op, Measure)
# This should be in the first component
self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while isinstance(op_node, DAGOpNode):
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
@data(1, 2, 3)
def test_shared_classical_between_components_condition_large_to_small_reverse_index(
self, opt_level
):
"""Test a condition sharing classical bits between components."""
creg = ClassicalRegister(2)
qc = QuantumCircuit(25)
qc.add_register(creg)
# Component 0
qc.h(0)
qc.cx(0, 1)
qc.measure(0, creg[0])
qc.measure(1, creg[1])
# Component 1
qc.h(24).c_if(creg, 0)
for i in range(23, 5, -1):
qc.ecr(24, i).c_if(creg, 0)
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
# Check that virtual qubits that interact with each other via quantum links are placed into
# the same component of the coupling map.
initial_layout = tqc.layout.initial_layout
coupling_map = self.backend.target.build_coupling_map()
components = [
connected_qubits(initial_layout[qc.qubits[0]], coupling_map),
connected_qubits(initial_layout[qc.qubits[6]], coupling_map),
]
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(2)}, components[0])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(6, 25)}, components[1])
# Check clbits are in order.
# Traverse the output dag over the sole clbit, checking that the qubits of the ops
# go in order between the components. This is a sanity check to ensure that routing
# doesn't reorder a classical data dependency between components. Inside a component
# we have the dag ordering so nothing should be out of order within a component.
tqc_dag = circuit_to_dag(tqc)
qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)}
input_node = tqc_dag.input_map[tqc_dag.clbits[0]]
first_meas_node = tqc_dag._multi_graph.find_successors_by_edge(
input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
# The first node should be a measurement
self.assertIsInstance(first_meas_node.op, Measure)
# This shoulde be in the first ocmponent
self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while isinstance(op_node, DAGOpNode):
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
@data(1, 2, 3)
def test_chained_data_dependency(self, opt_level):
"""Test 3 component circuit with shared clbits between each component."""
creg = ClassicalRegister(1)
qc = QuantumCircuit(30)
qc.add_register(creg)
# Component 0
qc.h(0)
for i in range(9):
qc.cx(0, i + 1)
measure_op = Measure()
qc.append(measure_op, [9], [creg[0]])
# Component 1
qc.h(10).c_if(creg, 0)
for i in range(11, 20):
qc.ecr(10, i).c_if(creg, 0)
measure_op = Measure()
qc.append(measure_op, [19], [creg[0]])
# Component 2
qc.h(20).c_if(creg, 0)
for i in range(21, 30):
qc.cz(20, i).c_if(creg, 0)
measure_op = Measure()
qc.append(measure_op, [29], [creg[0]])
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
# Check that virtual qubits that interact with each other via quantum links are placed into
# the same component of the coupling map.
initial_layout = tqc.layout.initial_layout
coupling_map = self.backend.target.build_coupling_map()
components = [
connected_qubits(initial_layout[qc.qubits[0]], coupling_map),
connected_qubits(initial_layout[qc.qubits[10]], coupling_map),
connected_qubits(initial_layout[qc.qubits[20]], coupling_map),
]
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10)}, components[0])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10, 20)}, components[1])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(20, 30)}, components[2])
# Check clbits are in order.
# Traverse the output dag over the sole clbit, checking that the qubits of the ops
# go in order between the components. This is a sanity check to ensure that routing
# doesn't reorder a classical data dependency between components. Inside a component
# we have the dag ordering so nothing should be out of order within a component.
tqc_dag = circuit_to_dag(tqc)
qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)}
input_node = tqc_dag.input_map[tqc_dag.clbits[0]]
first_meas_node = tqc_dag._multi_graph.find_successors_by_edge(
input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
self.assertIsInstance(first_meas_node.op, Measure)
self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while not isinstance(op_node.op, Measure):
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while not isinstance(op_node.op, Measure):
self.assertIn(qubit_map[op_node.qargs[0]], components[2])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
self.assertIn(qubit_map[op_node.qargs[0]], components[2])
@data("sabre", "stochastic", "basic", "lookahead")
def test_basic_connected_circuit_dense_layout(self, routing_method):
"""Test basic connected circuit on disjoint backend"""
qc = QuantumCircuit(5)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.measure_all()
tqc = transpile(
qc,
self.backend,
layout_method="dense",
routing_method=routing_method,
seed_transpiler=42,
)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
# Lookahead swap skipped for performance
@data("sabre", "stochastic", "basic")
def test_triple_circuit_dense_layout(self, routing_method):
"""Test a split circuit with one circuit component per chip."""
qc = QuantumCircuit(30)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.measure_all()
tqc = transpile(
qc,
self.backend,
layout_method="dense",
routing_method=routing_method,
seed_transpiler=42,
)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data("sabre", "stochastic", "basic", "lookahead")
def test_triple_circuit_invalid_layout(self, routing_method):
"""Test a split circuit with one circuit component per chip."""
qc = QuantumCircuit(30)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.measure_all()
with self.assertRaises(TranspilerError):
transpile(
qc,
self.backend,
layout_method="trivial",
routing_method=routing_method,
seed_transpiler=42,
)
# Lookahead swap skipped for performance reasons
@data("sabre", "stochastic", "basic")
def test_six_component_circuit_dense_layout(self, routing_method):
"""Test input circuit with more than 1 component per backend component."""
qc = QuantumCircuit(42)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.h(30)
qc.cx(30, 31)
qc.cx(30, 32)
qc.cx(30, 33)
qc.h(34)
qc.cx(34, 35)
qc.cx(34, 36)
qc.cx(34, 37)
qc.h(38)
qc.cx(38, 39)
qc.cx(39, 40)
qc.cx(39, 41)
qc.measure_all()
tqc = transpile(
qc,
self.backend,
layout_method="dense",
routing_method=routing_method,
seed_transpiler=42,
)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops(self, opt_level):
"""Test qubits without operations aren't ever used."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(
CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]}
)
qc = QuantumCircuit(3)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
tqc = transpile(qc, target=target, optimization_level=opt_level)
invalid_qubits = {3, 4}
self.assertEqual(tqc.num_qubits, 5)
for inst in tqc.data:
for bit in inst.qubits:
self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits)
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops_with_routing(self, opt_level):
"""Test qubits without operations aren't ever used."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)})
target.add_instruction(
CXGate(),
{edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0), (2, 3)]},
)
qc = QuantumCircuit(4)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(1, 3)
qc.cx(0, 3)
tqc = transpile(qc, target=target, optimization_level=opt_level)
invalid_qubits = {
4,
}
self.assertEqual(tqc.num_qubits, 5)
for inst in tqc.data:
for bit in inst.qubits:
self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits)
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops_circuit_too_large(self, opt_level):
"""Test qubits without operations aren't ever used and error if circuit needs them."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(
CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]}
)
qc = QuantumCircuit(4)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
with self.assertRaises(TranspilerError):
transpile(qc, target=target, optimization_level=opt_level)
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops_circuit_too_large_disconnected(
self, opt_level
):
"""Test qubits without operations aren't ever used if a disconnected circuit needs them."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(
CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]}
)
qc = QuantumCircuit(5)
qc.x(0)
qc.x(1)
qc.x(3)
qc.x(4)
with self.assertRaises(TranspilerError):
transpile(qc, target=target, optimization_level=opt_level)
@data(0, 1, 2, 3)
def test_transpile_does_not_affect_backend_coupling(self, opt_level):
"""Test that transpiliation of a circuit does not mutate the `CouplingMap` stored by a V2
backend. Regression test of gh-9997."""
if opt_level == 3:
raise unittest.SkipTest("unitary resynthesis fails due to gh-10004")
qc = QuantumCircuit(127)
for i in range(1, 127):
qc.ecr(0, i)
backend = FakeSherbrooke()
original_map = copy.deepcopy(backend.coupling_map)
transpile(qc, backend, optimization_level=opt_level)
self.assertEqual(original_map, backend.coupling_map)
@combine(
optimization_level=[0, 1, 2, 3],
scheduling_method=["asap", "alap"],
)
def test_transpile_target_with_qubits_without_delays_with_scheduling(
self, optimization_level, scheduling_method
):
"""Test qubits without operations aren't ever used."""
no_delay_qubits = [1, 3, 4]
target = Target(num_qubits=5, dt=1)
target.add_instruction(
XGate(), {(i,): InstructionProperties(duration=160) for i in range(4)}
)
target.add_instruction(
HGate(), {(i,): InstructionProperties(duration=160) for i in range(4)}
)
target.add_instruction(
CXGate(),
{
edge: InstructionProperties(duration=800)
for edge in [(0, 1), (1, 2), (2, 0), (2, 3)]
},
)
target.add_instruction(
Delay(Parameter("t")), {(i,): None for i in range(4) if i not in no_delay_qubits}
)
qc = QuantumCircuit(4)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(1, 3)
qc.cx(0, 3)
tqc = transpile(
qc,
target=target,
optimization_level=optimization_level,
scheduling_method=scheduling_method,
)
invalid_qubits = {
4,
}
self.assertEqual(tqc.num_qubits, 5)
for inst in tqc.data:
for bit in inst.qubits:
self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits)
if isinstance(inst.operation, Delay):
self.assertNotIn(tqc.find_bit(bit).index, no_delay_qubits)
|
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
|
AbdulahAmer
|
1 + 1
6 - 2
print("Hello World!")
my_integer = 8
my_decimal = 3.1415
my_expression = my_integer + my_decimal
my_string_1 = "a string"
my_string_2 = 'another string'
my_list = [ my_integer, my_decimal, my_expression, my_string_1, my_string_2]
print(my_integer)
print(my_decimal)
print(my_expression)
print(my_string_1)
print(my_string_2)
print(my_list)
print('my integer: ', my_integer)
print('my decimal: ', my_decimal)
print('my expression: ', my_expression)
print('my first string:', my_string_1)
print('my second string: ', my_string_2)
print('my list: ', my_list)
|
https://github.com/Seanaventure/HighErrorRateRouting
|
Seanaventure
|
import matplotlib.pyplot as plt
import networkx as nx
import qiskit
import HERR
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.passes.routing import BasicSwap
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.converters import dag_to_circuit
from math import pi
from qiskit.compiler import transpile, assemble
from qiskit.providers.aer.noise import NoiseModel
import qiskit.providers.aer.noise as noise
from qiskit.tools.visualization import dag_drawer
import random
from qiskit.circuit.instruction import Instruction
# This function can be use to count the number of CNOT gates. Useful for debugging
def countTwoQubitGates(transpiledCircuit):
num = 0
for gate in transpiledCircuit.data:
# print(type(gate[0]))
if issubclass(type(gate[0]), Instruction):
if gate[0].name == "cx":
num += 1
return num
"""
For the Berentien Varanzi algorithm we need a secret string and make a circuit around it. All this was taken from qiskit
https://qiskit.org/textbook/ch-algorithms/bernstein-vazirani.html
"""
s = '1101'
n = len(s)
circuit = QuantumCircuit(8, n)
# Step 0
circuit.x(n) # the n+1 qubits are indexed 0...n, so the last qubit is index n
circuit.barrier() # just a visual aid for now
# Step 1
# range(n+1) returns [0,1,2,...,n] in Python. This covers all the qubits
circuit.h(range(n+1))
circuit.barrier() # just a visual aid for now
# Step 2
for ii, yesno in enumerate(reversed(s)):
if yesno == '1':
circuit.cx(ii, n)
circuit.barrier() # just a visual aid for now
# Step 3
# range(n+1) returns [0,1,2,...,n] in Python. This covers all the qubits
circuit.h(range(n+1))
circuit.barrier() # just a visual aid for now
# measure the qubits indexed from 0 to n-1 and store them into the classical bits indexed 0 to n-
circuit.measure(range(n), range(n))
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_lima')
# To compile the circuit we need the basis gates. Just take one from a random backend
basis_gates = backend.configuration().basis_gates
# TO make the coupling maps we annoyingly need to make a list specifying each connection
squareCouplingList = list()
for i in range(4):
for j in range(4):
if i is not j:
if abs(i-j) == 1:
squareCouplingList.append([i, j])
squareCouplingList.append(([0, 3]))
squareCouplingList.append(([3, 0]))
squareCouplingMap = CouplingMap(squareCouplingList)
gridCouplingList = list()
for i in range(4):
for j in range(4):
if i is not j:
if abs(i-j) == 1:
gridCouplingList.append([i, j])
for i in range(4,8):
for j in range(4,8):
if i is not j:
if abs(i-j) == 1:
gridCouplingList.append([i, j])
gridCouplingList.append(([0, 4]))
gridCouplingList.append(([4, 0]))
gridCouplingList.append(([1, 5]))
gridCouplingList.append(([5, 1]))
gridCouplingList.append(([2, 6]))
gridCouplingList.append(([6, 2]))
gridCouplingList.append(([3, 7]))
gridCouplingList.append(([7, 3]))
gridCouplingMap = CouplingMap(gridCouplingList)
jakatraCouplingList = [[0, 1], [1, 0], [1, 2], [2, 1], [1, 3], [3, 1], [3,5], [5,3], [4,5], [5,4], [6,5], [5,6]]
jakatraCouplingMap = CouplingMap(jakatraCouplingList)
# We need to translate the circuit to a DAG to run it
circDag = circuit_to_dag(circuit)
transpiledBasic = transpile(circuit, Aer.get_backend('qasm_simulator'),
coupling_map=gridCouplingMap,
basis_gates=basis_gates,
routing_method='basic',
layout_method='trivial')
transpiledSabre = transpile(circuit, Aer.get_backend('qasm_simulator'),
coupling_map=gridCouplingMap,
basis_gates=basis_gates,
routing_method='sabre',
layout_method='trivial')
transpiledStochastic = transpile(circuit, Aer.get_backend('qasm_simulator'),
coupling_map=gridCouplingMap,
basis_gates=basis_gates,
routing_method='stochastic',
layout_method='trivial')
transpiledLookahead = transpile(circuit, Aer.get_backend('qasm_simulator'),
coupling_map=gridCouplingMap,
basis_gates=basis_gates,
routing_method='lookahead',
layout_method='trivial')
for i in range(200):
# Create a noise model for the simulations
noise_model = noise.NoiseModel()
errorRates = list()
qiskitErrors = list()
# Assemble the noise graph. This is a graph that represents the noise of each link. Nodes are qubits and edges are the corresponding link
for i in range(len(gridCouplingList)//2):
# Generate a random error for each link from 1-10%
errorRates.append(random.randrange(1, 10, 1)/100.0)
qiskitErrors.append(noise.depolarizing_error(errorRates[i], 2))
edges = gridCouplingMap.get_edges()
uniqueEdges = set()
for edge in edges:
uniqueEdges.add(tuple(sorted(edge)))
noiseGraph = nx.Graph()
noiseGraph.add_nodes_from([0, 7])
# Add quantum error for a randomly generated noise value
errorIdex = 0
for edge in uniqueEdges:
noise_model.add_quantum_error(qiskitErrors[errorIdex], ['cx'], edge)
noiseGraph.add_edge(edge[0], edge[1], weight=1-errorRates[errorIdex])
errorIdex += 1
herr = HERR.HERR(gridCouplingMap, noiseGraph)
basSwap = BasicSwap(gridCouplingMap)
# Run HERR
HERRRes = herr.run(circDag)
updatedCirc = dag_to_circuit(HERRRes)
# We ran HERR, but we need to do the rest of the transpiling process to get it ready for hardware
transpiledHERR = transpile(updatedCirc, Aer.get_backend('qasm_simulator'),
coupling_map=gridCouplingMap,
basis_gates=basis_gates,
routing_method='basic',
layout_method='trivial')
sim = Aer.get_backend('qasm_simulator')
# Run all the compiled circuits
simResultHERR = sim.run(transpiledHERR, noise_model=noise_model).result()
simResultBasic = sim.run(transpiledBasic, noise_model=noise_model).result()
simResultSabre = sim.run(transpiledSabre, noise_model=noise_model).result()
simResultLookahead = sim.run(transpiledLookahead, noise_model=noise_model).result()
simResultStochastic = sim.run(transpiledStochastic, noise_model=noise_model).result()
# Output file and print results
fName = "HERRQFTCouplingOutputs/HERRCirc" + str(i) + ".png"
fName2 = "HERRQFTCouplingOutputs/NonCirc" + str(i) + ".png"
if s in simResultHERR.get_counts() and s in simResultBasic.get_counts() and s in simResultSabre.get_counts() and s in simResultLookahead.get_counts() and s in simResultStochastic.get_counts():
print(str(simResultHERR.get_counts()[s]/1024.0) + " " + str(simResultBasic.get_counts()[s]/1024.0) + " " + str(simResultSabre.get_counts()[s]/1024.0) + " " + str(simResultLookahead.get_counts()[s]/1024.0) + " " + str(simResultStochastic.get_counts()[s]/1024.0))
else:
print("Key error! Oops!")
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
import qiskit
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
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 tsp_qaoa import marina_solution
G=nx.Graph()
i=1
G.add_node(i,pos=(i,i))
G.add_node(2,pos=(2,2))
G.add_node(3,pos=(1,0))
G.add_edge(1,2,weight=20.5)
G.add_edge(1,3,weight=9.8)
pos=nx.get_node_attributes(G,'pos')
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
def append_zz_term(qc,q1,q2,gamma):
qc.cx(q1,q2)
qc.rz(2*gamma,q2)
qc.cx(q1,q2)
def get_cost_circuit(G,gamma):
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
for i,j in G.edges():
append_zz_term(qc,i,j,gamma)
return qc
#print(get_cost_circuit(G,0.5))
def append_x_term(qc,q1,beta):
qc.rx(2*beta,q1)
def get_mixer_operator(G,beta):
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
for n in G.nodes():
append_x_term(qc,n,beta)
return qc
#print(get_mixer_operator(G,0.5))
def get_QAOA_circuit(G,beta,gamma):
assert(len(beta)==len(gamma))
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
qc.h(range(N))
p=len(beta)
#aplicamos las p rotaciones
for i in range(p):
qc=qc.compose(get_cost_circuit(G,gamma[i]))
qc=qc.compose(get_mixer_operator(G,beta[i]))
qc.barrier(range(N))
qc.measure(range(N),range(N))
return qc
print(get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6]))
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
qc=get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6])
backend=Aer.get_backend('qasm_simulator')
job=execute(qc,backend)
result=job.result()
print(invert_counts(result.get_counts()))
def maxcut_obj(x,G):
cut=0
for i,j in G.edges():
if x[i]!=x[j]:
cut = cut-1
return cut
print(maxcut_obj("00011",G))
def compute_maxcut_energy(counts,G):
energy=0
get_counts=0
total_counts=0
for meas, meas_count in counts.items():
obj_for_meas=maxcut_obj(meas,G)
energy+=obj_for_meas*meas_count
total_counts+=meas_count
return energy/total_counts
def get_black_box_objective(G,p):
backend=Aer.get_backend('qasm_simulator')
def f(theta):
beta=theta[:p]
gamma=theta[p:]
qc=get_QAOA_circuit(G,beta,gamma)
counts=execute(qc,backend,seed_simulator=10).result().get_counts()
return compute_maxcut_energy(invert_counts(counts),G)
return f
p=5
obj=get_black_box_objective(G,p)
init_point=np.array([0.8,2.2,0.83,2.15,0.37,2.4,6.1,2.2,3.8,6.1])#([2,2,1,1,1,1,1,1,1,1])
res_sample=minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
res_sample
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
cantidad_ciudades = 4
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)
pos=nx.spring_layout(G)
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
G
pos=nx.get_node_attributes(G,'weight')
pos
labels = nx.get_edge_attributes(G,'weight')
labels
def funcion_costo(multiplicador_lagrange, cantidad_ciudades, pesos, conexiones ):
N = G.number_of_nodes()
N_square = N^2
# restriccion 1
for i in range(cantidad_ciudades):
cur = sI(N_square)
for j in range(num_cities):
cur -= D(i, j)
ret += cur**2
# retorna el indice de qubit por conversion al problema
def quibit_indice(i, l, N):
return i * N + l
from qiskit.quantum_info.operators import Operator, Pauli
# Create an operator
XX = Operator(Pauli(label='XX'))
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(XX, [0, 1])
circ.measure([0,1], [0,1])
circ.draw('mpl')
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(a, [0])
#circ.measure([0,1], [0,1])
circ.draw('mpl')
a = I - ( 0.5*(I+ Z))**2
a = Operator(a)
a.is_unitary()
print(I @ Z)
|
https://github.com/Aman-Agrawal01/Quantum-Computing-Qiskit-Tutorial
|
Aman-Agrawal01
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
%matplotlib inline
qr1 = QuantumRegister(2)
cr1 = ClassicalRegister(2)
circuit1 = QuantumCircuit(qr1,cr1)
circuit1.draw(output='mpl')
circuit1.h(qr1[0])
circuit1.draw(output='mpl')
circuit1.cx(qr1[0],qr1[1])
circuit1.draw(output='mpl')
circuit1.measure(qr1,cr1)
circuit1.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result1 = execute(circuit1,backend=simulator).result()
plot_histogram(result1.get_counts())
qr2 = QuantumRegister(2)
cr2 = ClassicalRegister(2)
circuit2 = QuantumCircuit(qr2,cr2)
circuit2.draw(output='mpl')
circuit2.h(qr2[0])
circuit2.x(qr2[1])
circuit2.draw(output='mpl')
circuit2.cx(control_qubit=qr2[0],target_qubit=qr2[1])
circuit2.draw(output='mpl')
circuit2.measure(qr2,cr2)
circuit2.draw(output='mpl')
result2 = execute(circuit2,backend=simulator).result()
plot_histogram(result2.get_counts())
|
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 drawing of timeline drawer."""
import numpy as np
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import drawings, types
class TestDrawingObjects(QiskitTestCase):
"""Tests for drawings."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
# bits
self.qubits = list(qiskit.QuantumRegister(2))
# metadata
self.meta1 = {"val1": 0, "val2": 1}
self.meta2 = {"val1": 2, "val2": 3}
# style data
self.style1 = {"property1": 0, "property2": 1}
self.style2 = {"property1": 2, "property2": 3}
def test_line_data_equivalent(self):
"""Test LineData equivalent check."""
xs = list(np.arange(10))
ys = list(np.ones(10))
obj1 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_line_data_equivalent_abstract_coord(self):
"""Test LineData equivalent check with abstract coordinate."""
xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP]
obj1 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_box_data_equivalent(self):
"""Test BoxData equivalent check."""
xs = [0, 1]
ys = [0, 1]
obj1 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_box_data_equivalent_abstract_coord(self):
"""Test BoxData equivalent check with abstract coordinate."""
xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP]
obj1 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_text_data_equivalent(self):
"""Test TextData equivalent check."""
obj1 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=0,
yval=0,
text="test",
latex="test",
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=0,
yval=0,
text="test",
latex="test",
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_text_data_equivalent_abstract_coord(self):
"""Test TextData equivalent check with abstract coordinate."""
obj1 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=types.AbstractCoordinate.LEFT,
yval=types.AbstractCoordinate.BOTTOM,
text="test",
latex="test",
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=types.AbstractCoordinate.LEFT,
yval=types.AbstractCoordinate.BOTTOM,
text="test",
latex="test",
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_bit_link_data_equivalent(self):
"""Test BitLinkData equivalent check."""
obj1 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style1
)
obj2 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style2
)
self.assertEqual(obj1, obj2)
def test_bit_link_data_equivalent_abstract_coord(self):
"""Test BitLinkData equivalent check with abstract coordinate."""
obj1 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]],
xval=types.AbstractCoordinate.LEFT,
styles=self.style1,
)
obj2 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]],
xval=types.AbstractCoordinate.LEFT,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
|
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 numpy as np
from qiskit import QuantumRegister
from qiskit.aqua import Operator, AquaError
from qiskit.aqua import Pluggable, PluggableType, get_pluggable_class
from qiskit.aqua.components.eigs import Eigenvalues
from qiskit.aqua.circuits import PhaseEstimationCircuit
class EigsQPE(Eigenvalues):
""" This class embeds a PhaseEstimationCircuit for getting the eigenvalues of a matrix.
Specifically, this class is based on PhaseEstimationCircuit with no measurements and additional
handling of negative eigenvalues, e.g. for HHL. It uses many parameters
known from plain QPE. It depends on QFT and IQFT.
"""
CONFIGURATION = {
'name': 'EigsQPE',
'description': 'Quantum Phase Estimation for eigenvalues',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'eigsqpe_schema',
'type': 'object',
'properties': {
'num_time_slices': {
'type': 'integer',
'default': 1,
'minimum': 0
},
'expansion_mode': {
'type': 'string',
'default': 'trotter',
'oneOf': [
{'enum': [
'suzuki',
'trotter'
]}
]
},
'expansion_order': {
'type': 'integer',
'default': 1,
'minimum': 1
},
'num_ancillae': {
'type': 'integer',
'default': 1,
'minimum': 1
},
'evo_time': {
'type': ['number', 'null'],
'default': None
},
'negative_evals': {
'type': 'boolean',
'default': False
},
},
'additionalProperties': False
},
'depends': [
{'pluggable_type': 'iqft',
'default': {
'name': 'STANDARD',
}
},
{'pluggable_type': 'qft',
'default': {
'name': 'STANDARD',
}
},
],
}
def __init__(
self, operator, iqft,
num_time_slices=1,
num_ancillae=1,
expansion_mode='trotter',
expansion_order=1,
evo_time=None,
negative_evals=False,
ne_qfts=[None, None]
):
"""Constructor.
Args:
operator (Operator): the hamiltonian Operator object
iqft (IQFT): the Inverse Quantum Fourier Transform pluggable component
num_time_slices (int, optional): the number of time slices
num_ancillae (int, optional): the number of ancillary qubits to use for the measurement
expansion_mode (str, optional): the expansion mode (trotter|suzuki)
expansion_order (int, optional): the suzuki expansion order
evo_time (float, optional): the evolution time
negative_evals (bool, optional): indicate if negative eigenvalues need to be handled
ne_qfts ([QFT, IQFT], optional): the QFT and IQFT pluggable components for handling negative eigenvalues
"""
super().__init__()
super().validate(locals())
self._operator = operator
self._iqft = iqft
self._num_ancillae = num_ancillae
self._num_time_slices = num_time_slices
self._expansion_mode = expansion_mode
self._expansion_order = expansion_order
self._evo_time = evo_time
self._negative_evals = negative_evals
self._ne_qfts = ne_qfts
self._init_constants()
@classmethod
def init_params(cls, params, matrix):
"""
Initialize via parameters dictionary and algorithm input instance
Args:
params: parameters dictionary
matrix: two dimensional array which represents the operator
"""
if matrix is None:
raise AquaError("Operator instance is required.")
if not isinstance(matrix, np.ndarray):
matrix = np.array(matrix)
eigs_params = params.get(Pluggable.SECTION_KEY_EIGS)
args = {k: v for k, v in eigs_params.items() if k != 'name'}
num_ancillae = eigs_params['num_ancillae']
negative_evals = eigs_params['negative_evals']
# Adding an additional flag qubit for negative eigenvalues
if negative_evals:
num_ancillae += 1
args['num_ancillae'] = num_ancillae
args['operator'] = Operator(matrix=matrix)
# Set up iqft, we need to add num qubits to params which is our num_ancillae bits here
iqft_params = params.get(Pluggable.SECTION_KEY_IQFT)
iqft_params['num_qubits'] = num_ancillae
args['iqft'] = get_pluggable_class(PluggableType.IQFT,
iqft_params['name']).init_params(params)
# For converting the encoding of the negative eigenvalues, we need two
# additional instances for QFT and IQFT
if negative_evals:
ne_params = params
qft_num_qubits = iqft_params['num_qubits']
ne_qft_params = params.get(Pluggable.SECTION_KEY_QFT)
ne_qft_params['num_qubits'] = qft_num_qubits - 1
ne_iqft_params = params.get(Pluggable.SECTION_KEY_IQFT)
ne_iqft_params['num_qubits'] = qft_num_qubits - 1
ne_params['qft'] = ne_qft_params
ne_params['iqft'] = ne_iqft_params
args['ne_qfts'] = [get_pluggable_class(PluggableType.QFT,
ne_qft_params['name']).init_params(ne_params),
get_pluggable_class(PluggableType.IQFT,
ne_iqft_params['name']).init_params(ne_params)]
else:
args['ne_qfts'] = [None, None]
return cls(**args)
def _init_constants(self):
# estimate evolution time
self._operator._check_representation('paulis')
paulis = self._operator.paulis
if self._evo_time == None:
lmax = sum([abs(p[0]) for p in self._operator.paulis])
if not self._negative_evals:
self._evo_time = (1-2**-self._num_ancillae)*2*np.pi/lmax
else:
self._evo_time = (1/2-2**-self._num_ancillae)*2*np.pi/lmax
# check for identify paulis to get its coef for applying global phase shift on ancillae later
num_identities = 0
for p in self._operator.paulis:
if np.all(p[1].z == 0) and np.all(p[1].x == 0):
num_identities += 1
if num_identities > 1:
raise RuntimeError('Multiple identity pauli terms are present.')
self._ancilla_phase_coef = p[0].real if isinstance(p[0], complex) else p[0]
def get_register_sizes(self):
return self._operator.num_qubits, self._num_ancillae
def get_scaling(self):
return self._evo_time
def construct_circuit(self, mode, register=None):
""" Construct the eigenvalues estimation using the PhaseEstimationCircuit
Args:
mode (str): consctruction mode, 'matrix' not supported
register (QuantumRegister): the register to use for the quantum state
Returns:
the QuantumCircuit object for the constructed circuit
"""
if mode == 'matrix':
raise ValueError('QPE is only possible as a circuit not as a matrix.')
pe = PhaseEstimationCircuit(
operator=self._operator, state_in=None, iqft=self._iqft,
num_time_slices=self._num_time_slices, num_ancillae=self._num_ancillae,
expansion_mode=self._expansion_mode, expansion_order=self._expansion_order,
evo_time=self._evo_time
)
a = QuantumRegister(self._num_ancillae)
q = register
qc = pe.construct_circuit(state_register=q, ancillary_register=a)
# handle negative eigenvalues
if self._negative_evals:
self._handle_negative_evals(qc, a)
self._circuit = qc
self._output_register = a
self._input_register = q
return self._circuit
def _handle_negative_evals(self, qc, q):
sgn = q[0]
qs = [q[i] for i in range(1, len(q))]
for qi in qs:
qc.cx(sgn, qi)
self._ne_qfts[0].construct_circuit(mode='circuit', qubits=qs, circuit=qc, do_swaps=False)
for i, qi in enumerate(reversed(qs)):
qc.cu1(2*np.pi/2**(i+1), sgn, qi)
self._ne_qfts[1].construct_circuit(mode='circuit', qubits=qs, circuit=qc, do_swaps=False)
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import subprocess
import shutil
import os
# Include these lines if we run all files in one process
import qiskit_alt
qiskit_alt.project.ensure_init()
bench_scripts = [
"fermionic_alt_time.py",
"from_matrix_alt.py",
"jordan_wigner_alt_time.py",
"pauli_from_list_alt.py"
]
_python = shutil.which("python")
## Run each benchmark script in a separate process
def run_bench(fname):
dirname = os.path.dirname(os.path.abspath(__file__))
full = os.path.join(dirname, fname)
res = subprocess.run(
[_python, full], check=True, capture_output=True, encoding='utf8'
).stdout
print(res)
def exec_full_dir(fname):
dirname = os.path.dirname(os.path.abspath(__file__))
filepath = os.path.join(dirname, fname)
exec_full(filepath)
def exec_full(filepath):
global_namespace = {
"__file__": filepath,
"__name__": "__main__",
}
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), global_namespace)
def run_all():
for fname in bench_scripts:
print(fname)
exec_full_dir(fname)
print()
if __name__ == '__main__':
run_all()
|
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/Manish-Sudhir/QiskitCheck
|
Manish-Sudhir
|
from TestProperty import TestProperty, Precondition
from Generator import Generator
from ExecutionEngine import TestExecutor
from StatisticalEngine import StatAnalyser
from qiskit import QuantumCircuit
from math import cos, radians
from abc import ABC, abstractmethod
"""
INPUTS:
- list of quantum circuits
- function to filter the quantum circuits (that takes as input a QuantumCircuit)
OUTPUT:
- tuple of 2 values:
0. a list storing the indexes of the tests that passed the filtering process
1. another list storing the tests that passed the filtering
"""
def getFilteredInfo(inputTests, filter_qc):
if filter_qc != None:
filteredNumbered = list(filter(lambda x: filter_qc(x[1]), enumerate(inputTests)))
filteredIndexes = [x[0] for x in filteredNumbered]
filteredTests = [x[1] for x in filteredNumbered]
else:
filteredIndexes = range(len(inputTests))
filteredTests = inputTests
return (filteredIndexes, filteredTests)
class QiskitPropertyTest(ABC):
"""
This method handles all the required data to evaluate the equality between two qubits
INPUTS:
- qu0: int = the index of the first qubit to compare
- qu1: int = the index of the second qubit to compare
- qu0_pre: boolean = whether the first qubit should be compared
before running quantumFunction()
- qu1_pre: boolean = whether the second qubit should be compared
before running quantumFunction()
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the first and the second qubit
"""
#Manish- This is a helper function which takes in initTest which calls the test case generator to generate qc's, based on the
# preconditions, which are going to be used to be used in our tests. the two underscores are theta and phi.
def genListQC(self, sit):
genQCList = []
for qc, _, _ in sit:
genQCList.append(qc.copy())
return genQCList
def assertEqualData(self, qu0, qu1, qu0_pre, qu1_pre, basis, filter_qc):
generatedTests = self.genListQC(self.initTests)
filteredIndexes, filteredTests = getFilteredInfo(generatedTests, filter_qc)
#executes the tests twice faster if they're on the same circuit, but only possible if both pre values are the same
if qu0_pre == qu1_pre:
#Applies the function to the generated tests only if they are both sampled after running the full program
if not qu0_pre and not qu1_pre:
for circuit in generatedTests:
self.quantumFunction(circuit)
dataFromExec = TestExecutor().runTestsAssertEqual(filteredTests, self.testProperty.noOfExperiments, \
self.testProperty.noOfMeasurements, qu0, qu1, self.testProperty.noOfClassicalBits, \
self.testProperty.noOfClassicalBits + 1, basis, self.testProperty.backend)
testResults = StatAnalyser().testAssertEqual(self.testProperty.pVal, dataFromExec)
#gets the theta/phi each qubit was initialised with
qu0Params = [(self.initTests[index][1].get(qu0, 0),
self.initTests[index][2].get(qu0, 0)) for index in filteredIndexes]
qu1Params = [(self.initTests[index][1].get(qu1, 0),
self.initTests[index][2].get(qu1, 0)) for index in filteredIndexes]
params = tuple(zip(qu0Params, qu1Params))
testResultsWithInit = tuple(zip(testResults, params))
else:
for circuit in generatedTests:
self.quantumFunction(circuit)
generatedTestPre = [x[0].copy() for x in self.initTests]
filteredTestsPre = [generatedTestPre[index] for index in filteredIndexes]
if not qu0_pre:
tests_qu0 = filteredTests
tests_qu1 = filteredTestsPre
else:
tests_qu0 = filteredTestsPre
tests_qu1 = filteredTests
#can reuse testAssertEqual with data from 2 runTestsAssertProbability zipped together
dataFrom_qu0 = TestExecutor().runTestsAssertProbability(tests_qu0, self.testProperty.noOfExperiments, \
self.testProperty.noOfMeasurements, qu0, self.testProperty.noOfClassicalBits + 1, basis, self.testProperty.backend)
dataFrom_qu1 = TestExecutor().runTestsAssertProbability(tests_qu1, self.testProperty.noOfExperiments, \
self.testProperty.noOfMeasurements, qu1, self.testProperty.noOfClassicalBits + 1, basis, self.testProperty.backend)
formattedData = tuple(zip(dataFrom_qu0, dataFrom_qu1))
testResults = StatAnalyser().testAssertEqual(self.testProperty.pVal, formattedData)
#gets the theta/phi each qubit was initialised with
qu0Params = [(self.initTests[index][1].get(qu0, 0),
self.initTests[index][2].get(qu0, 0)) for index in filteredIndexes]
qu1Params = [(self.initTests[index][1].get(qu1, 0),
self.initTests[index][2].get(qu1, 0)) for index in filteredIndexes]
params = tuple(zip(qu0Params, qu1Params))
testResultsWithInit = tuple(zip(testResults, params))
return testResultsWithInit
"""
This method is a wrapper around assertEqualData that outputs the results
to the users
INPUTS:
- qu0: int = the index of the first qubit to compare
- qu1: int = the index of the second qubit to compare
- qu0_pre: boolean = whether the first qubit should be compared
before running quantumFunction()
- qu1_pre: boolean = whether the second qubit should be compared
before running quantumFunction()
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the first and the second qubits
"""
def assertEqual(self, qu0, qu1, qu0_pre=False, qu1_pre=False, basis="z", filter_qc=None):
results = self.assertEqualData(qu0, qu1, qu0_pre, qu1_pre, basis, filter_qc)
print(f"AssertEqual({qu0}{'_pre' if qu0_pre else ''}, {qu1}{'_pre' if qu1_pre else ''}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0][0]} Phi = {testResult[1][0][1]}")
print(f"qu1: Theta = {testResult[1][1][0]} Phi = {testResult[1][1][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method is a wrapper around assertEqualData that outputs the results
to the users
The "Not" is evaluated by negating all booleans returned by assertEqualData
INPUTS:
- qu0: int = the index of the first qubit to compare
- qu1: int = the index of the second qubit to compare
- qu0_pre: boolean = whether the first qubit should be compared
before running quantumFunction()
- qu1_pre: boolean = whether the second qubit should be compared
before running quantumFunction()
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the first and the second qubits
"""
def assertNotEqual(self, qu0, qu1, qu0_pre=False, qu1_pre=False, basis="z", filter_qc=None):
oppositeResults = self.assertEqualData(qu0, qu1, qu0_pre, qu1_pre, basis, filter_qc)
results = [(not x[0], x[1]) for x in oppositeResults]
print(f"AssertNotEqual({qu0}{'_pre' if qu0_pre else ''}, {qu1}{'_pre' if qu1_pre else ''}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0][0]} Phi = {testResult[1][0][1]}")
print(f"qu1: Theta = {testResult[1][1][0]} Phi = {testResult[1][1][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method handles all the required data to evaluate whether two qubits are entangled
INPUTS:
- qu0: int = the index of the first qubit to compare
- qu1: int = the index of the second qubit to compare
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the first and the second qubits
"""
def assertEntangledData(self, qu0, qu1, basis, filter_qc):
# generatedTests = [qc.copy() for qc, theta, phi in self.initTests]
generatedTests = self.genListQC(self.initTests)
for generatedTest in generatedTests:
self.quantumFunction(generatedTest)
filteredIndexes, filteredTests = getFilteredInfo(generatedTests, filter_qc)
dataFromExec = TestExecutor().runTestsAssertEntangled(filteredTests,
self.testProperty.noOfExperiments,
self.testProperty.noOfMeasurements,
qu0,
qu1,
self.testProperty.noOfClassicalBits,
self.testProperty.noOfClassicalBits + 1,
basis,
self.testProperty.backend)
testResults = StatAnalyser().testAssertEntangled(self.testProperty.pVal, dataFromExec)
qu0Params = [(self.initTests[index][1].get(qu0, 0),
self.initTests[index][2].get(qu0, 0)) for index in filteredIndexes]
qu1Params = [(self.initTests[index][1].get(qu1, 0),
self.initTests[index][2].get(qu1, 0)) for index in filteredIndexes]
params = tuple(zip(qu0Params, qu1Params))
testResultsWithInit = tuple(zip(testResults, params))
return testResultsWithInit
"""
This method is a wrapper of assertEntangledData that outputs the results to the user
INPUTS:
- qu0: int = the index of the first qubit to compare
- qu1: int = the index of the second qubit to compare
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the first and the second qubits
"""
def assertEntangled(self, qu0, qu1, basis="z", filter_qc=None):
results = self.assertEntangledData(qu0, qu1, basis, filter_qc)
print(f"AssertEntangled({qu0}, {qu1}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0][0]} Phi = {testResult[1][0][1]}")
print(f"qu1: Theta = {testResult[1][1][0]} Phi = {testResult[1][1][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method is a wrapper of assertEntangledData that outputs the results to the user
The result booleans are negated for the "Not" evaluation
INPUTS:
- qu0: int = the index of the first qubit to compare
- qu1: int = the index of the second qubit to compare
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the first and the second qubits
"""
def assertNotEntangled(self, qu0, qu1, basis="z", filter_qc=None):
oppositeResults = self.assertEntangledData(qu0, qu1, basis, filter_qc)
results = [(not x[0], x[1]) for x in oppositeResults]
print(f"AsserNotEntangled({qu0}, {qu1}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0][0]} Phi = {testResult[1][0][1]}")
print(f"qu1: Theta = {testResult[1][1][0]} Phi = {testResult[1][1][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method evaluates wether a given qubit is in state |0> with a given probability
INPUTS:
- qu0: int = the index of the qubit to test
- expectedProba: float = expected probability of the qubit to be in state |0>
- qu0_pre: bool = whether the data will be sampled before the application of the quantumFunction
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertProbabilityData(self, qu0, expectedProba, qu0_pre, basis, filter_qc):
expectedProbas = [expectedProba for _ in range(self.testProperty.nbTests)]
generatedTests = [qc.copy() for qc, theta, phi in self.initTests]
#Only apply the functions if specified
if not qu0_pre:
for generatedTest in generatedTests:
self.quantumFunction(generatedTest)
filteredIndexes, filteredTests = getFilteredInfo(generatedTests, filter_qc)
dataFromExec = TestExecutor().runTestsAssertProbability(filteredTests,
self.testProperty.noOfExperiments,
self.testProperty.noOfMeasurements,
qu0,
self.testProperty.noOfClassicalBits + 1,
basis,
self.testProperty.backend)
testResults = StatAnalyser().testAssertProbability(self.testProperty.pVal, expectedProbas, dataFromExec)
qu0Params = [(self.initTests[index][1].get(qu0, 0),
self.initTests[index][2].get(qu0, 0)) for index in filteredIndexes]
testResultsWithInit = tuple(zip(testResults, qu0Params))
return testResultsWithInit
"""
This method is a wrapper around assertprobabilitydata that outputs the results
to the user
INPUTS:
- qu0: int = the index of the qubit to test
- expectedproba: float = expected probability of the qubit to be in state |0>
- qu0_pre: bool = whether the data will be sampled before the application of the quantumfunction
- basis: str = the basis in which the measurements can take place
- filter_qc: function[quantumcircuit => bool] or none = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of the results for each test:
~ a result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertProbability(self, qu0, expectedProba, qu0_pre=False, basis="z", filter_qc=None):
results = self.assertProbabilityData(qu0, expectedProba, qu0_pre, basis, filter_qc)
print(f"AssertProbability({qu0}{'_pre' if qu0_pre else ''}, {expectedProba}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0]} Phi = {testResult[1][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method is a wrapper around assertProbabilityData that outputs the results
to the user
It negates the boolean values
INPUTS:
- qu0: int = the index of the qubit to test
- expectedProba: float = expected probability of the qubit to be in state |0>
- qu0_pre: bool = whether the data will be sampled before the application of the quantumFunction
- basis: str = the basis in which the measurements can take place
- filter_qc: function[QuantumCircuit => bool] or None = function applied
to a qc that filters out tests based on an input criterion
OUTPUTS:
- List of the results for each test:
~ A result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertNotProbability(self, qu0, expectedProba, qu0_pre=False, basis="z", filter_qc=None):
oppositeResults = self.assertProbabilityData(qu0, expectedProba, qu0_pre, basis, filter_qc)
results = [(not x[0], x[1]) for x in oppositeResults]
print(f"AssertNotProbability({qu0}{'_pre' if qu0_pre else ''}, {expectedProba}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0]} Phi = {testResult[1][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method asserts that a qubit's state has teleported from "sent" to "received"
INPUTS:
- sent: int = the index of the first qubit to test
- received: int = the index of the second qubit to test
- basis: str = the basis in which the measurements can take place
- filter_qc: function[quantumcircuit => bool] or none = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of the results for each test:
~ a result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertTeleportedData(self, sent, received, basis, filter_qc):
generatedTests = [qc.copy() for qc, theta, phi in self.initTests]
for generatedTest in generatedTests:
self.quantumFunction(generatedTest)
filteredIndexes, filteredTests = getFilteredInfo(generatedTests, filter_qc)
expectedProbas = []
for qc, thetas, phis in self.initTests:
expectedProba = cos(radians(thetas[sent]) / 2) ** 2
expectedProbas.append(expectedProba)
dataFromReceived = TestExecutor().runTestsAssertProbability(filteredTests,
self.testProperty.noOfExperiments,
self.testProperty.noOfMeasurements,
received,
self.testProperty.noOfClassicalBits + 1,
basis,
self.testProperty.backend)
testResults = StatAnalyser().testAssertProbability(self.testProperty.pVal, expectedProbas, dataFromReceived)
qu0Params = [(self.initTests[index][1].get(sent, 0),
self.initTests[index][2].get(sent, 0)) for index in filteredIndexes]
qu1Params = [(self.initTests[index][1].get(received, 0),
self.initTests[index][2].get(received, 0)) for index in filteredIndexes]
params = tuple(zip(qu0Params, qu1Params))
testResultsWithInit = tuple(zip(testResults, params))
return testResultsWithInit
"""
This method is a wrapper of assertTeleportedData that outputs its results to the user
INPUTS:
- sent: int = the index of the first qubit to test
- received: int = the index of the second qubit to test
- basis: str = the basis in which the measurements can take place
- filter_qc: function[quantumcircuit => bool] or none = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of the results for each test:
~ a result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertTeleported(self, sent, received, basis="z", filter_qc=None):
results = self.assertTeleportedData(sent, received, basis, filter_qc)
print(f"AssertTeleported({sent}, {received}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"sent: Theta = {testResult[1][0][0]} Phi = {testResult[1][0][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method is a wrapper of assertTeleportedData that reverses the booleans
and outputs its results to the user
INPUTS:
- sent: int = the index of the first qubit to test
- received: int = the index of the second qubit to test
- basis: str = the basis in which the measurements can take place
- filter_qc: function[quantumcircuit => bool] or none = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of the results for each test:
~ a result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertNotTeleported(self, sent, received, basis="z", filter_qc=None):
oppositeResults = self.assertTeleportedData(sent, received, basis, filter_qc)
results = [(not x[0], x[1]) for x in oppositeResults]
print(f"AssertTeleported({sent}, {received}) results using basis {basis.upper()}:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"sent: Theta = {testResult[1][0][0]} Phi = {testResult[1][0][1]}")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method asserts that a qubit's state is equal to an input state
(described with a theta and a phi)
INPUTS:
- qu0: int = the index of the qubit to test
- theta: int/float = the angle of the theta
- phi: int/float = the angle of the phi
- isRadian: bool = specifies whether theta and phi are in degrees or radians
- qu0_pre: bool = specifies whether the data is sampled before or after the initialisation
- filter_qc: function[quantumcircuit => bool]/None = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of the results for each test:
~ a result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertStateData(self, qu0, theta, phi, isRadian, qu0_pre, filter_qc):
generatedTests = [qc.copy() for qc, theta, phi in self.initTests]
#Only apply the functions if specified
if not qu0_pre:
for generatedTest in generatedTests:
self.quantumFunction(generatedTest)
filteredIndexes, filteredTests = getFilteredInfo(generatedTests, filter_qc)
dataFromExec = TestExecutor().runTestsAssertState(filteredTests,
self.testProperty.noOfExperiments,
self.testProperty.noOfMeasurements,
qu0,
self.testProperty.noOfClassicalBits + 1,
self.testProperty.backend)
testCircuit = QuantumCircuit(1, 1)
testCircuit.initialize(thetaPhiToStateVector(theta, phi, isRadian), 0)
testCircuits = [testCircuit.copy() for _ in range(len(filteredTests))]
dataFromTestCircuit = TestExecutor().runTestsAssertState(testCircuits,
self.testProperty.noOfExperiments,
self.testProperty.noOfMeasurements,
0,
0,
self.testProperty.backend)
testResultsZ = StatAnalyser().testAssertEqual(self.testProperty.pVal,
tuple(zip(dataFromExec[0], dataFromTestCircuit[0])))
testResultsY = StatAnalyser().testAssertEqual(self.testProperty.pVal,
tuple(zip(dataFromExec[1], dataFromTestCircuit[1])))
testResultsX = StatAnalyser().testAssertEqual(self.testProperty.pVal,
tuple(zip(dataFromExec[2], dataFromTestCircuit[2])))
testResults = [testResultsZ[index] and testResultsY[index] and testResultsX[index] for index in range(len(filteredTests))]
if filter_qc == None:
qu0Params = [(x[1].get(qu0, 0), x[2].get(qu0, 0)) for x in self.initTests]
else:
qu0Params = [(self.initTests[index][1].get(qu0, 0), self.initTests[index][2].get(qu0, 0)) for index in self.indexNotFilteredOut]
testResultsWithInit = tuple(zip(testResults, qu0Params))
return testResultsWithInit
"""
This method is a wrapper around assertStateData which outputs the results to the user
INPUTS:
- qu0: int = the index of the qubit to test
- theta: int/float = the angle of the theta
- phi: int/float = the angle of the phi
- isRadian: bool = specifies whether theta and phi are in degrees or radians
- qu0_pre: bool = specifies whether the data is sampled before or after the initialisation
- filter_qc: function[quantumcircuit => bool]/None = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of the results for each test:
~ a result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertState(self, qu0, theta, phi, isRadian=False, qu0_pre=False, filter_qc=None):
results = self.assertStateData(qu0, theta, phi, isRadian, qu0_pre, filter_qc)
print(f"AssertState({qu0}{'_pre' if qu0_pre else ''}, {theta}, {phi}) results:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0]} Phi = {testResult[1][1]} degrees")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method is a wrapper around assertStateData which negates the booleans and outputs the results to the user
INPUTS:
- qu0: int = the index of the qubit to test
- theta: int/float = the angle of the theta
- phi: int/float = the angle of the phi
- isRadian: bool = specifies whether theta and phi are in degrees or radians
- qu0_pre: bool = specifies whether the data is sampled before or after the initialisation
- filter_qc: function[quantumcircuit => bool]/None = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of the results for each test:
~ a result is a tuple containg a boolean (the result of one test),
the thetas and the phis used to initialise the qubit
"""
def assertNotState(self, qu0, theta, phi, isRadian=False, qu0_pre=False, filter_qc=None):
oppositeResults = self.assertStateData(qu0, theta, phi, isRadian, qu0_pre, filter_qc)
results = [(not x[0], x[1]) for x in oppositeResults]
print(f"AssertNotState({qu0}{'_pre' if qu0_pre else ''}, {theta}, {phi}) results:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult[0]:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed with qubits initialised to:")
print(f"qu0: Theta = {testResult[1][0]} Phi = {testResult[1][1]} degrees")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
"""
This method evaluates which multi-qubit states are the most common
INPUTS:
- outcome: str/list[str] = multi-state outcomes that should be the most common
- filter_qc: function[quantumcircuit => bool]/None = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of booleans
"""
def assertMostCommonData(self,
outcome,
filter_qc):
if isinstance(outcome, str):
outcome = outcome[::-1]
else:
outcome = [x[::-1] for x in outcome]
generatedTests = self.genListQC(self.initTests)
for generatedTest in generatedTests:
self.quantumFunction(generatedTest)
filteredIndexes, filteredTests = getFilteredInfo(generatedTests, filter_qc)
dataFromExec = TestExecutor().runTestsAssertMostProbable(filteredTests,
self.testProperty.noOfMeasurements, self.testProperty.backend)
results = StatAnalyser().testAssertMostCommon(dataFromExec, outcome)
return results
"""
This method is a wrapper that outputs the data of assertMostCommonData
INPUTS:
- outcome: str/list[str] = multi-state outcomes that should be the most common
- filter_qc: function[quantumcircuit => bool]/None = function applied
to a qc that filters out tests based on an input criterion
OUTPUT:
- list of booleans
"""
def assertMostCommon(self,
outcome,
filter_qc=None):
results = self.assertMostCommonData(outcome, filter_qc)
print(f"AssertMostCommon({outcome}) results:")
failed = False
nbFailed = 0
for testIndex, testResult in enumerate(results):
if not testResult:
failed = True
nbFailed += 1
print(f"Test at index {testIndex} failed")
if failed:
print(f"Not all tests have succeeded: {len(results) - nbFailed} / {len(results)} succeeded\n")
else:
print(f"All {len(results)} tests have succeeded!\n")
return results
# def assertEqualData(self, qu0, qu1, qu0_pre, qu1_pre, basis, filter_qc):
# def assertEqual(backend, quantumCircuit, qubit1, qubit2, measurements_to_make, alpha):
# def assertPhase(backend, quantumCircuit, qubits_to_assert, expected_phases, measurements_to_make, alpha):
# def assertPhaseData(self,qubit0,qubit1,expectedPhases,filter_qc):
# generatedTests = self.genListQC(self.initTests)
# filteredIndexes, filteredTests = getFilteredInfo(generatedTests, filter_qc)
# for generatedTest in generatedTests:
# self.quantumFunction(generatedTest)
# dataFromExec = TestExecutor().runTestsAssertPhase(filteredTests,
# self.testProperty.noOfExperiments,
# self.testProperty.noOfMeasurements,
# qu0,
# self.testProperty.noOfClassicalBits + 1,
# basis,
# self.testProperty.backend)
# testResults = StatAnalyser().testAssertPhase(self.testProperty.pVal, expectedProbas, dataFromExec)
# qu0Params = [(self.initTests[index][1].get(qu0, 0),
# self.initTests[index][2].get(qu0, 0)) for index in filteredIndexes]
# testResultsWithInit = tuple(zip(testResults, qu0Params))
# return testResultsWithInit
#Default functions that will be usually overwritten by the user
@abstractmethod
def property(self):
return TestProperty()
def quantumFunction(self, qc):
pass
@abstractmethod
def assertions(self):
pass
"""
This method runs the entirety of the tests
"""
def run(self):
print(f"Running tests for {type(self).__name__}:\n")
self.testProperty = self.property()
self.initTests = Generator().generateTests(self.testProperty)
self.assertions()
print(f"Tests for {type(self).__name__} finished\n")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import *
from qiskit.circuit import Gate
my_gate = Gate(name='my_gate', num_qubits=2, params=[])
qr = QuantumRegister(3, 'q')
circ = QuantumCircuit(qr)
circ.append(my_gate, [qr[0], qr[1]])
circ.append(my_gate, [qr[1], qr[2]])
circ.draw()
# Build a sub-circuit
sub_q = QuantumRegister(2)
sub_circ = QuantumCircuit(sub_q, name='sub_circ')
sub_circ.h(sub_q[0])
sub_circ.crz(1, sub_q[0], sub_q[1])
sub_circ.barrier()
sub_circ.id(sub_q[1])
sub_circ.u(1, 2, -2, sub_q[0])
# Convert to a gate and stick it into an arbitrary place in the bigger circuit
sub_inst = sub_circ.to_instruction()
qr = QuantumRegister(3, 'q')
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.cx(qr[1], qr[2])
circ.append(sub_inst, [qr[1], qr[2]])
circ.draw()
decomposed_circ = circ.decompose() # Does not modify original circuit
decomposed_circ.draw()
from qiskit.circuit import Parameter
theta = Parameter('θ')
n = 5
qc = QuantumCircuit(5, 1)
qc.h(0)
for i in range(n-1):
qc.cx(i, i+1)
qc.barrier()
qc.rz(theta, range(5))
qc.barrier()
for i in reversed(range(n-1)):
qc.cx(i, i+1)
qc.h(0)
qc.measure(0, 0)
qc.draw('mpl')
print(qc.parameters)
import numpy as np
theta_range = np.linspace(0, 2 * np.pi, 128)
circuits = [qc.bind_parameters({theta: theta_val})
for theta_val in theta_range]
circuits[-1].draw()
backend = BasicAer.get_backend('qasm_simulator')
job = backend.run(transpile(circuits, backend))
counts = job.result().get_counts()
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)
ax.plot(theta_range, list(map(lambda c: c.get('0', 0), counts)), '.-', label='0')
ax.plot(theta_range, list(map(lambda c: c.get('1', 0), counts)), '.-', label='1')
ax.set_xticks([i * np.pi / 2 for i in range(5)])
ax.set_xticklabels(['0', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'], fontsize=14)
ax.set_xlabel('θ', fontsize=14)
ax.set_ylabel('Counts', fontsize=14)
ax.legend(fontsize=14)
import time
from itertools import combinations
from qiskit.compiler import assemble
from qiskit.test.mock import FakeVigo
start = time.time()
qcs = []
theta_range = np.linspace(0, 2*np.pi, 32)
for n in theta_range:
qc = QuantumCircuit(5)
for k in range(8):
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qc.rz(n, range(5))
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qcs.append(qc)
compiled_circuits = transpile(qcs, backend=FakeVigo())
qobj = assemble(compiled_circuits, backend=FakeVigo())
end = time.time()
print('Time compiling over set of bound circuits: ', end-start)
start = time.time()
qc = QuantumCircuit(5)
theta = Parameter('theta')
for k in range(8):
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qc.rz(theta, range(5))
for i,j in combinations(range(5), 2):
qc.cx(i,j)
transpiled_qc = transpile(qc, backend=FakeVigo())
qobj = assemble([transpiled_qc.bind_parameters({theta: n})
for n in theta_range], backend=FakeVigo())
end = time.time()
print('Time compiling over parameterized circuit, then binding: ', end-start)
phi = Parameter('phi')
sub_circ1 = QuantumCircuit(2, name='sc_1')
sub_circ1.rz(phi, 0)
sub_circ1.rx(phi, 1)
sub_circ2 = QuantumCircuit(2, name='sc_2')
sub_circ2.rx(phi, 0)
sub_circ2.rz(phi, 1)
qc = QuantumCircuit(4)
qr = qc.qregs[0]
qc.append(sub_circ1.to_instruction(), [qr[0], qr[1]])
qc.append(sub_circ2.to_instruction(), [qr[0], qr[1]])
qc.append(sub_circ2.to_instruction(), [qr[2], qr[3]])
print(qc.draw())
# The following raises an error: "QiskitError: 'Name conflict on adding parameter: phi'"
# phi2 = Parameter('phi')
# qc.u3(0.1, phi2, 0.3, 0)
p = Parameter('p')
qc = QuantumCircuit(3, name='oracle')
qc.rz(p, 0)
qc.cx(0, 1)
qc.rz(p, 1)
qc.cx(1, 2)
qc.rz(p, 2)
theta = Parameter('theta')
phi = Parameter('phi')
gamma = Parameter('gamma')
qr = QuantumRegister(9)
larger_qc = QuantumCircuit(qr)
larger_qc.append(qc.to_instruction({p: theta}), qr[0:3])
larger_qc.append(qc.to_instruction({p: phi}), qr[3:6])
larger_qc.append(qc.to_instruction({p: gamma}), qr[6:9])
print(larger_qc.draw())
print(larger_qc.decompose().draw())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
p = 0.2
import numpy as np
from qiskit.circuit import QuantumCircuit
class BernoulliA(QuantumCircuit):
"""A circuit representing the Bernoulli A operator."""
def __init__(self, probability):
super().__init__(1) # circuit on 1 qubit
theta_p = 2 * np.arcsin(np.sqrt(probability))
self.ry(theta_p, 0)
class BernoulliQ(QuantumCircuit):
"""A circuit representing the Bernoulli Q operator."""
def __init__(self, probability):
super().__init__(1) # circuit on 1 qubit
self._theta_p = 2 * np.arcsin(np.sqrt(probability))
self.ry(2 * self._theta_p, 0)
def power(self, k):
# implement the efficient power of Q
q_k = QuantumCircuit(1)
q_k.ry(2 * k * self._theta_p, 0)
return q_k
A = BernoulliA(p)
Q = BernoulliQ(p)
from qiskit.algorithms import EstimationProblem
problem = EstimationProblem(
state_preparation=A, # A operator
grover_operator=Q, # Q operator
objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0
)
from qiskit.primitives import Sampler
sampler = Sampler()
from qiskit.algorithms import AmplitudeEstimation
ae = AmplitudeEstimation(
num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy
sampler=sampler,
)
ae_result = ae.estimate(problem)
print(ae_result.estimation)
import matplotlib.pyplot as plt
# plot estimated values
gridpoints = list(ae_result.samples.keys())
probabilities = list(ae_result.samples.values())
plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities))
plt.axvline(p, color="r", ls="--")
plt.xticks(size=15)
plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.title("Estimated Values", size=15)
plt.ylabel("Probability", size=15)
plt.xlabel(r"Amplitude $a$", size=15)
plt.ylim((0, 1))
plt.grid()
plt.show()
print("Interpolated MLE estimator:", ae_result.mle)
ae_circuit = ae.construct_circuit(problem)
ae_circuit.decompose().draw(
"mpl", style="iqx"
) # decompose 1 level: exposes the Phase estimation circuit!
from qiskit import transpile
basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"]
transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx")
from qiskit.algorithms import IterativeAmplitudeEstimation
iae = IterativeAmplitudeEstimation(
epsilon_target=0.01, # target accuracy
alpha=0.05, # width of the confidence interval
sampler=sampler,
)
iae_result = iae.estimate(problem)
print("Estimate:", iae_result.estimation)
iae_circuit = iae.construct_circuit(problem, k=3)
iae_circuit.draw("mpl", style="iqx")
from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation
mlae = MaximumLikelihoodAmplitudeEstimation(
evaluation_schedule=3, # log2 of the maximal Grover power
sampler=sampler,
)
mlae_result = mlae.estimate(problem)
print("Estimate:", mlae_result.estimation)
from qiskit.algorithms import FasterAmplitudeEstimation
fae = FasterAmplitudeEstimation(
delta=0.01, # target accuracy
maxiter=3, # determines the maximal power of the Grover operator
sampler=sampler,
)
fae_result = fae.estimate(problem)
print("Estimate:", fae_result.estimation)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/DuarteSerranoR/qiskit_quantum_algorithms
|
DuarteSerranoR
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram
from math import gcd
from numpy.random import randint
import pandas as pd
from fractions import Fraction
def qft_dagger(n):
"""n-qubit QFTdagger the first n qubits in circ"""
qc = QuantumCircuit(n)
# Don't forget the Swaps!
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-np.pi/float(2**(j-m)), m, j)
qc.h(j)
qc.name = "QFT†"
return qc
def c_amod15(a, power):
"""Controlled multiplication by a mod 15"""
if a not in [2,4,7,8,11,13]:
raise ValueError("'a' must be 2,4,7,8,11 or 13")
U = QuantumCircuit(4)
for iteration in range(power):
if a in [2,13]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
if a in [7,8]:
U.swap(2,3)
U.swap(1,2)
U.swap(0,1)
if a in [4, 11]:
U.swap(1,3)
U.swap(0,2)
if a in [7,11,13]:
for q in range(4):
U.x(q)
U = U.to_gate()
U.name = "%i^%i mod 15" % (a, power)
c_U = U.control()
return c_U
# Specify variables
n_count = 8 # number of counting qubits
a = 7
# Period finding
# Create QuantumCircuit with n_count counting qubits
# plus 4 qubits for U to act on
qc = QuantumCircuit(n_count + 4, n_count)
# Initialize counting qubits
# in state |+>
for q in range(n_count):
qc.h(q)
# And auxiliary register in state |1>
qc.x(3+n_count)
# Do controlled-U operations
for q in range(n_count):
qc.append(c_amod15(a, 2**q),
[q] + [i+n_count for i in range(4)])
# Do inverse-QFT
qc.append(qft_dagger(n_count), range(n_count))
# Measure circuit
qc.measure(range(n_count), range(n_count))
qc.draw(fold=-1) # -1 means 'do not fold'
# Factoring
N = 39
#np.random.seed(1) # This is to make sure we get reproduceable results
#a = randint(2, 15)
#print(a)
a = 2
from math import gcd # greatest common divisor
gcd(a, N)
def qpe_amod15(a):
n_count = 8
qc = QuantumCircuit(4+n_count, n_count)
for q in range(n_count):
qc.h(q) # Initialize counting qubits in state |+>
qc.x(3+n_count) # And auxiliary register in state |1>
for q in range(n_count): # Do controlled-U operations
qc.append(c_amod15(a, 2**q),
[q] + [i+n_count for i in range(4)])
qc.append(qft_dagger(n_count), range(n_count)) # Do inverse-QFT
qc.measure(range(n_count), range(n_count))
# Simulate Results
aer_sim = Aer.get_backend('aer_simulator')
# Setting memory=True below allows us to see a list of each sequential reading
t_qc = transpile(qc, aer_sim)
qobj = assemble(t_qc, shots=1)
result = aer_sim.run(qobj, memory=True).result()
readings = result.get_memory()
print("Register Reading: " + readings[0])
phase = int(readings[0],2)/(2**n_count)
print("Corresponding Phase: %f" % phase)
return phase
phase = qpe_amod15(a) # Phase = s/r
Fraction(phase).limit_denominator(15) # Denominator should (hopefully!) tell us r
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)
a = 2
#a = 7
factor_found = False
attempt = 0
while not factor_found:
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)
factor_found = True
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Classical Imaginary Evolver."""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from ddt import data, ddt, unpack
import numpy as np
from qiskit_algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem
from qiskit.quantum_info.states.statevector import Statevector
from qiskit.quantum_info import SparsePauliOp
from qiskit import QuantumCircuit
from qiskit_algorithms import SciPyImaginaryEvolver
from qiskit.opflow import PauliSumOp
@ddt
class TestSciPyImaginaryEvolver(QiskitAlgorithmsTestCase):
"""Test SciPy Imaginary Evolver."""
def create_hamiltonian_lattice(self, num_sites: int) -> SparsePauliOp:
"""Creates an Ising Hamiltonian on a lattice."""
j_const = 0.1
g_const = -1.0
zz_op = ["I" * i + "ZZ" + "I" * (num_sites - i - 2) for i in range(num_sites - 1)]
x_op = ["I" * i + "X" + "I" * (num_sites - i - 1) for i in range(num_sites)]
return SparsePauliOp(zz_op) * j_const + SparsePauliOp(x_op) * g_const
@data(
(Statevector.from_label("0"), 100, SparsePauliOp("X"), Statevector.from_label("-")),
(Statevector.from_label("0"), 100, SparsePauliOp("-X"), Statevector.from_label("+")),
)
@unpack
def test_evolve(
self,
initial_state: Statevector,
tau: float,
hamiltonian: SparsePauliOp,
expected_state: Statevector,
):
"""Initializes a classical imaginary evolver and evolves a state to find the ground state.
It compares the solution with the first eigenstate of the hamiltonian.
"""
expected_state_matrix = expected_state.data
evolution_problem = TimeEvolutionProblem(hamiltonian, tau, initial_state)
classic_evolver = SciPyImaginaryEvolver(num_timesteps=300)
result = classic_evolver.evolve(evolution_problem)
with self.subTest("Amplitudes"):
np.testing.assert_allclose(
np.absolute(result.evolved_state.data),
np.absolute(expected_state_matrix),
atol=1e-10,
rtol=0,
)
with self.subTest("Phases"):
np.testing.assert_allclose(
np.angle(result.evolved_state.data),
np.angle(expected_state_matrix),
atol=1e-10,
rtol=0,
)
@data(
(
Statevector.from_label("0" * 5),
SparsePauliOp.from_sparse_list([("X", [i], 1) for i in range(5)], num_qubits=5),
5,
),
(Statevector.from_label("0"), SparsePauliOp("X"), 1),
)
@unpack
def test_observables(
self, initial_state: Statevector, hamiltonian: SparsePauliOp, nqubits: int
):
"""Tests if the observables are properly evaluated at each timestep."""
time_ev = 5.0
observables = {"Energy": hamiltonian, "Z": SparsePauliOp("Z" * nqubits)}
evolution_problem = TimeEvolutionProblem(
hamiltonian, time_ev, initial_state, aux_operators=observables
)
classic_evolver = SciPyImaginaryEvolver(num_timesteps=300)
result = classic_evolver.evolve(evolution_problem)
z_mean, z_std = result.observables["Z"]
time_vector = result.times
expected_z = 1 / (np.cosh(time_vector) ** 2 + np.sinh(time_vector) ** 2)
expected_z_std = np.zeros_like(expected_z)
np.testing.assert_allclose(z_mean, expected_z**nqubits, atol=1e-10, rtol=0)
np.testing.assert_allclose(z_std, expected_z_std, atol=1e-10, rtol=0)
def test_quantum_circuit_initial_state(self):
"""Tests if the system can be evolved with a quantum circuit as an initial state."""
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, range(1, 3))
evolution_problem = TimeEvolutionProblem(
hamiltonian=SparsePauliOp("X" * 3), time=1.0, initial_state=qc
)
classic_evolver = SciPyImaginaryEvolver(num_timesteps=5)
result = classic_evolver.evolve(evolution_problem)
self.assertEqual(result.evolved_state, Statevector(qc))
def test_paulisumop_hamiltonian(self):
"""Tests if the hamiltonian can be a PauliSumOp"""
with self.assertWarns(DeprecationWarning):
hamiltonian = PauliSumOp.from_list(
[
("XI", 1),
("IX", 1),
]
)
observable = PauliSumOp.from_list([("ZZ", 1)])
evolution_problem = TimeEvolutionProblem(
hamiltonian=hamiltonian,
time=1.0,
initial_state=Statevector.from_label("00"),
aux_operators={"ZZ": observable},
)
classic_evolver = SciPyImaginaryEvolver(num_timesteps=5)
result = classic_evolver.evolve(evolution_problem)
expected = 1 / (np.cosh(1.0) ** 2 + np.sinh(1.0) ** 2)
np.testing.assert_almost_equal(result.aux_ops_evaluated["ZZ"][0], expected**2)
def test_error_time_dependency(self):
"""Tests if an error is raised for a time dependent Hamiltonian."""
evolution_problem = TimeEvolutionProblem(
hamiltonian=SparsePauliOp("X" * 3),
time=1.0,
initial_state=Statevector.from_label("0" * 3),
t_param=0,
)
classic_evolver = SciPyImaginaryEvolver(num_timesteps=5)
with self.assertRaises(ValueError):
classic_evolver.evolve(evolution_problem)
def test_no_time_steps(self):
"""Tests if the evolver handles some edge cases related to the number of timesteps."""
evolution_problem = TimeEvolutionProblem(
hamiltonian=SparsePauliOp("X"),
time=1.0,
initial_state=Statevector.from_label("0"),
aux_operators={"Energy": SparsePauliOp("X")},
)
with self.subTest("0 timesteps"):
with self.assertRaises(ValueError):
classic_evolver = SciPyImaginaryEvolver(num_timesteps=0)
classic_evolver.evolve(evolution_problem)
with self.subTest("1 timestep"):
classic_evolver = SciPyImaginaryEvolver(num_timesteps=1)
result = classic_evolver.evolve(evolution_problem)
np.testing.assert_equal(result.times, np.array([0.0, 1.0]))
with self.subTest("Negative timesteps"):
with self.assertRaises(ValueError):
classic_evolver = SciPyImaginaryEvolver(num_timesteps=-5)
classic_evolver.evolve(evolution_problem)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from docplex.mp.model import Model
from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import CobylaOptimizer, MinimumEigenOptimizer
from qiskit_optimization.algorithms.admm_optimizer import ADMMParameters, ADMMOptimizer
from qiskit_optimization.translators import from_docplex_mp
# If CPLEX is installed, you can uncomment this line to import the CplexOptimizer.
# CPLEX can be used in this tutorial to solve the convex continuous problem,
# but also as a reference to solve the QUBO, or even the full problem.
#
# from qiskit.optimization.algorithms import CplexOptimizer
# define COBYLA optimizer to handle convex continuous problems.
cobyla = CobylaOptimizer()
# define QAOA via the minimum eigen optimizer
qaoa = MinimumEigenOptimizer(QAOA(sampler=Sampler(), optimizer=COBYLA()))
# exact QUBO solver as classical benchmark
exact = MinimumEigenOptimizer(NumPyMinimumEigensolver()) # to solve QUBOs
# in case CPLEX is installed it can also be used for the convex problems, the QUBO,
# or as a benchmark for the full problem.
#
# cplex = CplexOptimizer()
# construct model using docplex
mdl = Model("ex6")
v = mdl.binary_var(name="v")
w = mdl.binary_var(name="w")
t = mdl.binary_var(name="t")
u = mdl.continuous_var(name="u")
mdl.minimize(v + w + t + 5 * (u - 2) ** 2)
mdl.add_constraint(v + 2 * w + t + u <= 3, "cons1")
mdl.add_constraint(v + w + t >= 1, "cons2")
mdl.add_constraint(v + w == 1, "cons3")
# load quadratic program from docplex model
qp = from_docplex_mp(mdl)
print(qp.prettyprint())
admm_params = ADMMParameters(
rho_initial=1001, beta=1000, factor_c=900, maxiter=100, three_block=True, tol=1.0e-6
)
# define QUBO optimizer
qubo_optimizer = exact
# qubo_optimizer = cplex # uncomment to use CPLEX instead
# define classical optimizer
convex_optimizer = cobyla
# convex_optimizer = cplex # uncomment to use CPLEX instead
# initialize ADMM with classical QUBO and convex optimizer
admm = ADMMOptimizer(
params=admm_params, qubo_optimizer=qubo_optimizer, continuous_optimizer=convex_optimizer
)
# run ADMM to solve problem
result = admm.solve(qp)
print(result.prettyprint())
plt.plot(result.state.residuals)
plt.xlabel("Iterations")
plt.ylabel("Residuals")
plt.show()
# define QUBO optimizer
qubo_optimizer = qaoa
# define classical optimizer
convex_optimizer = cobyla
# convex_optimizer = cplex # uncomment to use CPLEX instead
# initialize ADMM with quantum QUBO optimizer and classical convex optimizer
admm_q = ADMMOptimizer(
params=admm_params, qubo_optimizer=qubo_optimizer, continuous_optimizer=convex_optimizer
)
# run ADMM to solve problem
result_q = admm_q.solve(qp)
print(result.prettyprint())
plt.clf()
plt.plot(result_q.state.residuals)
plt.xlabel("Iterations")
plt.ylabel("Residuals")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver()
problem = driver.run()
fermionic_op = problem.hamiltonian.second_q_op()
from qiskit_nature.second_q.mappers import JordanWignerMapper
mapper = JordanWignerMapper()
qubit_jw_op = mapper.map(fermionic_op)
print(qubit_jw_op)
from qiskit_nature.second_q.mappers import ParityMapper
mapper = ParityMapper()
qubit_p_op = mapper.map(fermionic_op)
print(qubit_p_op)
mapper = ParityMapper(num_particles=problem.num_particles)
qubit_op = mapper.map(fermionic_op)
print(qubit_op)
tapered_mapper = problem.get_tapered_mapper(mapper)
print(type(tapered_mapper))
qubit_op = tapered_mapper.map(fermionic_op)
print(qubit_op)
from qiskit_nature.second_q.circuit.library import HartreeFock
hf_state = HartreeFock(2, (1, 1), JordanWignerMapper())
hf_state.draw()
from qiskit_nature.second_q.mappers import InterleavedQubitMapper
interleaved_mapper = InterleavedQubitMapper(JordanWignerMapper())
hf_state = HartreeFock(2, (1, 1), interleaved_mapper)
hf_state.draw()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
qc = QuantumCircuit(2)
qc.x(1)
qc.draw("mpl")
state = Statevector.from_instruction(qc)
state.draw('bloch')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
# Construct quantum circuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure([0,1], [0,1])
# Select the AerSimulator from the Aer provider
simulator = AerSimulator(method='matrix_product_state')
# Run and get counts, using the matrix_product_state method
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
counts = result.get_counts(0)
counts
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
# Define a snapshot that shows the current state vector
circ.save_statevector(label='my_sv')
circ.save_matrix_product_state(label='my_mps')
circ.measure([0,1], [0,1])
# Execute and get saved data
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
data = result.data(0)
#print the result data
data
num_qubits = 50
circ = QuantumCircuit(num_qubits, num_qubits)
# Create EPR state
circ.h(0)
for i in range (0, num_qubits-1):
circ.cx(i, i+1)
# Measure
circ.measure(range(num_qubits), range(num_qubits))
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
print("Time taken: {} sec".format(result.time_taken))
result.get_counts()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/erinaldi/bmn2-qiskit
|
erinaldi
|
import sys
import numpy as np
N = 2 # cutoff for Fock space. The number of qubits used will be K = log2(N)
annOp = np.array(np.diagflat(np.sqrt(np.linspace(1,N-1,N-1)),k=1))
with np.printoptions(precision=3, suppress=True, linewidth=120, threshold=sys.maxsize): # print array lines up to character 120 and floats using 3 digits
print(annOp)
iden = np.identity(N)
with np.printoptions(precision=3, suppress=True, linewidth=120, threshold=sys.maxsize): # print array lines up to character 120 and floats using 3 digits
print(iden)
Nmat = 6 # number of bosonic dof as matrices: SU(2) -> 2^2-1=6 generators
bosonList = [annOp]
for bosons in range(0,Nmat-1):
bosonList.append(iden)
with np.printoptions(precision=3, suppress=True, linewidth=120, threshold=sys.maxsize):
for i in bosonList:
print(f"{i}\n")
# This for loop takes the appropriate Kronecker products for each boson.
for i in range(0,Nmat):
for j in range(0,Nmat-1):
# For the nth boson, the nth Kronecker product is with the annihilation operator.
if j == i-1 and i != 0:
bosonList[i] = np.kron(bosonList[i], annOp)
# Else, the nth Kronecker product is with the identity matrix.
else:
bosonList[i] = np.kron(bosonList[i], iden)
# the following will crash the system
# with np.printoptions(precision=3, suppress=True, linewidth=120, threshold=sys.maxsize):
# for i in bosonList:
# print(f"{i}\n")
[x.shape for x in bosonList]
import matplotlib.pyplot as plt
fig, ax = plt.subplots(ncols=6, figsize=(18, 6))
fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.5, hspace=1)
for i,axi in enumerate(np.ravel(ax)):
pos = axi.imshow(bosonList[i], cmap='jet')
#fig.colorbar(pos, ax=axi)
axi.set_title(f"Boson {i+1}")
fig.suptitle('Operators', fontsize=16)
fig.subplots_adjust(top=0.9)
def bosonHamiltonians(numBosons, bosonMatrixDim, coupling=0.1):
# This function takes the number of bosons (numBosons) and the size of the bosons (bosonMatrixDim)
# as arguments. If the size of the boson is 2 x 2, for example, then bosonMatrixDim = 2.
# coupling is lambda/2 and lambda is the 'tHooft coupling
# Create the n x n annhiliation operator. Here, we create a list with all the integers from
# the square root of 1 to the square root of n-1, where n x n is the size of the boson.
# This list is injected as the upper diagonal in an array of zeros.
annOP = np.array(np.diagflat(np.sqrt(np.linspace(1,bosonMatrixDim-1,bosonMatrixDim-1)),k=1))
# Create the n x n identity matrix.
iden = np.identity(bosonMatrixDim)
# Create a list which holds the six bosons. bosonList[0] is the first boson. bosonList[5] is the 6th boson.
# For the first boson, the Kronecker product starts with the annihilation operator.
bosonList = [annOP]
# This for loop creates the list of bosons before the Kronecker products are taken. The first one was
# already created in the previous line.
for bosons in range(0,numBosons-1):
bosonList.append(iden)
# This for loop takes the appropriate Kronecker products for each boson.
for i in range(0,numBosons):
for j in range(0,numBosons-1):
# For the nth boson, the nth Kronecker product is with the annihilation operator.
if j == i-1 and i != 0:
bosonList[i] = np.kron(bosonList[i], annOP)
# Else, the nth Kronecker product is with the identity matrix.
else:
bosonList[i] = np.kron(bosonList[i], iden)
# Create the position operators. Normalized as in the notes
x = []
for r in range(0, numBosons):
x.append((1/np.sqrt(2))*(bosonList[r] + np.transpose(np.conjugate(bosonList[r]))))
# Create the simple quadratic Hamiltonian.
H2MM = 0
for i in range(0,numBosons):
# The @ symbol is a shorthand for matrix multiplication. It's equivalent to using np.matmul().
H2MM = H2MM + (np.transpose(np.conjugate(bosonList[i])) @ bosonList[i])
H2MM = H2MM + 0.5*numBosons*np.identity(bosonMatrixDim**(numBosons))
# Create the full quartic SU(2) Hamiltonian.
x_sq = []
for i in x:
x_sq.append(i @ i)
H4MM1 = (H2MM + coupling*((x_sq[2] @ x_sq[3])
+ (x_sq[2] @ x_sq[4])
+ (x_sq[1] @ x_sq[3])
+ (x_sq[1] @ x_sq[5])
+ (x_sq[0] @ x_sq[4])
+ (x_sq[0] @ x_sq[5])
- 2*((x[0] @ x[2]) @ (x[3] @ x[5]))
- 2*((x[0] @ x[1]) @ (x[3] @ x[4]))
- 2*((x[1] @ x[2]) @ (x[4] @ x[5]))))
return H2MM, H4MM1
# Set the number of bosons here. For the proper full quartic SU(2) Hamiltonian, this has to be 6.
numBosons = 6
# Set the size of the bosons here. For an n x n boson, bosonMatrixDim = n.
# 5 will crash on laptop -> out of memory > 10GB
# it also crashes this colab with 12Gb of RAM -> tries 6 of these tcmalloc: large alloc 1953128448 bytes
# THIS IS ONLY BECAUSE WE ARE USING NUMPY IN THE FUNCTION! THIS CAN BE AVOIDED USING QISKIT OR QUTIP DIRECTLY TO CREATE SPARSE REPRESENTATIONS
bosonMatrixDim = 4
# the function actually creates intermediate matrices x and x2 so the memory footprint is even higher...for N=5 it requires ~50GB of RAM
H2MM, H4MM1 = bosonHamiltonians(numBosons, bosonMatrixDim, coupling=0.1) # we can change the coupling by adding coupling=0.5 to the args
# Set the Hamiltonian that you want to run the VQE algorithm with here.
hamiltonian = H4MM1
# Use numpy to find the eigenvalues of the simple quartic Hamiltonian
# this can take a long time for large matrices
val,vec=np.linalg.eig(hamiltonian)
z = np.argsort(val)
z = z[0:len(hamiltonian)]
energies=(val[z])
if hamiltonian.all() == H4MM1.all():
# Sometimes there are negligible imaginary parts (e.g. order of 10^-16), so I take the real parts only.
print('Full Quartic SU2 Eigenvalues:\n\n', np.real(energies))
else:
print('Simple Quartic Eigenvalues:\n\n', energies)
from qiskit.algorithms import VQE, NumPyEigensolver
from qiskit import Aer
# Convert the Hamiltonian Matrix to a qubit operator.
import warnings
import time
from qiskit.opflow import MatrixOp
start_time = time.time()
warnings.filterwarnings("ignore")
qubitOp = MatrixOp(primitive=hamiltonian)
print("Size of Hamiltonian:", np.shape(hamiltonian))
print(qubitOp)
end_time = time.time()
runtime = end_time-start_time
print('Program runtime: ',runtime)
print("Total number of qubits: ",qubitOp.num_qubits)
print(type(qubitOp).__name__)
# Create the variational form.
from qiskit.circuit.library import EfficientSU2
var_form = EfficientSU2(qubitOp.num_qubits, su2_gates=['ry'], entanglement="full", reps=1)
var_form.draw(output='mpl',fold=100)
# var_form.draw(output='mpl',fold=100, style={"fontsize":10, "displaycolor": {"ry": ('#9DC3E6','#000000')}},filename="../figures/var_form_bmn2_Ry_depth1.pdf")
np.log2(hamiltonian.shape[0])
# This is a callback function that will allow us to store information about the optimizer while the VQE is running.
# This is called when instantiating an object of the VQE class.
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
from qiskit.algorithms.optimizers import SLSQP
from qiskit.utils import algorithm_globals, QuantumInstance
warnings.filterwarnings("ignore")
rngseed = 0
algorithm_globals.random_seed = rngseed
backend = Aer.get_backend(
"statevector_simulator", max_parallel_threads=6, max_parallel_experiments=0
)
q_instance = QuantumInstance(
backend, seed_transpiler=rngseed, seed_simulator=rngseed
)
counts = []
values = []
optim = SLSQP(maxiter=1000)
# Setup the VQE algorithm
vqe = VQE(
ansatz=var_form,
optimizer=optim,
quantum_instance=q_instance,
callback=store_intermediate_result,
)
# run the VQE with out Hamiltonian operator
result = vqe.compute_minimum_eigenvalue(qubitOp)
vqe_result = np.real(result.eigenvalue)
print(f"VQE gs energy: {vqe_result}")
# Plot all of the optimizers in a single convergence plot. If you see that the optimizer isn't converging,
# increase the maximum iterations or maximum function evaluations in the optimizer list above.
labelList = ["SLSQP"]
# Limit the range of the plot in order to make the convergence of each optimizer more visible.
plt.plot(counts, values)
plt.axhline(y=np.real(energies[0]),xmin=0,xmax=counts[-1],color='k',linestyle='--',label="Exact Energy")
plt.xlabel('Eval count')
plt.ylabel('Energy')
plt.title('Energy convergence for various optimizers')
plt.legend(loc='upper right', labels=labelList)
from qiskit.algorithms.optimizers import SPSA
from qiskit.utils import algorithm_globals, QuantumInstance
warnings.filterwarnings("ignore")
rngseed = 0
algorithm_globals.random_seed = rngseed
backend = Aer.get_backend("qasm_simulator")
q_instance = QuantumInstance(
backend, shots=1024, seed_transpiler=rngseed, seed_simulator=rngseed
)
counts = []
values = []
optim = SPSA(maxiter=1000)
# Setup the VQE algorithm
vqe = VQE(
ansatz=var_form,
optimizer=optim,
quantum_instance=q_instance,
callback=store_intermediate_result,
)
# run the VQE with out Hamiltonian operator
result = vqe.compute_minimum_eigenvalue(qubitOp)
vqe_result = np.real(result.eigenvalue)
print(f"VQE gs energy: {vqe_result}")
# Plot convergence plot for the SPSA optimizer
plt.figure(figsize=(15,15))
plt.plot(counts, values, label="SPSA")
plt.plot(counts,[np.real(energies[0])]*len(counts), 'k--',label="Exact Energy")
plt.xlabel('Eval count')
plt.ylabel('Energy')
plt.title('Energy convergence of SPSA optimizer (Qasm Simulation)')
plt.legend(loc='upper right')
from scipy.sparse import diags
from scipy.sparse import identity
from scipy.sparse import kron
from scipy.sparse i
def build_operators(L: int, N_bos: int) -> list:
"""Generate all the annihilation operators needed to build the hamiltonian
Args:
L (int): the cutoff of the single site Fock space
N_bos (int): the number of bosonic sites
Returns:
list: a list of annihilation operators, length=N_bos
"""
# The annihilation operator for the single boson
a_b = diags(np.sqrt(np.linspace(1, L - 1, L - 1)), offsets=1)
# The identity operator of the Fock space of a single boson
i_b = identity(L)
# Bosonic Hilbert space
product_list = [i_b] * N_bos # only the identity for bosons repeated N_bos times
a_b_list = [] # this will contain a1...a6
for i in np.arange(0, N_bos): # loop over all bosonic operators
operator_list = product_list.copy() # all elements are the identity operator
operator_list[
i
] = a_b # the i^th element is now the annihilation operator for a single boson
a_b_list.append(
operator_list[0]
) # start taking tensor products from first element
for a in operator_list[1:]:
a_b_list[i] = kron(
a_b_list[i], a
) # do the outer product between each operator_list element
return a_b_list
def build_gauge_casimir(L: int, N_bos: int) -> list:
"""Generate the gauge generators operators
Args:
L (int): the single site cutoff of the Fock space
N_bos (int): the number of bosonic sites
Returns:
list : 3 generators (for SU(2))
"""
# generate the annihilation operators
bosons = build_operators(L, N_bos)
# define the generator list for SU(2)
g_list = [0] * 3
g_list[0] = 1j * (
bosons[1].conjugate().transpose() * bosons[2]
- bosons[2].conjugate().transpose() * bosons[1]
+ bosons[4].conjugate().transpose() * bosons[5]
- bosons[5].conjugate().transpose() * bosons[4]
)
g_list[1] = 1j * (
bosons[2].conjugate().transpose() * bosons[0]
- bosons[0].conjugate().transpose() * bosons[2]
+ bosons[5].conjugate().transpose() * bosons[3]
- bosons[3].conjugate().transpose() * bosons[5]
)
g_list[2] = 1j * (
bosons[0].conjugate().transpose() * bosons[1]
- bosons[1].conjugate().transpose() * bosons[0]
+ bosons[3].conjugate().transpose() * bosons[4]
- bosons[4].conjugate().transpose() * bosons[3]
)
return g_list[0] * g_list[0] + g_list[1] * g_list[1] + g_list[2] * g_list[2]
g2 = build_gauge_casimir(bosonMatrixDim,numBosons)
# result is the output of the VQE
bra = result.eigenstate.conjugate().transpose()
ket = result.eigenstate
op = g2
expect = bra.dot(op.dot(ket))
print(f"<0| g2 |0>: {expect.real}")
counts = []
values = []
optim = SLSQP(maxiter=1000)
# Setup the VQE algorithm
vqe = VQE(
ansatz=var_form,
optimizer=optim,
quantum_instance=q_instance,
callback=store_intermediate_result,
)
# run the VQE with our Hamiltonian operator
result = vqe.compute_minimum_eigenvalue(qubitOp, aux_operators=[MatrixOp(g2)])
vqe_result = np.real(result.eigenvalue)
print(f"VQE gs energy: {vqe_result}")
print(result)
print("<0| g2 |0> from VQE: ",result.aux_operator_eigenvalues[0,0].real)
bra = result.eigenstate.conjugate().transpose()
ket = result.eigenstate
op = g2
expect = bra.dot(op.dot(ket))
print(f"<0| g2 |0> from matrix-vector: {expect.real}")
from scipy.sparse.linalg import eigsh
eigv, eigk = eigsh(H4MM1, 1, which="SA", return_eigenvectors=True, tol=0)
# eigk[:,0] is the ground state vector
bra = eigk[:,0].conjugate().transpose()
ket = eigk[:,0]
op = H4MM1
expect = bra.dot(op.dot(ket))
print(f"<0| H |0> from matrix-vector: {expect.real}")
print(f"eigenvalue of H: {eigv[0]}")
# eigk[:,0] is the ground state vector
bra = eigk[:,0].conjugate().transpose()
ket = eigk[:,0]
op = g2
expect = bra.dot(op.dot(ket))
print(f"<0| G2 |0> from matrix-vector: {expect.real}")
from numpy.linalg import eigh
eigv, eigk = eigh(H4MM1)
print(eigk.shape)
print(eigv[0])
_, eigk = eigh(H4MM1)
for i in np.arange(3):
bra = eigk[:,i].conjugate().transpose()
ket = eigk[:,i]
expect = bra @ g2 @ ket
print(f"<{i}| G2 |{i}> from matrix-vector: {expect.real}")
|
https://github.com/maryrbarros2/QuantumAlgorithms_Qiskit
|
maryrbarros2
|
from qiskit import QuantumCircuit, assemble, Aer
from math import pi, sqrt
from qiskit.visualization import plot_bloch_multivector, plot_histogram
sim = Aer.get_backend('aer_simulator')
# Let's do an X-gate on a |0> qubit
qc = QuantumCircuit(1)
qc.x(0)
qc.draw()
# Let's see the result
qc.save_statevector()
qobj = assemble(qc)
state = sim.run(qobj).result().get_statevector()
plot_bloch_multivector(state)
# Let's do an Y-gate on a |0> qubit
qc = QuantumCircuit(1)
qc.y(0)
qc.draw()
qc.save_statevector()
qobj = assemble(qc)
state = sim.run(qobj).result().get_statevector()
plot_bloch_multivector(state)
#### Z gate
# Let's do an Z-gate on a |0> qubit
qc = QuantumCircuit(1)
qc.z(0)
qc.draw()
qc.save_statevector()
qobj = assemble(qc)
state = sim.run(qobj).result().get_statevector()
plot_bloch_multivector(state)
# Run the code in this cell to see the widget
from qiskit_textbook.widgets import gate_demo
gate_demo(gates='pauli')
# Run the code in this cell to see the widget
from qiskit_textbook.widgets import gate_demo
gate_demo(gates='pauli+h')
# Create the X-measurement function:
def x_measurement(qc, qubit, cbit):
"""Measure 'qubit' in the X-basis, and store the result in 'cbit'"""
qc.h(qubit)
qc.measure(qubit, cbit)
return qc
initial_state = [1/sqrt(2), -1/sqrt(2)]
# Initialize our qubit and measure it
qc = QuantumCircuit(1,1)
qc.initialize(initial_state, 0)
x_measurement(qc, 0, 0) # measure qubit 0 to classical bit 0
qc.draw()
qobj = assemble(qc) # Assemble circuit into a Qobj that can be run
counts = sim.run(qobj).result().get_counts() # Do the simulation, returning the state vector
plot_histogram(counts) # Display the output on measurement of state vector
# Run the code in this cell to see the widget
from qiskit_textbook.widgets import gate_demo
gate_demo(gates='pauli+h+p')
#Specifically,using a P-gate:
qc = QuantumCircuit(1)
qc.p(pi/4, 0)
qc.draw()
qc = QuantumCircuit(1)
qc.s(0) # Apply S-gate to qubit 0
qc.sdg(0) # Apply Sdg-gate to qubit 0
qc.draw()
qc = QuantumCircuit(1)
qc.t(0) # Apply T-gate to qubit 0
qc.tdg(0) # Apply Tdg-gate to qubit 0
qc.draw()
|
https://github.com/fedimser/quantum_decomp
|
fedimser
|
import math
import numpy as np
from .src.decompose_2x2 import unitary2x2_to_gates
from .src.decompose_4x4 import decompose_4x4_optimal
from .src.gate import GateFC, GateSingle
from .src.gate2 import Gate2
from .src.two_level_unitary import TwoLevelUnitary
from .src.utils import PAULI_X, is_unitary, is_special_unitary, \
is_power_of_two, IDENTITY_2x2, permute_matrix
def two_level_decompose(A):
"""Returns list of two-level unitary matrices, which multiply to A.
Matrices are listed in application order, i.e. if answer is
[u_1, u_2, u_3], it means A = u_3 u_2 u_1.
:param A: matrix to decompose.
:return: The decomposition - list of two-level unitary matrices.
"""
def make_eliminating_matrix(a, b):
"""Returns unitary matrix U, s.t. [a, b] U = [c, 0].
Makes second element equal to zero.
Guarantees np.angle(c)=0.
"""
assert (np.abs(a) > 1e-9 and np.abs(b) > 1e-9)
theta = np.arctan(np.abs(b / a))
lmbda = -np.angle(a)
mu = np.pi + np.angle(b) - np.angle(a) - lmbda
result = np.array([[np.cos(theta) * np.exp(1j * lmbda),
np.sin(theta) * np.exp(1j * mu)],
[-np.sin(theta) * np.exp(-1j * mu),
np.cos(theta) * np.exp(-1j * lmbda)]])
assert is_special_unitary(result)
assert np.allclose(np.angle(result[0, 0] * a + result[1, 0] * b), 0)
assert (np.abs(result[0, 1] * a + result[1, 1] * b) < 1e-9)
return result
assert is_unitary(A)
n = A.shape[0]
result = []
# Make a copy, because we are going to mutate it.
cur_A = np.array(A)
for i in range(n - 2):
for j in range(n - 1, i, -1):
a = cur_A[i, j - 1]
b = cur_A[i, j]
if abs(cur_A[i, j]) < 1e-9:
# Element is already zero, nothing to do.
u_2x2 = IDENTITY_2x2
# But if it's last in row, ensure diagonal element will be 1.
if j == i + 1:
u_2x2 = np.array([[1 / a, 0], [0, a]])
elif abs(cur_A[i, j - 1]) < 1e-9:
# Just swap columns.
u_2x2 = PAULI_X
# But if it's last in row, ensure diagonal element will be 1.
if j == i + 1:
u_2x2 = np.array([[0, b], [1 / b, 0]])
else:
u_2x2 = make_eliminating_matrix(a, b)
u_2x2 = TwoLevelUnitary(u_2x2, n, j - 1, j)
u_2x2.multiply_right(cur_A)
if not u_2x2.is_identity():
result.append(u_2x2.inv())
# After we are done with row, diagonal element is 1.
assert np.allclose(cur_A[i, i], 1.0)
last_matrix = TwoLevelUnitary(cur_A[n - 2:n, n - 2:n], n, n - 2, n - 1)
if not last_matrix.is_identity():
result.append(last_matrix)
return result
def two_level_decompose_gray(A):
"""Returns list of two-level matrices, which multiply to A.
:param A: matrix to decompose.
:return: The decomposition - list of two-level unitary matrices. Guarantees
that each matrix acts on single bit.
"""
N = A.shape[0]
assert is_power_of_two(N)
assert A.shape == (N, N), "Matrix must be square."
assert is_unitary(A)
perm = [x ^ (x // 2) for x in range(N)] # Gray code.
result = two_level_decompose(permute_matrix(A, perm))
for matrix in result:
matrix.apply_permutation(perm)
return result
def add_flips(flip_mask, gates):
"""Adds X gates for all qubits specified by qubit_mask."""
qubit_id = 0
while (flip_mask > 0):
if (flip_mask % 2) == 1:
gates.append(GateSingle(Gate2('X'), qubit_id))
flip_mask //= 2
qubit_id += 1
def matrix_to_gates(A, **kwargs):
"""Given unitary matrix A, returns sequence of gates which implements
action of this matrix on register of qubits.
If `optimize=True`, applies optimized algorithm yielding less gates. Will
affect output only when A is 4x4 matrix.
:param A: 2^N x 2^N unitary matrix.
:return: sequence of `Gate`s.
"""
if 'optimize' in kwargs and kwargs['optimize'] and A.shape[0] == 4:
return decompose_4x4_optimal(A)
matrices = two_level_decompose_gray(A)
gates = []
prev_flip_mask = 0
for matrix in matrices:
matrix.order_indices() # Ensures that index2 > index1.
qubit_id_mask = matrix.index1 ^ matrix.index2
assert is_power_of_two(qubit_id_mask)
qubit_id = int(math.log2(qubit_id_mask))
flip_mask = (matrix.matrix_size - 1) - matrix.index2
add_flips(flip_mask ^ prev_flip_mask, gates)
for gate2 in unitary2x2_to_gates(matrix.matrix_2x2):
gates.append(GateFC(gate2, qubit_id))
prev_flip_mask = flip_mask
add_flips(prev_flip_mask, gates)
return gates
def matrix_to_qsharp(matrix, **kwargs):
"""Given unitary matrix A, retuns Q# code which implements
action of this matrix on register of qubits called `qs`.
:param matrix: 2^N x 2^N unitary matrix to convert to Q# code.
:param op_name: name which operation should have. Default name is
"ApplyUnitaryMatrix".
:return: string - Q# code.
"""
op_name = 'ApplyUnitaryMatrix'
if 'op_name' in kwargs:
op_name = kwargs['op_name']
header = ('operation %s (qs : Qubit[]) : Unit {\n' % op_name)
footer = '}\n'
qubits_count = int(np.log2(matrix.shape[0]))
code = '\n'.join([' ' + gate.to_qsharp_command(qubits_count)
for gate in matrix_to_gates(matrix, **kwargs)])
return header + code + '\n' + footer
def matrix_to_cirq_circuit(A, **kwargs):
"""Converts unitary matrix to Cirq circuit.
:param A: 2^N x 2^N unitary matrix.
:return: `cirq.Circuit` implementing this matrix.
"""
import cirq
def gate_to_cirq(gate2):
if gate2.name == 'X':
return cirq.X
elif gate2.name == 'Ry':
return cirq.ry(-gate2.arg)
elif gate2.name == 'Rz':
return cirq.rz(-gate2.arg)
elif gate2.name == 'R1':
return cirq.ZPowGate(exponent=gate2.arg / np.pi)
else:
raise RuntimeError("Can't implement: %s" % gate2)
gates = matrix_to_gates(A, **kwargs)
qubits_count = int(np.log2(A.shape[0]))
circuit = cirq.Circuit()
qubits = cirq.LineQubit.range(qubits_count)[::-1]
for gate in gates:
if isinstance(gate, GateFC):
controls = [qubits[i]
for i in range(qubits_count) if i != gate.qubit_id]
target = qubits[gate.qubit_id]
arg_gates = controls + [target]
cgate = cirq.ControlledGate(
gate_to_cirq(gate.gate2),
num_controls=qubits_count - 1)
circuit.append(cgate.on(*arg_gates))
elif isinstance(gate, GateSingle):
circuit.append(gate_to_cirq(gate.gate2).on(qubits[gate.qubit_id]))
else:
raise RuntimeError('Unknown gate type.')
return circuit
def matrix_to_qiskit_circuit(A, **kwargs):
"""Converts unitary matrix to Qiskit circuit.
:param A: 2^N x 2^N unitary matrix.
:return: `qiskit.QuantumCircuit` implementing this matrix.
"""
from qiskit import QuantumCircuit
from qiskit.circuit.library import XGate, RYGate, RZGate, U1Gate
def gate_to_qiskit(gate2):
if gate2.name == 'X':
return XGate()
elif gate2.name == 'Ry':
return RYGate(-gate2.arg)
elif gate2.name == 'Rz':
return RZGate(-gate2.arg)
elif gate2.name == 'R1':
return U1Gate(gate2.arg)
else:
raise RuntimeError("Can't implement: %s" % gate2)
gates = matrix_to_gates(A, **kwargs)
qubits_count = int(np.log2(A.shape[0]))
circuit = QuantumCircuit(qubits_count)
qubits = circuit.qubits
for gate in gates:
if isinstance(gate, GateFC):
controls = [qubits[i]
for i in range(qubits_count) if i != gate.qubit_id]
target = qubits[gate.qubit_id]
arg_gates = controls + [target]
cgate = gate_to_qiskit(gate.gate2)
if len(controls):
cgate = cgate.control(num_ctrl_qubits=len(controls))
circuit.append(cgate, arg_gates)
elif isinstance(gate, GateSingle):
circuit.append(gate_to_qiskit(gate.gate2), [qubits[gate.qubit_id]])
else:
raise RuntimeError('Unknown gate type.')
return circuit
|
https://github.com/hamburgerguy/Quantum-Algorithm-Implementations
|
hamburgerguy
|
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>)
out of four possible values."""
#import numpy and plot library
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.quantum_info import Statevector
# import basic plot tools
from qiskit.visualization import plot_histogram
# define variables, 1) initialize qubits to zero
n = 2
grover_circuit = QuantumCircuit(n)
#define initialization function
def initialize_s(qc, qubits):
'''Apply a H-gate to 'qubits' in qc'''
for q in qubits:
qc.h(q)
return qc
### begin grovers circuit ###
#2) Put qubits in equal state of superposition
grover_circuit = initialize_s(grover_circuit, [0,1])
# 3) Apply oracle reflection to marked instance x_0 = 3, (|11>)
grover_circuit.cz(0,1)
statevec = job_sim.result().get_statevector()
from qiskit_textbook.tools import vector2latex
vector2latex(statevec, pretext="|\\psi\\rangle =")
# 4) apply additional reflection (diffusion operator)
grover_circuit.h([0,1])
grover_circuit.z([0,1])
grover_circuit.cz(0,1)
grover_circuit.h([0,1])
# 5) measure the qubits
grover_circuit.measure_all()
# Load IBM Q account and get the least busy backend device
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)
from qiskit.tools.monitor import job_monitor
job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(grover_circuit)
plot_histogram(answer)
#highest amplitude should correspond with marked value x_0 (|11>)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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.
# pylint: disable=missing-docstring
import math
from qiskit.circuit.library import (
RZGate,
SXGate,
XGate,
CXGate,
RYGate,
RXGate,
RXXGate,
RGate,
IGate,
ECRGate,
UGate,
CCXGate,
RZXGate,
CZGate,
)
from qiskit.circuit import IfElseOp, ForLoopOp, WhileLoopOp, SwitchCaseOp
from qiskit.circuit.measure import Measure
from qiskit.circuit.parameter import Parameter
from qiskit import pulse
from qiskit.pulse.instruction_schedule_map import InstructionScheduleMap
from qiskit.pulse.calibration_entries import CalibrationPublisher, ScheduleDef
from qiskit.transpiler.coupling import CouplingMap
from qiskit.transpiler.instruction_durations import InstructionDurations
from qiskit.transpiler.timing_constraints import TimingConstraints
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler import Target
from qiskit.transpiler import InstructionProperties
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import (
FakeBackendV2,
FakeMumbaiFractionalCX,
FakeVigo,
FakeNairobi,
FakeGeneva,
)
class TestTarget(QiskitTestCase):
def setUp(self):
super().setUp()
self.fake_backend = FakeBackendV2()
self.fake_backend_target = self.fake_backend.target
self.theta = Parameter("theta")
self.phi = Parameter("phi")
self.ibm_target = Target()
i_props = {
(0,): InstructionProperties(duration=35.5e-9, error=0.000413),
(1,): InstructionProperties(duration=35.5e-9, error=0.000502),
(2,): InstructionProperties(duration=35.5e-9, error=0.0004003),
(3,): InstructionProperties(duration=35.5e-9, error=0.000614),
(4,): InstructionProperties(duration=35.5e-9, error=0.006149),
}
self.ibm_target.add_instruction(IGate(), i_props)
rz_props = {
(0,): InstructionProperties(duration=0, error=0),
(1,): InstructionProperties(duration=0, error=0),
(2,): InstructionProperties(duration=0, error=0),
(3,): InstructionProperties(duration=0, error=0),
(4,): InstructionProperties(duration=0, error=0),
}
self.ibm_target.add_instruction(RZGate(self.theta), rz_props)
sx_props = {
(0,): InstructionProperties(duration=35.5e-9, error=0.000413),
(1,): InstructionProperties(duration=35.5e-9, error=0.000502),
(2,): InstructionProperties(duration=35.5e-9, error=0.0004003),
(3,): InstructionProperties(duration=35.5e-9, error=0.000614),
(4,): InstructionProperties(duration=35.5e-9, error=0.006149),
}
self.ibm_target.add_instruction(SXGate(), sx_props)
x_props = {
(0,): InstructionProperties(duration=35.5e-9, error=0.000413),
(1,): InstructionProperties(duration=35.5e-9, error=0.000502),
(2,): InstructionProperties(duration=35.5e-9, error=0.0004003),
(3,): InstructionProperties(duration=35.5e-9, error=0.000614),
(4,): InstructionProperties(duration=35.5e-9, error=0.006149),
}
self.ibm_target.add_instruction(XGate(), x_props)
cx_props = {
(3, 4): InstructionProperties(duration=270.22e-9, error=0.00713),
(4, 3): InstructionProperties(duration=305.77e-9, error=0.00713),
(3, 1): InstructionProperties(duration=462.22e-9, error=0.00929),
(1, 3): InstructionProperties(duration=497.77e-9, error=0.00929),
(1, 2): InstructionProperties(duration=227.55e-9, error=0.00659),
(2, 1): InstructionProperties(duration=263.11e-9, error=0.00659),
(0, 1): InstructionProperties(duration=519.11e-9, error=0.01201),
(1, 0): InstructionProperties(duration=554.66e-9, error=0.01201),
}
self.ibm_target.add_instruction(CXGate(), cx_props)
measure_props = {
(0,): InstructionProperties(duration=5.813e-6, error=0.0751),
(1,): InstructionProperties(duration=5.813e-6, error=0.0225),
(2,): InstructionProperties(duration=5.813e-6, error=0.0146),
(3,): InstructionProperties(duration=5.813e-6, error=0.0215),
(4,): InstructionProperties(duration=5.813e-6, error=0.0333),
}
self.ibm_target.add_instruction(Measure(), measure_props)
self.aqt_target = Target(description="AQT Target")
rx_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RXGate(self.theta), rx_props)
ry_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RYGate(self.theta), ry_props)
rz_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RZGate(self.theta), rz_props)
r_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RGate(self.theta, self.phi), r_props)
rxx_props = {
(0, 1): None,
(0, 2): None,
(0, 3): None,
(0, 4): None,
(1, 0): None,
(2, 0): None,
(3, 0): None,
(4, 0): None,
(1, 2): None,
(1, 3): None,
(1, 4): None,
(2, 1): None,
(3, 1): None,
(4, 1): None,
(2, 3): None,
(2, 4): None,
(3, 2): None,
(4, 2): None,
(3, 4): None,
(4, 3): None,
}
self.aqt_target.add_instruction(RXXGate(self.theta), rxx_props)
measure_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(Measure(), measure_props)
self.empty_target = Target()
self.ideal_sim_target = Target(num_qubits=3, description="Ideal Simulator")
self.lam = Parameter("lam")
for inst in [
UGate(self.theta, self.phi, self.lam),
RXGate(self.theta),
RYGate(self.theta),
RZGate(self.theta),
CXGate(),
ECRGate(),
CCXGate(),
Measure(),
]:
self.ideal_sim_target.add_instruction(inst, {None: None})
def test_qargs(self):
self.assertEqual(set(), self.empty_target.qargs)
expected_ibm = {
(0,),
(1,),
(2,),
(3,),
(4,),
(3, 4),
(4, 3),
(3, 1),
(1, 3),
(1, 2),
(2, 1),
(0, 1),
(1, 0),
}
self.assertEqual(expected_ibm, self.ibm_target.qargs)
expected_aqt = {
(0,),
(1,),
(2,),
(3,),
(4,),
(0, 1),
(0, 2),
(0, 3),
(0, 4),
(1, 0),
(2, 0),
(3, 0),
(4, 0),
(1, 2),
(1, 3),
(1, 4),
(2, 1),
(3, 1),
(4, 1),
(2, 3),
(2, 4),
(3, 2),
(4, 2),
(3, 4),
(4, 3),
}
self.assertEqual(expected_aqt, self.aqt_target.qargs)
expected_fake = {
(0,),
(1,),
(0, 1),
(1, 0),
}
self.assertEqual(expected_fake, self.fake_backend_target.qargs)
self.assertEqual(None, self.ideal_sim_target.qargs)
def test_qargs_for_operation_name(self):
with self.assertRaises(KeyError):
self.empty_target.qargs_for_operation_name("rz")
self.assertEqual(
self.ibm_target.qargs_for_operation_name("rz"), {(0,), (1,), (2,), (3,), (4,)}
)
self.assertEqual(
self.aqt_target.qargs_for_operation_name("rz"), {(0,), (1,), (2,), (3,), (4,)}
)
self.assertEqual(self.fake_backend_target.qargs_for_operation_name("cx"), {(0, 1)})
self.assertEqual(
self.fake_backend_target.qargs_for_operation_name("ecr"),
{
(1, 0),
},
)
self.assertEqual(self.ideal_sim_target.qargs_for_operation_name("cx"), None)
def test_instruction_names(self):
self.assertEqual(self.empty_target.operation_names, set())
self.assertEqual(self.ibm_target.operation_names, {"rz", "id", "sx", "x", "cx", "measure"})
self.assertEqual(self.aqt_target.operation_names, {"rz", "ry", "rx", "rxx", "r", "measure"})
self.assertEqual(
self.fake_backend_target.operation_names, {"u", "cx", "measure", "ecr", "rx_30", "rx"}
)
self.assertEqual(
self.ideal_sim_target.operation_names,
{"u", "rz", "ry", "rx", "cx", "ecr", "ccx", "measure"},
)
def test_operations(self):
self.assertEqual(self.empty_target.operations, [])
ibm_expected = [RZGate(self.theta), IGate(), SXGate(), XGate(), CXGate(), Measure()]
for gate in ibm_expected:
self.assertIn(gate, self.ibm_target.operations)
aqt_expected = [
RZGate(self.theta),
RXGate(self.theta),
RYGate(self.theta),
RGate(self.theta, self.phi),
RXXGate(self.theta),
]
for gate in aqt_expected:
self.assertIn(gate, self.aqt_target.operations)
fake_expected = [
UGate(self.fake_backend._theta, self.fake_backend._phi, self.fake_backend._lam),
CXGate(),
Measure(),
ECRGate(),
RXGate(math.pi / 6),
RXGate(self.fake_backend._theta),
]
for gate in fake_expected:
self.assertIn(gate, self.fake_backend_target.operations)
ideal_sim_expected = [
UGate(self.theta, self.phi, self.lam),
RXGate(self.theta),
RYGate(self.theta),
RZGate(self.theta),
CXGate(),
ECRGate(),
CCXGate(),
Measure(),
]
for gate in ideal_sim_expected:
self.assertIn(gate, self.ideal_sim_target.operations)
def test_instructions(self):
self.assertEqual(self.empty_target.instructions, [])
ibm_expected = [
(IGate(), (0,)),
(IGate(), (1,)),
(IGate(), (2,)),
(IGate(), (3,)),
(IGate(), (4,)),
(RZGate(self.theta), (0,)),
(RZGate(self.theta), (1,)),
(RZGate(self.theta), (2,)),
(RZGate(self.theta), (3,)),
(RZGate(self.theta), (4,)),
(SXGate(), (0,)),
(SXGate(), (1,)),
(SXGate(), (2,)),
(SXGate(), (3,)),
(SXGate(), (4,)),
(XGate(), (0,)),
(XGate(), (1,)),
(XGate(), (2,)),
(XGate(), (3,)),
(XGate(), (4,)),
(CXGate(), (3, 4)),
(CXGate(), (4, 3)),
(CXGate(), (3, 1)),
(CXGate(), (1, 3)),
(CXGate(), (1, 2)),
(CXGate(), (2, 1)),
(CXGate(), (0, 1)),
(CXGate(), (1, 0)),
(Measure(), (0,)),
(Measure(), (1,)),
(Measure(), (2,)),
(Measure(), (3,)),
(Measure(), (4,)),
]
self.assertEqual(ibm_expected, self.ibm_target.instructions)
ideal_sim_expected = [
(UGate(self.theta, self.phi, self.lam), None),
(RXGate(self.theta), None),
(RYGate(self.theta), None),
(RZGate(self.theta), None),
(CXGate(), None),
(ECRGate(), None),
(CCXGate(), None),
(Measure(), None),
]
self.assertEqual(ideal_sim_expected, self.ideal_sim_target.instructions)
def test_instruction_properties(self):
i_gate_2 = self.ibm_target.instruction_properties(2)
self.assertEqual(i_gate_2.error, 0.0004003)
self.assertIsNone(self.ideal_sim_target.instruction_properties(4))
def test_get_instruction_from_name(self):
with self.assertRaises(KeyError):
self.empty_target.operation_from_name("measure")
self.assertEqual(self.ibm_target.operation_from_name("measure"), Measure())
self.assertEqual(self.fake_backend_target.operation_from_name("rx_30"), RXGate(math.pi / 6))
self.assertEqual(
self.fake_backend_target.operation_from_name("rx"),
RXGate(self.fake_backend._theta),
)
self.assertEqual(self.ideal_sim_target.operation_from_name("ccx"), CCXGate())
def test_get_instructions_for_qargs(self):
with self.assertRaises(KeyError):
self.empty_target.operations_for_qargs((0,))
expected = [RZGate(self.theta), IGate(), SXGate(), XGate(), Measure()]
res = self.ibm_target.operations_for_qargs((0,))
for gate in expected:
self.assertIn(gate, res)
expected = [ECRGate()]
res = self.fake_backend_target.operations_for_qargs((1, 0))
for gate in expected:
self.assertIn(gate, res)
expected = [CXGate()]
res = self.fake_backend_target.operations_for_qargs((0, 1))
self.assertEqual(expected, res)
ideal_sim_expected = [
UGate(self.theta, self.phi, self.lam),
RXGate(self.theta),
RYGate(self.theta),
RZGate(self.theta),
CXGate(),
ECRGate(),
CCXGate(),
Measure(),
]
for gate in ideal_sim_expected:
self.assertIn(gate, self.ideal_sim_target.operations_for_qargs(None))
def test_get_operation_for_qargs_global(self):
expected = [
RXGate(self.theta),
RYGate(self.theta),
RZGate(self.theta),
RGate(self.theta, self.phi),
Measure(),
]
res = self.aqt_target.operations_for_qargs((0,))
self.assertEqual(len(expected), len(res))
for x in expected:
self.assertIn(x, res)
expected = [RXXGate(self.theta)]
res = self.aqt_target.operations_for_qargs((0, 1))
self.assertEqual(len(expected), len(res))
for x in expected:
self.assertIn(x, res)
def test_get_invalid_operations_for_qargs(self):
with self.assertRaises(KeyError):
self.ibm_target.operations_for_qargs((0, 102))
with self.assertRaises(KeyError):
self.ibm_target.operations_for_qargs(None)
def test_get_operation_names_for_qargs(self):
with self.assertRaises(KeyError):
self.empty_target.operation_names_for_qargs((0,))
expected = {"rz", "id", "sx", "x", "measure"}
res = self.ibm_target.operation_names_for_qargs((0,))
for gate in expected:
self.assertIn(gate, res)
expected = {"ecr"}
res = self.fake_backend_target.operation_names_for_qargs((1, 0))
for gate in expected:
self.assertIn(gate, res)
expected = {"cx"}
res = self.fake_backend_target.operation_names_for_qargs((0, 1))
self.assertEqual(expected, res)
ideal_sim_expected = ["u", "rx", "ry", "rz", "cx", "ecr", "ccx", "measure"]
for gate in ideal_sim_expected:
self.assertIn(gate, self.ideal_sim_target.operation_names_for_qargs(None))
def test_get_operation_names_for_qargs_invalid_qargs(self):
with self.assertRaises(KeyError):
self.ibm_target.operation_names_for_qargs((0, 102))
with self.assertRaises(KeyError):
self.ibm_target.operation_names_for_qargs(None)
def test_get_operation_names_for_qargs_global_insts(self):
expected = {"r", "rx", "rz", "ry", "measure"}
self.assertEqual(self.aqt_target.operation_names_for_qargs((0,)), expected)
expected = {
"rxx",
}
self.assertEqual(self.aqt_target.operation_names_for_qargs((0, 1)), expected)
def test_coupling_map(self):
self.assertEqual(
CouplingMap().get_edges(), self.empty_target.build_coupling_map().get_edges()
)
self.assertEqual(
set(CouplingMap.from_full(5).get_edges()),
set(self.aqt_target.build_coupling_map().get_edges()),
)
self.assertEqual(
{(0, 1), (1, 0)}, set(self.fake_backend_target.build_coupling_map().get_edges())
)
self.assertEqual(
{
(3, 4),
(4, 3),
(3, 1),
(1, 3),
(1, 2),
(2, 1),
(0, 1),
(1, 0),
},
set(self.ibm_target.build_coupling_map().get_edges()),
)
self.assertEqual(None, self.ideal_sim_target.build_coupling_map())
def test_coupling_map_mutations_do_not_propagate(self):
cm = CouplingMap.from_line(5, bidirectional=False)
cx_props = {
edge: InstructionProperties(duration=270.22e-9, error=0.00713)
for edge in cm.get_edges()
}
target = Target()
target.add_instruction(CXGate(), cx_props)
self.assertEqual(cm, target.build_coupling_map())
symmetric = target.build_coupling_map()
symmetric.make_symmetric()
self.assertNotEqual(cm, symmetric) # sanity check for the test.
# Verify that mutating the output of `build_coupling_map` doesn't affect the target.
self.assertNotEqual(target.build_coupling_map(), symmetric)
def test_coupling_map_filtered_mutations_do_not_propagate(self):
cm = CouplingMap.from_line(5, bidirectional=False)
cx_props = {
edge: InstructionProperties(duration=270.22e-9, error=0.00713)
for edge in cm.get_edges()
if 2 not in edge
}
target = Target()
target.add_instruction(CXGate(), cx_props)
symmetric = target.build_coupling_map(filter_idle_qubits=True)
symmetric.make_symmetric()
self.assertNotEqual(cm, symmetric) # sanity check for the test.
# Verify that mutating the output of `build_coupling_map` doesn't affect the target.
self.assertNotEqual(target.build_coupling_map(filter_idle_qubits=True), symmetric)
def test_coupling_map_no_filter_mutations_do_not_propagate(self):
cm = CouplingMap.from_line(5, bidirectional=False)
cx_props = {
edge: InstructionProperties(duration=270.22e-9, error=0.00713)
for edge in cm.get_edges()
}
target = Target()
target.add_instruction(CXGate(), cx_props)
# The filter here does not actually do anything, because there's no idle qubits. This is
# just a test that this path is also not cached.
self.assertEqual(cm, target.build_coupling_map(filter_idle_qubits=True))
symmetric = target.build_coupling_map(filter_idle_qubits=True)
symmetric.make_symmetric()
self.assertNotEqual(cm, symmetric) # sanity check for the test.
# Verify that mutating the output of `build_coupling_map` doesn't affect the target.
self.assertNotEqual(target.build_coupling_map(filter_idle_qubits=True), symmetric)
def test_coupling_map_2q_gate(self):
cmap = self.fake_backend_target.build_coupling_map("ecr")
self.assertEqual(
[
(1, 0),
],
cmap.get_edges(),
)
def test_coupling_map_3q_gate(self):
fake_target = Target()
ccx_props = {
(0, 1, 2): None,
(1, 0, 2): None,
(2, 1, 0): None,
}
fake_target.add_instruction(CCXGate(), ccx_props)
with self.assertLogs("qiskit.transpiler.target", level="WARN") as log:
cmap = fake_target.build_coupling_map()
self.assertEqual(
log.output,
[
"WARNING:qiskit.transpiler.target:"
"This Target object contains multiqubit gates that "
"operate on > 2 qubits. This will not be reflected in "
"the output coupling map."
],
)
self.assertEqual([], cmap.get_edges())
with self.assertRaises(ValueError):
fake_target.build_coupling_map("ccx")
def test_coupling_map_mixed_ideal_global_1q_and_2q_gates(self):
n_qubits = 3
target = Target()
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
target.add_instruction(RXGate(Parameter("theta")), {None: None})
cmap = target.build_coupling_map()
self.assertEqual([(0, 1), (1, 2)], cmap.get_edges())
def test_coupling_map_mixed_global_1q_and_2q_gates(self):
n_qubits = 3
target = Target()
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
target.add_instruction(RXGate(Parameter("theta")))
cmap = target.build_coupling_map()
self.assertEqual([(0, 1), (1, 2)], cmap.get_edges())
def test_coupling_map_mixed_ideal_global_2q_and_real_2q_gates(self):
n_qubits = 3
target = Target()
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
target.add_instruction(ECRGate())
cmap = target.build_coupling_map()
self.assertIsNone(cmap)
def test_physical_qubits(self):
self.assertEqual([], self.empty_target.physical_qubits)
self.assertEqual(list(range(5)), self.ibm_target.physical_qubits)
self.assertEqual(list(range(5)), self.aqt_target.physical_qubits)
self.assertEqual(list(range(2)), self.fake_backend_target.physical_qubits)
self.assertEqual(list(range(3)), self.ideal_sim_target.physical_qubits)
def test_duplicate_instruction_add_instruction(self):
target = Target()
target.add_instruction(XGate(), {(0,): None})
with self.assertRaises(AttributeError):
target.add_instruction(XGate(), {(1,): None})
def test_durations(self):
empty_durations = self.empty_target.durations()
self.assertEqual(
empty_durations.duration_by_name_qubits, InstructionDurations().duration_by_name_qubits
)
aqt_durations = self.aqt_target.durations()
self.assertEqual(aqt_durations.duration_by_name_qubits, {})
ibm_durations = self.ibm_target.durations()
expected = {
("cx", (0, 1)): (5.1911e-07, "s"),
("cx", (1, 0)): (5.5466e-07, "s"),
("cx", (1, 2)): (2.2755e-07, "s"),
("cx", (1, 3)): (4.9777e-07, "s"),
("cx", (2, 1)): (2.6311e-07, "s"),
("cx", (3, 1)): (4.6222e-07, "s"),
("cx", (3, 4)): (2.7022e-07, "s"),
("cx", (4, 3)): (3.0577e-07, "s"),
("id", (0,)): (3.55e-08, "s"),
("id", (1,)): (3.55e-08, "s"),
("id", (2,)): (3.55e-08, "s"),
("id", (3,)): (3.55e-08, "s"),
("id", (4,)): (3.55e-08, "s"),
("measure", (0,)): (5.813e-06, "s"),
("measure", (1,)): (5.813e-06, "s"),
("measure", (2,)): (5.813e-06, "s"),
("measure", (3,)): (5.813e-06, "s"),
("measure", (4,)): (5.813e-06, "s"),
("rz", (0,)): (0, "s"),
("rz", (1,)): (0, "s"),
("rz", (2,)): (0, "s"),
("rz", (3,)): (0, "s"),
("rz", (4,)): (0, "s"),
("sx", (0,)): (3.55e-08, "s"),
("sx", (1,)): (3.55e-08, "s"),
("sx", (2,)): (3.55e-08, "s"),
("sx", (3,)): (3.55e-08, "s"),
("sx", (4,)): (3.55e-08, "s"),
("x", (0,)): (3.55e-08, "s"),
("x", (1,)): (3.55e-08, "s"),
("x", (2,)): (3.55e-08, "s"),
("x", (3,)): (3.55e-08, "s"),
("x", (4,)): (3.55e-08, "s"),
}
self.assertEqual(ibm_durations.duration_by_name_qubits, expected)
def test_mapping(self):
with self.assertRaises(KeyError):
_res = self.empty_target["cx"]
expected = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.assertEqual(self.aqt_target["r"], expected)
self.assertEqual(["rx", "ry", "rz", "r", "rxx", "measure"], list(self.aqt_target))
expected_values = [
{
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
{
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
{
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
{
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
{
(0, 1): None,
(0, 2): None,
(0, 3): None,
(0, 4): None,
(1, 0): None,
(2, 0): None,
(3, 0): None,
(4, 0): None,
(1, 2): None,
(1, 3): None,
(1, 4): None,
(2, 1): None,
(3, 1): None,
(4, 1): None,
(2, 3): None,
(2, 4): None,
(3, 2): None,
(4, 2): None,
(3, 4): None,
(4, 3): None,
},
{
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
]
self.assertEqual(expected_values, list(self.aqt_target.values()))
expected_items = {
"rx": {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
"ry": {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
"rz": {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
"r": {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
"rxx": {
(0, 1): None,
(0, 2): None,
(0, 3): None,
(0, 4): None,
(1, 0): None,
(2, 0): None,
(3, 0): None,
(4, 0): None,
(1, 2): None,
(1, 3): None,
(1, 4): None,
(2, 1): None,
(3, 1): None,
(4, 1): None,
(2, 3): None,
(2, 4): None,
(3, 2): None,
(4, 2): None,
(3, 4): None,
(4, 3): None,
},
"measure": {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
}
self.assertEqual(expected_items, dict(self.aqt_target.items()))
self.assertIn("cx", self.ibm_target)
self.assertNotIn("ecr", self.ibm_target)
self.assertEqual(len(self.ibm_target), 6)
def test_update_instruction_properties(self):
self.aqt_target.update_instruction_properties(
"rxx",
(0, 1),
InstructionProperties(duration=1e-6, error=1e-5),
)
self.assertEqual(self.aqt_target["rxx"][(0, 1)].duration, 1e-6)
self.assertEqual(self.aqt_target["rxx"][(0, 1)].error, 1e-5)
def test_update_instruction_properties_invalid_instruction(self):
with self.assertRaises(KeyError):
self.ibm_target.update_instruction_properties("rxx", (0, 1), None)
def test_update_instruction_properties_invalid_qarg(self):
with self.assertRaises(KeyError):
self.fake_backend_target.update_instruction_properties("ecr", (0, 1), None)
def test_str(self):
expected = """Target
Number of qubits: 5
Instructions:
id
(0,):
Duration: 3.55e-08 sec.
Error Rate: 0.000413
(1,):
Duration: 3.55e-08 sec.
Error Rate: 0.000502
(2,):
Duration: 3.55e-08 sec.
Error Rate: 0.0004003
(3,):
Duration: 3.55e-08 sec.
Error Rate: 0.000614
(4,):
Duration: 3.55e-08 sec.
Error Rate: 0.006149
rz
(0,):
Duration: 0 sec.
Error Rate: 0
(1,):
Duration: 0 sec.
Error Rate: 0
(2,):
Duration: 0 sec.
Error Rate: 0
(3,):
Duration: 0 sec.
Error Rate: 0
(4,):
Duration: 0 sec.
Error Rate: 0
sx
(0,):
Duration: 3.55e-08 sec.
Error Rate: 0.000413
(1,):
Duration: 3.55e-08 sec.
Error Rate: 0.000502
(2,):
Duration: 3.55e-08 sec.
Error Rate: 0.0004003
(3,):
Duration: 3.55e-08 sec.
Error Rate: 0.000614
(4,):
Duration: 3.55e-08 sec.
Error Rate: 0.006149
x
(0,):
Duration: 3.55e-08 sec.
Error Rate: 0.000413
(1,):
Duration: 3.55e-08 sec.
Error Rate: 0.000502
(2,):
Duration: 3.55e-08 sec.
Error Rate: 0.0004003
(3,):
Duration: 3.55e-08 sec.
Error Rate: 0.000614
(4,):
Duration: 3.55e-08 sec.
Error Rate: 0.006149
cx
(3, 4):
Duration: 2.7022e-07 sec.
Error Rate: 0.00713
(4, 3):
Duration: 3.0577e-07 sec.
Error Rate: 0.00713
(3, 1):
Duration: 4.6222e-07 sec.
Error Rate: 0.00929
(1, 3):
Duration: 4.9777e-07 sec.
Error Rate: 0.00929
(1, 2):
Duration: 2.2755e-07 sec.
Error Rate: 0.00659
(2, 1):
Duration: 2.6311e-07 sec.
Error Rate: 0.00659
(0, 1):
Duration: 5.1911e-07 sec.
Error Rate: 0.01201
(1, 0):
Duration: 5.5466e-07 sec.
Error Rate: 0.01201
measure
(0,):
Duration: 5.813e-06 sec.
Error Rate: 0.0751
(1,):
Duration: 5.813e-06 sec.
Error Rate: 0.0225
(2,):
Duration: 5.813e-06 sec.
Error Rate: 0.0146
(3,):
Duration: 5.813e-06 sec.
Error Rate: 0.0215
(4,):
Duration: 5.813e-06 sec.
Error Rate: 0.0333
"""
self.assertEqual(expected, str(self.ibm_target))
aqt_expected = """Target: AQT Target
Number of qubits: 5
Instructions:
rx
(0,)
(1,)
(2,)
(3,)
(4,)
ry
(0,)
(1,)
(2,)
(3,)
(4,)
rz
(0,)
(1,)
(2,)
(3,)
(4,)
r
(0,)
(1,)
(2,)
(3,)
(4,)
rxx
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 0)
(2, 0)
(3, 0)
(4, 0)
(1, 2)
(1, 3)
(1, 4)
(2, 1)
(3, 1)
(4, 1)
(2, 3)
(2, 4)
(3, 2)
(4, 2)
(3, 4)
(4, 3)
measure
(0,)
(1,)
(2,)
(3,)
(4,)
"""
self.assertEqual(aqt_expected, str(self.aqt_target))
sim_expected = """Target: Ideal Simulator
Number of qubits: 3
Instructions:
u
rx
ry
rz
cx
ecr
ccx
measure
"""
self.assertEqual(sim_expected, str(self.ideal_sim_target))
def test_extra_props_str(self):
target = Target(description="Extra Properties")
class ExtraProperties(InstructionProperties):
"""An example properties subclass."""
def __init__(
self,
duration=None,
error=None,
calibration=None,
tuned=None,
diamond_norm_error=None,
):
super().__init__(duration=duration, error=error, calibration=calibration)
self.tuned = tuned
self.diamond_norm_error = diamond_norm_error
cx_props = {
(3, 4): ExtraProperties(
duration=270.22e-9, error=0.00713, tuned=False, diamond_norm_error=2.12e-6
),
}
target.add_instruction(CXGate(), cx_props)
expected = """Target: Extra Properties
Number of qubits: 5
Instructions:
cx
(3, 4):
Duration: 2.7022e-07 sec.
Error Rate: 0.00713
"""
self.assertEqual(expected, str(target))
def test_timing_constraints(self):
generated_constraints = self.aqt_target.timing_constraints()
expected_constraints = TimingConstraints()
for i in ["granularity", "min_length", "pulse_alignment", "acquire_alignment"]:
self.assertEqual(
getattr(generated_constraints, i),
getattr(expected_constraints, i),
f"Generated constraints differs from expected for attribute {i}"
f"{getattr(generated_constraints, i)}!={getattr(expected_constraints, i)}",
)
def test_get_non_global_operation_name_ideal_backend(self):
self.assertEqual(self.aqt_target.get_non_global_operation_names(), [])
self.assertEqual(self.ideal_sim_target.get_non_global_operation_names(), [])
self.assertEqual(self.ibm_target.get_non_global_operation_names(), [])
self.assertEqual(self.fake_backend_target.get_non_global_operation_names(), [])
def test_get_non_global_operation_name_ideal_backend_strict_direction(self):
self.assertEqual(self.aqt_target.get_non_global_operation_names(True), [])
self.assertEqual(self.ideal_sim_target.get_non_global_operation_names(True), [])
self.assertEqual(self.ibm_target.get_non_global_operation_names(True), [])
self.assertEqual(
self.fake_backend_target.get_non_global_operation_names(True), ["cx", "ecr"]
)
def test_instruction_supported(self):
self.assertTrue(self.aqt_target.instruction_supported("r", (0,)))
self.assertFalse(self.aqt_target.instruction_supported("cx", (0, 1)))
self.assertTrue(self.ideal_sim_target.instruction_supported("cx", (0, 1)))
self.assertFalse(self.ideal_sim_target.instruction_supported("cx", (0, 524)))
self.assertTrue(self.fake_backend_target.instruction_supported("cx", (0, 1)))
self.assertFalse(self.fake_backend_target.instruction_supported("cx", (1, 0)))
self.assertFalse(self.ideal_sim_target.instruction_supported("cx", (0, 1, 2)))
def test_instruction_supported_parameters(self):
mumbai = FakeMumbaiFractionalCX()
self.assertTrue(
mumbai.target.instruction_supported(
qargs=(0, 1), operation_class=RZXGate, parameters=[math.pi / 4]
)
)
self.assertTrue(mumbai.target.instruction_supported(qargs=(0, 1), operation_class=RZXGate))
self.assertTrue(
mumbai.target.instruction_supported(operation_class=RZXGate, parameters=[math.pi / 4])
)
self.assertFalse(mumbai.target.instruction_supported("rzx", parameters=[math.pi / 4]))
self.assertTrue(mumbai.target.instruction_supported("rz", parameters=[Parameter("angle")]))
self.assertTrue(
mumbai.target.instruction_supported("rzx_45", qargs=(0, 1), parameters=[math.pi / 4])
)
self.assertTrue(mumbai.target.instruction_supported("rzx_45", qargs=(0, 1)))
self.assertTrue(mumbai.target.instruction_supported("rzx_45", parameters=[math.pi / 4]))
self.assertFalse(mumbai.target.instruction_supported("rzx_45", parameters=[math.pi / 6]))
self.assertFalse(
mumbai.target.instruction_supported("rzx_45", parameters=[Parameter("angle")])
)
self.assertTrue(
self.ideal_sim_target.instruction_supported(
qargs=(0,), operation_class=RXGate, parameters=[Parameter("angle")]
)
)
self.assertTrue(
self.ideal_sim_target.instruction_supported(
qargs=(0,), operation_class=RXGate, parameters=[math.pi]
)
)
self.assertTrue(
self.ideal_sim_target.instruction_supported(
operation_class=RXGate, parameters=[math.pi]
)
)
self.assertTrue(
self.ideal_sim_target.instruction_supported(
operation_class=RXGate, parameters=[Parameter("angle")]
)
)
self.assertTrue(
self.ideal_sim_target.instruction_supported(
"rx", qargs=(0,), parameters=[Parameter("angle")]
)
)
self.assertTrue(
self.ideal_sim_target.instruction_supported("rx", qargs=(0,), parameters=[math.pi])
)
self.assertTrue(self.ideal_sim_target.instruction_supported("rx", parameters=[math.pi]))
self.assertTrue(
self.ideal_sim_target.instruction_supported("rx", parameters=[Parameter("angle")])
)
def test_instruction_supported_multiple_parameters(self):
target = Target(1)
target.add_instruction(
UGate(self.theta, self.phi, self.lam),
{(0,): InstructionProperties(duration=270.22e-9, error=0.00713)},
)
self.assertFalse(target.instruction_supported("u", parameters=[math.pi]))
self.assertTrue(target.instruction_supported("u", parameters=[math.pi, math.pi, math.pi]))
self.assertTrue(
target.instruction_supported(
operation_class=UGate, parameters=[math.pi, math.pi, math.pi]
)
)
self.assertFalse(
target.instruction_supported(operation_class=UGate, parameters=[Parameter("x")])
)
def test_instruction_supported_arg_len_mismatch(self):
self.assertFalse(
self.ideal_sim_target.instruction_supported(operation_class=UGate, parameters=[math.pi])
)
self.assertFalse(self.ideal_sim_target.instruction_supported("u", parameters=[math.pi]))
def test_instruction_supported_class_not_in_target(self):
self.assertFalse(
self.ibm_target.instruction_supported(operation_class=CZGate, parameters=[math.pi])
)
def test_instruction_supported_no_args(self):
self.assertFalse(self.ibm_target.instruction_supported())
def test_instruction_supported_no_operation(self):
self.assertFalse(self.ibm_target.instruction_supported(qargs=(0,), parameters=[math.pi]))
class TestPulseTarget(QiskitTestCase):
def setUp(self):
super().setUp()
self.pulse_target = Target(
dt=3e-7, granularity=2, min_length=4, pulse_alignment=8, acquire_alignment=8
)
with pulse.build(name="sx_q0") as self.custom_sx_q0:
pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0))
with pulse.build(name="sx_q1") as self.custom_sx_q1:
pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(1))
sx_props = {
(0,): InstructionProperties(
duration=35.5e-9, error=0.000413, calibration=self.custom_sx_q0
),
(1,): InstructionProperties(
duration=35.5e-9, error=0.000502, calibration=self.custom_sx_q1
),
}
self.pulse_target.add_instruction(SXGate(), sx_props)
def test_instruction_schedule_map(self):
inst_map = self.pulse_target.instruction_schedule_map()
self.assertIn("sx", inst_map.instructions)
self.assertEqual(inst_map.qubits_with_instruction("sx"), [0, 1])
self.assertTrue("sx" in inst_map.qubit_instructions(0))
def test_instruction_schedule_map_ideal_sim_backend(self):
ideal_sim_target = Target(num_qubits=3)
theta = Parameter("theta")
phi = Parameter("phi")
lam = Parameter("lambda")
for inst in [
UGate(theta, phi, lam),
RXGate(theta),
RYGate(theta),
RZGate(theta),
CXGate(),
ECRGate(),
CCXGate(),
Measure(),
]:
ideal_sim_target.add_instruction(inst, {None: None})
inst_map = ideal_sim_target.instruction_schedule_map()
self.assertEqual(InstructionScheduleMap(), inst_map)
def test_str(self):
expected = """Target
Number of qubits: 2
Instructions:
sx
(0,):
Duration: 3.55e-08 sec.
Error Rate: 0.000413
With pulse schedule calibration
(1,):
Duration: 3.55e-08 sec.
Error Rate: 0.000502
With pulse schedule calibration
"""
self.assertEqual(expected, str(self.pulse_target))
def test_update_from_instruction_schedule_map_add_instruction(self):
target = Target()
inst_map = InstructionScheduleMap()
inst_map.add("sx", 0, self.custom_sx_q0)
inst_map.add("sx", 1, self.custom_sx_q1)
target.update_from_instruction_schedule_map(inst_map, {"sx": SXGate()})
self.assertEqual(inst_map, target.instruction_schedule_map())
def test_update_from_instruction_schedule_map_with_schedule_parameter(self):
self.pulse_target.dt = None
inst_map = InstructionScheduleMap()
duration = Parameter("duration")
with pulse.build(name="sx_q0") as custom_sx:
pulse.play(pulse.Constant(duration, 0.2), pulse.DriveChannel(0))
inst_map.add("sx", 0, custom_sx, ["duration"])
target = Target(dt=3e-7)
target.update_from_instruction_schedule_map(inst_map, {"sx": SXGate()})
self.assertEqual(inst_map, target.instruction_schedule_map())
def test_update_from_instruction_schedule_map_update_schedule(self):
self.pulse_target.dt = None
inst_map = InstructionScheduleMap()
with pulse.build(name="sx_q1") as custom_sx:
pulse.play(pulse.Constant(1000, 0.2), pulse.DriveChannel(1))
inst_map.add("sx", 0, self.custom_sx_q0)
inst_map.add("sx", 1, custom_sx)
self.pulse_target.update_from_instruction_schedule_map(inst_map, {"sx": SXGate()})
self.assertEqual(inst_map, self.pulse_target.instruction_schedule_map())
# Calibration doesn't change for q0
self.assertEqual(self.pulse_target["sx"][(0,)].duration, 35.5e-9)
self.assertEqual(self.pulse_target["sx"][(0,)].error, 0.000413)
# Calibration is updated for q1 without error dict and gate time
self.assertIsNone(self.pulse_target["sx"][(1,)].duration)
self.assertIsNone(self.pulse_target["sx"][(1,)].error)
def test_update_from_instruction_schedule_map_new_instruction_no_name_map(self):
target = Target()
inst_map = InstructionScheduleMap()
inst_map.add("sx", 0, self.custom_sx_q0)
inst_map.add("sx", 1, self.custom_sx_q1)
target.update_from_instruction_schedule_map(inst_map)
self.assertEqual(target["sx"][(0,)].calibration, self.custom_sx_q0)
self.assertEqual(target["sx"][(1,)].calibration, self.custom_sx_q1)
def test_update_from_instruction_schedule_map_new_qarg_raises(self):
inst_map = InstructionScheduleMap()
inst_map.add("sx", 0, self.custom_sx_q0)
inst_map.add("sx", 1, self.custom_sx_q1)
inst_map.add("sx", 2, self.custom_sx_q1)
self.pulse_target.update_from_instruction_schedule_map(inst_map)
self.assertFalse(self.pulse_target.instruction_supported("sx", (2,)))
def test_update_from_instruction_schedule_map_with_dt_set(self):
inst_map = InstructionScheduleMap()
with pulse.build(name="sx_q1") as custom_sx:
pulse.play(pulse.Constant(1000, 0.2), pulse.DriveChannel(1))
inst_map.add("sx", 0, self.custom_sx_q0)
inst_map.add("sx", 1, custom_sx)
self.pulse_target.dt = 1.0
self.pulse_target.update_from_instruction_schedule_map(inst_map, {"sx": SXGate()})
self.assertEqual(inst_map, self.pulse_target.instruction_schedule_map())
self.assertEqual(self.pulse_target["sx"][(1,)].duration, 1000.0)
self.assertIsNone(self.pulse_target["sx"][(1,)].error)
# This is an edge case.
# System dt is read-only property and changing it will break all underlying calibrations.
# duration of sx0 returns previous value since calibration doesn't change.
self.assertEqual(self.pulse_target["sx"][(0,)].duration, 35.5e-9)
self.assertEqual(self.pulse_target["sx"][(0,)].error, 0.000413)
def test_update_from_instruction_schedule_map_with_error_dict(self):
inst_map = InstructionScheduleMap()
with pulse.build(name="sx_q1") as custom_sx:
pulse.play(pulse.Constant(1000, 0.2), pulse.DriveChannel(1))
inst_map.add("sx", 0, self.custom_sx_q0)
inst_map.add("sx", 1, custom_sx)
self.pulse_target.dt = 1.0
error_dict = {"sx": {(1,): 1.0}}
self.pulse_target.update_from_instruction_schedule_map(
inst_map, {"sx": SXGate()}, error_dict=error_dict
)
self.assertEqual(self.pulse_target["sx"][(1,)].error, 1.0)
self.assertEqual(self.pulse_target["sx"][(0,)].error, 0.000413)
def test_timing_constraints(self):
generated_constraints = self.pulse_target.timing_constraints()
expected_constraints = TimingConstraints(2, 4, 8, 8)
for i in ["granularity", "min_length", "pulse_alignment", "acquire_alignment"]:
self.assertEqual(
getattr(generated_constraints, i),
getattr(expected_constraints, i),
f"Generated constraints differs from expected for attribute {i}"
f"{getattr(generated_constraints, i)}!={getattr(expected_constraints, i)}",
)
def test_default_instmap_has_no_custom_gate(self):
backend = FakeGeneva()
target = backend.target
# This copies .calibraiton of InstructionProperties of each instruction
# This must not convert PulseQobj to Schedule during this.
# See qiskit-terra/#9595
inst_map = target.instruction_schedule_map()
self.assertFalse(inst_map.has_custom_gate())
# Get pulse schedule. This generates Schedule provided by backend.
sched = inst_map.get("sx", (0,))
self.assertEqual(sched.metadata["publisher"], CalibrationPublisher.BACKEND_PROVIDER)
self.assertFalse(inst_map.has_custom_gate())
# Update target with custom instruction. This is user provided schedule.
new_prop = InstructionProperties(
duration=self.custom_sx_q0.duration,
error=None,
calibration=self.custom_sx_q0,
)
target.update_instruction_properties(instruction="sx", qargs=(0,), properties=new_prop)
inst_map = target.instruction_schedule_map()
self.assertTrue(inst_map.has_custom_gate())
empty = InstructionProperties()
target.update_instruction_properties(instruction="sx", qargs=(0,), properties=empty)
inst_map = target.instruction_schedule_map()
self.assertFalse(inst_map.has_custom_gate())
def test_get_empty_target_calibration(self):
target = Target()
properties = {(0,): InstructionProperties(duration=100, error=0.1)}
target.add_instruction(XGate(), properties)
self.assertIsNone(target["x"][(0,)].calibration)
def test_loading_legacy_ugate_instmap(self):
# This is typical IBM backend situation.
# IBM provider used to have u1, u2, u3 in the basis gates and
# these have been replaced with sx and rz.
# However, IBM provider still provides calibration of these u gates,
# and the inst map loads them as backend calibrations.
# Target is implicitly updated with inst map when it is set in transpile.
# If u gates are not excluded, they may appear in the transpiled circuit.
# These gates are no longer supported by hardware.
entry = ScheduleDef()
entry.define(pulse.Schedule(name="fake_u3"), user_provided=False) # backend provided
instmap = InstructionScheduleMap()
instmap._add("u3", (0,), entry)
# Today's standard IBM backend target with sx, rz basis
target = Target()
target.add_instruction(SXGate(), {(0,): InstructionProperties()})
target.add_instruction(RZGate(Parameter("θ")), {(0,): InstructionProperties()})
target.add_instruction(Measure(), {(0,): InstructionProperties()})
names_before = set(target.operation_names)
target.update_from_instruction_schedule_map(instmap)
names_after = set(target.operation_names)
# Otherwise u3 and sx-rz basis conflict in 1q decomposition.
self.assertSetEqual(names_before, names_after)
class TestGlobalVariableWidthOperations(QiskitTestCase):
def setUp(self):
super().setUp()
self.theta = Parameter("theta")
self.phi = Parameter("phi")
self.lam = Parameter("lambda")
self.target_global_gates_only = Target(num_qubits=5)
self.target_global_gates_only.add_instruction(CXGate())
self.target_global_gates_only.add_instruction(UGate(self.theta, self.phi, self.lam))
self.target_global_gates_only.add_instruction(Measure())
self.target_global_gates_only.add_instruction(IfElseOp, name="if_else")
self.target_global_gates_only.add_instruction(ForLoopOp, name="for_loop")
self.target_global_gates_only.add_instruction(WhileLoopOp, name="while_loop")
self.target_global_gates_only.add_instruction(SwitchCaseOp, name="switch_case")
self.ibm_target = Target()
i_props = {
(0,): InstructionProperties(duration=35.5e-9, error=0.000413),
(1,): InstructionProperties(duration=35.5e-9, error=0.000502),
(2,): InstructionProperties(duration=35.5e-9, error=0.0004003),
(3,): InstructionProperties(duration=35.5e-9, error=0.000614),
(4,): InstructionProperties(duration=35.5e-9, error=0.006149),
}
self.ibm_target.add_instruction(IGate(), i_props)
rz_props = {
(0,): InstructionProperties(duration=0, error=0),
(1,): InstructionProperties(duration=0, error=0),
(2,): InstructionProperties(duration=0, error=0),
(3,): InstructionProperties(duration=0, error=0),
(4,): InstructionProperties(duration=0, error=0),
}
self.ibm_target.add_instruction(RZGate(self.theta), rz_props)
sx_props = {
(0,): InstructionProperties(duration=35.5e-9, error=0.000413),
(1,): InstructionProperties(duration=35.5e-9, error=0.000502),
(2,): InstructionProperties(duration=35.5e-9, error=0.0004003),
(3,): InstructionProperties(duration=35.5e-9, error=0.000614),
(4,): InstructionProperties(duration=35.5e-9, error=0.006149),
}
self.ibm_target.add_instruction(SXGate(), sx_props)
x_props = {
(0,): InstructionProperties(duration=35.5e-9, error=0.000413),
(1,): InstructionProperties(duration=35.5e-9, error=0.000502),
(2,): InstructionProperties(duration=35.5e-9, error=0.0004003),
(3,): InstructionProperties(duration=35.5e-9, error=0.000614),
(4,): InstructionProperties(duration=35.5e-9, error=0.006149),
}
self.ibm_target.add_instruction(XGate(), x_props)
cx_props = {
(3, 4): InstructionProperties(duration=270.22e-9, error=0.00713),
(4, 3): InstructionProperties(duration=305.77e-9, error=0.00713),
(3, 1): InstructionProperties(duration=462.22e-9, error=0.00929),
(1, 3): InstructionProperties(duration=497.77e-9, error=0.00929),
(1, 2): InstructionProperties(duration=227.55e-9, error=0.00659),
(2, 1): InstructionProperties(duration=263.11e-9, error=0.00659),
(0, 1): InstructionProperties(duration=519.11e-9, error=0.01201),
(1, 0): InstructionProperties(duration=554.66e-9, error=0.01201),
}
self.ibm_target.add_instruction(CXGate(), cx_props)
measure_props = {
(0,): InstructionProperties(duration=5.813e-6, error=0.0751),
(1,): InstructionProperties(duration=5.813e-6, error=0.0225),
(2,): InstructionProperties(duration=5.813e-6, error=0.0146),
(3,): InstructionProperties(duration=5.813e-6, error=0.0215),
(4,): InstructionProperties(duration=5.813e-6, error=0.0333),
}
self.ibm_target.add_instruction(Measure(), measure_props)
self.ibm_target.add_instruction(IfElseOp, name="if_else")
self.ibm_target.add_instruction(ForLoopOp, name="for_loop")
self.ibm_target.add_instruction(WhileLoopOp, name="while_loop")
self.ibm_target.add_instruction(SwitchCaseOp, name="switch_case")
self.aqt_target = Target(description="AQT Target")
rx_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RXGate(self.theta), rx_props)
ry_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RYGate(self.theta), ry_props)
rz_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RZGate(self.theta), rz_props)
r_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RGate(self.theta, self.phi), r_props)
rxx_props = {
(0, 1): None,
(0, 2): None,
(0, 3): None,
(0, 4): None,
(1, 0): None,
(2, 0): None,
(3, 0): None,
(4, 0): None,
(1, 2): None,
(1, 3): None,
(1, 4): None,
(2, 1): None,
(3, 1): None,
(4, 1): None,
(2, 3): None,
(2, 4): None,
(3, 2): None,
(4, 2): None,
(3, 4): None,
(4, 3): None,
}
self.aqt_target.add_instruction(RXXGate(self.theta), rxx_props)
measure_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(Measure(), measure_props)
self.aqt_target.add_instruction(IfElseOp, name="if_else")
self.aqt_target.add_instruction(ForLoopOp, name="for_loop")
self.aqt_target.add_instruction(WhileLoopOp, name="while_loop")
self.aqt_target.add_instruction(SwitchCaseOp, name="switch_case")
def test_qargs(self):
expected_ibm = {
(0,),
(1,),
(2,),
(3,),
(4,),
(3, 4),
(4, 3),
(3, 1),
(1, 3),
(1, 2),
(2, 1),
(0, 1),
(1, 0),
}
self.assertEqual(expected_ibm, self.ibm_target.qargs)
expected_aqt = {
(0,),
(1,),
(2,),
(3,),
(4,),
(0, 1),
(0, 2),
(0, 3),
(0, 4),
(1, 0),
(2, 0),
(3, 0),
(4, 0),
(1, 2),
(1, 3),
(1, 4),
(2, 1),
(3, 1),
(4, 1),
(2, 3),
(2, 4),
(3, 2),
(4, 2),
(3, 4),
(4, 3),
}
self.assertEqual(expected_aqt, self.aqt_target.qargs)
self.assertEqual(None, self.target_global_gates_only.qargs)
def test_qargs_single_qarg(self):
target = Target()
target.add_instruction(XGate(), {(0,): None})
self.assertEqual(
{
(0,),
},
target.qargs,
)
def test_qargs_for_operation_name(self):
self.assertEqual(
self.ibm_target.qargs_for_operation_name("rz"), {(0,), (1,), (2,), (3,), (4,)}
)
self.assertEqual(
self.aqt_target.qargs_for_operation_name("rz"), {(0,), (1,), (2,), (3,), (4,)}
)
self.assertIsNone(self.target_global_gates_only.qargs_for_operation_name("cx"))
self.assertIsNone(self.ibm_target.qargs_for_operation_name("if_else"))
self.assertIsNone(self.aqt_target.qargs_for_operation_name("while_loop"))
self.assertIsNone(self.aqt_target.qargs_for_operation_name("switch_case"))
def test_instruction_names(self):
self.assertEqual(
self.ibm_target.operation_names,
{
"rz",
"id",
"sx",
"x",
"cx",
"measure",
"if_else",
"while_loop",
"for_loop",
"switch_case",
},
)
self.assertEqual(
self.aqt_target.operation_names,
{
"rz",
"ry",
"rx",
"rxx",
"r",
"measure",
"if_else",
"while_loop",
"for_loop",
"switch_case",
},
)
self.assertEqual(
self.target_global_gates_only.operation_names,
{"u", "cx", "measure", "if_else", "while_loop", "for_loop", "switch_case"},
)
def test_operations_for_qargs(self):
expected = [
IGate(),
RZGate(self.theta),
SXGate(),
XGate(),
Measure(),
IfElseOp,
ForLoopOp,
WhileLoopOp,
SwitchCaseOp,
]
res = self.ibm_target.operations_for_qargs((0,))
self.assertEqual(len(expected), len(res))
for x in expected:
self.assertIn(x, res)
expected = [
CXGate(),
IfElseOp,
ForLoopOp,
WhileLoopOp,
SwitchCaseOp,
]
res = self.ibm_target.operations_for_qargs((0, 1))
self.assertEqual(len(expected), len(res))
for x in expected:
self.assertIn(x, res)
expected = [
RXGate(self.theta),
RYGate(self.theta),
RZGate(self.theta),
RGate(self.theta, self.phi),
Measure(),
IfElseOp,
ForLoopOp,
WhileLoopOp,
SwitchCaseOp,
]
res = self.aqt_target.operations_for_qargs((0,))
self.assertEqual(len(expected), len(res))
for x in expected:
self.assertIn(x, res)
expected = [RXXGate(self.theta), IfElseOp, ForLoopOp, WhileLoopOp, SwitchCaseOp]
res = self.aqt_target.operations_for_qargs((0, 1))
self.assertEqual(len(expected), len(res))
for x in expected:
self.assertIn(x, res)
def test_operation_names_for_qargs(self):
expected = {
"id",
"rz",
"sx",
"x",
"measure",
"if_else",
"for_loop",
"while_loop",
"switch_case",
}
self.assertEqual(expected, self.ibm_target.operation_names_for_qargs((0,)))
expected = {
"cx",
"if_else",
"for_loop",
"while_loop",
"switch_case",
}
self.assertEqual(expected, self.ibm_target.operation_names_for_qargs((0, 1)))
expected = {
"rx",
"ry",
"rz",
"r",
"measure",
"if_else",
"for_loop",
"while_loop",
"switch_case",
}
self.assertEqual(self.aqt_target.operation_names_for_qargs((0,)), expected)
expected = {"rxx", "if_else", "for_loop", "while_loop", "switch_case"}
self.assertEqual(self.aqt_target.operation_names_for_qargs((0, 1)), expected)
def test_operations(self):
ibm_expected = [
RZGate(self.theta),
IGate(),
SXGate(),
XGate(),
CXGate(),
Measure(),
WhileLoopOp,
IfElseOp,
ForLoopOp,
SwitchCaseOp,
]
for gate in ibm_expected:
self.assertIn(gate, self.ibm_target.operations)
aqt_expected = [
RZGate(self.theta),
RXGate(self.theta),
RYGate(self.theta),
RGate(self.theta, self.phi),
RXXGate(self.theta),
ForLoopOp,
IfElseOp,
WhileLoopOp,
SwitchCaseOp,
]
for gate in aqt_expected:
self.assertIn(gate, self.aqt_target.operations)
fake_expected = [
UGate(self.theta, self.phi, self.lam),
CXGate(),
Measure(),
ForLoopOp,
WhileLoopOp,
IfElseOp,
SwitchCaseOp,
]
for gate in fake_expected:
self.assertIn(gate, self.target_global_gates_only.operations)
def test_add_invalid_instruction(self):
inst_props = {(0, 1, 2, 3): None}
target = Target()
with self.assertRaises(TranspilerError):
target.add_instruction(CXGate(), inst_props)
def test_instructions(self):
ibm_expected = [
(IGate(), (0,)),
(IGate(), (1,)),
(IGate(), (2,)),
(IGate(), (3,)),
(IGate(), (4,)),
(RZGate(self.theta), (0,)),
(RZGate(self.theta), (1,)),
(RZGate(self.theta), (2,)),
(RZGate(self.theta), (3,)),
(RZGate(self.theta), (4,)),
(SXGate(), (0,)),
(SXGate(), (1,)),
(SXGate(), (2,)),
(SXGate(), (3,)),
(SXGate(), (4,)),
(XGate(), (0,)),
(XGate(), (1,)),
(XGate(), (2,)),
(XGate(), (3,)),
(XGate(), (4,)),
(CXGate(), (3, 4)),
(CXGate(), (4, 3)),
(CXGate(), (3, 1)),
(CXGate(), (1, 3)),
(CXGate(), (1, 2)),
(CXGate(), (2, 1)),
(CXGate(), (0, 1)),
(CXGate(), (1, 0)),
(Measure(), (0,)),
(Measure(), (1,)),
(Measure(), (2,)),
(Measure(), (3,)),
(Measure(), (4,)),
(IfElseOp, None),
(ForLoopOp, None),
(WhileLoopOp, None),
(SwitchCaseOp, None),
]
self.assertEqual(ibm_expected, self.ibm_target.instructions)
ideal_sim_expected = [
(CXGate(), None),
(UGate(self.theta, self.phi, self.lam), None),
(Measure(), None),
(IfElseOp, None),
(ForLoopOp, None),
(WhileLoopOp, None),
(SwitchCaseOp, None),
]
self.assertEqual(ideal_sim_expected, self.target_global_gates_only.instructions)
def test_instruction_supported(self):
self.assertTrue(self.aqt_target.instruction_supported("r", (0,)))
self.assertFalse(self.aqt_target.instruction_supported("cx", (0, 1)))
self.assertTrue(self.target_global_gates_only.instruction_supported("cx", (0, 1)))
self.assertFalse(self.target_global_gates_only.instruction_supported("cx", (0, 524)))
self.assertFalse(self.target_global_gates_only.instruction_supported("cx", (0, 1, 2)))
self.assertTrue(self.aqt_target.instruction_supported("while_loop", (0, 1, 2, 3)))
self.assertTrue(
self.aqt_target.instruction_supported(operation_class=WhileLoopOp, qargs=(0, 1, 2, 3))
)
self.assertTrue(
self.aqt_target.instruction_supported(operation_class=SwitchCaseOp, qargs=(0, 1, 2, 3))
)
self.assertFalse(
self.ibm_target.instruction_supported(
operation_class=IfElseOp, qargs=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
)
)
self.assertFalse(
self.ibm_target.instruction_supported(operation_class=IfElseOp, qargs=(0, 425))
)
self.assertFalse(self.ibm_target.instruction_supported("for_loop", qargs=(0, 425)))
def test_coupling_map(self):
self.assertIsNone(self.target_global_gates_only.build_coupling_map())
self.assertEqual(
set(CouplingMap.from_full(5).get_edges()),
set(self.aqt_target.build_coupling_map().get_edges()),
)
self.assertEqual(
{
(3, 4),
(4, 3),
(3, 1),
(1, 3),
(1, 2),
(2, 1),
(0, 1),
(1, 0),
},
set(self.ibm_target.build_coupling_map().get_edges()),
)
class TestInstructionProperties(QiskitTestCase):
def test_empty_repr(self):
properties = InstructionProperties()
self.assertEqual(
repr(properties),
"InstructionProperties(duration=None, error=None, calibration=None)",
)
class TestTargetFromConfiguration(QiskitTestCase):
"""Test the from_configuration() constructor."""
def test_basis_gates_qubits_only(self):
"""Test construction with only basis gates."""
target = Target.from_configuration(["u", "cx"], 3)
self.assertEqual(target.operation_names, {"u", "cx"})
def test_basis_gates_no_qubits(self):
target = Target.from_configuration(["u", "cx"])
self.assertEqual(target.operation_names, {"u", "cx"})
def test_basis_gates_coupling_map(self):
"""Test construction with only basis gates."""
target = Target.from_configuration(
["u", "cx"], 3, CouplingMap.from_ring(3, bidirectional=False)
)
self.assertEqual(target.operation_names, {"u", "cx"})
self.assertEqual({(0,), (1,), (2,)}, target["u"].keys())
self.assertEqual({(0, 1), (1, 2), (2, 0)}, target["cx"].keys())
def test_properties(self):
fake_backend = FakeVigo()
config = fake_backend.configuration()
properties = fake_backend.properties()
target = Target.from_configuration(
basis_gates=config.basis_gates,
num_qubits=config.num_qubits,
coupling_map=CouplingMap(config.coupling_map),
backend_properties=properties,
)
self.assertEqual(0, target["rz"][(0,)].error)
self.assertEqual(0, target["rz"][(0,)].duration)
def test_properties_with_durations(self):
fake_backend = FakeVigo()
config = fake_backend.configuration()
properties = fake_backend.properties()
durations = InstructionDurations([("rz", 0, 0.5)], dt=1.0)
target = Target.from_configuration(
basis_gates=config.basis_gates,
num_qubits=config.num_qubits,
coupling_map=CouplingMap(config.coupling_map),
backend_properties=properties,
instruction_durations=durations,
dt=config.dt,
)
self.assertEqual(0.5, target["rz"][(0,)].duration)
def test_inst_map(self):
fake_backend = FakeNairobi()
config = fake_backend.configuration()
properties = fake_backend.properties()
defaults = fake_backend.defaults()
constraints = TimingConstraints(**config.timing_constraints)
target = Target.from_configuration(
basis_gates=config.basis_gates,
num_qubits=config.num_qubits,
coupling_map=CouplingMap(config.coupling_map),
backend_properties=properties,
dt=config.dt,
inst_map=defaults.instruction_schedule_map,
timing_constraints=constraints,
)
self.assertIsNotNone(target["sx"][(0,)].calibration)
self.assertEqual(target.granularity, constraints.granularity)
self.assertEqual(target.min_length, constraints.min_length)
self.assertEqual(target.pulse_alignment, constraints.pulse_alignment)
self.assertEqual(target.acquire_alignment, constraints.acquire_alignment)
def test_concurrent_measurements(self):
fake_backend = FakeVigo()
config = fake_backend.configuration()
target = Target.from_configuration(
basis_gates=config.basis_gates,
concurrent_measurements=config.meas_map,
)
self.assertEqual(target.concurrent_measurements, config.meas_map)
def test_custom_basis_gates(self):
basis_gates = ["my_x", "cx"]
custom_name_mapping = {"my_x": XGate()}
target = Target.from_configuration(
basis_gates=basis_gates, num_qubits=2, custom_name_mapping=custom_name_mapping
)
self.assertEqual(target.operation_names, {"my_x", "cx"})
def test_missing_custom_basis_no_coupling(self):
basis_gates = ["my_X", "cx"]
with self.assertRaisesRegex(KeyError, "is not present in the standard gate names"):
Target.from_configuration(basis_gates, num_qubits=4)
def test_missing_custom_basis_with_coupling(self):
basis_gates = ["my_X", "cx"]
cmap = CouplingMap.from_line(3)
with self.assertRaisesRegex(KeyError, "is not present in the standard gate names"):
Target.from_configuration(basis_gates, 3, cmap)
def test_over_two_qubit_gate_without_coupling(self):
basis_gates = ["ccx", "cx", "swap", "u"]
target = Target.from_configuration(basis_gates, 15)
self.assertEqual(target.operation_names, {"ccx", "cx", "swap", "u"})
def test_over_two_qubits_with_coupling(self):
basis_gates = ["ccx", "cx", "swap", "u"]
cmap = CouplingMap.from_line(15)
with self.assertRaisesRegex(TranspilerError, "This constructor method only supports"):
Target.from_configuration(basis_gates, 15, cmap)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# -*- 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.
# pylint: disable=too-many-function-args, unexpected-keyword-arg
"""THIS FILE IS DEPRECATED AND WILL BE REMOVED IN RELEASE 0.9.
"""
import warnings
from qiskit.converters import dag_to_circuit, circuit_to_dag
from qiskit.transpiler import CouplingMap
from qiskit import compiler
from qiskit.transpiler.preset_passmanagers import (default_pass_manager_simulator,
default_pass_manager)
def transpile(circuits, backend=None, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None, pass_manager=None):
"""transpile one or more circuits.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
basis_gates (list[str]): list of basis gate names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (Layout or dict or list):
Initial position of virtual qubits on physical qubits. The final
layout is not guaranteed to be the same, as the transpiler may permute
qubits through swaps or other means.
seed_mapper (int): random seed for the swap_mapper
pass_manager (PassManager): a pass_manager for the transpiler stages
Returns:
QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).
Raises:
TranspilerError: in case of bad inputs to transpiler or errors in passes
"""
warnings.warn("qiskit.transpiler.transpile() has been deprecated and will be "
"removed in the 0.9 release. Use qiskit.compiler.transpile() instead.",
DeprecationWarning)
return compiler.transpile(circuits=circuits, backend=backend,
basis_gates=basis_gates, coupling_map=coupling_map,
initial_layout=initial_layout, seed_transpiler=seed_mapper,
pass_manager=pass_manager)
def transpile_dag(dag, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None, pass_manager=None):
"""Deprecated - Use qiskit.compiler.transpile for transpiling from
circuits to circuits.
Transform a dag circuit into another dag circuit
(transpile), through consecutive passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via transpilation
basis_gates (list[str]): list of basis gate names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
initial_layout (Layout or None): A layout object
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: transformed dag
"""
warnings.warn("transpile_dag has been deprecated and will be removed in the "
"0.9 release. Circuits can be transpiled directly to other "
"circuits with the transpile function.", DeprecationWarning)
if basis_gates is None:
basis_gates = ['u1', 'u2', 'u3', 'cx', 'id']
if pass_manager is None:
# default set of passes
# if a coupling map is given compile to the map
if coupling_map:
pass_manager = default_pass_manager(basis_gates,
CouplingMap(coupling_map),
initial_layout,
seed_transpiler=seed_mapper)
else:
pass_manager = default_pass_manager_simulator(basis_gates)
# run the passes specified by the pass manager
# TODO return the property set too. See #1086
name = dag.name
circuit = dag_to_circuit(dag)
circuit = pass_manager.run(circuit)
dag = circuit_to_dag(circuit)
dag.name = name
return dag
|
https://github.com/BoschSamuel/QizGloria
|
BoschSamuel
|
# -- coding: utf-8 --
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
from qiskit import *
import numpy as np
import torch
from torch.autograd import Function
class myExp(Function):
@staticmethod
def forward(ctx, i):
result = i.exp()
ctx.save_for_backward(result)
return result
@staticmethod
def backward(ctx, grad_output):
result, = ctx.saved_tensors
return grad_output * result
x = torch.tensor([[1., -1.], [1., 1.]], requires_grad=True)
myexp = myExp.apply
y1 = x**2
y2 = myexp(y1).sum().backward()
x.grad
np.ones(1)
import numpy as np
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import matplotlib.pyplot as plt
%matplotlib inline
parameters = np.random.rand(3)
shots = 1000
circuit = QuantumCircuit(2, 2)
def add_measurements(circuit):
nr_qubits = circuit.n_qubits
circuit.measure(range(nr_qubits), range(nr_qubits))
return circuit
def add_x_rotation(circuit):
nr_qubits = circuit.n_qubits
for i in range(nr_qubits):
circuit.rx(np.pi/2, i)
return circuit
def add_y_rotation(circuit):
nr_qubits = circuit.n_qubits
for i in range(nr_qubits):
circuit.ry(np.pi/2, i)
return circuit
def execute_job(circuit, shots):
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=shots)
result = job.result()
counts = result.get_counts(circuit)
return counts
def N_qubit_expectation(circuit, shots, measurement='Z'):
if measurement=='Z':
print("Measure in Z")
nr_qubits = circuit.n_qubits
circuit = add_measurements(circuit)
counts = execute_job(circuit, shots)
return N_qubit_expectation_Z(counts, shots, nr_qubits)
if measurement=='X':
print("Measure in X")
nr_qubits = circuit.n_qubits
circuit = add_x_rotation(circuit)
#circuit.h(0)
circuit = add_measurements(circuit)
counts = execute_job(circuit, shots)
return N_qubit_expectation_Z(counts, shots, nr_qubits), circuit
if measurement=='Y':
nr_qubits = circuit.n_qubits
circuit = add_y_rotation(circuit)
circuit = add_measurements(circuit)
counts = execute_job(circuit, shots)
return N_qubit_expectation_Z(counts, shots, nr_qubits)
else:
print("Measurement type not yet defined")
def N_qubit_expectation_Z(counts, shots, nr_qubits):
expects = np.zeros(nr_qubits)
for key in counts.keys():
perc = counts[key]/shots
check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)])
expects += check
return expects
def one_qubit_expectation_Z(counts, shots):
probs = sorted([(i, c/shots) for i, c in counts.items()])
P = np.float64(np.array(probs)[:, 1])
print(P[0], P[1])
return P[0]*1 + P[1]*-1
def one_qubit_error(counts, shots, Z_traget):
return (one_qubit_expectation_Z(counts, shots)- Z_target)**2
def N_qubit_error(counts, shots, nr_qubits, target_array):
return ((N_qubit_expectation_Z(counts, shots, nr_qubits)-target_array)**2).sum()
#circuit = add_measurements(circuit)
#counts = execute_job(circuit, 1000)
expects, circuit = N_qubit_expectation(circuit, shots, measurement="X")
circuit.draw()
print(expects, circuit)
circuit.n_qubits
class QiskitCircuit():
def __init__(self,shots):
self.theta = Parameter('Theta')
self.phi = Parameter('Phi')
self.lam = Parameter('Lambda')
self.shots = shots
def create_circuit():
qr = QuantumRegister(1,'q')
cr = ClassicalRegister(1,'c')
ckt = QuantumCircuit(qr,cr)
ckt.h(qr[0])
ckt.barrier()
ckt.u3(self.theta,self.phi,self.lam,qr[0])
ckt.barrier()
ckt.measure(qr,cr)
return ckt
self.circuit = create_circuit()
def N_qubit_expectation_Z(self,counts, shots, nr_qubits):
expects = np.zeros(nr_qubits)
for key in counts.keys():
perc = counts[key]/shots
check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)])
expects += check
return expects
def bind(self,parameters):
[self.theta,self.phi,self.lam] = parameters
self.circuit.data[2][0]._params = parameters
return self.circuit
def run(self):
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(self.circuit,backend,shots=self.shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(self.circuit)
return self.N_qubit_expectation_Z(counts,self.shots,1)
class TorchCircuit(Function):
@staticmethod
def forward(ctx, i):
if not hasattr(ctx, 'QiskitCirc'):
ctx.QiskitCirc = QiskitCircuit(shots=100000)
ckt = ctx.QiskitCirc.bind([i[0][0].item(), i[0][1].item(), i[0][2].item()])
exp_value = ctx.QiskitCirc.run()
result = torch.tensor([[exp_value]])
ctx.save_for_backward(result, i)
print(result)
return result
@staticmethod
def backward(ctx, grad_output):
eps = 0.01
forward_tensor, i = ctx.saved_tensors
input_numbers = [i[0][0].item(), i[0][1].item(), i[0][2].item()]
gradient = [0,0,0]
for k in range(len(input_numbers)):
input_eps = input_numbers
input_eps[k] = input_numbers[k] + eps
_ckt = ctx.QiskitCirc.bind(input_eps)
exp_value = ctx.QiskitCirc.run()[0]
result_eps = torch.tensor([[exp_value]])
gradient_result = (exp_value - forward_tensor[0][0].item())
gradient[k] = gradient_result
result = torch.tensor([gradient])
return result.float() * grad_output.float()
# useful additional packages
import matplotlib.pyplot as plt
import matplotlib.axes as axes
%matplotlib inline
import numpy as np
import networkx as nx
from qiskit import BasicAer
from qiskit.tools.visualization import plot_histogram
from qiskit.aqua import run_algorithm
from qiskit.aqua.input import EnergyInput
from qiskit.aqua.translators.ising import max_cut, tsp
from qiskit.aqua.algorithms import VQE, ExactEigensolver
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua.components.variational_forms import RY
from qiskit.aqua import QuantumInstance
# setup aqua logging
import logging
from qiskit.aqua import set_qiskit_aqua_logging
# Generating a graph of 4 nodes
n=4 # 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),(2,3,1.0)]
# tuple is (i,j,weight) where (i,j) is the edge
G.add_weighted_edges_from(elist)
colors = ['r' for node in G.nodes()]
pos = nx.spring_layout(G)
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos)
from docplex.mp.model import Model
from qiskit.aqua.translators.ising import docplex
n=4
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)
qubitOp, offset = max_cut.get_max_cut_qubitops(w)
algo_input = EnergyInput(qubitOp)
mdl = Model(name='max_cut')
x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(n)}
# Object function
max_cut_func = mdl.sum(w[i,j]* x[i] * ( 1 - x[j] ) for i in range(n) for j in range(n))
mdl.maximize(max_cut_func)
# No constraints for Max-Cut problems.
qubitOp_docplex, offset_docplex = docplex.get_qubitops(mdl)
seed = 10598
spsa = SPSA(max_trials=300)
ry = RY(qubitOp.num_qubits, depth=1, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa)
print(vqe.setting)
backend = BasicAer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)
parameters = np.random.rand(8)
circuits = vqe.construct_circuit(parameters)
print(circuits[0])
algorithm_cfg = {'name': 'VQE'}
dictio = {'problem': {'name': 'ising'},'algorithm': algorithm_cfg}
vqe.energy_evaluation(parameters)
import torch
import numpy as np
from torchvision import datasets, transforms
batch_size_train = 64
batch_size_test = 1000
learning_rate = 0.01
momentum = 0.5
log_interval = 10
torch.backends.cudnn.enabled = False
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor()])
mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
labels = mnist_trainset.targets #get labels
labels = labels.numpy()
idx1 = np.where(labels == 0) #search all zeros
idx2 = np.where(labels == 1) # search all ones
idx = np.concatenate((idx1[0],idx2[0])) # concatenate their indices
mnist_trainset.targets = labels[idx]
mnist_trainset.data = mnist_trainset.data[idx]
print(mnist_trainset)
train_loader = torch.utils.data.DataLoader(mnist_trainset, batch_size=batch_size_train, shuffle=True)
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 2)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return F.softmax(x)
network = Net()
optimizer = optim.SGD(network.parameters(), lr=learning_rate,
momentum=momentum)
epochs = 3
for epoch in range(epochs):
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
output = network(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
print(loss)
length = target.shape[0]
print(length)
for i in range(length):
print(target[i], output[i][1])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.problems import ElectronicBasis
driver = PySCFDriver()
driver.run_pyscf()
ao_problem = driver.to_problem(basis=ElectronicBasis.AO)
print(ao_problem.basis)
ao_hamil = ao_problem.hamiltonian
print(ao_hamil.electronic_integrals.alpha)
from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema
qcschema = driver.to_qcschema()
basis_transformer = get_ao_to_mo_from_qcschema(qcschema)
print(basis_transformer.initial_basis)
print(basis_transformer.final_basis)
mo_problem = basis_transformer.transform(ao_problem)
print(mo_problem.basis)
mo_hamil = mo_problem.hamiltonian
print(mo_hamil.electronic_integrals.alpha)
import numpy as np
from qiskit_nature.second_q.operators import ElectronicIntegrals
from qiskit_nature.second_q.problems import ElectronicBasis
from qiskit_nature.second_q.transformers import BasisTransformer
ao2mo_alpha = np.random.random((2, 2))
ao2mo_beta = np.random.random((2, 2))
basis_transformer = BasisTransformer(
ElectronicBasis.AO,
ElectronicBasis.MO,
ElectronicIntegrals.from_raw_integrals(ao2mo_alpha, h1_b=ao2mo_beta),
)
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5")
full_problem = driver.run()
print(full_problem.molecule)
print(full_problem.num_particles)
print(full_problem.num_spatial_orbitals)
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
fc_transformer = FreezeCoreTransformer()
fc_problem = fc_transformer.transform(full_problem)
print(fc_problem.num_particles)
print(fc_problem.num_spatial_orbitals)
print(fc_problem.hamiltonian.constants)
fc_transformer = FreezeCoreTransformer(remove_orbitals=[4, 5])
fc_problem = fc_transformer.transform(full_problem)
print(fc_problem.num_particles)
print(fc_problem.num_spatial_orbitals)
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5")
full_problem = driver.run()
print(full_problem.num_particles)
print(full_problem.num_spatial_orbitals)
from qiskit_nature.second_q.transformers import ActiveSpaceTransformer
as_transformer = ActiveSpaceTransformer(2, 2)
as_problem = as_transformer.transform(full_problem)
print(as_problem.num_particles)
print(as_problem.num_spatial_orbitals)
print(as_problem.hamiltonian.electronic_integrals.alpha)
as_transformer = ActiveSpaceTransformer(2, 2, active_orbitals=[0, 4])
as_problem = as_transformer.transform(full_problem)
print(as_problem.num_particles)
print(as_problem.num_spatial_orbitals)
print(as_problem.hamiltonian.electronic_integrals.alpha)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/alexyev/Grover-s_Algorithm
|
alexyev
|
import matplotlib.pyplot as plt
import numpy as np
!pip install qiskit
from qiskit import IBMQ, Aer, assemble, transpile, execute
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.providers.ibmq import least_busy
!pip install qiskit.visualization
from qiskit.visualization import *
from qiskit.tools.jupyter import *
!pip install ibm_quantum_widgets
from ibm_quantum_widgets import *
from qiskit.tools.monitor import job_monitor
def initialize_circuit(qc, qubits):
for q in qubits:
qc.h(q)
return qc
qc = QuantumCircuit(3)
qc.cz(0, 2)
qc.cz(1, 2)
oracle_3 = qc.to_gate()
oracle_3.name = "Uω"
def diffuser(qubits):
qc = QuantumCircuit(qubits)
for qubit in range(qubits):
qc.h(qubit)
for qubit in range(qubits):
qc.x(qubit)
qc.h(qubits-1)
qc.mct(list(range(qubits-1)), qubits -1)
qc.h(qubits-1)
for qubit in range(qubits):
qc.x(qubit)
for qubit in range(qubits):
qc.h(qubit)
U_s = qc.to_gate()
U_s.name = "Us"
return U_s
n_qubits = 3
grover_circuit = QuantumCircuit(n_qubits)
grover_circuit = initialize_circuit(grover_circuit, [0, 1, 2])
grover_circuit.append(oracle_3, [0, 1, 2])
grover_circuit.append(diffuser(n_qubits), [0, 1, 2])
grover_circuit.measure_all()
grover_circuit.draw()
backend = Aer.get_backend('qasm_simulator')
transpiled_grover_circuit = transpile(grover_circuit, backend)
job = execute(transpiled_grover_circuit, backend)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
provider = IBMQ.load_account()
device_2 = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print(device_2)
transpiled_grover_circuit_2 = transpile(grover_circuit, backend_2, optimization_level=3)
job = device_2.run(transpiled_grover_circuit_2)
job_monitor(job, interval=2)
results_2 = job.result()
answer_2 = results_2.get_counts()
plot_histogram(answer_2)
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
import numpy as np
from scipy.linalg import expm, sinm, cosm
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import math
from scipy import stats
%matplotlib inline
from IPython.display import Image, display, Math, Latex
sns.set(color_codes=True)
|
https://github.com/usamisaori/quantum-expressibility-entangling-capability
|
usamisaori
|
import numpy as np
from qiskit.quantum_info import state_fidelity, Statevector
def getStatevector(circuit):
return Statevector(circuit).data
import warnings
warnings.filterwarnings('ignore')
def P_haar(N, F):
if F == 1:
return 0
else:
return (N - 1) * ((1 - F) ** (N - 2))
def KL(P, Q):
epsilon = 1e-8
kl_divergence = 0.0
for p, q in zip(P, Q):
kl_divergence += p * np.log( (p + epsilon) / (q + epsilon) )
return abs(kl_divergence)
def expressibility(qubits, sampler, *, bins=100, epoch=3000, layer=1, encode=False, return_detail=False):
unit = 1 / bins
limits = []
probabilities = np.array([0] * bins)
for i in range(1, bins + 1):
limits.append(unit * i)
for i in range(epoch):
circuit_1 = sampler(layer=layer, qubits=qubits)
circuit_2 = sampler(layer=layer, qubits=qubits)
f = state_fidelity(
getStatevector(circuit_1),
getStatevector(circuit_2)
)
for j in range(bins):
if f <= limits[j]:
probabilities[j] += 1
break
pHaar_vqc = [ P_haar(2 ** qubits, f - (unit/2)) / bins for f in limits]
probabilities = [ p / epoch for p in probabilities ]
if return_detail:
return pHaar_vqc, probabilities
else:
return KL(probabilities, pHaar_vqc)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- 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.
"""A module of magic functions"""
import time
import threading
from IPython.display import display # pylint: disable=import-error
from IPython.core import magic_arguments # pylint: disable=import-error
from IPython.core.magic import cell_magic, Magics, magics_class # pylint: disable=import-error
try:
import ipywidgets as widgets # pylint: disable=import-error
except ImportError:
raise ImportError('These functions need ipywidgets. '
'Run "pip install ipywidgets" before.')
import qiskit
from qiskit.tools.events.progressbar import TextProgressBar
from .progressbar import HTMLProgressBar
def _html_checker(job_var, interval, status, header,
_interval_set=False):
"""Internal function that updates the status
of a HTML job monitor.
Args:
job_var (BaseJob): The job to keep track of.
interval (int): The status check interval
status (widget): HTML ipywidget for output ot screen
header (str): String representing HTML code for status.
_interval_set (bool): Was interval set by user?
"""
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
status.value = header % (job_status_msg)
while job_status_name not in ['DONE', 'CANCELLED']:
time.sleep(interval)
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
if job_status_name == 'ERROR':
break
else:
if job_status_name == 'QUEUED':
job_status_msg += ' (%s)' % job_var.queue_position()
if not _interval_set:
interval = max(job_var.queue_position(), 2)
else:
if not _interval_set:
interval = 2
status.value = header % (job_status_msg)
status.value = header % (job_status_msg)
@magics_class
class StatusMagic(Magics):
"""A class of status magic functions.
"""
@cell_magic
@magic_arguments.magic_arguments()
@magic_arguments.argument(
'-i',
'--interval',
type=float,
default=None,
help='Interval for status check.'
)
def qiskit_job_status(self, line='', cell=None):
"""A Jupyter magic function to check the status of a Qiskit job instance.
"""
args = magic_arguments.parse_argstring(self.qiskit_job_status, line)
if args.interval is None:
args.interval = 2
_interval_set = False
else:
_interval_set = True
# Split cell lines to get LHS variables
cell_lines = cell.split('\n')
line_vars = []
for cline in cell_lines:
if '=' in cline and '==' not in cline:
line_vars.append(cline.replace(' ', '').split('=')[0])
elif '.append(' in cline:
line_vars.append(cline.replace(' ', '').split('(')[0])
# Execute the cell
self.shell.ex(cell)
# Look for all vars that are BaseJob instances
jobs = []
for var in line_vars:
iter_var = False
if '#' not in var:
# The line var is a list or array, but we cannot parse the index
# so just iterate over the whole array for jobs.
if '[' in var:
var = var.split('[')[0]
iter_var = True
elif '.append' in var:
var = var.split('.append')[0]
iter_var = True
if iter_var:
for item in self.shell.user_ns[var]:
if isinstance(item, qiskit.providers.basejob.BaseJob):
jobs.append(item)
else:
if isinstance(self.shell.user_ns[var],
qiskit.providers.basejob.BaseJob):
jobs.append(self.shell.user_ns[var])
# Must have one job class
if not any(jobs):
raise Exception(
"Cell must contain at least one variable of BaseJob type.")
# List index of job if checking status of multiple jobs.
multi_job = False
if len(jobs) > 1:
multi_job = True
job_checkers = []
# Loop over every BaseJob that was found.
for idx, job_var in enumerate(jobs):
style = "font-size:16px;"
if multi_job:
idx_str = '[%s]' % idx
else:
idx_str = ''
header = "<p style='{style}'>Job Status {id}: %s </p>".format(id=idx_str,
style=style)
status = widgets.HTML(
value=header % job_var.status().value)
thread = threading.Thread(target=_html_checker, args=(job_var, args.interval,
status, header,
_interval_set))
thread.start()
job_checkers.append(status)
# Group all HTML widgets into single vertical layout
box = widgets.VBox(job_checkers)
display(box)
@magics_class
class ProgressBarMagic(Magics):
"""A class of progress bar magic functions.
"""
@cell_magic
@magic_arguments.magic_arguments()
@magic_arguments.argument(
'-t',
'--type',
type=str,
default='html',
help="Type of progress bar, 'html' or 'text'."
)
def qiskit_progress_bar(self, line='', cell=None): # pylint: disable=W0613
"""A Jupyter magic function to generate progressbar.
"""
args = magic_arguments.parse_argstring(self.qiskit_progress_bar, line)
if args.type == 'html':
HTMLProgressBar()
elif args.type == 'text':
TextProgressBar()
else:
raise qiskit.QiskitError('Invalid progress bar type.')
self.shell.ex(cell)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from utils import version; version.version_information()
|
https://github.com/rubenandrebarreiro/summer-school-on-quantum-computing-software-for-near-term-quantum-devices-2020
|
rubenandrebarreiro
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# importing Qiskit
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.quantum_info import Statevector
def cz(circuit,qr):
circuit.h(qr[1])
circuit.cx(qr[0],qr[1])
circuit.h(qr[1])
qr2 = QuantumRegister(2)
czCircuit = QuantumCircuit(qr2)
cz(czCircuit,qr2)
czCircuit.draw(output="mpl")
#Since Z=HXH and X=HZH
#This is identical to a CZ (controlled Z)
def ccz(circuit,qr):
circuit.h(qr[2])
# ccx is the Toffoli gate
circuit.ccx(qr[0], qr[1], qr[2])
circuit.h(qr[2])
qr3 = QuantumRegister(3)
cczCircuit = QuantumCircuit(qr3)
ccz(cczCircuit,qr3)
cczCircuit.draw(output="mpl")
#We are going to check numerically whether this is the CCCZ gate
def cccz(circuit,qr):
pi = math.pi
circuit.x(qr[0]) #we change the inputvalue by applying an X gate at the beggining
circuit.x(qr[1]) #second qubit to 1
circuit.x(qr[2]) #third qubit to 1
circuit.x(qr[3]) #fourth qubit to 1
circuit.cu1(pi/4,qr[0],qr[3])
circuit.cx(qr[0], qr[1])
circuit.cu1(-pi/4, qr[1],qr[3])
circuit.cx(qr[0], qr[1])
circuit.cu1(pi/4, qr[1],qr[3])
circuit.cx(qr[1], qr[2])
circuit.cu1(-pi/4, qr[2],qr[3])
circuit.cx(qr[0], qr[2])
circuit.cu1(pi/4, qr[2],qr[3])
circuit.cx(qr[1], qr[2])
circuit.cu1(-pi/4, qr[2],qr[3])
circuit.cx(qr[0], qr[2])
circuit.cu1(pi/4, qr[2],qr[3])
qr4 = QuantumRegister(4)
ccczCircuit = QuantumCircuit(qr4)
cccz(ccczCircuit,qr4)
ccczCircuit.draw(output="mpl")
from qiskit.visualization import plot_state_qsphere
sv_sim = Aer.get_backend('statevector_simulator')
job_sim = execute(ccczCircuit, sv_sim)
statevec = job_sim.result().get_statevector()
from qiskit_textbook.tools import vector2latex
#vector2latex(statevec, pretext="|\\psi\\rangle =")
plot_state_qsphere(statevec)
def n_controlled_Z(circuit, qr):
"""Implement a Z gate with multiple controls"""
if (len(qr) > 4):
raise ValueError('The controlled Z with more than 3 controls is not implemented')
# This is the case n = 2 (1 control + 1 target qubit)
elif (len(qr) == 2):
cz(circuit,qr)
# This is the case n = 3 (2 control + 1 target qubit)
elif (len(qr) == 3):
ccz(circuit,qr)
# This is the case n = 4 (3 control + 1 target qubit)
elif (len(qr) == 4):
cccz(circuit,qr)
def phase_oracle(circuit,qr,element):
# element is an array that defines the searched element, for example, element = [0,1,0,1]
circuit.x(qr[0]) #we change the inputvalue by applying an X gate at the beggining
# circuit.x(qr[1]) #for the second qubit
circuit.x(qr[2])
# circuit.x(qr[3])
circuit.barrier() #in this part, we are changing the input to the oracle circuit
n = len(element)
for j,x in enumerate(element):
if (x == 0):
circuit.x(qr[j])
n_controlled_Z(circuit,qr)
for j,x in enumerate(element):
if (x == 0):
circuit.x(qr[j])
element=[0,1,0,1]
qr4 = QuantumRegister(4)
oracleCircuit = QuantumCircuit(qr4)
phase_oracle(oracleCircuit,qr4, element)
oracleCircuit.draw(output="mpl")
oracleCircuit.measure_all()
qasm_simulator = Aer.get_backend('statevector_simulator')
job_sim = execute(oracleCircuit, sv_sim)
statevec = job_sim.result().get_statevector()
from qiskit_textbook.tools import vector2latex
vector2latex(statevec, pretext="|\\psi\\rangle =")
def inversion_about_average(circuit, register):
"""Apply inversion about the average step of Grover's algorithm."""
circuit.h(register)
circuit.x(register)
n_controlled_Z(circuit, qr)
circuit.x(register)
circuit.h(register)
#Let's plot it!
qr = QuantumRegister(4)
qAverage = QuantumCircuit(qr)
inversion_about_average(qAverage, qr, 4)
qAverage.draw(output='mpl')
#implementation of the whole Grover Search Algorithm
def cccz(circuit,qr): #first I define again the oracle, since before it was personalized
pi = math.pi
circuit.cu1(pi/4,qr[0],qr[3])
circuit.cx(qr[0], qr[1])
circuit.cu1(-pi/4, qr[1],qr[3])
circuit.cx(qr[0], qr[1])
circuit.cu1(pi/4, qr[1],qr[3])
circuit.cx(qr[1], qr[2])
circuit.cu1(-pi/4, qr[2],qr[3])
circuit.cx(qr[0], qr[2])
circuit.cu1(pi/4, qr[2],qr[3])
circuit.cx(qr[1], qr[2])
circuit.cu1(-pi/4, qr[2],qr[3])
circuit.cx(qr[0], qr[2])
circuit.cu1(pi/4, qr[2],qr[3])
def phase_oracle(circuit,qr,element): #first I define again the oracle, since before it was personalized
circuit.barrier() #in this part, we are changing the input to the oracle circuit
n = len(element)
for j,x in enumerate(element):
if (x == 0):
circuit.x(qr[j])
n_controlled_Z(circuit,qr)
for j,x in enumerate(element):
if (x == 0):
circuit.x(qr[j])
def n_controlled_Z(circuit, qr):
"""Implement a Z gate with multiple controls"""
if (len(qr) > 4):
raise ValueError('The controlled Z with more than 3 controls is not implemented')
# This is the case n = 2 (1 control + 1 target qubit)
elif (len(qr) == 2):
cz(circuit,qr)
# This is the case n = 3 (2 control + 1 target qubit)
elif (len(qr) == 3):
ccz(circuit,qr)
# This is the case n = 4 (3 control + 1 target qubit)
elif (len(qr) == 4):
cccz(circuit,qr)
def grover_algorithm(Circuit,R,qr,element):
for i in range(1,R):
phase_oracle(Circuit,qr,element)
inversion_about_average(Circuit,qr)
#n=2 circuit
qr2=QuantumRegister(2)
print(len(qr2))
cr2=ClassicalRegister(2)
circuit2=QuantumCircuit(qr2,cr2)
circuit2.h(0)
circuit2.h(1)#quantum superposition of the initial states
element2 = [0,1]
grover_algorithm(circuit2,2,qr2,[0,1])
|
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/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
print(qiskit.__version__)
from qiskit_machine_learning.datasets import ad_hoc_data
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(training_size = 20, test_size = 5,
n = adhoc_dimension, gap=0.3,
plot_data =False, one_hot=False,
include_sample_total=True)
import numpy
print(numpy.array(adhoc_total).shape)
print("train data shape: ", train_features.shape,"\ttrain labels shape: ", train_labels.shape)
print("test data shape: ", test_features.shape,"\ttest labels shape: ", test_labels.shape)
print('train data:\n',train_features[:5])
print('\ntrain label:\n',train_labels[:5])
# plot_adhoc_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
from qiskit import Aer
from qiskit.utils import QuantumInstance
seed=20
quantum_instance = QuantumInstance(Aer.get_backend("qasm_simulator"), shots=1024,
seed_simulator=seed, seed_transpiler=seed)
from qiskit.circuit.library import ZFeatureMap
from qiskit_machine_learning.kernels import QuantumKernel
z_feature_map = ZFeatureMap(feature_dimension=adhoc_dimension, reps=2)
z_kernel = QuantumKernel(feature_map = z_feature_map, quantum_instance=quantum_instance)
# z_feature_map.draw(output='mpl', scale=2)
z_feature_map.decompose().draw(output='mpl', scale=2)
from sklearn.svm import SVC
svc = SVC(kernel=z_kernel.evaluate)
svc.fit(train_features, train_labels)
score = svc.score(test_features, test_labels)
print('Callable kernel with ZFeatureMap classification test score: ', score)
prediction = svc.predict(test_features)
print(prediction)
from qiskit.circuit.library import ZZFeatureMap
zz_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement='linear')
zz_kernel = QuantumKernel(feature_map = zz_feature_map, quantum_instance=quantum_instance)
zz_feature_map.decompose().draw(output='mpl', scale=2)
from sklearn.svm import SVC
svc = SVC(kernel=zz_kernel.evaluate)
svc.fit(train_features, train_labels)
score = svc.score(test_features, test_labels)
print('Callable kernel with ZZFeatureMap classification test score: ', score)
prediction = svc.predict(test_features)
print(prediction)
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC()
qsvc.quantum_kernel.quantum_instance = quantum_instance
qsvc.fit(train_features, train_labels)
score = qsvc.score(test_features, test_labels)
print('QSVC classification test score: ', score)
prediction = qsvc.predict(test_features)
print(prediction)
from qiskit.circuit.library import ZFeatureMap
from qiskit_machine_learning.kernels import QuantumKernel
# here feature_dimension = 2 and reps = 1
adhoc_dimension = 2
z_feature_map = ZFeatureMap(feature_dimension=adhoc_dimension, reps=1)
z_kernel = QuantumKernel(feature_map = z_feature_map, quantum_instance=quantum_instance)
z_feature_map.decompose().draw(output='mpl', scale=2)
from qiskit.circuit.library import ZFeatureMap
from qiskit_machine_learning.kernels import QuantumKernel
# here feature_dimension = 2 and reps = 2
adhoc_dimension = 2
z_feature_map = ZFeatureMap(feature_dimension=adhoc_dimension, reps=2)
z_kernel = QuantumKernel(feature_map = z_feature_map, quantum_instance=quantum_instance)
z_feature_map.decompose().draw(output='mpl', scale=2)
from qiskit.circuit.library import ZFeatureMap
from qiskit_machine_learning.kernels import QuantumKernel
# here feature_dimension = 3 and reps = 4
adhoc_dimension = 3
z_feature_map = ZFeatureMap(feature_dimension=adhoc_dimension, reps=4)
z_kernel = QuantumKernel(feature_map = z_feature_map, quantum_instance=quantum_instance)
z_feature_map.decompose().draw(output='mpl', scale=2)
# same happens for ZZFeatureMap
from qiskit.circuit.library import ZZFeatureMap
adhoc_dimension=2
zz_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=1, entanglement='linear')
zz_kernel = QuantumKernel(feature_map = zz_feature_map, quantum_instance=quantum_instance)
zz_feature_map.decompose().draw(output='mpl', scale=2)
# same happens for ZZFeatureMap
from qiskit.circuit.library import ZZFeatureMap
adhoc_dimension=2
zz_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement='linear')
zz_kernel = QuantumKernel(feature_map = zz_feature_map, quantum_instance=quantum_instance)
zz_feature_map.decompose().draw(output='mpl', scale=2)
# same happens for ZZFeatureMap
from qiskit.circuit.library import ZZFeatureMap
adhoc_dimension=3
zz_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=1, entanglement='linear')
zz_kernel = QuantumKernel(feature_map = zz_feature_map, quantum_instance=quantum_instance)
zz_feature_map.decompose().draw(output='mpl', scale=2)
# same happens for ZZFeatureMap
from qiskit.circuit.library import ZZFeatureMap
adhoc_dimension=3
zz_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement='linear')
zz_kernel = QuantumKernel(feature_map = zz_feature_map, quantum_instance=quantum_instance)
zz_feature_map.decompose().draw(output='mpl', scale=2)
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas_profiling as pp
%matplotlib inline
# Constants
DATA_PATH = "../../Data/Raw/data.csv"
PP_PATH = "../../Output/Figures/pandasProfile.html"
CLEAN_DATA_PATH = "../../Data/Processed/data.csv"
data = pd.read_csv(DATA_PATH)
data.shape
data.columns
data.head(7)
data.info()
data.describe()
def check_unique(df):
""""
Checks the unique value in each column
:param df: The dataframe
"""
for col in df.columns:
unique = df[col].unique()
print("Column: {} has {} unique values\n".format(col, unique))
check_unique(data)
data['num '].value_counts()
fig = plt.figure()
sns.countplot(x="num ", data=data, palette="gist_rainbow_r")
plt.xlabel("Heart disease (0 = have, 1 = don't)")
plt.title("Target distribution")
plt.show()
fig.savefig("../../Output/Figures/targetdist.png", )
sns.countplot(x='sex', data=data, palette="mako_r")
plt.xlabel("Sex (0 = female, 1= male)")
plt.title("Age distribution")
plt.savefig("../../Output/Figures/agedist.png", format="png")
pd.crosstab(data['age'], data['num ']).plot(kind="bar",figsize=(20,6))
plt.title('Heart Disease Frequency for Ages')
plt.xlabel('Age')
plt.ylabel('Frequency')
plt.savefig('../../Output/Figures/heartDiseaseAndAges.png')
plt.figure(figsize=(15,8))
ax = sns.boxplot(data=data, orient="v", palette="Set2")
plt.title("Box plots")
plt.savefig("../../Output/Figures/boxplot.png")
sns.pairplot(data, diag_kind="kde")
plt.title("Pair plots")
plt.savefig("../../Output/Figures/pairplot.png")
data = data.rename(columns={'num ':'num'})
def fix_missing_values(df):
""""
Changes ? in the data to be np.Nan
:param df: The dataframe
:return df: Fixed dataframe
"""
cols = df.columns
for col in cols:
for i in range(len(df[col])):
if df[col][i] == '?':
df[col][i] = np.NaN
return df
data = fix_missing_values(data)
data.info()
def change_dtype(df):
""""
Changes the data type from object to float64
:param df: The dataframe
:return df: Fixed dataframe
"""
cols = df.columns
for col in cols:
if df[col].dtype == 'O':
df[col] = df[col].astype("float64")
return df
data = change_dtype(data)
def fix_missing_values(df):
def delete_missing_values(df):
"""
Deletes the column with Null values which are less than half of its values
"""
df = df[['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach','exang', 'oldpeak', 'num']]
return df
def fill_with_mean(df):
"""
Fills the NaN values with the mean value of the column
"""
cols = ['trestbps', 'chol', 'thalach']
for col in cols:
df[col].fillna(value=df[col].mean(), inplace=True)
return df
def fill_with_mode(df):
"""
Fills the NaN values with the mode value of the column
"""
cols =['fbs', 'restecg', 'exang']
for col in cols:
df[col].fillna(value=df[col].mode()[0], inplace=True)
return df
df = delete_missing_values(df)
df = fill_with_mean(df)
df = fill_with_mode(df)
return df
data = fix_missing_values(data)
data.duplicated().sum()
data.drop_duplicates(inplace=True)
data.drop('num', axis=1).corrwith(data['num']).plot(kind='bar', grid=True, figsize=(12, 8), title="Correlation with target")
plt.savefig("../../Output/Figures/correlation.png")
pp.ProfileReport(df=data, dark_mode=True, explorative=True)
pp.ProfileReport(df=data, dark_mode=True, explorative=True).to_file(PP_PATH)
data.to_csv(CLEAN_DATA_PATH, index=False)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test schedule block subroutine reference mechanism."""
import numpy as np
from qiskit import circuit, pulse
from qiskit.pulse import builder
from qiskit.pulse.transforms import inline_subroutines
from qiskit.test import QiskitTestCase
class TestReference(QiskitTestCase):
"""Test for basic behavior of reference mechanism."""
def test_append_schedule(self):
"""Test appending schedule without calling.
Appended schedules are not subroutines.
These are directly exposed to the outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.append_schedule(sched_x1)
with pulse.build() as sched_z1:
builder.append_schedule(sched_y1)
self.assertEqual(len(sched_z1.references), 0)
def test_append_schedule_parameter_scope(self):
"""Test appending schedule without calling.
Parameter in the appended schedule has the scope of outer schedule.
"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.append_schedule(sched_x1)
with pulse.build() as sched_z1:
builder.append_schedule(sched_y1)
sched_param = next(iter(sched_z1.scoped_parameters()))
self.assertEqual(sched_param.name, "root::name")
# object equality
self.assertEqual(
sched_z1.search_parameters("root::name")[0],
param,
)
def test_refer_schedule(self):
"""Test refer to schedule by name.
Outer block is only aware of its inner reference.
Nested reference is not directly exposed to the most outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.reference("x1", "d0")
with pulse.build() as sched_z1:
builder.reference("y1", "d0")
sched_y1.assign_references({("x1", "d0"): sched_x1})
sched_z1.assign_references({("y1", "d0"): sched_y1})
self.assertEqual(len(sched_z1.references), 1)
self.assertEqual(sched_z1.references[("y1", "d0")], sched_y1)
self.assertEqual(len(sched_y1.references), 1)
self.assertEqual(sched_y1.references[("x1", "d0")], sched_x1)
def test_refer_schedule_parameter_scope(self):
"""Test refer to schedule by name.
Parameter in the called schedule has the scope of called schedule.
"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.reference("x1", "d0")
with pulse.build() as sched_z1:
builder.reference("y1", "d0")
sched_y1.assign_references({("x1", "d0"): sched_x1})
sched_z1.assign_references({("y1", "d0"): sched_y1})
sched_param = next(iter(sched_z1.scoped_parameters()))
self.assertEqual(sched_param.name, "root::y1,d0::x1,d0::name")
# object equality
self.assertEqual(
sched_z1.search_parameters("root::y1,d0::x1,d0::name")[0],
param,
)
# regex
self.assertEqual(
sched_z1.search_parameters(r"\S::x1,d0::name")[0],
param,
)
def test_call_schedule(self):
"""Test call schedule.
Outer block is only aware of its inner reference.
Nested reference is not directly exposed to the most outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_z1:
builder.call(sched_y1, name="y1")
self.assertEqual(len(sched_z1.references), 1)
self.assertEqual(sched_z1.references[("y1",)], sched_y1)
self.assertEqual(len(sched_y1.references), 1)
self.assertEqual(sched_y1.references[("x1",)], sched_x1)
def test_call_schedule_parameter_scope(self):
"""Test call schedule.
Parameter in the called schedule has the scope of called schedule.
"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_z1:
builder.call(sched_y1, name="y1")
sched_param = next(iter(sched_z1.scoped_parameters()))
self.assertEqual(sched_param.name, "root::y1::x1::name")
# object equality
self.assertEqual(
sched_z1.search_parameters("root::y1::x1::name")[0],
param,
)
# regex
self.assertEqual(
sched_z1.search_parameters(r"\S::x1::name")[0],
param,
)
def test_append_and_call_schedule(self):
"""Test call and append schedule.
Reference is copied to the outer schedule by appending.
Original reference remains unchanged.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_z1:
builder.append_schedule(sched_y1)
self.assertEqual(len(sched_z1.references), 1)
self.assertEqual(sched_z1.references[("x1",)], sched_x1)
# blocks[0] is sched_y1 and its reference is now point to outer block reference
self.assertIs(sched_z1.blocks[0].references, sched_z1.references)
# however the original program is protected to prevent unexpected mutation
self.assertIsNot(sched_y1.references, sched_z1.references)
# appended schedule is preserved
self.assertEqual(len(sched_y1.references), 1)
self.assertEqual(sched_y1.references[("x1",)], sched_x1)
def test_calling_similar_schedule(self):
"""Test calling schedules with the same representation.
sched_x1 and sched_y1 are the different subroutines, but same representation.
Two references shoud be created.
"""
param1 = circuit.Parameter("param")
param2 = circuit.Parameter("param")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param1, name="p"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, param2, name="p"), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1)
pulse.call(sched_y1)
self.assertEqual(len(sched_z1.references), 2)
def test_calling_same_schedule(self):
"""Test calling same schedule twice.
Because it calls the same schedule, no duplication should occur in reference table.
"""
param = circuit.Parameter("param")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1, name="same_sched")
pulse.call(sched_x1, name="same_sched")
self.assertEqual(len(sched_z1.references), 1)
def test_calling_same_schedule_with_different_assignment(self):
"""Test calling same schedule twice but with different parameters.
Same schedule is called twice but with different assignment.
Two references should be created.
"""
param = circuit.Parameter("param")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1, param=0.1)
pulse.call(sched_x1, param=0.2)
self.assertEqual(len(sched_z1.references), 2)
def test_alignment_context(self):
"""Test nested alignment context.
Inline alignment is identical to append_schedule operation.
Thus scope is not newly generated.
"""
with pulse.build(name="x1") as sched_x1:
with pulse.align_right():
with pulse.align_left():
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
self.assertEqual(len(sched_x1.references), 0)
def test_appending_child_block(self):
"""Test for edge case.
User can append blocks which is an element of another schedule block.
But this is not standard use case.
In this case, references may contain subroutines which don't exist in the context.
This is because all references within the program are centrally
managed in the most outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2, name="y1"), pulse.DriveChannel(0))
with pulse.build() as sched_x2:
builder.call(sched_x1, name="x1")
self.assertEqual(list(sched_x2.references.keys()), [("x1",)])
with pulse.build() as sched_y2:
builder.call(sched_y1, name="y1")
self.assertEqual(list(sched_y2.references.keys()), [("y1",)])
with pulse.build() as sched_z1:
builder.append_schedule(sched_x2)
builder.append_schedule(sched_y2)
self.assertEqual(list(sched_z1.references.keys()), [("x1",), ("y1",)])
# child block references point to its parent, i.e. sched_z1
self.assertIs(sched_z1.blocks[0].references, sched_z1._reference_manager)
self.assertIs(sched_z1.blocks[1].references, sched_z1._reference_manager)
with pulse.build() as sched_z2:
# Append child block
# The reference of this block is sched_z1.reference thus it contains both x1 and y1.
# However, y1 doesn't exist in the context, so only x1 should be added.
# Usually, user will append sched_x2 directly here, rather than sched_z1.blocks[0]
# This is why this situation is an edge case.
builder.append_schedule(sched_z1.blocks[0])
self.assertEqual(len(sched_z2.references), 1)
self.assertEqual(sched_z2.references[("x1",)], sched_x1)
def test_replacement(self):
"""Test nested alignment context.
Replacing schedule block with schedule block.
Removed block contains own reference, that should be removed with replacement.
New block also contains reference, that should be passed to the current reference.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2, name="y1"), pulse.DriveChannel(0))
with pulse.build() as sched_x2:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_y2:
builder.call(sched_y1, name="y1")
with pulse.build() as sched_z1:
builder.append_schedule(sched_x2)
builder.append_schedule(sched_y2)
self.assertEqual(len(sched_z1.references), 2)
self.assertEqual(sched_z1.references[("x1",)], sched_x1)
self.assertEqual(sched_z1.references[("y1",)], sched_y1)
# Define schedule to replace
with pulse.build() as sched_r1:
pulse.play(pulse.Constant(100, 0.1, name="r1"), pulse.DriveChannel(0))
with pulse.build() as sched_r2:
pulse.call(sched_r1, name="r1")
sched_z2 = sched_z1.replace(sched_x2, sched_r2)
self.assertEqual(len(sched_z2.references), 2)
self.assertEqual(sched_z2.references[("r1",)], sched_r1)
self.assertEqual(sched_z2.references[("y1",)], sched_y1)
def test_special_parameter_name(self):
"""Testcase to guarantee usage of some special symbols in parameter name.
These symbols might be often used in user code.
No conflict should occur with the default scope delimiter.
"""
param = circuit.Parameter("my.parameter_object")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.reference("sub", "q0")
sched_y1.assign_references({("sub", "q0"): sched_x1})
ret_param = sched_y1.search_parameters(r"\Ssub,q0::my.parameter_object")[0]
self.assertEqual(param, ret_param)
def test_parameter_in_multiple_scope(self):
"""Testcase for scope-aware parameter getter.
When a single parameter object is used in multiple scopes,
the scoped_parameters method must return parameter objects associated to each scope,
while parameters property returns a single parameter object.
"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, param), pulse.DriveChannel(1))
with pulse.build() as sched_z1:
pulse.call(sched_x1, name="x1")
pulse.call(sched_y1, name="y1")
self.assertEqual(len(sched_z1.parameters), 1)
self.assertEqual(len(sched_z1.scoped_parameters()), 2)
self.assertEqual(sched_z1.search_parameters("root::x1::name")[0], param)
self.assertEqual(sched_z1.search_parameters("root::y1::name")[0], param)
def test_parallel_alignment_equality(self):
"""Testcase for potential edge case.
In parallel alignment context, reference instruction is broadcasted to
all channels. When new channel is added after reference, this should be
connected with reference node.
"""
with pulse.build() as subroutine:
pulse.reference("unassigned")
with pulse.build() as sched1:
with pulse.align_left():
pulse.delay(10, pulse.DriveChannel(0))
pulse.call(subroutine) # This should be broadcasted to d1 as well
pulse.delay(10, pulse.DriveChannel(1))
with pulse.build() as sched2:
with pulse.align_left():
pulse.delay(10, pulse.DriveChannel(0))
pulse.delay(10, pulse.DriveChannel(1))
pulse.call(subroutine)
self.assertNotEqual(sched1, sched2)
def test_subroutine_conflict(self):
"""Test for edge case of appending two schedule blocks having the
references with conflicting reference key.
This operation should fail because one of references will be gone after assignment.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0))
with pulse.build() as sched_x2:
pulse.call(sched_x1, name="conflict_name")
self.assertEqual(sched_x2.references[("conflict_name",)], sched_x1)
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(0))
with pulse.build() as sched_y2:
pulse.call(sched_y1, name="conflict_name")
self.assertEqual(sched_y2.references[("conflict_name",)], sched_y1)
with self.assertRaises(pulse.exceptions.PulseError):
with pulse.build():
builder.append_schedule(sched_x2)
builder.append_schedule(sched_y2)
def test_assign_existing_reference(self):
"""Test for explicitly assign existing reference.
This operation should fail because overriding reference is not allowed.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1, name="conflict_name")
with self.assertRaises(pulse.exceptions.PulseError):
sched_z1.assign_references({("conflict_name",): sched_y1})
class TestSubroutineWithCXGate(QiskitTestCase):
"""Test called program scope with practical example of building fully parametrized CX gate."""
def setUp(self):
super().setUp()
# parameters of X pulse
self.xp_dur = circuit.Parameter("dur")
self.xp_amp = circuit.Parameter("amp")
self.xp_sigma = circuit.Parameter("sigma")
self.xp_beta = circuit.Parameter("beta")
# amplitude of SX pulse
self.sxp_amp = circuit.Parameter("amp")
# parameters of CR pulse
self.cr_dur = circuit.Parameter("dur")
self.cr_amp = circuit.Parameter("amp")
self.cr_sigma = circuit.Parameter("sigma")
self.cr_risefall = circuit.Parameter("risefall")
# channels
self.control_ch = circuit.Parameter("ctrl")
self.target_ch = circuit.Parameter("tgt")
self.cr_ch = circuit.Parameter("cr")
# echo pulse on control qubit
with pulse.build(name="xp") as xp_sched_q0:
pulse.play(
pulse.Drag(
duration=self.xp_dur,
amp=self.xp_amp,
sigma=self.xp_sigma,
beta=self.xp_beta,
),
channel=pulse.DriveChannel(self.control_ch),
)
self.xp_sched = xp_sched_q0
# local rotation on target qubit
with pulse.build(name="sx") as sx_sched_q1:
pulse.play(
pulse.Drag(
duration=self.xp_dur,
amp=self.sxp_amp,
sigma=self.xp_sigma,
beta=self.xp_beta,
),
channel=pulse.DriveChannel(self.target_ch),
)
self.sx_sched = sx_sched_q1
# cross resonance
with pulse.build(name="cr") as cr_sched:
pulse.play(
pulse.GaussianSquare(
duration=self.cr_dur,
amp=self.cr_amp,
sigma=self.cr_sigma,
risefall_sigma_ratio=self.cr_risefall,
),
channel=pulse.ControlChannel(self.cr_ch),
)
self.cr_sched = cr_sched
def test_lazy_ecr(self):
"""Test lazy subroutines through ECR schedule construction."""
with pulse.build(name="lazy_ecr") as sched:
with pulse.align_sequential():
pulse.reference("cr", "q0", "q1")
pulse.reference("xp", "q0")
with pulse.phase_offset(np.pi, pulse.ControlChannel(self.cr_ch)):
pulse.reference("cr", "q0", "q1")
pulse.reference("xp", "q0")
# Schedule has references
self.assertTrue(sched.is_referenced())
# Schedule is not schedulable because of unassigned references
self.assertFalse(sched.is_schedulable())
# Two references cr and xp are called
self.assertEqual(len(sched.references), 2)
# Parameters in the current scope are Parameter("cr") which is used in phase_offset
# References are not assigned yet.
params = {p.name for p in sched.parameters}
self.assertSetEqual(params, {"cr"})
# Parameter names are scoepd
scoped_params = {p.name for p in sched.scoped_parameters()}
self.assertSetEqual(scoped_params, {"root::cr"})
# Assign CR and XP schedule to the empty reference
sched.assign_references({("cr", "q0", "q1"): self.cr_sched})
sched.assign_references({("xp", "q0"): self.xp_sched})
# Check updated references
assigned_refs = sched.references
self.assertEqual(assigned_refs[("cr", "q0", "q1")], self.cr_sched)
self.assertEqual(assigned_refs[("xp", "q0")], self.xp_sched)
# Parameter added from subroutines
scoped_params = {p.name for p in sched.scoped_parameters()}
ref_params = {
# This is the cr parameter that belongs to phase_offset instruction in the root scope
"root::cr",
# This is the same cr parameter that belongs to the play instruction in a child scope
"root::cr,q0,q1::cr",
"root::cr,q0,q1::amp",
"root::cr,q0,q1::dur",
"root::cr,q0,q1::risefall",
"root::cr,q0,q1::sigma",
"root::xp,q0::ctrl",
"root::xp,q0::amp",
"root::xp,q0::beta",
"root::xp,q0::dur",
"root::xp,q0::sigma",
}
self.assertSetEqual(scoped_params, ref_params)
# Get parameter without scope, cr amp and xp amp are hit.
params = sched.get_parameters(parameter_name="amp")
self.assertEqual(len(params), 2)
# Get parameter with scope, only xp amp
params = sched.search_parameters(parameter_regex="root::xp,q0::amp")
self.assertEqual(len(params), 1)
def test_cnot(self):
"""Integration test with CNOT schedule construction."""
# echeod cross resonance
with pulse.build(name="ecr", default_alignment="sequential") as ecr_sched:
pulse.call(self.cr_sched, name="cr")
pulse.call(self.xp_sched, name="xp")
with pulse.phase_offset(np.pi, pulse.ControlChannel(self.cr_ch)):
pulse.call(self.cr_sched, name="cr")
pulse.call(self.xp_sched, name="xp")
# cnot gate, locally equivalent to ecr
with pulse.build(name="cx", default_alignment="sequential") as cx_sched:
pulse.shift_phase(np.pi / 2, pulse.DriveChannel(self.control_ch))
pulse.call(self.sx_sched, name="sx")
pulse.call(ecr_sched, name="ecr")
# get parameter with scope, full scope is not needed
xp_amp = cx_sched.search_parameters(r"\S:xp::amp")[0]
self.assertEqual(self.xp_amp, xp_amp)
# get parameter with scope, of course full scope can be specified
xp_amp_full_scoped = cx_sched.search_parameters("root::ecr::xp::amp")[0]
self.assertEqual(xp_amp_full_scoped, xp_amp)
# assign parameters
assigned_cx = cx_sched.assign_parameters(
value_dict={
self.cr_ch: 0,
self.control_ch: 0,
self.target_ch: 1,
self.sxp_amp: 0.1,
self.xp_amp: 0.2,
self.xp_dur: 160,
self.xp_sigma: 40,
self.xp_beta: 3.0,
self.cr_amp: 0.5,
self.cr_dur: 800,
self.cr_sigma: 64,
self.cr_risefall: 2,
},
inplace=True,
)
flatten_cx = inline_subroutines(assigned_cx)
with pulse.build(default_alignment="sequential") as ref_cx:
# sz
pulse.shift_phase(np.pi / 2, pulse.DriveChannel(0))
with pulse.align_left():
# sx
pulse.play(
pulse.Drag(
duration=160,
amp=0.1,
sigma=40,
beta=3.0,
),
channel=pulse.DriveChannel(1),
)
with pulse.align_sequential():
# cr
with pulse.align_left():
pulse.play(
pulse.GaussianSquare(
duration=800,
amp=0.5,
sigma=64,
risefall_sigma_ratio=2,
),
channel=pulse.ControlChannel(0),
)
# xp
with pulse.align_left():
pulse.play(
pulse.Drag(
duration=160,
amp=0.2,
sigma=40,
beta=3.0,
),
channel=pulse.DriveChannel(0),
)
with pulse.phase_offset(np.pi, pulse.ControlChannel(0)):
# cr
with pulse.align_left():
pulse.play(
pulse.GaussianSquare(
duration=800,
amp=0.5,
sigma=64,
risefall_sigma_ratio=2,
),
channel=pulse.ControlChannel(0),
)
# xp
with pulse.align_left():
pulse.play(
pulse.Drag(
duration=160,
amp=0.2,
sigma=40,
beta=3.0,
),
channel=pulse.DriveChannel(0),
)
self.assertEqual(flatten_cx, ref_cx)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info import state_fidelity
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test RemoveResetInZeroState pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import RemoveResetInZeroState, DAGFixedPoint
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestRemoveResetInZeroState(QiskitTestCase):
"""Test swap-followed-by-measure optimizations."""
def test_optimize_single_reset(self):
"""Remove a single reset
qr0:--|0>-- ==> qr0:----
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.reset(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
pass_ = RemoveResetInZeroState()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_dont_optimize_non_zero_state(self):
"""Do not remove reset if not in a zero state
qr0:--[H]--|0>-- ==> qr0:--[H]--|0>--
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
circuit.reset(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.h(qr)
expected.reset(qr)
pass_ = RemoveResetInZeroState()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_single_reset_in_diff_qubits(self):
"""Remove a single reset in different qubits
qr0:--|0>-- qr0:----
==>
qr1:--|0>-- qr1:----
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.reset(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
pass_ = RemoveResetInZeroState()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
class TestRemoveResetInZeroStateFixedPoint(QiskitTestCase):
"""Test RemoveResetInZeroState in a transpiler, using fixed point."""
def test_two_resets(self):
"""Remove two initial resets
qr0:--|0>-|0>-- ==> qr0:----
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.reset(qr[0])
circuit.reset(qr[0])
expected = QuantumCircuit(qr)
pass_manager = PassManager()
pass_manager.append(
[RemoveResetInZeroState(), DAGFixedPoint()],
do_while=lambda property_set: not property_set["dag_fixed_point"],
)
after = pass_manager.run(circuit)
self.assertEqual(expected, after)
if __name__ == "__main__":
unittest.main()
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
|
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
|
jonasmaziero
|
from qiskit import QuantumCircuit; qc = QuantumCircuit(2,2)
qc.barrier()
qc.cx(0,1); qc.h(0)
qc.barrier()
qc.measure([0,1],[0,1])
qc.draw('mpl')
from qiskit import QuantumCircuit, execute, Aer; from qiskit.tools.visualization import plot_histogram
simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13
qc = QuantumCircuit(2,2)
qc.h(0); qc.cx(0,1) # prepara |Phi+>
qc.barrier()
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
qc.draw('mpl')
job = execute(qc, backend=simulator, shots=nshots)
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(2,2)
qc.x(1); qc.h(0); qc.cx(0,1) # prepara |Psi+>
qc.barrier()
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
qc.draw('mpl')
job = execute(qc, backend=simulator, shots=nshots)
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(2,2)
qc.x(0); qc.h(0); qc.cx(0,1) # prepara |Phi->
qc.barrier()
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
qc.draw('mpl')
job = execute(qc, backend=simulator, shots=nshots)
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(2,2)
qc.x([0,1]); qc.h(0); qc.cx(0,1) # prepara |Psi->
qc.barrier()
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
qc.draw('mpl')
job = execute(qc, backend=simulator, shots=nshots)
plot_histogram(job.result().get_counts())
import qiskit
qiskit.IBMQ.save_account('72f5d1e3769658b4908c384492eb3a9bd6d6ac4ab1fdf613d7fbe72884114d62728d6fd60a8bf8d0b6698f2f5463a605742658fee1ce3318181105c6acb8120e',
overwrite = True)
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
qc = QuantumCircuit(2,2)
qc.h(0); qc.cx(0,1) # prepara |Phi+>
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
job = execute(qc, backend=device, shots=nshots)
print(job.job_id())
job = device.retrieve_job('cmjn5w752bbg00825esg')
from qiskit.tools.visualization import plot_histogram; plot_histogram(job.result().get_counts())
qc = QuantumCircuit(2,2)
qc.x(1); qc.h(0); qc.cx(0,1) # prepara |Psi+>
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
job = execute(qc, backend=device, shots=nshots); print(job.job_id())
job = device.retrieve_job('cmjn66rffjhg0084we5g')
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(2,2)
qc.x(0); qc.h(0); qc.cx(0,1) # prepara |Phi->
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
job = execute(qc, backend=device, shots=nshots); print(job.job_id())
job = device.retrieve_job('cmjn6wk6n5g0008xpgg0')
plot_histogram(job.result().get_counts())
provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main')
device = provider.get_backend('ibm_nairobi')
qc = QuantumCircuit(2,2)
qc.x([0,1]); qc.h(0); qc.cx(0,1) # prepara |Psi->
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
job = execute(qc, backend=device, shots=nshots); print(job.job_id())
job = device.retrieve_job('cmjnb9nz44x0008bwa3g'); plot_histogram(job.result().get_counts())
def qc_psi(th,ph,lb): # prepara o estado a ser teletransportado
from qiskit import QuantumCircuit
qc = QuantumCircuit(1, name=r'$|\psi\rangle$'); qc.x(0); qc.u(th,ph,lb, 0)
return qc
qc_psi_ = qc_psi(0.1,0.2,0.3); qc_psi_.draw('mpl')
from qiskit.quantum_info import random_statevector
for j in range(0,6):
psi = random_statevector(2)
print(psi)
def angulos(psi): # psi = [c0,c1]
c0_abs = math.sqrt(psi[0].real**2 + psi[0].imag**2); c1_abs = math.sqrt(psi[1].real**2 + psi[1].imag**2)
ph0 = math.acos(psi[0].real/c0_abs); ph1 = math.acos(psi[1].real/c1_abs)
th = 2*math.acos(c1_abs)
lb = ph0 - math.pi; ph = ph1 - lb
return th, ph, lb # existem erros de sinal!
import math; import numpy as np
for j in range(0,3):
psi = random_statevector(2); print('rand = ',psi); th, ph, lb = angulos(psi)
psin = np.array([(math.cos(math.pi+lb)+1j*math.sin(math.pi+lb))*math.sin(th/2),
(math.cos(ph+lb)+1j*math.sin(ph+lb))*math.cos(th/2)])
print('new = ',psin) # existem erros de sinal!
def acosm(x): # solução do chagpt não funciona
angle = math.acos(x)
if x >= 0:
return angle
else:
return 2*math.pi - angle
import math; import numpy as np
thmax = 2*math.pi; npt = 10; dth = thmax/npt; th = np.arange(0,thmax+dth,dth)
for j in range(0,len(th)):
cs = math.cos(th[j]); acs = math.acos(cs); nacs = acosm(cs)
print('th=',th[j],', acs=',acs,', nacs=',nacs) # não funcionam
for j in range(0,len(th)):
tg = math.tan(th[j]); atg = math.atan(tg); sn = math.sin(th[j]); asn = math.asin(sn)
print('th=', th[j], ', atg=', atg,', asn=', asn) # também não funcionam
# As funções anteriores não funcionam pois o mapa é 2 pra 1
# Essa função retorna o ângulo cert0, fornecidos os valores (seno,cosseno)
def arc_fun(cs, sn):
if sn >= 0:
return math.acos(cs)
if sn < 0:
return 2*math.pi - math.acos(cs)
for j in range(0,len(th)):
cs = math.cos(th[j]); sn = math.sin(th[j])
print('th=', th[j], ', nth=', arc_fun(cs, sn))
def angulosn(psi): # psi = [c0,c1]
c0_abs = math.sqrt(psi[0].real**2 + psi[0].imag**2); c1_abs = math.sqrt(psi[1].real**2 + psi[1].imag**2)
ph0 = arc_fun(psi[0].real/c0_abs, psi[0].imag/c0_abs); ph1 = arc_fun(psi[1].real/c1_abs, psi[1].imag/c1_abs)
th = 2*arc_fun(c1_abs,c0_abs)
lb = ph0 - math.pi; ph = ph1 - lb
return th, ph, lb
import math; import numpy as np
for j in range(0,5):
psi = random_statevector(2); print('rand = ',psi); th, ph, lb = angulosn(psi)
psin = np.array([(math.cos(math.pi+lb)+1j*math.sin(math.pi+lb))*math.sin(th/2),
(math.cos(ph+lb)+1j*math.sin(ph+lb))*math.cos(th/2)])
print('new = ',psin) # Agora está certo ...
from qiskit import *
def qc_teleport(th,ph,lb):
qc = QuantumCircuit(3,2, name='tel')
qc_psi_ = qc_psi(th,ph,lb); qc.append(qc_psi_, [0]); qc.barrier()
qc.h(2); qc.cx(2,1); qc.barrier()
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]); qc.barrier()
qc.x(2).c_if(1, 1); qc.z(2).c_if(0, 1) # oprações condicionadas em info clássica
return qc
qc_teleport_ = qc_teleport(0.1,0.2,0.3); qc_teleport_.draw('mpl')
import qiskit; import math; import numpy as np; from qiskit import Aer, QuantumCircuit, execute
from qiskit.quantum_info import state_fidelity
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13; qc = QuantumCircuit(3)
psi = np.array([1/math.sqrt(2),1/math.sqrt(2)]); th,ph,lb=angulosn(psi) # estado a ser teletransportado
qc_teleport_ = qc_teleport(th,ph,lb); qc.append(qc_teleport_, [0,1,2])
qstc = state_tomography_circuits(qc_teleport_, [2])
job = execute(qstc, backend = simulator, shots = nshots)
qstf = StateTomographyFitter(job.result(), qstc)
rho_sim = qstf.fit(method='lstsq')
F = state_fidelity(rho_sim, psi); from sympy import Matrix
rho_teo = Matrix([[1/2,1/2],[1/2,1/2]]); print('rho_teo = ',rho_teo); print('rho_sim =',rho_sim); print('F = ', F)
import qiskit
qiskit.IBMQ.save_account('7ec48a29167ab443c525564bd84b033895cf87b6c6da8d263be59ad00a2d9e70718cf1398362403ace62320d0044793f08dbaa2629bfde7f6ec339f90fe74e7b',
overwrite = True)
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibm_nairobi')
qc = QuantumCircuit(3)
psi = np.array([1/math.sqrt(2),1/math.sqrt(2)])
th,ph,lb=angulosn(psi)
qc_teleport_ = qc_teleport(th,ph,lb)
qc.append(qc_teleport_, [0,1,2])
qstc = state_tomography_circuits(qc_teleport_, [2])
job = execute(qstc, backend = device, shots = nshots)
jobid = job.job_id()
print(jobid)
def qc_teleport_coe(th,ph,lb):
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, name='tel')
qc_psi_ = qc_psi(th,ph,lb); qc.append(qc_psi_, [0]); qc.barrier()
qc.h(2); qc.cx(2,1); qc.barrier(); qc.cx(0,1); qc.h(0); qc.barrier()
qc.cx(1,2); qc.cz(0,2) # oprações quânticas controladas
return qc
qc_teleport_coe_ = qc_teleport_coe(0.1,0.2,0.3); qc_teleport_coe_.draw('mpl')
import qiskit; import math; import numpy as np
from qiskit import Aer, QuantumCircuit, execute
from qiskit.quantum_info import state_fidelity
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13; qc = QuantumCircuit(3)
psi = np.array([1/math.sqrt(2),(1/math.sqrt(2))*1j]); th,ph,lb=angulosn(psi)
qc_teleport_coe_ = qc_teleport_coe(th,ph,lb); qc.append(qc_teleport_coe_, [0,1,2])
qstc = state_tomography_circuits(qc_teleport_coe_, [2])
job = qiskit.execute(qstc, backend = simulator, shots = nshots)
qstf = StateTomographyFitter(job.result(), qstc)
rho_sim = qstf.fit(method='lstsq')
F = state_fidelity(rho_sim, psi)
from sympy import Matrix,sqrt; rho = Matrix([[1/2,-1j/2],[1j/2,1/2]]); print('rho_teo =',rho)
print('rho_sim =',rho_sim); print('F = ', F)
import qiskit
qiskit.IBMQ.save_account('585d2242bad08223e0d894363adf8e4f76b1d426a84e85b2fbd51678adcb8e54e39cf0f33ff6c84c41e60a534a61ad4775091a01e338f0f9eff2265aa59a6a19',
overwrite = True); qiskit.IBMQ.load_account()
#provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main')
device = provider.get_backend('ibm_nairobi')
qc = QuantumCircuit(3)
psi = np.array([1/math.sqrt(2),(1/math.sqrt(2))*1j])
th,ph,lb=angulosn(psi)
qc_teleport_coe_ = qc_teleport_coe(th,ph,lb)
qc.append(qc_teleport_coe_, [0,1,2])
qstc = state_tomography_circuits(qc_teleport_coe_, [2])
job = execute(qstc, backend = device, shots = nshots)
jobid = job.job_id()
print(jobid)
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibm_nairobi')
job = device.retrieve_job('cmke9bn8tsq00080987g')
qstf = StateTomographyFitter(job.result(), qstc)
rho_exp = qstf.fit(method='lstsq')
psi = np.array([1/math.sqrt(2),(1/math.sqrt(2))*1j])
from sympy import Matrix, sqrt
rho = Matrix([[0.5,-0.5*1j],[0.5*1j,0.5]])
print('rho_teo =',rho)
F = state_fidelity(psi, rho_exp)
print('rho_exp = ',rho_exp,', F = ', F)
import qiskit; import math; import numpy as np
from qiskit import Aer, QuantumCircuit, execute
from qiskit.quantum_info import state_fidelity
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13
for j in range(0,13):
qc = QuantumCircuit(3)
psi = random_statevector(2); th,ph,lb = angulosn(psi)#; print('psi=',psi)
qc_teleport_coe_ = qc_teleport_coe(th,ph,lb); qc.append(qc_teleport_coe_, [0,1,2])
qstc = state_tomography_circuits(qc_teleport_coe_, [2])
job = qiskit.execute(qstc, backend=simulator, shots=nshots)
qstf = StateTomographyFitter(job.result(), qstc); rho_sim = qstf.fit(method='lstsq')
F = state_fidelity(rho_sim, psi); print('F=', F)
|
https://github.com/JavaFXpert/QiskitBlocksService
|
JavaFXpert
|
#!/usr/bin/env python3
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, Aer, execute
def run_qasm(qasm, backend_to_run="qasm_simulator"):
qc = QuantumCircuit.from_qasm_str(qasm)
backend = Aer.get_backend(backend_to_run)
job_sim = execute(qc, backend)
sim_result = job_sim.result()
return sim_result.get_counts(qc)
|
https://github.com/dnnagy/qintro
|
dnnagy
|
import math
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.visualization import plot_bloch_multivector
from qiskit.visualization import plot_bloch_vector
from qiskit.visualization import plot_histogram
qbackend = Aer.get_backend('qasm_simulator')
sbackend = Aer.get_backend('statevector_simulator')
ubackend = Aer.get_backend('unitary_simulator')
qiskit.__version__
import torch
torch.__version__
import strawberryfields as sf
sf.__version__
help(sf)
import cirq
cirq.__version__
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing the QISKit
from qiskit import QuantumProgram
import Qconfig
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
backend = 'local_qasm_simulator' # the backend to run on
shots = 1024 # the number of shots in the experiment
Q_program = QuantumProgram()
Q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url
# Creating registers
qr = Q_program.create_quantum_register("qr", 1)
cr = Q_program.create_classical_register("cr", 1)
circuits = []
phase_vector = range(0,100)
for phase_index in phase_vector:
phase_shift = phase_index-50
phase = 2*np.pi*phase_shift/50
circuit_name = "phase_gate_%d"%phase_index
qc_phase_gate = Q_program.create_circuit(circuit_name, [qr], [cr])
qc_phase_gate.h(qr)
qc_phase_gate.u1(phase, qr)
qc_phase_gate.h(qr)
qc_phase_gate.measure(qr[0], cr[0])
circuits.append(circuit_name)
result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=3, wait=10, timeout=240)
probz = []
phase_value = []
for phase_index in phase_vector:
phase_shift = phase_index - 50
phase_value.append(2*phase_shift/50)
if '0' in result.get_counts(circuits[phase_index]):
probz.append(2*result.get_counts(circuits[phase_index]).get('0')/shots-1)
else:
probz.append(-1)
plt.plot(phase_value, probz, 'b',0.25,1/np.sqrt(2),'ro',0.5,0,'ko',1,-1,'go',-0.25,1/np.sqrt(2),'rx',-0.5,0,'kx',-1,-1,'gx')
plt.xlabel('Phase value (Pi)')
plt.ylabel('Eigenvalue of X')
plt.show()
backend = 'local_qasm_simulator' # the backend to run on
shots = 1024 # the number of shots in the experiment
Q_program = QuantumProgram()
Q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url
# Creating registers
qr = Q_program.create_quantum_register("qr", 1)
cr = Q_program.create_classical_register("cr", 1)
circuits = []
phase_vector = range(0,100)
for phase_index in phase_vector:
phase_shift = phase_index-50
phase = 2*np.pi*phase_shift/50
circuit_name = "phase_gate_%d"%phase_index
qc_phase_gate = Q_program.create_circuit(circuit_name, [qr], [cr])
qc_phase_gate.u3(phase,0,np.pi, qr)
qc_phase_gate.measure(qr[0], cr[0])
circuits.append(circuit_name)
result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=3, wait=10, timeout=240)
probz = []
phase_value = []
for phase_index in phase_vector:
phase_shift = phase_index - 50
phase_value.append(2*phase_shift/50)
if '0' in result.get_counts(circuits[phase_index]):
probz.append(2*result.get_counts(circuits[phase_index]).get('0')/shots-1)
else:
probz.append(-1)
plt.plot(phase_value, probz, 'b',0.5,0,'ko',1,-1,'go',-0.5,0,'kx',-1,-1,'gx')
plt.xlabel('Phase value (Pi)')
plt.ylabel('Eigenvalue of Z')
plt.show()
|
https://github.com/gaurav-iiser/qosf_task1
|
gaurav-iiser
|
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute,Aer
from qiskit import quantum_info as qi
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_histogram
import sys
class Task_1:
"""
Class for creating a quantum state which is a superposition of the indices of the numbers from a given list such that
these number's binary representation alternates in 0 and 1.
Valid input: List of integers.
Output: 1. A histogram indicating the states of superpostion and their coefficient in the superposed state.
2. The state vector of the final quantum state.
Variables and functions in this class:
self.integer_list: List of input integers
self.binary : List of binary representation of the above integers
self.index_binary: List of binary representation of the indices of the above integers
self.qc : List of quantum circuits. Each element is a quantum circuit pertaining to the preparation of a state
which is a tensor product of the state formed from the index and the state formed from the binary
representation of the number at that index
self.q and self.c: List of quantum registers and classical registers used for the above Quantum Circuits
Basic idea of the algorithm (step-wise):
1. self.construct_state() : prepares a list of quantum states which encode the index along with the respective integer
from the provided list.
2. self.construct_superposition() : prepares a state which is an equal superposition of the states prepared above.
This is stored in self.superposed_vec. This is an object of Statevector class.
3. self.construct_proj() : Constructs the projection operator pertaining to the desired result. The result is stored in
self.proj
4. self.apply_proj() : This function applies the above projection operator to the state prepared in step 2. The resultant
state is an equal superposition of the desired states
5. self.evol() : This function further processes the resultant vector obtained from step 4. First this function gets rid
of all the qubits (except one) which contain the information of the binary representation of the special
numbers. We are now left with an entangled state whose first part is the index of the desired number and]
the second part is |0> or |1>. Then, this function projects the second part of this system onto the
maximally coherent state or the |+> state and traces it away. We are now left with the desired superposed
state.
Other functions that I have added (although, the idea was to enhance the code even further by adding more such helper
functions, but due to the deadline and other time constraints, I will submit the code as is for now leaving scope for
adding more functions later):
get_integers() : Prints the list of integers
get_binary() : Prints the binary representation of integers
get_index_binary(): Prints the indices of the integers.
"""
def __init__(self, integer_list=[0,1]):
if any(not isinstance(x, int) for x in integer_list):
sys.exit("Numbers in the list are not all integers.")
self.integer_list = integer_list
self.binary = self.convert_to_bin(self.integer_list)
self.index_binary = self.convert_to_bin(len(self.integer_list))
self.qc = []
self.q = []
self.c = []
self.construct_state()
self.superposed_vec = self.construct_superposition()
self.proj = self.construct_proj()
self.vec_after_proj = self.apply_proj()
self.evolved_vec = self.evol()
print(self.evolved_vec)
def convert_to_bin(self, list_or_num):
binary_list=[]
if isinstance(list_or_num, list):
max_elem = max(list_or_num)
self.total_dig = np.log2(max_elem)
if abs(self.total_dig - int(self.total_dig))<1e-12:
self.total_dig += 1
else:
self.total_dig = np.ceil(self.total_dig)
self.total_dig = int(self.total_dig)
for integer in list_or_num:
if isinstance(integer,int):
binary_list.append(self.binary_(integer,self.total_dig))
else:
sys.exit("the input list has elements which are not integers")
return binary_list
elif isinstance(list_or_num, int):
self.index_total_dig = np.log2(list_or_num-1)
if abs(self.index_total_dig - int(self.index_total_dig))<1e-12:
self.index_total_dig += 1
else:
self.index_total_dig = np.ceil(self.index_total_dig)
self.index_total_dig = int(self.index_total_dig)
for integer_index in range(list_or_num):
binary_list.append(self.binary_(integer_index, self.index_total_dig))
return binary_list
else:
sys.exit("the input is not a list")
def binary_(self, number, total_digits):
return np.binary_repr(number, width=total_digits)
def construct_state(self):
num_qbits = self.index_total_dig + self.total_dig
self.total_qubit_registers = num_qbits
for i in range(len(self.integer_list)):
self.q.append(QuantumRegister(num_qbits,"qreg"))
self.qc.append(QuantumCircuit(self.q[i]))
new_string = self.index_binary[i] + self.binary[i]
for j in range(num_qbits):
if new_string[j] == '1':
self.qc[i].x(self.q[i][j])
def construct_superposition(self):
new_qc = QuantumCircuit(self.total_qubit_registers, 1)
for i in range(self.total_qubit_registers):
new_qc.h(i)
superposed_state = Statevector(new_qc)
proj_ = []
index_proj = []
for i in range(len(self.qc)):
proj_.append(Statevector(self.qc[i]))
proj_[i] = proj_[i].to_operator()
for i in range(self.total_qubit_registers):
index_proj.append(i)
projector = proj_[0]
if len(self.qc)>1:
for i in range(1,len(self.qc)):
projector += proj_[i]
superposed_state = superposed_state.evolve(projector,index_proj)
tr = superposed_state.trace()
superposed_state = superposed_state/np.sqrt(tr)
return superposed_state
def construct_proj(self):
n = self.total_dig
qc1 = QuantumCircuit(n)
qc2 = QuantumCircuit(n)
for i in range(n):
if i%2 == 0:
qc1.x(i)
else:
qc2.x(i)
proj_1 = qi.Statevector(qc1)
proj_2 = qi.Statevector(qc2)
proj_1 = proj_1.to_operator()
proj_2 = proj_2.to_operator()
proj = proj_1+proj_2
return proj
def apply_proj(self):
index_proj_list = []
for i in range(self.total_qubit_registers-1,self.index_total_dig-1, -1):
index_proj_list.append(i)
new_qc_statevec = self.superposed_vec.evolve(self.proj,index_proj_list)
temp_op = qi.DensityMatrix(new_qc_statevec)
tr = temp_op.trace()
if tr <= 1e-12:
sys.exit("No number in the input whose binary structure is alternate")
return
temp_op = temp_op/tr
new_qc_statevec = temp_op.to_statevector()
return new_qc_statevec
def evol(self):
### Create a quantum circuit and initialize it with the vector obtained after projection.
qc_evol = QuantumCircuit(self.total_qubit_registers)
qc_evol.initialize(self.vec_after_proj)
###############################################################################################################
### Apply CNOT to the qubits that contain the binary representation of selected integers and ####
### leave the index part as it is. The control qubit can be chosen to any qubit. For simplicity, we have ####
### chosen the first qubit of the state containing the binary rep of selected integer from the list. ####
### See step 7 of algorithm given above. ####
###############################################################################################################
for i in range(self.index_total_dig+1, self.total_qubit_registers):
qc_evol.cnot(self.index_total_dig, i)
new_statevec = qi.Statevector(qc_evol)
#####################################################
### Project the control qubit to the plus state. ###
### See step 9 of algorithm ###
#####################################################
qc2 = QuantumCircuit(1)
qc2.h(0)
plus_St = Statevector(qc2)
plus_St = plus_St.to_operator()
new_statevec = new_statevec.evolve(plus_St,[self.index_total_dig])
partial_trace_index = []
for j in range(self.index_total_dig, self.total_qubit_registers):
partial_trace_index.append(j)
if len(partial_trace_index)!=0:
new_statevec = qi.partial_trace(new_statevec, partial_trace_index)
tr = new_statevec.trace()
new_statevec = (1/tr)*new_statevec
new_statevec = new_statevec.to_statevector()
qc_fin = QuantumCircuit(self.index_total_dig, self.index_total_dig)
qc_fin.initialize(new_statevec)
for i in range(int(np.floor(self.index_total_dig/2))):
if i!=self.index_total_dig-1 -i:
qc_fin.swap(i,self.index_total_dig-1 -i)
qc_fin_ = qc_fin
new_statevec = Statevector(qc_fin)
#########################################################
######### Measurements to represent the counts ##########
#########################################################
for i in range(self.index_total_dig):
qc_fin_.measure(i,i)
job = execute(qc_fin_,Aer.get_backend('qasm_simulator'),shots=10000)
counts = job.result().get_counts(qc_fin_)
print(counts) # print the outcomes
display(plot_histogram(counts))
return new_statevec
#######################################################################################
############################## Helper Functions #######################################
#######################################################################################
def get_integers(self):
return self.integer_list
def get_binary(self):
#self.binary = self.convert_to_bin(self.integer_list)
return self.binary
def get_index_binary(self):
#self.index_binary = self.convert_to_bin(len(self.integer_list))
return self.index_binary
c = Task_1([1,5,7,10])
d = Task_1([3,5,8,10,11,12])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, backend=FakeBoeblingen())
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for the converters."""
import math
import unittest
import numpy as np
from qiskit.converters import circuit_to_instruction
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit, Instruction
from qiskit.circuit import Parameter
from qiskit.quantum_info import Operator
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError
class TestCircuitToInstruction(QiskitTestCase):
"""Test Circuit to Instruction."""
def test_flatten_circuit_registers(self):
"""Check correct flattening"""
qr1 = QuantumRegister(4, "qr1")
qr2 = QuantumRegister(3, "qr2")
qr3 = QuantumRegister(3, "qr3")
cr1 = ClassicalRegister(4, "cr1")
cr2 = ClassicalRegister(1, "cr2")
circ = QuantumCircuit(qr1, qr2, qr3, cr1, cr2)
circ.cx(qr1[1], qr2[2])
circ.measure(qr3[0], cr2[0])
inst = circuit_to_instruction(circ)
q = QuantumRegister(10, "q")
c = ClassicalRegister(5, "c")
self.assertEqual(inst.definition[0].qubits, (q[1], q[6]))
self.assertEqual(inst.definition[1].qubits, (q[7],))
self.assertEqual(inst.definition[1].clbits, (c[4],))
def test_flatten_registers_of_circuit_single_bit_cond(self):
"""Check correct mapping of registers gates conditioned on single classical bits."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(3, "qr2")
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
circ = QuantumCircuit(qr1, qr2, cr1, cr2)
circ.h(qr1[0]).c_if(cr1[1], True)
circ.h(qr2[1]).c_if(cr2[0], False)
circ.cx(qr1[1], qr2[2]).c_if(cr2[2], True)
circ.measure(qr2[2], cr2[0])
inst = circuit_to_instruction(circ)
q = QuantumRegister(5, "q")
c = ClassicalRegister(6, "c")
self.assertEqual(inst.definition[0].qubits, (q[0],))
self.assertEqual(inst.definition[1].qubits, (q[3],))
self.assertEqual(inst.definition[2].qubits, (q[1], q[4]))
self.assertEqual(inst.definition[0].operation.condition, (c[1], True))
self.assertEqual(inst.definition[1].operation.condition, (c[3], False))
self.assertEqual(inst.definition[2].operation.condition, (c[5], True))
def test_flatten_circuit_registerless(self):
"""Test that the conversion works when the given circuit has bits that are not contained in
any register."""
qr1 = QuantumRegister(2)
qubits = [Qubit(), Qubit(), Qubit()]
qr2 = QuantumRegister(3)
cr1 = ClassicalRegister(2)
clbits = [Clbit(), Clbit(), Clbit()]
cr2 = ClassicalRegister(3)
circ = QuantumCircuit(qr1, qubits, qr2, cr1, clbits, cr2)
circ.cx(3, 5)
circ.measure(4, 4)
inst = circuit_to_instruction(circ)
self.assertEqual(inst.num_qubits, len(qr1) + len(qubits) + len(qr2))
self.assertEqual(inst.num_clbits, len(cr1) + len(clbits) + len(cr2))
inst_definition = inst.definition
cx = inst_definition.data[0]
measure = inst_definition.data[1]
self.assertEqual(cx.qubits, (inst_definition.qubits[3], inst_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
self.assertEqual(measure.qubits, (inst_definition.qubits[4],))
self.assertEqual(measure.clbits, (inst_definition.clbits[4],))
def test_flatten_circuit_overlapping_registers(self):
"""Test that the conversion works when the given circuit has bits that are contained in more
than one register."""
qubits = [Qubit() for _ in [None] * 10]
qr1 = QuantumRegister(bits=qubits[:6])
qr2 = QuantumRegister(bits=qubits[4:])
clbits = [Clbit() for _ in [None] * 10]
cr1 = ClassicalRegister(bits=clbits[:6])
cr2 = ClassicalRegister(bits=clbits[4:])
circ = QuantumCircuit(qubits, clbits, qr1, qr2, cr1, cr2)
circ.cx(3, 5)
circ.measure(4, 4)
inst = circuit_to_instruction(circ)
self.assertEqual(inst.num_qubits, len(qubits))
self.assertEqual(inst.num_clbits, len(clbits))
inst_definition = inst.definition
cx = inst_definition.data[0]
measure = inst_definition.data[1]
self.assertEqual(cx.qubits, (inst_definition.qubits[3], inst_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
self.assertEqual(measure.qubits, (inst_definition.qubits[4],))
self.assertEqual(measure.clbits, (inst_definition.clbits[4],))
def test_flatten_parameters(self):
"""Verify parameters from circuit are moved to instruction.params"""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
qc.rz(theta, qr[0])
qc.rz(phi, qr[1])
qc.u(theta, phi, 0, qr[2])
qc.rz(sum_, qr[0])
inst = circuit_to_instruction(qc)
self.assertEqual(inst.params, [phi, theta])
self.assertEqual(inst.definition[0].operation.params, [theta])
self.assertEqual(inst.definition[1].operation.params, [phi])
self.assertEqual(inst.definition[2].operation.params, [theta, phi, 0])
self.assertEqual(str(inst.definition[3].operation.params[0]), "phi + theta")
def test_underspecified_parameter_map_raises(self):
"""Verify we raise if not all circuit parameters are present in parameter_map."""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
gamma = Parameter("gamma")
qc.rz(theta, qr[0])
qc.rz(phi, qr[1])
qc.u(theta, phi, 0, qr[2])
qc.rz(sum_, qr[0])
self.assertRaises(QiskitError, circuit_to_instruction, qc, {theta: gamma})
# Raise if provided more parameters than present in the circuit
delta = Parameter("delta")
self.assertRaises(
QiskitError, circuit_to_instruction, qc, {theta: gamma, phi: phi, delta: delta}
)
def test_parameter_map(self):
"""Verify alternate parameter specification"""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
gamma = Parameter("gamma")
qc.rz(theta, qr[0])
qc.rz(phi, qr[1])
qc.u(theta, phi, 0, qr[2])
qc.rz(sum_, qr[0])
inst = circuit_to_instruction(qc, {theta: gamma, phi: phi})
self.assertEqual(inst.params, [gamma, phi])
self.assertEqual(inst.definition[0].operation.params, [gamma])
self.assertEqual(inst.definition[1].operation.params, [phi])
self.assertEqual(inst.definition[2].operation.params, [gamma, phi, 0])
self.assertEqual(str(inst.definition[3].operation.params[0]), "gamma + phi")
def test_registerless_classical_bits(self):
"""Test that conditions on registerless classical bits can be handled during the conversion.
Regression test of gh-7394."""
expected = QuantumCircuit([Qubit(), Clbit()])
expected.h(0).c_if(expected.clbits[0], 0)
test = circuit_to_instruction(expected)
self.assertIsInstance(test, Instruction)
self.assertIsInstance(test.definition, QuantumCircuit)
self.assertEqual(len(test.definition.data), 1)
test_instruction = test.definition.data[0]
expected_instruction = expected.data[0]
self.assertIs(type(test_instruction.operation), type(expected_instruction.operation))
self.assertEqual(test_instruction.operation.condition, (test.definition.clbits[0], 0))
def test_zero_operands(self):
"""Test that an instruction can be created, even if it has zero operands."""
base = QuantumCircuit(global_phase=math.pi)
instruction = base.to_instruction()
self.assertEqual(instruction.num_qubits, 0)
self.assertEqual(instruction.num_clbits, 0)
self.assertEqual(instruction.definition, base)
compound = QuantumCircuit(1)
compound.append(instruction, [], [])
np.testing.assert_allclose(-np.eye(2), Operator(compound), atol=1e-16)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/arthurfaria/Qiskit_certificate_prep
|
arthurfaria
|
import numpy as np
from qiskit import QuantumCircuit, BasicAer, execute, Aer
from qiskit.quantum_info import Operator, DensityMatrix, Pauli
from qiskit.extensions import YGate
from qiskit.visualization import plot_histogram
Cnot = Operator([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]])
Cnot
#returns Numpy array
Cnot.data
#total input and output dimension
in_dim, out_dim = Cnot.dim
in_dim, out_dim
ghz = QuantumCircuit(3)
ghz.h(0)
ghz.cx([0,0],[1,2])
ghz.draw('mpl')
U_ghz = Operator(ghz)
np.around(U_ghz.data,3)
#np.around specifies how many decimals is desired in the oputput
#Aer has also a unitary_simulator backend.
back_uni = Aer.get_backend('unitary_simulator')
job = execute(ghz, back_uni)
result = job.result()
#getting the unitary with 3 decimals
U_qc = result.get_unitary(decimals=3)
U_qc
op1 = [[1+0.j, 0.5+0.j], [0.5+0.j, 1+0.j]]
op2 = [[0.5+0.j, 1+0.j], [0.5+0.j, 1+0.j]]
matrix = DensityMatrix(op1)
#doing the tensor product between op1 and op2
matrix.tensor(op2)
# Pauli('Y') generates the Pauli Y-matrix object
# On the other hand, Operator generates the operator of Pauli('Y')
Operator( Pauli('Y')) == Operator(YGate())
Operator(YGate()) == np.exp(1j * 0.4) * Operator(YGate())
ZZ = Operator(Pauli('ZZ'))
ZZ
# Add to a circuit
qc = QuantumCircuit(2, 2)
qc.append(ZZ, [0, 1])
qc.measure([0,1], [0,1])
qc.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
result = backend.run(qc).result()
counts = result.get_counts()
plot_histogram(counts)
decomp = qc.decompose()
decomp.draw('mpl')
op1 = Operator(Pauli('Y'))
op2 = Operator(Pauli('Z'))
op1.compose(op2, front=True)
op1 = Operator(Pauli('X'))
op2 = Operator(Pauli('Y'))
op1.tensor(op2)
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
from qiskit import *
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
%matplotlib inline
circuit.draw()
circuit.h(qr[0])
circuit.draw(output = 'mpl')
circuit.cx(qr[0], qr[1])
circuit.draw(output='mpl')
circuit.measure(qr, cr)
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
execute(circuit, backend=simulator)
result = execute(circuit, backend=simulator).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
# plot_histogram
provider = IBMQ.get_provider('ibm-q')
backend = provider.get_backend('ibmq_16_melbourne')
job =execute(circuit, backend= backend)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(circuit))
|
https://github.com/BoxiLi/qiskit-CR-calibration
|
BoxiLi
|
import logging
from copy import deepcopy
import numpy as np
from numpy import pi
from qiskit.circuit import Gate
from qiskit import transpile
from qiskit.transpiler import InstructionProperties
from qiskit_utilities import (
save_job_data,
setup_logger,
retrieve_expdata,
get_cr_schedule,
iy_drag_calibration,
get_default_cr_params,
read_calibration_data,
iterative_cr_pulse_calibration,
create_echoed_cnot_schedule,
initilize_qiskit_dynamics_backend
)
session = None # qiskit runtime session
# Setup a logging system.
setup_logger(filename=None, level=logging.INFO, stdout=True)
logger = logging.getLogger("qiskit_utilities")
# Create a qiskit-dynamics backend with two Transmon, see fake_backend.py for detail.
# fidelity
f0 = 5.188339840468758e9
f1 = 5.079647268847252e9
# anharmonicity
a0 = -0.341931669003125e9
a1 = -0.343248404293835e9
backend = initilize_qiskit_dynamics_backend(f0, f1, a0, a1, J=0.003e9)
# Operating qubits
QUBIT_C, QUBIT_T = (0, 1)
# Compute the sampling time steps for the CR tomography experiments
if backend.name == 'DynamicsBackend':
amp = 2 * pi * 0.04
cr_times = np.arange(16*16, 1440*3, 32*4, dtype=int)
duration = 720 # Used for plotting only, not tomography.
else:
amp = get_default_cr_params(backend, QUBIT_C, QUBIT_T)[0]
duration = backend.defaults().instruction_schedule_map.get("cx", (QUBIT_C, QUBIT_T)).duration/16 * 4
cr_times = 16 * np.arange(16, duration + 16, duration//30, dtype=int)
## Custom shape
gate_name = "CR-Hann-tr10"
params = {
"order": "1", # order m for the initial pulse shape, order 1 is the Hann shape
"t_r": 10,
"drag_type" : False, # Givens rotation, use "sw" for perturbation
"duration": duration, # only for plotting
"amp": amp,
"angle": 0.0,
## If real device, use the following
# "Delta": (backend.properties().frequency(QUBIT_C) - backend.properties().frequency(QUBIT_T)) * 1.0e-9 * 2 * pi,
# "a1": 2 * pi * backend.properties().qubit_property(QUBIT_C)["anharmonicity"][0] * 1.0e-9,
## If Dynamicsbackend, use this
"Delta": 2 * pi * (f0 - f1) * 1.0e-9,
"a1": 2 * pi * a0 * 1.0e-9,
"drag_scale": [1., 1., 1.],
}
cr_params = params.copy()
ix_params = params.copy()
ix_params["amp"] = 0.0
ix_params["order"] = "2"
initial_calibration_data = {
"cr_params": cr_params,
"ix_params": ix_params,
"frequency_offset": 0.,
}
get_cr_schedule((QUBIT_C, QUBIT_T), backend, cr_params=cr_params, ix_params=ix_params).draw()
iterative_cr_pulse_calibration(
(QUBIT_C, QUBIT_T),
backend,
initial_calibration_data=initial_calibration_data,
cr_times=cr_times,
session=session,
gate_name=gate_name,
verbose=True,
restart=True, # fresh start
max_repeat=3,
shots=2048,
mode="CR",
)
from qiskit_experiments.library import ProcessTomography
calibration_data = read_calibration_data(backend, gate_name, (QUBIT_C, QUBIT_T))
custom_cnot_sched = create_echoed_cnot_schedule(backend, (QUBIT_C, QUBIT_T), calibration_data, reverse_direction=False)
# Show the custom CNOT schedule.
custom_cnot_sched.draw()
custom_cnot = Gate("custom_cnot", 2, [])
backend_tmp = deepcopy(backend)
backend_tmp.target.add_instruction(
custom_cnot,
{(QUBIT_C, QUBIT_T): InstructionProperties(calibration=custom_cnot_sched)},
name="custom_cnot",
)
qptexp = ProcessTomography(custom_cnot, physical_qubits=[QUBIT_C, QUBIT_T])
try:
basis_gates = backend.configuration().basis_gates
except AttributeError:
basis_gates = ["measure", "sx", "x", "rz"]
transpiled_circ_list = transpile(
qptexp._transpiled_circuits(),
backend=backend_tmp,
basis_gates = basis_gates + ["custom_cnot"],
optimization_level= 1, # Turn off optimization to keep the custom pulse
)
shots = 8096
if session is not None:
qpt_job = session.run(
"circuit-runner",
inputs={
"circuits": transpiled_circ_list,
"skip_transpilation": True,
"shots": shots,
},
)
else:
qpt_job = backend.run(transpiled_circ_list, shots=shots)
parameters = {
"backend": backend.name,
"qubits": (QUBIT_C, QUBIT_T),
"shots": shots,
}
logger.info(
"Quantum process tomography job: "+
str(qpt_job.job_id()) + "\n"
+ "\n".join([f"{key}: {val}" for key, val in parameters.items()])
+ "\n"
)
save_job_data(qpt_job, backend=backend, parameters=parameters)
import qutip
qptdata = retrieve_expdata(qpt_job, backend=backend, exp=qptexp)
state_result = qptdata.analysis_results("state")
choi_matrix = state_result.value.data
choi_qobj = qutip.Qobj(
choi_matrix, dims=[[[2, 2], [2, 2]], [[2, 2], [2, 2]]], superrep="choi"
)
choi_qobj = choi_qobj.permute([[1, 0], [3, 2]]) # Permute the two qubit
qutip.to_super(choi_qobj)
op_basis = [[qutip.qeye(2), qutip.sigmax(), qutip.sigmay(), qutip.sigmaz()]] * 2
chi_qobj = qutip.qpt(qutip.to_super(choi_qobj), op_basis)
qutip.qpt_plot_combined(
chi_qobj, lbls_list=[["i", "x", "y", "z"]] * 2, title="Process Matrix"
)
# Operating qubits
QUBIT_C, QUBIT_T = (0, 1)
# Compute the sampling time steps for the CR tomography experiments
if backend.name == 'DynamicsBackend':
amp = 2 * pi * 0.04
cr_times = np.arange(16*16, 1440*3, 32*4, dtype=int)
duration = 720 # Used for plotting only, not tomography.
else:
amp = get_default_cr_params(backend, QUBIT_C, QUBIT_T)[0]
duration = backend.defaults().instruction_schedule_map.get("cx", (QUBIT_C, QUBIT_T)).duration/16 * 4
cr_times = 16 * np.arange(16, duration + 16, duration//30, dtype=int)
## Custom shape
gate_name = "CR-recursive-tr10"
params = {
"order": "3", # order m for the initial pulse shape, order 1 is the Hann shape
"t_r": 10,
"drag_type" : "exact", # Givens rotation, use "sw" for perturbation
"duration": duration, # only for plotting
"amp": amp,
"angle": 0.0,
## If real device, use the following
# "Delta": (backend.properties().frequency(QUBIT_C) - backend.properties().frequency(QUBIT_T)) * 1.0e-9 * 2 * pi,
# "a1": 2 * pi * backend.properties().qubit_property(QUBIT_C)["anharmonicity"][0] * 1.0e-9,
## If Dynamicsbackend, use this
"Delta": 2 * pi * (f0 - f1) * 1.0e-9,
"a1": 2 * pi * a0 * 1.0e-9,
"drag_scale": [1., 1., 1.],
}
cr_params = params.copy()
ix_params = params.copy()
ix_params["amp"] = 0.0
ix_params["order"] = "2"
initial_calibration_data = {
"cr_params": cr_params,
"ix_params": ix_params,
"frequency_offset": 0.,
}
get_cr_schedule((QUBIT_C, QUBIT_T), backend, cr_params=cr_params, ix_params=ix_params).draw()
iterative_cr_pulse_calibration(
(QUBIT_C, QUBIT_T),
backend,
initial_calibration_data=initial_calibration_data,
cr_times=cr_times,
session=session,
gate_name=gate_name,
verbose=True,
restart=True, # fresh start
max_repeat=3,
shots=2048,
mode="CR",
)
from qiskit_experiments.library import ProcessTomography
calibration_data = read_calibration_data(backend, gate_name, (QUBIT_C, QUBIT_T))
custom_cnot_sched = create_echoed_cnot_schedule(backend, (QUBIT_C, QUBIT_T), calibration_data, reverse_direction=False)
# Show the custom CNOT schedule.
custom_cnot_sched.draw()
custom_cnot = Gate("custom_cnot", 2, [])
backend_tmp = deepcopy(backend)
backend_tmp.target.add_instruction(
custom_cnot,
{(QUBIT_C, QUBIT_T): InstructionProperties(calibration=custom_cnot_sched)},
name="custom_cnot",
)
qptexp = ProcessTomography(custom_cnot, physical_qubits=[QUBIT_C, QUBIT_T])
try:
basis_gates = backend.configuration().basis_gates
except AttributeError:
basis_gates = ["measure", "sx", "x", "rz"]
transpiled_circ_list = transpile(
qptexp._transpiled_circuits(),
backend=backend_tmp,
basis_gates = basis_gates + ["custom_cnot"],
optimization_level= 1, # Turn off optimization to keep the custom pulse
)
shots = 8096
if session is not None:
qpt_job = session.run(
"circuit-runner",
inputs={
"circuits": transpiled_circ_list,
"skip_transpilation": True,
"shots": shots,
},
)
else:
qpt_job = backend.run(transpiled_circ_list, shots=shots)
parameters = {
"backend": backend.name,
"qubits": (QUBIT_C, QUBIT_T),
"shots": shots,
}
logger.info(
"Quantum process tomography job: "+
str(qpt_job.job_id()) + "\n"
+ "\n".join([f"{key}: {val}" for key, val in parameters.items()])
+ "\n"
)
save_job_data(qpt_job, backend=backend, parameters=parameters)
import qutip
qptdata = retrieve_expdata(qpt_job, backend=backend, exp=qptexp)
state_result = qptdata.analysis_results("state")
choi_matrix = state_result.value.data
choi_qobj = qutip.Qobj(
choi_matrix, dims=[[[2, 2], [2, 2]], [[2, 2], [2, 2]]], superrep="choi"
)
choi_qobj = choi_qobj.permute([[1, 0], [3, 2]]) # Permute the two qubit
qutip.to_super(choi_qobj)
op_basis = [[qutip.qeye(2), qutip.sigmax(), qutip.sigmay(), qutip.sigmaz()]] * 2
chi_qobj = qutip.qpt(qutip.to_super(choi_qobj), op_basis)
qutip.qpt_plot_combined(
chi_qobj, lbls_list=[["i", "x", "y", "z"]] * 2, title="Process Matrix"
)
iy_drag_calibration((QUBIT_C, QUBIT_T), backend, gate_name, cr_times, session, verbose=True, delta_beta=10.)
calibration_data = read_calibration_data(backend, gate_name, (QUBIT_C, QUBIT_T))
custom_cnot_sched = create_echoed_cnot_schedule(backend, (QUBIT_C, QUBIT_T), calibration_data, reverse_direction=False)
# Show the custom CNOT schedule.
custom_cnot_sched.draw()
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
import json
from typing import Any, Dict, List
import pytest
import qiskit
import requests
import qiskit_superstaq as qss
def test_default_options() -> None:
ss_provider = qss.superstaq_provider.SuperstaQProvider("MY_TOKEN")
device = qss.superstaq_backend.SuperstaQBackend(
provider=ss_provider,
url=qss.API_URL,
backend="ibmq_qasm_simulator",
)
assert qiskit.providers.Options(shots=1000) == device._default_options()
class MockResponse:
def __init__(self, job_ids: List[str]) -> None:
self.content = json.dumps({"job_ids": job_ids})
def json(self) -> Dict:
return json.loads(self.content)
def raise_for_status(self) -> None:
pass
class MockBadResponse:
def __init__(self) -> None:
self.content = json.dumps({})
def json(self) -> Dict:
return {}
def raise_for_status(self) -> None:
pass
class MockProvider(qss.superstaq_provider.SuperstaQProvider):
def __init__(self) -> None:
self.access_token = "super.tech"
class MockDevice(qss.superstaq_backend.SuperstaQBackend):
def __init__(self) -> None:
super().__init__(MockProvider(), "super.tech", "mock_backend")
self._provider = MockProvider()
def test_run(monkeypatch: Any) -> None:
qc = qiskit.QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 0], [1, 1])
device = MockDevice()
monkeypatch.setattr(requests, "post", lambda *_, **__: MockResponse(["123abc"]))
answer = device.run(circuits=qc)
expected = qss.superstaq_job.SuperstaQJob(device, "123abc")
assert answer == expected
monkeypatch.setattr(requests, "post", lambda *_, **__: MockBadResponse())
with pytest.raises(Exception):
device.run(circuits=qc)
def test_multi_circuit_run(monkeypatch: Any) -> None:
device = MockDevice()
qc1 = qiskit.QuantumCircuit(1, 1)
qc1.h(0)
qc1.measure(0, 0)
qc2 = qiskit.QuantumCircuit(2, 2)
qc2.h(0)
qc2.cx(0, 1)
qc2.measure([0, 1], [0, 1])
monkeypatch.setattr(requests, "post", lambda *_, **__: MockResponse(["123abc", "456efg"]))
answer = device.run(circuits=[qc1, qc2])
expected = qss.superstaq_job.SuperstaQJob(device, "123abc,456efg")
assert answer == expected
def test_eq() -> None:
assert MockDevice() != 3
provider = qss.superstaq_provider.SuperstaQProvider(access_token="123")
backend1 = qss.superstaq_backend.SuperstaQBackend(
provider=provider, backend="ibmq_qasm_simulator", url=qss.API_URL
)
backend2 = qss.superstaq_backend.SuperstaQBackend(
provider=provider, backend="ibmq_athens", url=qss.API_URL
)
assert backend1 != backend2
backend3 = qss.superstaq_backend.SuperstaQBackend(
provider=provider, backend="ibmq_qasm_simulator", url=qss.API_URL
)
assert backend1 == backend3
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""CircuitGradient Class"""
from abc import abstractmethod
from typing import List, Union, Optional, Tuple, Set
from qiskit import QuantumCircuit, QiskitError, transpile
from qiskit.circuit import ParameterExpression, ParameterVector
from qiskit.utils.deprecation import deprecate_func
from ...converters.converter_base import ConverterBase
from ...operator_base import OperatorBase
class CircuitGradient(ConverterBase):
r"""Deprecated: Circuit to gradient operator converter.
Converter for changing parameterized circuits into operators
whose evaluation yields the gradient with respect to the circuit parameters.
This is distinct from DerivativeBase converters which take gradients of composite
operators and handle things like differentiating combo_fn's and enforcing product rules
when operator coefficients are parameterized.
CircuitGradient - uses quantum techniques to get derivatives of circuits
DerivativeBase - uses classical techniques to differentiate operator flow data structures
"""
@deprecate_func(
since="0.24.0",
additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(self) -> None:
super().__init__()
# pylint: disable=arguments-differ
@abstractmethod
def convert(
self,
operator: OperatorBase,
params: Optional[
Union[
ParameterExpression,
ParameterVector,
List[ParameterExpression],
Tuple[ParameterExpression, ParameterExpression],
List[Tuple[ParameterExpression, ParameterExpression]],
]
] = None,
) -> OperatorBase:
r"""
Args:
operator: The operator we are taking the gradient of
params: The parameters we are taking the gradient wrt: ω
If a ParameterExpression, ParameterVector or List[ParameterExpression] is given,
then the 1st order derivative of the operator is calculated.
If a Tuple[ParameterExpression, ParameterExpression] or
List[Tuple[ParameterExpression, ParameterExpression]]
is given, then the 2nd order derivative of the operator is calculated.
Returns:
An operator whose evaluation yields the Gradient.
Raises:
ValueError: If ``params`` contains a parameter not present in ``operator``.
"""
raise NotImplementedError
@staticmethod
def _transpile_to_supported_operations(
circuit: QuantumCircuit, supported_gates: Set[str]
) -> QuantumCircuit:
"""Transpile the given circuit into a gate set for which the gradients may be computed.
Args:
circuit: Quantum circuit to be transpiled into supported operations.
supported_gates: Set of quantum operations supported by a gradient method intended to
be used on the quantum circuit.
Returns:
Quantum circuit which is transpiled into supported operations.
Raises:
QiskitError: when circuit transpiling fails.
"""
unique_ops = set(circuit.count_ops())
if not unique_ops.issubset(supported_gates):
try:
circuit = transpile(
circuit, basis_gates=list(supported_gates), optimization_level=0
)
except Exception as exc:
raise QiskitError(
f"Could not transpile the circuit provided {circuit} into supported gates "
f"{supported_gates}."
) from exc
return circuit
|
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.
"""Assembler Test."""
import unittest
import io
from logging import StreamHandler, getLogger
import sys
import copy
import numpy as np
from qiskit import pulse
from qiskit.circuit import Instruction, Gate, Parameter, ParameterVector
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.compiler.assembler import assemble
from qiskit.exceptions import QiskitError
from qiskit.pulse import Schedule, Acquire, Play
from qiskit.pulse.channels import MemorySlot, AcquireChannel, DriveChannel, MeasureChannel
from qiskit.pulse.configuration import Kernel, Discriminator
from qiskit.pulse.library import gaussian
from qiskit.qobj import QasmQobj, PulseQobj
from qiskit.qobj.utils import MeasLevel, MeasReturnType
from qiskit.pulse.macros import measure
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import (
FakeOpenPulse2Q,
FakeOpenPulse3Q,
FakeYorktown,
FakeHanoi,
)
class RxGate(Gate):
"""Used to test custom gate assembly.
Useful for testing pulse gates with parameters, as well.
Note: Parallel maps (e.g., in assemble_circuits) pickle their input,
so circuit features have to be defined top level.
"""
def __init__(self, theta):
super().__init__("rxtheta", 1, [theta])
class TestCircuitAssembler(QiskitTestCase):
"""Tests for assembling circuits to qobj."""
def setUp(self):
super().setUp()
qr = QuantumRegister(2, name="q")
cr = ClassicalRegister(2, name="c")
self.circ = QuantumCircuit(qr, cr, name="circ")
self.circ.h(qr[0])
self.circ.cx(qr[0], qr[1])
self.circ.measure(qr, cr)
self.backend = FakeYorktown()
self.backend_config = self.backend.configuration()
self.num_qubits = self.backend_config.n_qubits
# lo test values
self.default_qubit_lo_freq = [5e9 for _ in range(self.num_qubits)]
self.default_meas_lo_freq = [6.7e9 for _ in range(self.num_qubits)]
self.user_lo_config_dict = {
pulse.DriveChannel(0): 5.55e9,
pulse.MeasureChannel(0): 6.64e9,
pulse.DriveChannel(3): 4.91e9,
pulse.MeasureChannel(4): 6.1e9,
}
self.user_lo_config = pulse.LoConfig(self.user_lo_config_dict)
def test_assemble_single_circuit(self):
"""Test assembling a single circuit."""
qobj = assemble(self.circ, shots=2000, memory=True)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.shots, 2000)
self.assertEqual(qobj.config.memory, True)
self.assertEqual(len(qobj.experiments), 1)
self.assertEqual(qobj.experiments[0].instructions[1].name, "cx")
def test_assemble_multiple_circuits(self):
"""Test assembling multiple circuits, all should have the same config."""
qr0 = QuantumRegister(2, name="q0")
qc0 = ClassicalRegister(2, name="c0")
circ0 = QuantumCircuit(qr0, qc0, name="circ0")
circ0.h(qr0[0])
circ0.cx(qr0[0], qr0[1])
circ0.measure(qr0, qc0)
qr1 = QuantumRegister(3, name="q1")
qc1 = ClassicalRegister(3, name="c1")
circ1 = QuantumCircuit(qr1, qc1, name="circ0")
circ1.h(qr1[0])
circ1.cx(qr1[0], qr1[1])
circ1.cx(qr1[0], qr1[2])
circ1.measure(qr1, qc1)
qobj = assemble([circ0, circ1], shots=100, memory=False, seed_simulator=6)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.seed_simulator, 6)
self.assertEqual(len(qobj.experiments), 2)
self.assertEqual(qobj.experiments[1].config.n_qubits, 3)
self.assertEqual(len(qobj.experiments), 2)
self.assertEqual(len(qobj.experiments[1].instructions), 6)
def test_assemble_no_run_config(self):
"""Test assembling with no run_config, relying on default."""
qobj = assemble(self.circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.shots, 1024)
def test_shots_greater_than_max_shots(self):
"""Test assembling with shots greater than max shots"""
self.assertRaises(QiskitError, assemble, self.backend, shots=1024000)
def test_shots_not_of_type_int(self):
"""Test assembling with shots having type other than int"""
self.assertRaises(QiskitError, assemble, self.backend, shots="1024")
def test_shots_of_type_numpy_int64(self):
"""Test assembling with shots having type numpy.int64"""
qobj = assemble(self.circ, shots=np.int64(2048))
self.assertEqual(qobj.config.shots, 2048)
def test_default_shots_greater_than_max_shots(self):
"""Test assembling with default shots greater than max shots"""
self.backend_config.max_shots = 5
qobj = assemble(self.circ, self.backend)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.shots, 5)
def test_assemble_initialize(self):
"""Test assembling a circuit with an initialize."""
q = QuantumRegister(2, name="q")
circ = QuantumCircuit(q, name="circ")
circ.initialize([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)], q[:])
qobj = assemble(circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.experiments[0].instructions[0].name, "initialize")
np.testing.assert_almost_equal(
qobj.experiments[0].instructions[0].params, [0.7071067811865, 0, 0, 0.707106781186]
)
def test_assemble_meas_level_meas_return(self):
"""Test assembling a circuit schedule with `meas_level`."""
qobj = assemble(self.circ, meas_level=1, meas_return="single")
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.meas_level, 1)
self.assertEqual(qobj.config.meas_return, "single")
# no meas_level set
qobj = assemble(self.circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.meas_level, 2)
self.assertEqual(hasattr(qobj.config, "meas_return"), False)
def test_assemble_backend_rep_delays(self):
"""Check that rep_delay is properly set from backend values."""
rep_delay_range = [2.5e-3, 4.5e-3] # sec
default_rep_delay = 3.0e-3
setattr(self.backend_config, "rep_delay_range", rep_delay_range)
setattr(self.backend_config, "default_rep_delay", default_rep_delay)
# dynamic rep rates off
setattr(self.backend_config, "dynamic_reprate_enabled", False)
qobj = assemble(self.circ, self.backend)
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# dynamic rep rates on
setattr(self.backend_config, "dynamic_reprate_enabled", True)
qobj = assemble(self.circ, self.backend)
self.assertEqual(qobj.config.rep_delay, default_rep_delay * 1e6)
def test_assemble_user_rep_time_delay(self):
"""Check that user runtime config rep_delay works."""
# set custom rep_delay in runtime config
rep_delay = 2.2e-6
rep_delay_range = [0, 3e-6] # sec
setattr(self.backend_config, "rep_delay_range", rep_delay_range)
# dynamic rep rates off (no default so shouldn't be in qobj config)
setattr(self.backend_config, "dynamic_reprate_enabled", False)
qobj = assemble(self.circ, self.backend, rep_delay=rep_delay)
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# turn on dynamic rep rates, rep_delay should be set
setattr(self.backend_config, "dynamic_reprate_enabled", True)
qobj = assemble(self.circ, self.backend, rep_delay=rep_delay)
self.assertEqual(qobj.config.rep_delay, 2.2)
# test ``rep_delay=0``
qobj = assemble(self.circ, self.backend, rep_delay=0)
self.assertEqual(qobj.config.rep_delay, 0)
# use ``rep_delay`` outside of ``rep_delay_range```
rep_delay_large = 5.0e-6
with self.assertRaises(QiskitError):
assemble(self.circ, self.backend, rep_delay=rep_delay_large)
def test_assemble_opaque_inst(self):
"""Test opaque instruction is assembled as-is"""
opaque_inst = Instruction(name="my_inst", num_qubits=4, num_clbits=2, params=[0.5, 0.4])
q = QuantumRegister(6, name="q")
c = ClassicalRegister(4, name="c")
circ = QuantumCircuit(q, c, name="circ")
circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]])
qobj = assemble(circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(len(qobj.experiments[0].instructions), 1)
self.assertEqual(qobj.experiments[0].instructions[0].name, "my_inst")
self.assertEqual(qobj.experiments[0].instructions[0].qubits, [0, 2, 5, 3])
self.assertEqual(qobj.experiments[0].instructions[0].memory, [3, 0])
self.assertEqual(qobj.experiments[0].instructions[0].params, [0.5, 0.4])
def test_assemble_unroll_parametervector(self):
"""Verfiy that assemble unrolls parametervectors ref #5467"""
pv1 = ParameterVector("pv1", 3)
pv2 = ParameterVector("pv2", 3)
qc = QuantumCircuit(2, 2)
for i in range(3):
qc.rx(pv1[i], 0)
qc.ry(pv2[i], 1)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.bind_parameters({pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]})
qobj = assemble(qc, parameter_binds=[{pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]}])
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.experiments[0].instructions[0].params[0], 0.100000000000000)
self.assertEqual(qobj.experiments[0].instructions[1].params[0], 0.400000000000000)
self.assertEqual(qobj.experiments[0].instructions[2].params[0], 0.200000000000000)
self.assertEqual(qobj.experiments[0].instructions[3].params[0], 0.500000000000000)
self.assertEqual(qobj.experiments[0].instructions[4].params[0], 0.300000000000000)
self.assertEqual(qobj.experiments[0].instructions[5].params[0], 0.600000000000000)
def test_measure_to_registers_when_conditionals(self):
"""Verify assemble_circuits maps all measure ops on to a register slot
for a circuit containing conditionals."""
qr = QuantumRegister(2)
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr1, cr2)
qc.measure(qr[0], cr1) # Measure not required for a later conditional
qc.measure(qr[1], cr2[1]) # Measure required for a later conditional
qc.h(qr[1]).c_if(cr2, 3)
qobj = assemble(qc)
first_measure, second_measure = (
op for op in qobj.experiments[0].instructions if op.name == "measure"
)
self.assertTrue(hasattr(first_measure, "register"))
self.assertEqual(first_measure.register, first_measure.memory)
self.assertTrue(hasattr(second_measure, "register"))
self.assertEqual(second_measure.register, second_measure.memory)
def test_convert_to_bfunc_plus_conditional(self):
"""Verify assemble_circuits converts conditionals from QASM to Qobj."""
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr, 1)
qobj = assemble(qc)
bfunc_op, h_op = qobj.experiments[0].instructions
self.assertEqual(bfunc_op.name, "bfunc")
self.assertEqual(bfunc_op.mask, "0x1")
self.assertEqual(bfunc_op.val, "0x1")
self.assertEqual(bfunc_op.relation, "==")
self.assertTrue(hasattr(h_op, "conditional"))
self.assertEqual(bfunc_op.register, h_op.conditional)
def test_convert_to_bfunc_plus_conditional_onebit(self):
"""Verify assemble_circuits converts single bit conditionals from QASM to Qobj."""
qr = QuantumRegister(1)
cr = ClassicalRegister(3)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr[2], 1)
qobj = assemble(qc)
inst_set = qobj.experiments[0].instructions
[bfunc_op, h_op] = inst_set
self.assertEqual(len(inst_set), 2)
self.assertEqual(bfunc_op.name, "bfunc")
self.assertEqual(bfunc_op.mask, "0x4")
self.assertEqual(bfunc_op.val, "0x4")
self.assertEqual(bfunc_op.relation, "==")
self.assertTrue(hasattr(h_op, "conditional"))
self.assertEqual(bfunc_op.register, h_op.conditional)
def test_resize_value_to_register(self):
"""Verify assemble_circuits converts the value provided on the classical
creg to its mapped location on the device register."""
qr = QuantumRegister(1)
cr1 = ClassicalRegister(2)
cr2 = ClassicalRegister(2)
cr3 = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr1, cr2, cr3)
qc.h(qr[0]).c_if(cr2, 2)
qobj = assemble(qc)
bfunc_op, h_op = qobj.experiments[0].instructions
self.assertEqual(bfunc_op.name, "bfunc")
self.assertEqual(bfunc_op.mask, "0xC")
self.assertEqual(bfunc_op.val, "0x8")
self.assertEqual(bfunc_op.relation, "==")
self.assertTrue(hasattr(h_op, "conditional"))
self.assertEqual(bfunc_op.register, h_op.conditional)
def test_assemble_circuits_raises_for_bind_circuit_mismatch(self):
"""Verify assemble_circuits raises error for parameterized circuits without matching
binds."""
qr = QuantumRegister(2)
x = Parameter("x")
y = Parameter("y")
full_bound_circ = QuantumCircuit(qr)
full_param_circ = QuantumCircuit(qr)
partial_param_circ = QuantumCircuit(qr)
partial_param_circ.p(x, qr[0])
full_param_circ.p(x, qr[0])
full_param_circ.p(y, qr[1])
partial_bind_args = {"parameter_binds": [{x: 1}, {x: 0}]}
full_bind_args = {"parameter_binds": [{x: 1, y: 1}, {x: 0, y: 0}]}
inconsistent_bind_args = {"parameter_binds": [{x: 1}, {x: 0, y: 0}]}
# Raise when parameters passed for non-parametric circuit
self.assertRaises(QiskitError, assemble, full_bound_circ, **partial_bind_args)
# Raise when no parameters passed for parametric circuit
self.assertRaises(QiskitError, assemble, partial_param_circ)
self.assertRaises(QiskitError, assemble, full_param_circ)
# Raise when circuit has more parameters than run_config
self.assertRaises(QiskitError, assemble, full_param_circ, **partial_bind_args)
# Raise when not all circuits have all parameters
self.assertRaises(
QiskitError, assemble, [full_param_circ, partial_param_circ], **full_bind_args
)
# Raise when not all binds have all circuit params
self.assertRaises(QiskitError, assemble, full_param_circ, **inconsistent_bind_args)
def test_assemble_circuits_rases_for_bind_mismatch_over_expressions(self):
"""Verify assemble_circuits raises for invalid binds for circuit including
ParameterExpressions.
"""
qr = QuantumRegister(1)
x = Parameter("x")
y = Parameter("y")
expr_circ = QuantumCircuit(qr)
expr_circ.p(x + y, qr[0])
partial_bind_args = {"parameter_binds": [{x: 1}, {x: 0}]}
# Raise when no parameters passed for parametric circuit
self.assertRaises(QiskitError, assemble, expr_circ)
# Raise when circuit has more parameters than run_config
self.assertRaises(QiskitError, assemble, expr_circ, **partial_bind_args)
def test_assemble_circuits_binds_parameters(self):
"""Verify assemble_circuits applies parameter bindings and output circuits are bound."""
qr = QuantumRegister(1)
qc1 = QuantumCircuit(qr)
qc2 = QuantumCircuit(qr)
qc3 = QuantumCircuit(qr)
x = Parameter("x")
y = Parameter("y")
sum_ = x + y
product_ = x * y
qc1.u(x, y, 0, qr[0])
qc2.rz(x, qr[0])
qc2.rz(y, qr[0])
qc3.u(sum_, product_, 0, qr[0])
bind_args = {"parameter_binds": [{x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}]}
qobj = assemble([qc1, qc2, qc3], **bind_args)
self.assertEqual(len(qobj.experiments), 9)
self.assertEqual(
[len(expt.instructions) for expt in qobj.experiments], [1, 1, 1, 2, 2, 2, 1, 1, 1]
)
def _qobj_inst_params(expt_no, inst_no):
expt = qobj.experiments[expt_no]
inst = expt.instructions[inst_no]
return [float(p) for p in inst.params]
self.assertEqual(_qobj_inst_params(0, 0), [0, 0, 0])
self.assertEqual(_qobj_inst_params(1, 0), [1, 0, 0])
self.assertEqual(_qobj_inst_params(2, 0), [1, 1, 0])
self.assertEqual(_qobj_inst_params(3, 0), [0])
self.assertEqual(_qobj_inst_params(3, 1), [0])
self.assertEqual(_qobj_inst_params(4, 0), [1])
self.assertEqual(_qobj_inst_params(4, 1), [0])
self.assertEqual(_qobj_inst_params(5, 0), [1])
self.assertEqual(_qobj_inst_params(5, 1), [1])
self.assertEqual(_qobj_inst_params(6, 0), [0, 0, 0])
self.assertEqual(_qobj_inst_params(7, 0), [1, 0, 0])
self.assertEqual(_qobj_inst_params(8, 0), [2, 1, 0])
def test_init_qubits_default(self):
"""Check that the init_qubits=None assemble option is passed on to the qobj."""
qobj = assemble(self.circ)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_true(self):
"""Check that the init_qubits=True assemble option is passed on to the qobj."""
qobj = assemble(self.circ, init_qubits=True)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_false(self):
"""Check that the init_qubits=False assemble option is passed on to the qobj."""
qobj = assemble(self.circ, init_qubits=False)
self.assertEqual(qobj.config.init_qubits, False)
def test_circuit_with_global_phase(self):
"""Test that global phase for a circuit is handled correctly."""
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.measure_all()
circ.global_phase = 0.3 * np.pi
qobj = assemble([circ, self.circ])
self.assertEqual(getattr(qobj.experiments[1].header, "global_phase"), 0)
self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), 0.3 * np.pi)
def test_circuit_global_phase_gate_definitions(self):
"""Test circuit with global phase on gate definitions."""
class TestGate(Gate):
"""dummy gate"""
def __init__(self):
super().__init__("test_gate", 1, [])
def _define(self):
circ_def = QuantumCircuit(1)
circ_def.x(0)
circ_def.global_phase = np.pi
self._definition = circ_def
gate = TestGate()
circ = QuantumCircuit(1)
circ.append(gate, [0])
qobj = assemble([circ])
self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), 0)
circ.global_phase = np.pi / 2
qobj = assemble([circ])
self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), np.pi / 2)
def test_pulse_gates_single_circ(self):
"""Test that we can add calibrations to circuits."""
theta = Parameter("theta")
circ = QuantumCircuit(2)
circ.h(0)
circ.append(RxGate(3.14), [0])
circ.append(RxGate(theta), [1])
circ = circ.assign_parameters({theta: 3.14})
with pulse.build() as custom_h_schedule:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
with pulse.build() as x180:
pulse.play(pulse.library.Gaussian(50, 0.2, 5), pulse.DriveChannel(1))
circ.add_calibration("h", [0], custom_h_schedule)
circ.add_calibration(RxGate(3.14), [0], x180)
circ.add_calibration(RxGate(3.14), [1], x180)
qobj = assemble(circ, FakeOpenPulse2Q())
# Only one circuit, so everything is stored at the job level
cals = qobj.config.calibrations
lib = qobj.config.pulse_library
self.assertFalse(hasattr(qobj.experiments[0].config, "calibrations"))
self.assertEqual([gate.name == "rxtheta" for gate in cals.gates].count(True), 2)
self.assertEqual([gate.name == "h" for gate in cals.gates].count(True), 1)
self.assertEqual(len(lib), 2)
self.assertTrue(all(len(item.samples) == 50 for item in lib))
def test_pulse_gates_with_parameteric_pulses(self):
"""Test that pulse gates are assembled efficiently for backends that enable
parametric pulses.
"""
with pulse.build() as custom_h_schedule:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
circ = QuantumCircuit(2)
circ.h(0)
circ.add_calibration("h", [0], custom_h_schedule)
backend = FakeOpenPulse2Q()
backend.configuration().parametric_pulses = ["drag"]
qobj = assemble(circ, backend)
self.assertFalse(hasattr(qobj.config, "pulse_library"))
self.assertTrue(hasattr(qobj.config, "calibrations"))
def test_pulse_gates_multiple_circuits(self):
"""Test one circuit with cals and another without."""
with pulse.build() as dummy_sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
circ = QuantumCircuit(2)
circ.h(0)
circ.append(RxGate(3.14), [1])
circ.add_calibration("h", [0], dummy_sched)
circ.add_calibration(RxGate(3.14), [1], dummy_sched)
circ2 = QuantumCircuit(2)
circ2.h(0)
qobj = assemble([circ, circ2], FakeOpenPulse2Q())
self.assertEqual(len(qobj.config.pulse_library), 1)
self.assertEqual(len(qobj.experiments[0].config.calibrations.gates), 2)
self.assertFalse(hasattr(qobj.config, "calibrations"))
self.assertFalse(hasattr(qobj.experiments[1].config, "calibrations"))
def test_pulse_gates_common_cals(self):
"""Test that common calibrations are added at the top level."""
with pulse.build() as dummy_sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
circ = QuantumCircuit(2)
circ.h(0)
circ.append(RxGate(3.14), [1])
circ.add_calibration("h", [0], dummy_sched)
circ.add_calibration(RxGate(3.14), [1], dummy_sched)
circ2 = QuantumCircuit(2)
circ2.h(0)
circ2.add_calibration(RxGate(3.14), [1], dummy_sched)
qobj = assemble([circ, circ2], FakeOpenPulse2Q())
# Identical pulses are only added once
self.assertEqual(len(qobj.config.pulse_library), 1)
# Identical calibrations are only added once
self.assertEqual(qobj.config.calibrations.gates[0].name, "rxtheta")
self.assertEqual(qobj.config.calibrations.gates[0].params, [3.14])
self.assertEqual(qobj.config.calibrations.gates[0].qubits, [1])
self.assertEqual(len(qobj.experiments[0].config.calibrations.gates), 1)
self.assertFalse(hasattr(qobj.experiments[1].config, "calibrations"))
def test_assemble_adds_circuit_metadata_to_experiment_header(self):
"""Verify that any circuit metadata is added to the exeriment header."""
circ = QuantumCircuit(2, metadata={"experiment_type": "gst", "execution_number": "1234"})
qobj = assemble(circ, shots=100, memory=False, seed_simulator=6)
self.assertEqual(
qobj.experiments[0].header.metadata,
{"experiment_type": "gst", "execution_number": "1234"},
)
def test_pulse_gates_delay_only(self):
"""Test that a single delay gate is translated to an instruction."""
circ = QuantumCircuit(2)
circ.append(Gate("test", 1, []), [0])
test_sched = pulse.Delay(64, DriveChannel(0)) + pulse.Delay(160, DriveChannel(0))
circ.add_calibration("test", [0], test_sched)
qobj = assemble(circ, FakeOpenPulse2Q())
self.assertEqual(len(qobj.config.calibrations.gates[0].instructions), 2)
self.assertEqual(
qobj.config.calibrations.gates[0].instructions[1].to_dict(),
{"name": "delay", "t0": 64, "ch": "d0", "duration": 160},
)
def test_job_qubit_meas_los_no_range(self):
"""Test that adding job qubit/meas lo freq lists are assembled into the qobj.config, w/ out
any lo range."""
qobj = assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
)
# convert to ghz
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
def test_job_lo_errors(self):
"""Test that job lo's are checked against the lo ranges and that errors are thrown if either
quantity has an incorrect length or type."""
qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_qubit_lo_freq]
meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_meas_lo_freq]
# lo range not a nested list
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=[4.995e9 for i in range(self.num_qubits)],
meas_lo_range=meas_lo_range,
)
# qubit lo range inner list not 2d
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=[[6.695e9] for i in range(self.num_qubits)],
)
# meas lo range inner list not 2d
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=[[6.695e9] for i in range(self.num_qubits)],
)
# qubit lo out of range
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=[[5.005e9, 5.010e9] for i in range(self.num_qubits)],
meas_lo_range=meas_lo_range,
)
# meas lo out of range
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=[[6.705e9, 6.710e9] for i in range(self.num_qubits)],
)
def test_job_qubit_meas_los_w_range(self):
"""Test that adding job qubit/meas lo freq lists are assembled into the qobj.config, w/ lo
ranges input. Verify that lo ranges do not enter into the config."""
qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_qubit_lo_freq]
meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_meas_lo_freq]
qobj = assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=meas_lo_range,
)
# convert to ghz
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
self.assertNotIn("qubit_lo_range", qobj.config.to_dict())
self.assertNotIn("meas_lo_range", qobj.config.to_dict())
def test_assemble_single_circ_single_lo_config(self):
"""Test assembling a single circuit, with a single experiment level lo config."""
qobj = assemble(
self.circ,
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config,
)
self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
self.assertEqual(len(qobj.experiments), 1)
def test_assemble_single_circ_single_lo_config_dict(self):
"""Test assembling a single circuit, with a single experiment level lo config supplied as
dictionary."""
qobj = assemble(
self.circ,
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config_dict,
)
self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
self.assertEqual(len(qobj.experiments), 1)
def test_assemble_single_circ_multi_lo_config(self):
"""Test assembling a single circuit, with multiple experiment level lo configs (frequency
sweep).
"""
user_lo_config_dict2 = {
pulse.DriveChannel(1): 5.55e9,
pulse.MeasureChannel(1): 6.64e9,
pulse.DriveChannel(4): 4.91e9,
pulse.MeasureChannel(3): 6.1e9,
}
user_lo_config2 = pulse.LoConfig(user_lo_config_dict2)
qobj = assemble(
self.circ,
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, user_lo_config2],
)
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertListEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertListEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
self.assertEqual(len(qobj.experiments), 2)
# experiment 0 los
self.assertEqual(qobj.experiments[0].config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertEqual(qobj.experiments[0].config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
# experiment 1 los
self.assertEqual(qobj.experiments[1].config.qubit_lo_freq, [5, 5.55, 5, 5, 4.91])
self.assertEqual(qobj.experiments[1].config.meas_lo_freq, [6.7, 6.64, 6.7, 6.1, 6.7])
def test_assemble_multi_circ_multi_lo_config(self):
"""Test assembling circuits, with the same number of experiment level lo configs (n:n
setup)."""
user_lo_config_dict2 = {
pulse.DriveChannel(1): 5.55e9,
pulse.MeasureChannel(1): 6.64e9,
pulse.DriveChannel(4): 4.91e9,
pulse.MeasureChannel(3): 6.1e9,
}
user_lo_config2 = pulse.LoConfig(user_lo_config_dict2)
qobj = assemble(
[self.circ, self.circ],
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, user_lo_config2],
)
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertListEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertListEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
self.assertEqual(len(qobj.experiments), 2)
# experiment 0 los
self.assertEqual(qobj.experiments[0].config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertEqual(qobj.experiments[0].config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
# experiment 1 los
self.assertEqual(qobj.experiments[1].config.qubit_lo_freq, [5, 5.55, 5, 5, 4.91])
self.assertEqual(qobj.experiments[1].config.meas_lo_freq, [6.7, 6.64, 6.7, 6.1, 6.7])
def test_assemble_multi_circ_single_lo_config(self):
"""Test assembling multiple circuits, with a single experiment level lo config (should
override job level)."""
qobj = assemble(
[self.circ, self.circ],
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config,
)
self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
self.assertEqual(len(qobj.experiments), 2)
def test_assemble_multi_circ_wrong_number_of_multi_lo_configs(self):
"""Test assembling circuits, with a different number of experiment level lo configs (n:m
setup).
"""
with self.assertRaises(QiskitError):
assemble(
[self.circ, self.circ, self.circ],
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
)
def test_assemble_circ_lo_config_errors(self):
"""Test that lo config errors are raised properly if experiment level los are provided and
some are missing or if default values are not provided. Also check that experiment level lo
range is validated."""
# no defaults, but have drive/meas experiment level los for each qubit (no error)
full_lo_config_dict = {
pulse.DriveChannel(0): 4.85e9,
pulse.DriveChannel(1): 4.9e9,
pulse.DriveChannel(2): 4.95e9,
pulse.DriveChannel(3): 5e9,
pulse.DriveChannel(4): 5.05e9,
pulse.MeasureChannel(0): 6.8e9,
pulse.MeasureChannel(1): 6.85e9,
pulse.MeasureChannel(2): 6.9e9,
pulse.MeasureChannel(3): 6.95e9,
pulse.MeasureChannel(4): 7e9,
}
qobj = assemble(self.circ, self.backend, schedule_los=full_lo_config_dict)
self.assertListEqual(qobj.config.qubit_lo_freq, [4.85, 4.9, 4.95, 5, 5.05])
self.assertListEqual(qobj.config.meas_lo_freq, [6.8, 6.85, 6.9, 6.95, 7])
self.assertEqual(len(qobj.experiments), 1)
# no defaults and missing experiment level drive lo raises
missing_drive_lo_config_dict = copy.deepcopy(full_lo_config_dict)
missing_drive_lo_config_dict.pop(pulse.DriveChannel(0))
with self.assertRaises(QiskitError):
qobj = assemble(self.circ, self.backend, schedule_los=missing_drive_lo_config_dict)
# no defaults and missing experiment level meas lo raises
missing_meas_lo_config_dict = copy.deepcopy(full_lo_config_dict)
missing_meas_lo_config_dict.pop(pulse.MeasureChannel(0))
with self.assertRaises(QiskitError):
qobj = assemble(self.circ, self.backend, schedule_los=missing_meas_lo_config_dict)
# verify lo ranges are checked at experiment level
lo_values = list(full_lo_config_dict.values())
qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in lo_values[:5]]
meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in lo_values[5:]]
# out of range drive lo
full_lo_config_dict[pulse.DriveChannel(0)] -= 5.5e6
with self.assertRaises(QiskitError):
qobj = assemble(
self.circ,
self.backend,
qubit_lo_range=qubit_lo_range,
schedule_los=full_lo_config_dict,
)
full_lo_config_dict[pulse.DriveChannel(0)] += 5.5e6 # reset drive value
# out of range meas lo
full_lo_config_dict[pulse.MeasureChannel(0)] += 5.5e6
with self.assertRaises(QiskitError):
qobj = assemble(
self.circ,
self.backend,
meas_lo_range=meas_lo_range,
schedule_los=full_lo_config_dict,
)
class TestPulseAssembler(QiskitTestCase):
"""Tests for assembling schedules to qobj."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.backend_config = self.backend.configuration()
test_pulse = pulse.Waveform(
samples=np.array([0.02739068, 0.05, 0.05, 0.05, 0.02739068], dtype=np.complex128),
name="pulse0",
)
self.schedule = pulse.Schedule(name="fake_experiment")
self.schedule = self.schedule.insert(0, Play(test_pulse, self.backend_config.drive(0)))
for i in range(self.backend_config.n_qubits):
self.schedule = self.schedule.insert(
5, Acquire(5, self.backend_config.acquire(i), MemorySlot(i))
)
self.user_lo_config_dict = {self.backend_config.drive(0): 4.91e9}
self.user_lo_config = pulse.LoConfig(self.user_lo_config_dict)
self.default_qubit_lo_freq = [4.9e9, 5.0e9]
self.default_meas_lo_freq = [6.5e9, 6.6e9]
self.config = {"meas_level": 1, "memory_slot_size": 100, "meas_return": "avg"}
self.header = {"backend_name": "FakeOpenPulse2Q", "backend_version": "0.0.0"}
def test_assemble_adds_schedule_metadata_to_experiment_header(self):
"""Verify that any circuit metadata is added to the exeriment header."""
self.schedule.metadata = {"experiment_type": "gst", "execution_number": "1234"}
qobj = assemble(
self.schedule,
shots=100,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
)
self.assertEqual(
qobj.experiments[0].header.metadata,
{"experiment_type": "gst", "execution_number": "1234"},
)
def test_assemble_sample_pulse(self):
"""Test that the pulse lib and qobj instruction can be paired up."""
schedule = pulse.Schedule()
schedule += pulse.Play(
pulse.Waveform([0.1] * 16, name="test0"), pulse.DriveChannel(0), name="test1"
)
schedule += pulse.Play(
pulse.Waveform([0.1] * 16, name="test1"), pulse.DriveChannel(0), name="test2"
)
schedule += pulse.Play(
pulse.Waveform([0.5] * 16, name="test0"), pulse.DriveChannel(0), name="test1"
)
qobj = assemble(
schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
**self.config,
)
test_dict = qobj.to_dict()
experiment = test_dict["experiments"][0]
inst0_name = experiment["instructions"][0]["name"]
inst1_name = experiment["instructions"][1]["name"]
inst2_name = experiment["instructions"][2]["name"]
pulses = {}
for item in test_dict["config"]["pulse_library"]:
pulses[item["name"]] = item["samples"]
self.assertTrue(all(name in pulses for name in [inst0_name, inst1_name, inst2_name]))
# Their pulses are the same
self.assertEqual(inst0_name, inst1_name)
self.assertTrue(np.allclose(pulses[inst0_name], [0.1] * 16))
self.assertTrue(np.allclose(pulses[inst2_name], [0.5] * 16))
def test_assemble_single_schedule_without_lo_config(self):
"""Test assembling a single schedule, no lo config."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 1)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_multi_schedules_without_lo_config(self):
"""Test assembling schedules, no lo config."""
qobj = assemble(
[self.schedule, self.schedule],
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 2)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_single_schedule_with_lo_config(self):
"""Test assembling a single schedule, with a single lo config."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config,
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.91, 5.0])
self.assertEqual(len(test_dict["experiments"]), 1)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_single_schedule_with_lo_config_dict(self):
"""Test assembling a single schedule, with a single lo config supplied as dictionary."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config_dict,
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.91, 5.0])
self.assertEqual(len(test_dict["experiments"]), 1)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_single_schedule_with_multi_lo_configs(self):
"""Test assembling a single schedule, with multiple lo configs (frequency sweep)."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 2)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
self.assertDictEqual(test_dict["experiments"][0]["config"], {"qubit_lo_freq": [4.91, 5.0]})
def test_assemble_multi_schedules_with_multi_lo_configs(self):
"""Test assembling schedules, with the same number of lo configs (n:n setup)."""
qobj = assemble(
[self.schedule, self.schedule],
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 2)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
self.assertDictEqual(test_dict["experiments"][0]["config"], {"qubit_lo_freq": [4.91, 5.0]})
def test_assemble_multi_schedules_with_wrong_number_of_multi_lo_configs(self):
"""Test assembling schedules, with a different number of lo configs (n:m setup)."""
with self.assertRaises(QiskitError):
assemble(
[self.schedule, self.schedule, self.schedule],
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
**self.config,
)
def test_assemble_meas_map(self):
"""Test assembling a single schedule, no lo config."""
schedule = Schedule(name="fake_experiment")
schedule = schedule.insert(5, Acquire(5, AcquireChannel(0), MemorySlot(0)))
schedule = schedule.insert(5, Acquire(5, AcquireChannel(1), MemorySlot(1)))
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertIsInstance(qobj, PulseQobj)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2]],
)
self.assertIsInstance(qobj, PulseQobj)
def test_assemble_memory_slots(self):
"""Test assembling a schedule and inferring number of memoryslots."""
n_memoryslots = 10
# single acquisition
schedule = Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1)
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertEqual(qobj.config.memory_slots, n_memoryslots)
# this should be in experimental header as well
self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots)
# multiple acquisition
schedule = Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1)
)
schedule = schedule.insert(
10,
Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1)
),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertEqual(qobj.config.memory_slots, n_memoryslots)
# this should be in experimental header as well
self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots)
def test_assemble_memory_slots_for_schedules(self):
"""Test assembling schedules with different memory slots."""
n_memoryslots = [10, 5, 7]
schedules = []
for n_memoryslot in n_memoryslots:
schedule = Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslot - 1)
)
schedules.append(schedule)
qobj = assemble(
schedules,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertEqual(qobj.config.memory_slots, max(n_memoryslots))
self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots[0])
self.assertEqual(qobj.experiments[1].header.memory_slots, n_memoryslots[1])
self.assertEqual(qobj.experiments[2].header.memory_slots, n_memoryslots[2])
def test_pulse_name_conflicts(self):
"""Test that pulse name conflicts can be resolved."""
name_conflict_pulse = pulse.Waveform(
samples=np.array([0.02, 0.05, 0.05, 0.05, 0.02], dtype=np.complex128), name="pulse0"
)
self.schedule = self.schedule.insert(
1, Play(name_conflict_pulse, self.backend_config.drive(1))
)
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
**self.config,
)
self.assertNotEqual(qobj.config.pulse_library[0].name, qobj.config.pulse_library[1].name)
def test_pulse_name_conflicts_in_other_schedule(self):
"""Test two pulses with the same name in different schedule can be resolved."""
backend = FakeHanoi()
defaults = backend.defaults()
schedules = []
ch_d0 = pulse.DriveChannel(0)
for amp in (0.1, 0.2):
sched = Schedule()
sched += Play(gaussian(duration=100, amp=amp, sigma=30, name="my_pulse"), ch_d0)
sched += measure(qubits=[0], backend=backend) << 100
schedules.append(sched)
qobj = assemble(
schedules, qubit_lo_freq=defaults.qubit_freq_est, meas_lo_freq=defaults.meas_freq_est
)
# two user pulses and one measurement pulse should be contained
self.assertEqual(len(qobj.config.pulse_library), 3)
def test_assemble_with_delay(self):
"""Test that delay instruction is not ignored in assembly."""
delay_schedule = pulse.Delay(10, self.backend_config.drive(0))
delay_schedule += self.schedule
delay_qobj = assemble(delay_schedule, self.backend)
self.assertEqual(delay_qobj.experiments[0].instructions[0].name, "delay")
self.assertEqual(delay_qobj.experiments[0].instructions[0].duration, 10)
self.assertEqual(delay_qobj.experiments[0].instructions[0].t0, 0)
def test_delay_removed_on_acq_ch(self):
"""Test that delay instructions on acquire channels are skipped on assembly with times
shifted properly.
"""
delay0 = pulse.Delay(5, self.backend_config.acquire(0))
delay1 = pulse.Delay(7, self.backend_config.acquire(1))
sched0 = delay0
sched0 += self.schedule # includes ``Acquire`` instr
sched0 += delay1
sched1 = self.schedule # includes ``Acquire`` instr
sched1 += delay0
sched1 += delay1
sched2 = delay0
sched2 += delay1
sched2 += self.schedule # includes ``Acquire`` instr
delay_qobj = assemble([sched0, sched1, sched2], self.backend)
# check that no delay instrs occur on acquire channels
is_acq_delay = False
for exp in delay_qobj.experiments:
for instr in exp.instructions:
if instr.name == "delay" and "a" in instr.ch:
is_acq_delay = True
self.assertFalse(is_acq_delay)
# check that acquire instr are shifted from ``t0=5`` as needed
self.assertEqual(delay_qobj.experiments[0].instructions[1].t0, 10)
self.assertEqual(delay_qobj.experiments[0].instructions[1].name, "acquire")
self.assertEqual(delay_qobj.experiments[1].instructions[1].t0, 5)
self.assertEqual(delay_qobj.experiments[1].instructions[1].name, "acquire")
self.assertEqual(delay_qobj.experiments[2].instructions[1].t0, 12)
self.assertEqual(delay_qobj.experiments[2].instructions[1].name, "acquire")
def test_assemble_schedule_enum(self):
"""Test assembling a schedule with enum input values to assemble."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
meas_level=MeasLevel.CLASSIFIED,
meas_return=MeasReturnType.AVERAGE,
)
test_dict = qobj.to_dict()
self.assertEqual(test_dict["config"]["meas_return"], "avg")
self.assertEqual(test_dict["config"]["meas_level"], 2)
def test_assemble_parametric(self):
"""Test that parametric pulses can be assembled properly into a PulseQobj."""
amp = [0.5, 0.6, 1, 0.2]
angle = [np.pi / 2, 0.6, 0, 0]
sched = pulse.Schedule(name="test_parametric")
sched += Play(
pulse.Gaussian(duration=25, sigma=4, amp=amp[0], angle=angle[0]), DriveChannel(0)
)
sched += Play(
pulse.Drag(duration=25, amp=amp[1], angle=angle[1], sigma=7.8, beta=4), DriveChannel(1)
)
sched += Play(pulse.Constant(duration=25, amp=amp[2], angle=angle[2]), DriveChannel(2))
sched += (
Play(
pulse.GaussianSquare(duration=150, amp=amp[3], angle=angle[3], sigma=8, width=140),
MeasureChannel(0),
)
<< sched.duration
)
backend = FakeOpenPulse3Q()
backend.configuration().parametric_pulses = [
"gaussian",
"drag",
"gaussian_square",
"constant",
]
qobj = assemble(sched, backend)
self.assertEqual(qobj.config.pulse_library, [])
qobj_insts = qobj.experiments[0].instructions
self.assertTrue(all(inst.name == "parametric_pulse" for inst in qobj_insts))
self.assertEqual(qobj_insts[0].pulse_shape, "gaussian")
self.assertEqual(qobj_insts[1].pulse_shape, "drag")
self.assertEqual(qobj_insts[2].pulse_shape, "constant")
self.assertEqual(qobj_insts[3].pulse_shape, "gaussian_square")
self.assertDictEqual(
qobj_insts[0].parameters,
{"duration": 25, "sigma": 4, "amp": amp[0] * np.exp(1j * angle[0])},
)
self.assertDictEqual(
qobj_insts[1].parameters,
{"duration": 25, "sigma": 7.8, "amp": amp[1] * np.exp(1j * angle[1]), "beta": 4},
)
self.assertDictEqual(
qobj_insts[2].parameters, {"duration": 25, "amp": amp[2] * np.exp(1j * angle[2])}
)
self.assertDictEqual(
qobj_insts[3].parameters,
{"duration": 150, "sigma": 8, "amp": amp[3] * np.exp(1j * angle[3]), "width": 140},
)
self.assertEqual(
qobj.to_dict()["experiments"][0]["instructions"][0]["parameters"]["amp"],
amp[0] * np.exp(1j * angle[0]),
)
def test_assemble_parametric_unsupported(self):
"""Test that parametric pulses are translated to Waveform if they're not supported
by the backend during assemble time.
"""
sched = pulse.Schedule(name="test_parametric_to_sample_pulse")
sched += Play(
pulse.Drag(duration=25, amp=0.5, angle=-0.3, sigma=7.8, beta=4), DriveChannel(1)
)
sched += Play(pulse.Constant(duration=25, amp=1), DriveChannel(2))
backend = FakeOpenPulse3Q()
backend.configuration().parametric_pulses = ["something_extra"]
qobj = assemble(sched, backend)
self.assertNotEqual(qobj.config.pulse_library, [])
qobj_insts = qobj.experiments[0].instructions
self.assertFalse(hasattr(qobj_insts[0], "pulse_shape"))
def test_assemble_parametric_pulse_kwarg_with_backend_setting(self):
"""Test that parametric pulses respect the kwarg over backend"""
backend = FakeHanoi()
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.measure(0, 0)
with pulse.build(backend, name="x") as x_q0:
pulse.play(pulse.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
qc.add_calibration("x", (0,), x_q0)
qobj = assemble(qc, backend, parametric_pulses=["gaussian"])
self.assertEqual(qobj.config.parametric_pulses, ["gaussian"])
def test_assemble_parametric_pulse_kwarg_empty_list_with_backend_setting(self):
"""Test that parametric pulses respect the kwarg as empty list over backend"""
backend = FakeHanoi()
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.measure(0, 0)
with pulse.build(backend, name="x") as x_q0:
pulse.play(pulse.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
qc.add_calibration("x", (0,), x_q0)
qobj = assemble(qc, backend, parametric_pulses=[])
self.assertEqual(qobj.config.parametric_pulses, [])
def test_init_qubits_default(self):
"""Check that the init_qubits=None assemble option is passed on to the qobj."""
qobj = assemble(self.schedule, self.backend)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_true(self):
"""Check that the init_qubits=True assemble option is passed on to the qobj."""
qobj = assemble(self.schedule, self.backend, init_qubits=True)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_false(self):
"""Check that the init_qubits=False assemble option is passed on to the qobj."""
qobj = assemble(self.schedule, self.backend, init_qubits=False)
self.assertEqual(qobj.config.init_qubits, False)
def test_assemble_backend_rep_times_delays(self):
"""Check that rep_time and rep_delay are properly set from backend values."""
# use first entry from allowed backend values
rep_times = [2.0, 3.0, 4.0] # sec
rep_delay_range = [2.5e-3, 4.5e-3]
default_rep_delay = 3.0e-3
self.backend_config.rep_times = rep_times
setattr(self.backend_config, "rep_delay_range", rep_delay_range)
setattr(self.backend_config, "default_rep_delay", default_rep_delay)
# dynamic rep rates off
qobj = assemble(self.schedule, self.backend)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# dynamic rep rates on
setattr(self.backend_config, "dynamic_reprate_enabled", True)
# RuntimeWarning bc ``rep_time`` is specified`` when dynamic rep rates not enabled
with self.assertWarns(RuntimeWarning):
qobj = assemble(self.schedule, self.backend)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(qobj.config.rep_delay, default_rep_delay * 1e6)
def test_assemble_user_rep_time_delay(self):
"""Check that user runtime config rep_time and rep_delay work."""
# set custom rep_time and rep_delay in runtime config
rep_time = 200.0e-6
rep_delay = 2.5e-6
self.config["rep_time"] = rep_time
self.config["rep_delay"] = rep_delay
# dynamic rep rates off
# RuntimeWarning bc using ``rep_delay`` when dynamic rep rates off
with self.assertWarns(RuntimeWarning):
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_time * 1e6))
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# now remove rep_delay and enable dynamic rep rates
# RuntimeWarning bc using ``rep_time`` when dynamic rep rates are enabled
del self.config["rep_delay"]
setattr(self.backend_config, "dynamic_reprate_enabled", True)
with self.assertWarns(RuntimeWarning):
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_time * 1e6))
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# use ``default_rep_delay``
# ``rep_time`` comes from allowed backend rep_times
rep_times = [0.5, 1.0, 1.5] # sec
self.backend_config.rep_times = rep_times
setattr(self.backend_config, "rep_delay_range", [0, 3.0e-6])
setattr(self.backend_config, "default_rep_delay", 2.2e-6)
del self.config["rep_time"]
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(qobj.config.rep_delay, 2.2)
# use qobj ``default_rep_delay``
self.config["rep_delay"] = 1.5e-6
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(qobj.config.rep_delay, 1.5)
# use ``rep_delay`` outside of ``rep_delay_range
self.config["rep_delay"] = 5.0e-6
with self.assertRaises(QiskitError):
assemble(self.schedule, self.backend, **self.config)
def test_assemble_with_individual_discriminators(self):
"""Test that assembly works with individual discriminators."""
disc_one = Discriminator("disc_one", test_params=True)
disc_two = Discriminator("disc_two", test_params=False)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_discriminators = qobj.experiments[0].instructions[0].discriminators
self.assertEqual(len(qobj_discriminators), 2)
self.assertEqual(qobj_discriminators[0].name, "disc_one")
self.assertEqual(qobj_discriminators[0].params["test_params"], True)
self.assertEqual(qobj_discriminators[1].name, "disc_two")
self.assertEqual(qobj_discriminators[1].params["test_params"], False)
def test_assemble_with_single_discriminators(self):
"""Test that assembly works with both a single discriminator."""
disc_one = Discriminator("disc_one", test_params=True)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_discriminators = qobj.experiments[0].instructions[0].discriminators
self.assertEqual(len(qobj_discriminators), 1)
self.assertEqual(qobj_discriminators[0].name, "disc_one")
self.assertEqual(qobj_discriminators[0].params["test_params"], True)
def test_assemble_with_unequal_discriminators(self):
"""Test that assembly works with incorrect number of discriminators for
number of qubits."""
disc_one = Discriminator("disc_one", test_params=True)
disc_two = Discriminator("disc_two", test_params=False)
schedule = Schedule()
schedule += Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one)
schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two)
schedule += Acquire(5, AcquireChannel(2), MemorySlot(2))
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2]],
)
def test_assemble_with_individual_kernels(self):
"""Test that assembly works with individual kernels."""
disc_one = Kernel("disc_one", test_params=True)
disc_two = Kernel("disc_two", test_params=False)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_kernels = qobj.experiments[0].instructions[0].kernels
self.assertEqual(len(qobj_kernels), 2)
self.assertEqual(qobj_kernels[0].name, "disc_one")
self.assertEqual(qobj_kernels[0].params["test_params"], True)
self.assertEqual(qobj_kernels[1].name, "disc_two")
self.assertEqual(qobj_kernels[1].params["test_params"], False)
def test_assemble_with_single_kernels(self):
"""Test that assembly works with both a single kernel."""
disc_one = Kernel("disc_one", test_params=True)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_kernels = qobj.experiments[0].instructions[0].kernels
self.assertEqual(len(qobj_kernels), 1)
self.assertEqual(qobj_kernels[0].name, "disc_one")
self.assertEqual(qobj_kernels[0].params["test_params"], True)
def test_assemble_with_unequal_kernels(self):
"""Test that assembly works with incorrect number of discriminators for
number of qubits."""
disc_one = Kernel("disc_one", test_params=True)
disc_two = Kernel("disc_two", test_params=False)
schedule = Schedule()
schedule += Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one)
schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two)
schedule += Acquire(5, AcquireChannel(2), MemorySlot(2))
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2]],
)
def test_assemble_single_instruction(self):
"""Test assembling schedules, no lo config."""
inst = pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0))
self.assertIsInstance(assemble(inst, self.backend), PulseQobj)
def test_assemble_overlapping_time(self):
"""Test that assembly errors when qubits are measured in overlapping time."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1,
)
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
def test_assemble_meas_map_vs_insts(self):
"""Test that assembly errors when the qubits are measured in overlapping time
and qubits are not in the first meas_map list."""
schedule = Schedule()
schedule += Acquire(5, AcquireChannel(0), MemorySlot(0))
schedule += Acquire(5, AcquireChannel(1), MemorySlot(1))
schedule += Acquire(5, AcquireChannel(2), MemorySlot(2)) << 2
schedule += Acquire(5, AcquireChannel(3), MemorySlot(3)) << 2
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1, 2], [3]],
)
def test_assemble_non_overlapping_time_single_meas_map(self):
"""Test that assembly works when qubits are measured in non-overlapping
time within the same measurement map list."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)) << 5,
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
self.assertIsInstance(qobj, PulseQobj)
def test_assemble_disjoint_time(self):
"""Test that assembly works when qubits are in disjoint meas map sets."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1,
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 2], [1, 3]],
)
self.assertIsInstance(qobj, PulseQobj)
def test_assemble_valid_qubits(self):
"""Test that assembly works when qubits that are in the measurement map
is measured."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(2), MemorySlot(2)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(3), MemorySlot(3)),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2], [3]],
)
self.assertIsInstance(qobj, PulseQobj)
class TestPulseAssemblerMissingKwargs(QiskitTestCase):
"""Verify that errors are raised in case backend is not provided and kwargs are missing."""
def setUp(self):
super().setUp()
self.schedule = pulse.Schedule(name="fake_experiment")
self.backend = FakeOpenPulse2Q()
self.config = self.backend.configuration()
self.defaults = self.backend.defaults()
self.qubit_lo_freq = list(self.defaults.qubit_freq_est)
self.meas_lo_freq = list(self.defaults.meas_freq_est)
self.qubit_lo_range = self.config.qubit_lo_range
self.meas_lo_range = self.config.meas_lo_range
self.schedule_los = {
pulse.DriveChannel(0): self.qubit_lo_freq[0],
pulse.DriveChannel(1): self.qubit_lo_freq[1],
pulse.MeasureChannel(0): self.meas_lo_freq[0],
pulse.MeasureChannel(1): self.meas_lo_freq[1],
}
self.meas_map = self.config.meas_map
self.memory_slots = self.config.n_qubits
# default rep_time and rep_delay
self.rep_time = self.config.rep_times[0]
self.rep_delay = None
def test_defaults(self):
"""Test defaults work."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_missing_qubit_lo_freq(self):
"""Test error raised if qubit_lo_freq missing."""
with self.assertRaises(QiskitError):
assemble(
self.schedule,
qubit_lo_freq=None,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
def test_missing_meas_lo_freq(self):
"""Test error raised if meas_lo_freq missing."""
with self.assertRaises(QiskitError):
assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=None,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
def test_missing_memory_slots(self):
"""Test error is not raised if memory_slots are missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=None,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_missing_rep_time_and_delay(self):
"""Test qobj is valid if rep_time and rep_delay are missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=None,
rep_time=None,
rep_delay=None,
)
self.assertEqual(hasattr(qobj, "rep_time"), False)
self.assertEqual(hasattr(qobj, "rep_delay"), False)
def test_missing_meas_map(self):
"""Test that assembly still works if meas_map is missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=None,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_missing_lo_ranges(self):
"""Test that assembly still works if lo_ranges are missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=None,
meas_lo_range=None,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_unsupported_meas_level(self):
"""Test that assembly raises an error if meas_level is not supported"""
backend = FakeOpenPulse2Q()
backend.configuration().meas_levels = [1, 2]
with self.assertRaises(QiskitError):
assemble(
self.schedule,
backend,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_level=0,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
def test_single_and_deprecated_acquire_styles(self):
"""Test that acquires are identically combined with Acquires that take a single channel."""
backend = FakeOpenPulse2Q()
new_style_schedule = Schedule()
acq_dur = 1200
for i in range(2):
new_style_schedule += Acquire(acq_dur, AcquireChannel(i), MemorySlot(i))
deprecated_style_schedule = Schedule()
for i in range(2):
deprecated_style_schedule += Acquire(1200, AcquireChannel(i), MemorySlot(i))
# The Qobj IDs will be different
n_qobj = assemble(new_style_schedule, backend)
n_qobj.qobj_id = None
n_qobj.experiments[0].header.name = None
d_qobj = assemble(deprecated_style_schedule, backend)
d_qobj.qobj_id = None
d_qobj.experiments[0].header.name = None
self.assertEqual(n_qobj, d_qobj)
assembled_acquire = n_qobj.experiments[0].instructions[0]
self.assertEqual(assembled_acquire.qubits, [0, 1])
self.assertEqual(assembled_acquire.memory_slot, [0, 1])
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestLogAssembler(QiskitTestCase):
"""Testing the log_assembly option."""
def setUp(self):
super().setUp()
logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)
logger.setLevel("DEBUG")
self.output = io.StringIO()
logger.addHandler(StreamHandlerRaiseException(self.output))
self.circuit = QuantumCircuit(QuantumRegister(1))
def assertAssembleLog(self, log_msg):
"""Runs assemble and checks for logs containing specified message"""
assemble(self.circuit, shots=2000, memory=True)
self.output.seek(0)
# Filter unrelated log lines
output_lines = self.output.readlines()
assembly_log_lines = [x for x in output_lines if log_msg in x]
self.assertTrue(len(assembly_log_lines) == 1)
def test_assembly_log_time(self):
"""Check Total Assembly Time is logged"""
self.assertAssembleLog("Total Assembly Time")
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
import unittest
import sys
import math
from qiskit import QuantumCircuit, Aer, transpile, assemble, execute
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit.circuit.library import Barrier, HGate, XGate
from numpy.random import randint
import numpy as np
np.seterr(divide='ignore', invalid='ignore')
import hypothesis.strategies as st
from hypothesis import given, settings
def generate_binary(len):
return randint(2, size=len)
def encode_message(bits, bases, messageLen):
message = []
for i in range(messageLen):
qc = QuantumCircuit(1,1)
if bases[i] == 0: # Prepare qubit in Z-basis
if bits[i] == 0:
pass
else:
qc.x(0)
else: # Prepare qubit in X-basis
if bits[i] == 0:
qc.h(0)
else:
qc.x(0)
qc.h(0)
qc.barrier()
message.append(qc)
return message
def measure_message(message, bases, messageLen):
measurements = []
for q in range(messageLen):
if bases[q] == 0: # measuring in Z-basis
message[q].measure(0,0)
if bases[q] == 1: # measuring in X-basis
message[q].h(0)
message[q].measure(0,0)
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(message[q], shots=1, memory=True)
result = aer_sim.run(qobj).result()
measured_bit = int(result.get_memory()[0])
measurements.append(measured_bit)
return measurements
def remove_garbage(a_bases, b_bases, bits, messageLen):
good_bits = []
for q in range(messageLen):
if a_bases[q] == b_bases[q]:
# If both used the same basis, add
# this to the list of 'good' bits
good_bits.append(bits[q])
return good_bits
def sample_bits(bits, selection):
sample = []
for i in selection:
# use np.mod to make sure the
# bit we sample is always in
# the list range
i = np.mod(i, len(bits))
# pop(i) removes the element of the
# list at index 'i'
sample.append(bits.pop(i))
return sample
np.random.seed(seed=10)
messageLen = 100
## Step 1
# Alice generates bits
alice_bits = generate_binary(messageLen)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = generate_binary(messageLen)
message = encode_message(alice_bits, alice_bases, messageLen)
## Step 3
# Decide which basis to measure in:
bob_bases = generate_binary(messageLen)
bob_results = measure_message(message, bob_bases, messageLen)
## Step 4
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits, messageLen)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results, messageLen)
## Step 5
sample_size = 15
bit_selection = generate_binary(sample_size)
print(alice_key)
print(bob_key)
bob_sample = sample_bits(bob_key, bit_selection)
print(" bob_sample = " + str(bob_sample))
alice_sample = sample_bits(alice_key, bit_selection)
print("alice_sample = "+ str(alice_sample))
bob_sample == alice_sample
n = 100
# Step 1
alice_bits = generate_binary(messageLen)
alice_bases = generate_binary(messageLen)
# Step 2
message = encode_message(alice_bits, alice_bases, messageLen)
# Interception!
eve_bases = generate_binary(messageLen)
intercepted_message = measure_message(message, eve_bases, messageLen)
# Step 3
bob_bases = generate_binary(messageLen)
bob_results = measure_message(message, bob_bases, messageLen)
# Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results, messageLen)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits, messageLen)
# Step 5
sample_size = 1 # Change this to something lower and see if
# Eve can intercept the message without Alice
# and Bob finding out
bit_selection = generate_binary(sample_size)
bob_sample = sample_bits(bob_key, bit_selection)
alice_sample = sample_bits(alice_key, bit_selection)
if bob_sample != alice_sample:
print("Eve's interference was detected.")
else:
print("Eve went undetected!")
###########################################################################
## Define composite strategies to generate lists of ints in equal length ##
###########################################################################
@st.composite
def single_list(draw):
arrayLengths = draw(st.integers(min_value=1, max_value=100))
fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths)
return (draw(fixed_length_list))
@st.composite
def pair_of_lists(draw):
arrayLengths = draw(st.integers(min_value=1, max_value=100))
fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths)
return (draw(fixed_length_list), draw(fixed_length_list))
@st.composite
def trio_of_lists(draw):
arrayLengths = draw(st.integers(min_value=1, max_value=100))
fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths)
return (draw(fixed_length_list), draw(fixed_length_list), draw(fixed_length_list))
@st.composite
def long_trio_of_lists(draw):
arrayLengths = draw(st.integers(min_value=100, max_value=110))
fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths)
return (draw(fixed_length_list), draw(fixed_length_list), draw(fixed_length_list))
##########################
## test generate binary ##
##########################
@given(testLength = st.integers(min_value=0, max_value=10000))
def test_created_message_is_binary(testLength):
binArr = generate_binary(testLength)
for i in binArr:
assert (i == 1 or i == 0)
@given(testLength = st.integers(min_value=1, max_value=10000))
def test_created_message_equal_length_to_int_passed_in(testLength):
binArr = generate_binary(testLength)
assert(len(binArr) == testLength)
############################
## encoding message tests ##
############################
@given(pair_of_lists())
@settings(deadline=None)
def test_encode_message_equal_length_to_base(lists):
alice_bits, alice_bases = lists
circuitArr = encode_message(alice_bits, alice_bases, len(alice_bits))
assert(len(circuitArr) == len(alice_bits))
############################
## decoding message tests ##
############################
@given(lists = trio_of_lists())
@settings(deadline=None)
def test_decode_message_length_equals_base_length(lists):
alice_bits, alice_bases, bob_base = lists
encoded_message = encode_message(alice_bits, alice_bases, len(bob_base))
msmtArr = measure_message(encoded_message, bob_base, len(bob_base))
assert len(msmtArr) == len(bob_base)
@given(lists = trio_of_lists())
@settings(deadline=None)
def test_decode_message_is_binary(lists):
alice_bits, alice_bases, bob_base = lists
encoded_message = encode_message(alice_bits, alice_bases, len(bob_base))
msmtArr = measure_message(encoded_message, bob_base, len(bob_base))
for i in msmtArr:
assert (i == 1 or i == 0)
@given(lists = pair_of_lists())
@settings(deadline=None)
def test_decode_with_same_base_returns_original_bits(lists):
alice_bits, alice_bases = lists
encoded_message = encode_message(alice_bits, alice_bases, len(alice_bits))
decodeWithSameBases = measure_message(encoded_message, alice_bases, len(alice_bases))
assert(np.array_equal(np.array(alice_bits), np.array(decodeWithSameBases)))
@given(lists = pair_of_lists())
@settings(deadline=None)
def test_decode_with_same_bases_return_same_array(lists):
alice_bits, alice_bases = lists
encoded_message = encode_message(alice_bits, alice_bases, len(alice_bits))
encoded_message2 = encode_message(alice_bits, alice_bases, len(alice_bits))
decodeWithSameBases = measure_message(encoded_message, alice_bases, len(alice_bases))
decodeWithSameBases2 = measure_message(encoded_message2, alice_bases, len(alice_bases))
assert(np.array_equal(np.array(decodeWithSameBases), np.array(decodeWithSameBases2)))
@given(lists = long_trio_of_lists())
@settings(deadline=None)
def test_decoding_runs_likely_different(lists):
alice_bits, alice_bases, bob_base = lists
encoded_message = encode_message(alice_bits, alice_bases, len(bob_base))
msmtArr = measure_message(encoded_message, alice_bases, len(alice_bases))
msmtArrRun2 = measure_message(encoded_message, bob_bases, len(bob_base))
assert(not np.array_equal(np.array(msmtArr), np.array(msmtArrRun2)))
##############################
## remove garbage/key tests ##
##############################
@given(lists = trio_of_lists())
@settings(deadline=None)
def test_key_smaller_or_equal_len_to_original_bits(lists):
alice_bits, alice_bases, bob_base = lists
assert len(remove_garbage(alice_bits, alice_bases, bob_base, len(bob_base))) <= len(bob_base)
@given(lists = trio_of_lists())
@settings(deadline=None)
def test_check_keys_equal(lists):
alice_bits, alice_bases, bob_bases = lists
message = encode_message(alice_bits, alice_bases, len(bob_bases))
bob_results = measure_message(message, bob_bases, len(bob_bases))
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits, len(bob_bases))
bob_key = remove_garbage(alice_bases, bob_bases, bob_results, len(bob_bases))
assert(np.array_equal(np.array(alice_key), np.array(bob_key)))
@given(lists = trio_of_lists())
@settings(deadline=None)
def test_key_is_binary(lists):
alice_bits, alice_bases, bob_bases = lists
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits, len(bob_bases))
for i in alice_key:
assert (i == 1 or i == 0)
@given(pair_of_lists())
@settings(deadline=None, max_examples=10)
def test_encode_message_applies_correct_phase(lists):
backend = Aer.get_backend('aer_simulator')
alice_bits, alice_bases = lists
circuitArr = encode_message(alice_bits, alice_bases, len(alice_bits))
for idx, base in enumerate(alice_bases):
if (base == 0):
if(alice_bits[idx] == 0):
print("no assert")
else:
print("no assert")
else:
if(alice_bits[idx] == 0):
assertPhase(backend, circuitArr[idx], [0], [0], 100000, 0.0001)
else:
assertPhase(backend, circuitArr[idx], [0], [180], 100000, 0.0001)
if __name__ == "__main__":
# test_created_message_is_binary()
# test_created_message_equal_length_to_int_passed_in()
# test_encode_message_equal_length_to_base()
# test_decode_message_length_equals_base_length()
# test_decode_message_is_binary()
# test_decode_with_same_base_returns_original_bits()
# test_decode_with_same_bases_return_same_array()
#test_decoding_runs_likely_different()
# test_key_smaller_or_equal_len_to_original_bits()
# test_check_keys_equal()
# test_key_is_binary()
#test_encode_message_applies_correct_phase()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the ResetAfterMeasureSimplification pass"""
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.circuit.classicalregister import Clbit
from qiskit.transpiler.passes.optimization import ResetAfterMeasureSimplification
from qiskit.test import QiskitTestCase
class TestResetAfterMeasureSimplificationt(QiskitTestCase):
"""Test ResetAfterMeasureSimplification transpiler pass."""
def test_simple(self):
"""Test simple"""
qc = QuantumCircuit(1, 1)
qc.measure(0, 0)
qc.reset(0)
new_qc = ResetAfterMeasureSimplification()(qc)
ans_qc = QuantumCircuit(1, 1)
ans_qc.measure(0, 0)
ans_qc.x(0).c_if(ans_qc.clbits[0], 1)
self.assertEqual(new_qc, ans_qc)
def test_simple_null(self):
"""Test simple no change in circuit"""
qc = QuantumCircuit(1, 1)
qc.measure(0, 0)
qc.x(0)
qc.reset(0)
new_qc = ResetAfterMeasureSimplification()(qc)
self.assertEqual(new_qc, qc)
def test_simple_multi_reg(self):
"""Test simple, multiple registers"""
cr1 = ClassicalRegister(1, "c1")
cr2 = ClassicalRegister(1, "c2")
qr = QuantumRegister(1, "q")
qc = QuantumCircuit(qr, cr1, cr2)
qc.measure(0, 1)
qc.reset(0)
new_qc = ResetAfterMeasureSimplification()(qc)
ans_qc = QuantumCircuit(qr, cr1, cr2)
ans_qc.measure(0, 1)
ans_qc.x(0).c_if(cr2[0], 1)
self.assertEqual(new_qc, ans_qc)
def test_simple_multi_reg_null(self):
"""Test simple, multiple registers, null change"""
cr1 = ClassicalRegister(1, "c1")
cr2 = ClassicalRegister(1, "c2")
qr = QuantumRegister(2, "q")
qc = QuantumCircuit(qr, cr1, cr2)
qc.measure(0, 1)
qc.reset(1) # reset not on same qubit as meas
new_qc = ResetAfterMeasureSimplification()(qc)
self.assertEqual(new_qc, qc)
def test_simple_multi_resets(self):
"""Only first reset is collapsed"""
qc = QuantumCircuit(1, 2)
qc.measure(0, 0)
qc.reset(0)
qc.reset(0)
new_qc = ResetAfterMeasureSimplification()(qc)
ans_qc = QuantumCircuit(1, 2)
ans_qc.measure(0, 0)
ans_qc.x(0).c_if(ans_qc.clbits[0], 1)
ans_qc.reset(0)
self.assertEqual(new_qc, ans_qc)
def test_simple_multi_resets_with_resets_before_measure(self):
"""Reset BEFORE measurement not collapsed"""
qc = QuantumCircuit(2, 2)
qc.measure(0, 0)
qc.reset(0)
qc.reset(1)
qc.measure(1, 1)
new_qc = ResetAfterMeasureSimplification()(qc)
ans_qc = QuantumCircuit(2, 2)
ans_qc.measure(0, 0)
ans_qc.x(0).c_if(Clbit(ClassicalRegister(2, "c"), 0), 1)
ans_qc.reset(1)
ans_qc.measure(1, 1)
self.assertEqual(new_qc, ans_qc)
def test_barriers_work(self):
"""Test that barriers block consolidation"""
qc = QuantumCircuit(1, 1)
qc.measure(0, 0)
qc.barrier(0)
qc.reset(0)
new_qc = ResetAfterMeasureSimplification()(qc)
self.assertEqual(new_qc, qc)
def test_bv_circuit(self):
"""Test Bernstein Vazirani circuit with midcircuit measurement."""
bitstring = "11111"
qc = QuantumCircuit(2, len(bitstring))
qc.x(1)
qc.h(1)
for idx, bit in enumerate(bitstring[::-1]):
qc.h(0)
if int(bit):
qc.cx(0, 1)
qc.h(0)
qc.measure(0, idx)
if idx != len(bitstring) - 1:
qc.reset(0)
# reset control
qc.reset(1)
qc.x(1)
qc.h(1)
new_qc = ResetAfterMeasureSimplification()(qc)
for op in new_qc.data:
if op.operation.name == "reset":
self.assertEqual(op.qubits[0], new_qc.qubits[1])
def test_simple_if_else(self):
"""Test that the pass recurses into an if-else."""
pass_ = ResetAfterMeasureSimplification()
base_test = QuantumCircuit(1, 1)
base_test.measure(0, 0)
base_test.reset(0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
base_expected.x(0).c_if(0, True)
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_ = ResetAfterMeasureSimplification()
base_test = QuantumCircuit(1, 1)
base_test.measure(0, 0)
base_test.reset(0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
base_expected.x(0).c_if(0, True)
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)
|
https://github.com/PayalSolanki2906/Quantum_algorithms_using_Qiskit
|
PayalSolanki2906
|
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
qc=QuantumCircuit(4,2) ## for adder we need four quantum register and 2 classical register
qc.barrier()
# use cnots to write the XOR of the inputs on qubit 2
qc.cx(0,2)
qc.cx(1,2)
qc.ccx(0,1,3)
qc.barrier()
# extract outputs
qc.measure(2,0) # extract XOR value
qc.measure(3,1)
qc.draw()
from qiskit import Aer
sim = Aer.get_backend('aer_simulator')
from qiskit import assemble
qobj = assemble(qc)
counts = sim.run(qobj).result().get_counts()
plot_histogram(counts)
from qiskit import QuantumCircuit
qc1=QuantumCircuit(4,2) ## for adder we need four quantum register and 2 classical register
qc1.x(1)
qc1.barrier()
# use cnots to write the XOR of the inputs on qubit 2
qc1.cx(0,2)
qc1.cx(1,2)
qc1.ccx(0,1,3)
qc1.barrier()
# extract outputs
qc1.measure(2,0) # extract XOR value
qc1.measure(3,1)
qc1.draw()
from qiskit import Aer
sim = Aer.get_backend('aer_simulator')
from qiskit import assemble
qobj = assemble(qc1)
counts = sim.run(qobj).result().get_counts()
plot_histogram(counts)
from qiskit import QuantumCircuit
qc2=QuantumCircuit(4,2) ## for adder we need four quantum register and 2 classical register
qc2.x(0)
qc2.barrier()
# use cnots to write the XOR of the inputs on qubit 2
qc2.cx(0,2)
qc2.cx(1,2)
qc2.ccx(0,1,3)
qc2.barrier()
# extract outputs
qc2.measure(2,0) # extract XOR value
qc2.measure(3,1)
qc2.draw()
from qiskit import Aer
sim = Aer.get_backend('aer_simulator')
from qiskit import assemble
qobj = assemble(qc2)
counts = sim.run(qobj).result().get_counts()
plot_histogram(counts)
from qiskit import QuantumCircuit
qc3=QuantumCircuit(4,2) ## for adder we need four quantum register and 2 classical register
qc3.x(0)
qc3.x(1)
qc3.barrier()
# use cnots to write the XOR of the inputs on qubit 2
qc3.cx(0,2)
qc3.cx(1,2)
qc3.ccx(0,1,3)
qc3.barrier()
# extract outputs
qc3.measure(2,0) # extract XOR value
qc3.measure(3,1)
qc3.draw()
from qiskit import Aer
sim = Aer.get_backend('aer_simulator')
from qiskit import assemble
qobj = assemble(qc3)
counts = sim.run(qobj).result().get_counts()
plot_histogram(counts)
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
from IPython.display import IFrame
IFrame(src="https://www.youtube.com/embed/yuDxHJOKsVA", width=1920/2, height=1080/2)
from qiskit import *
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# let's create a circuit
n_qubits = 3
n_bits = 3
qc = QuantumCircuit(n_qubits, n_bits)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 2)
qc.measure([0,1,2], [0,1,2])
qc.draw('mpl')
# let's try to find what we have measured by simulating our circuit
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend=simulator, shots=1024).result()
plot_histogram(result.get_counts(qc))
## let's run this circuit on the real ibm quantum computer
IBMQ.load_account()
provider = IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmqx2')
job = execute(qc, backend=qcomp, shots=1024)
job_monitor(job)
job_result = qcomp.result()
plot_histogram(qcomp.get_counts(qc))
# lets calibrate the measurement error using ignis
cal_circuits, state_labels = complete_meas_cal(qr=qc.qregs[0],
circlabel='measurement_calibration')
cal_circuits[7].draw(output='mpl')
cal_job = execute(cal_circuits,
backend=qcomp,
shots=8192,
optimization_level=0)
#print(cal_job.job_id())
job_monitor(cal_job)
cal_results = cal_job.result()
plot_histogram(cal_results.get_counts(cal_circuits[3]))
# Creating the Measurement Fitter Object in Ignis
meas_fitter = CompleteMeasFitter(cal_results, state_labels)
meas_fitter.plot_calibration()
# Mitigating the measurement errors in our previous device run
meas_filter = meas_fitter.filter
mitigated_result = meas_filter.apply(device_result)
device_counts = device_result.get_counts(qc)
mitigated_counts = mitigated_result.get_counts(qc)
plot_histogram([device_counts, mitigated_counts],
legend=['device, noisy', 'device, mitigated'])
# Running error mitigation on a second circuit
circuit2 = QuantumCircuit(3,3)
circuit2.x(1)
circuit2.h(0)
circuit2.cx(0,1)
circuit2.cx(1,2)
circuit2.measure([0,1,2], [0,1,2])
circuit2.draw(output='mpl')
plot_histogram(
execute(circuit2, backend=simulator, shots=1024).result().get_counts(circuit2)
)
device_counts_2 = execute(circuit2, backend=qcomp, shots=1024).result().get_counts(circuit2)
plot_histogram(device_counts_2)
mitigated_counts_2 = meas_filter.apply(device_counts_2)
plot_histogram([device_counts_2, mitigated_counts_2], legend=['device, noisy','device, mitigated'])
|
https://github.com/Zhaoyilunnn/qdao
|
Zhaoyilunnn
|
from qiskit import transpile
from qiskit.circuit.random import random_circuit
from qiskit_aer import Aer
from qdao import Engine
num_qubits = 12
num_primary = 10
num_local = 8
# Create a qiskit quantum circuit `circ`
circ = random_circuit(num_qubits, 10, measure=False, max_operands=2)
backend = Aer.get_backend("aer_simulator")
circ = transpile(circ, backend=backend)
# `num_primary`: size of a compute unit
# `num_local`: size of a storage unit
eng = Engine(circuit=circ, num_primary=num_primary, num_local=num_local)
eng.run()
# First transform qiskit circuit to a quafu circuit
from quafu import QuantumCircuit
quafu_circ = QuantumCircuit(1)
# For qiskit >= 1.0, `qasm()` api has been deprecated.
from qiskit.qasm2 import dumps
quafu_circ.from_openqasm(dumps(circ))
# For qiskit < 1.0
# quafu_circ.from_openqasm(circ.qasm())
# Create a new engine using quafu backend
eng = Engine(
circuit=quafu_circ, num_primary=num_primary, num_local=num_local, backend="quafu"
)
eng.run()
from qdao.util import retrieve_sv
res = retrieve_sv(num_qubits, num_local=num_local)
print(res)
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Unit-testing linear_function_collection"""
import pytest
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.collection import CollectLinearFunctions
def test_lf_collection_pass(random_circuit_transpiled):
collect = PassManager(
[
CollectLinearFunctions(),
]
)
collected_circuit = collect.run(random_circuit_transpiled)
assert isinstance(collected_circuit, QuantumCircuit)
def test_lf_collection_pass_collect(cnot_circ):
collect = PassManager(
[
CollectLinearFunctions(min_block_size=1, max_block_size=5),
]
)
collected_circuit = collect.run(cnot_circ)
assert isinstance(collected_circuit, QuantumCircuit)
assert any(g.operation.name.lower() == "linear_function" for g in collected_circuit)
def test_lf_collection_pass_no_collect(rzz_circ):
collect = PassManager(
[
CollectLinearFunctions(min_block_size=7, max_block_size=12),
]
)
collected_circuit = collect.run(rzz_circ)
assert all(g.operation.name.lower() != "linear_function" for g in collected_circuit)
def test_lf_collection_max_block_size(cnot_circ):
collect = PassManager(
[
CollectLinearFunctions(max_block_size=7),
]
)
collected_circuit = collect.run(cnot_circ)
assert all(len(g.qubits) <= 7 for g in collected_circuit)
def test_lf_collection_min_block_size(cnot_circ):
collect = PassManager(
[
CollectLinearFunctions(min_block_size=7, max_block_size=12),
]
)
collected_circuit = collect.run(cnot_circ)
assert all(
len(g.qubits) >= 7 or g.operation.name.lower() != "linear_function"
for g in collected_circuit
)
@pytest.mark.timeout(10)
def test_collection_with_barrier(cnot_circ):
cnot_circ.measure_all()
collect = PassManager(
[
CollectLinearFunctions(min_block_size=7, max_block_size=12),
]
)
# Without proper handling this test timeouts (actually the collect runs forever)
collect.run(cnot_circ)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can show the phase of each state and use
# degrees instead of radians
from qiskit.quantum_info import DensityMatrix
import numpy as np
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
qc.z(1)
matrix = DensityMatrix(qc)
plot_state_qsphere(matrix,
show_state_phases = True, use_degrees = True)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.h(1)
custom = qc1.to_gate().control(2)
qc2 = QuantumCircuit(4)
qc2.append(custom, [0, 3, 1, 2])
qc2.draw('mpl')
|
https://github.com/GabrielPontolillo/QiskitPBT
|
GabrielPontolillo
|
# class that inherits from property based test
import numpy as np
from qiskit import QuantumCircuit
from QiskitPBT.property import Property
from QiskitPBT.input_generators.random_pauli_basis_state import RandomPauliBasisState
from QiskitPBT.case_studies.quantum_fourier_transform.quantum_fourier_transform import qft_general
class LinearShiftToPhaseShift(Property):
# specify the inputs that are to be generated
def get_input_generators(self):
state = RandomPauliBasisState(1, 5, tuple("z"))
return [state]
# specify the preconditions for the test
def preconditions(self, state):
return True
# specify the operations to be performed on the input
def operations(self, state):
n = state.num_qubits
qft_1 = QuantumCircuit(n, n)
qft_1.initialize(state, reversed(range(n)))
qft_1 = qft_1.compose(qft_general(n, swap=False))
qft_1 = phase_shift(qft_1)
init_state = state.data
# make the first element the last element, and vice versa
shifted_vector = np.roll(init_state, -1)
qft_2 = QuantumCircuit(n, n)
qft_2.initialize(shifted_vector, reversed(range(n)))
qft_2 = qft_2.compose(qft_general(n, swap=False))
self.statistical_analysis.assert_equal(self, list(range(n)), qft_1, list(range(n)), qft_2)
def phase_shift(qc):
for i in range(qc.num_qubits):
qc.p(-np.pi / 2 ** (qc.num_qubits - 1 - i), i)
return qc
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.