repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
"""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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
"""The following is python code utilizing the qiskit library that can be run on extant quantum hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding, for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1, results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>). To find the factor, use the equivalence a^r mod 15. From this: (a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15 Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients, gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15, so the result of running shors algorithm to find the prime factors of an integer using quantum hardware are demonstrated. Note, this is not the same as the technical implementation of shor's algorithm described in this section for breaking the discrete log hardness assumption, though the proof of concept remains.""" # Import libraries from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from numpy import pi from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram # Initialize qubit registers qreg_q = QuantumRegister(5, 'q') creg_c = ClassicalRegister(5, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.reset(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.reset(qreg_q[2]) circuit.reset(qreg_q[3]) circuit.reset(qreg_q[4]) # Apply Hadamard transformations to qubit registers circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) # Apply first QFT, modular exponentiation, and another QFT circuit.h(qreg_q[1]) circuit.cx(qreg_q[2], qreg_q[3]) circuit.crx(pi/2, qreg_q[0], qreg_q[1]) circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) # Run the circuit on available quantum hardware and plot histogram from qiskit.tools.monitor import job_monitor job = execute(circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(circuit) plot_histogram(answer) #largest amplitude results correspond with r values used to find the prime factor of N.
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Quantum teleportation example. Note: if you have only cloned the Qiskit repository but not used `pip install`, the examples only work from the root directory. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]] backend = BasicAer.get_backend("qasm_simulator") ############################################################### # Make a quantum program for quantum teleportation. ############################################################### q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2, name="teleport") # Prepare an initial state qc.u(0.3, 0.2, 0.1, q[0]) # Prepare a Bell pair qc.h(q[1]) qc.cx(q[1], q[2]) # Barrier following state preparation qc.barrier(q) # Measure in the Bell basis qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) # Apply a correction qc.barrier(q) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.measure(q[2], c2[0]) ############################################################### # Execute. # Experiment does not support feedback, so we use the simulator ############################################################### # First version: not mapped initial_layout = {q[0]: 0, q[1]: 1, q[2]: 2} job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph job = execute( qc, backend=backend, coupling_map=coupling_map, shots=1024, initial_layout=initial_layout ) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import numpy as np from qiskit import * import matplotlib qr = QuantumRegister(2) #measurements from quantum bits = use classical register cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.draw() # adding quantum gates to create entanglement (Hadamart gate) circuit.h(qr[0]) %matplotlib inline circuit.draw(output='mpl') #two qubit operation control X (logical if) circuit.cx(qr[0], qr[1]) circuit.draw(output='mpl') #entanglement achieved #measurement, storing measurements into computational register circuit.measure(qr,cr) circuit.draw(output='mpl') #performance simulations simulator = Aer.get_backend('qasm_simulator') execute(circuit, backend = simulator) result = execute(circuit, backend = simulator).result() #plotting results from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) #running circuit on quantum computer IBMQ.load_account() provider= IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_manila') job= execute(circuit, backend=qcomp) from qiskit.tools import job_monitor job_monitor(job) result = job.result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit), title='Performance metric on Quantum Computer')
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * backend = BasicAer.get_backend('dm_simulator') qc1 = QuantumCircuit(1) options1 = { 'custom_densitymatrix': 'max_mixed' } run1 = execute(qc1,backend,**options1) result1 = run1.result() print('Density Matrix: \n',result1['results'][0]['data']['densitymatrix']) qc2 = QuantumCircuit(2) options2 = { 'custom_densitymatrix': 'binary_string', 'initial_densitymatrix': '01' } backend = BasicAer.get_backend('dm_simulator') run2 = execute(qc2,backend,**options2) result2 = run2.result() print('Density Matrix: \n',result2['results'][0]['data']['densitymatrix'])
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * import numpy as np %matplotlib inline qc = QuantumCircuit(1,1) qc.s(0) qc.measure(0,0,basis='X') backend = BasicAer.get_backend('dm_simulator') run = execute(qc,backend) result = run.result() result['results'][0]['data']['densitymatrix'] qc1 = QuantumCircuit(1,1) qc1.s(0) qc1.measure(0,0, basis='N', add_param=np.array([1,2,3])) backend = BasicAer.get_backend('dm_simulator') run1 = execute(qc1,backend) result1 = run1.result() result1['results'][0]['data']['densitymatrix'] qc2 = QuantumCircuit(3,2) qc2.measure(0,0,basis='Bell',add_param='01') options2 = { 'plot': True } backend = BasicAer.get_backend('dm_simulator') run2 = execute(qc2,backend,**options2) result2 = run2.result() result2['results'][0]['data']['bell_probabilities01'] qc3 = QuantumCircuit(3,3) qc3.h(0) qc3.cx(0,1) qc3.cx(1,2) qc3.measure(0,0,basis='Ensemble',add_param='X') backend = BasicAer.get_backend('dm_simulator') options3 = { 'plot': True } run3 = execute(qc3,backend,**options3) result3 = run3.result() result3['results'][0]['data']['ensemble_probability'] qc4 = QuantumCircuit(3,3) qc4.h(0) qc4.cx(0,1) qc4.cx(1,2) qc4.measure(0,0,basis='Expect',add_param='ZIZ') backend = BasicAer.get_backend('dm_simulator') run4 = execute(qc4,backend) result4 = run4.result() result4['results'][0]['data']['Pauli_string_expectation']
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * %matplotlib inline import matplotlib.pyplot as plt # The Circuit q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q,c) qc.u1(3.6,0) qc.cx(0,1) qc.u1(2.6,2) qc.cx(1,0) qc.s(2) qc.y(2) qc.measure(q,c,basis='Ensemble',add_param='Z') backend = BasicAer.get_backend('dm_simulator') # Noise parameters options = {} options1 = { "thermal_factor": 0., "decoherence_factor": .9, "depolarization_factor": 0.99, "bell_depolarization_factor": 0.99, "decay_factor": 0.99, "rotation_error": {'rx':[1., 0.], 'ry':[1., 0.], 'rz': [1., 0.]}, "tsp_model_error": [1., 0.], "plot": False } # Execution with and without noise run = execute(qc,backend,**options) result = run.result() run_error = execute(qc,backend,**options1) result_error = run_error.result() # Final state (probabilities) prob = result['results'][0]['data']['ensemble_probability'] prob1 = result_error['results'][0]['data']['ensemble_probability'] import numpy as np labels = prob1.keys() without_noise = prob.values() with_noise = prob1.values() x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, without_noise, width, label='Without Noise') rects2 = ax.bar(x + width/2, with_noise, width, label='With Noise') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Probability') ax.set_title('Ensemble Probabilities with Noise') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.show()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import numpy as np from qiskit_aqua import Operator, run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import partition from qiskit import Aer from qiskit_aqua.algorithms.classical.cplex.cplex_ising import CPLEX_Ising number_list = partition.read_numbers_from_file('sample.partition') qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input = EnergyInput(qubitOp) print(number_list) if True: np.random.seed(8123179) number_list = partition.random_number_list(5, weight_range=25) qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input.qubit_op = qubitOp print(number_list) to_be_tested_algos = ['ExactEigensolver', 'CPLEX.Ising', 'VQE'] print(to_be_tested_algos) algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) cplex_installed = True try: CPLEX_Ising.check_pluggable_valid() except Exception as e: cplex_installed = False if cplex_installed: algorithm_cfg = { 'name': 'CPLEX.Ising', 'display': 0 } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params, algo_input) x_dict = result['x_sol'] print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) x = np.array([x_dict[i] for i in sorted(x_dict.keys())]) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'L_BFGS_B', 'maxfun': 6000 } var_form_cfg = { 'name': 'RYRZ', 'depth': 3, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('statevector_simulator') result = run_algorithm(params, algo_input, backend=backend) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import QuantumCircuit from qiskit.visualization import visualize_transition,circuit_drawer from math import pi qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) circuit_drawer(qc,output="mpl") qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") visualize_transition(qc)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Example showing how to draw a quantum circuit using Qiskit. """ from qiskit import QuantumCircuit def build_bell_circuit(): """Returns a circuit putting 2 qubits in the Bell state.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) return qc # Create the circuit bell_circuit = build_bell_circuit() # Use the internal .draw() to print the circuit print(bell_circuit)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. from qiskit import QuantumCircuit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import CommutationAnalysis, CommutativeCancellation circuit = QuantumCircuit(5) # Quantum Instantaneous Polynomial Time example circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.z(0) circuit.z(4) circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.cx(3, 2) print(circuit) pm = PassManager() pm.append([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = pm.run(circuit) print(new_circuit)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute from qiskit import Aer import numpy as np import sys N=int(sys.argv[1]) filename = sys.argv[2] backend = Aer.get_backend('unitary_simulator') def GHZ(n): if n<=0: return None circ = QuantumCircuit(n) # Put your code below # ---------------------------- circ.h(0) for x in range(1,n): circ.cx(x-1,x) # ---------------------------- return circ circuit = GHZ(N) job = execute(circuit, backend, shots=8192) result = job.result() array = result.get_unitary(circuit,3) np.savetxt(filename, array, delimiter=",", fmt = "%0.3f")
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Example use of the initialize gate to prepare arbitrary pure states. """ import math from qiskit import QuantumCircuit, execute, BasicAer ############################################################### # Make a quantum circuit for state initialization. ############################################################### circuit = QuantumCircuit(4, 4, name="initializer_circ") desired_vector = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0), ] circuit.initialize(desired_vector, [0, 1, 2, 3]) circuit.measure([0, 1, 2, 3], [0, 1, 2, 3]) print(circuit) ############################################################### # Execute on a simulator backend. ############################################################### shots = 10000 # Desired vector print("Desired probabilities: ") print([format(abs(x * x), ".3f") for x in desired_vector]) # Initialize on local simulator sim_backend = BasicAer.get_backend("qasm_simulator") job = execute(circuit, sim_backend, shots=shots) result = job.result() counts = result.get_counts(circuit) qubit_strings = [format(i, "04b") for i in range(2**4)] print("Probabilities from simulator: ") print([format(counts.get(s, 0) / shots, ".3f") for s in qubit_strings])
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Example on how to load a file into a QuantumCircuit.""" from qiskit import QuantumCircuit from qiskit import execute, BasicAer circ = QuantumCircuit.from_qasm_file("examples/qasm/entangled_registers.qasm") print(circ) # See the backend sim_backend = BasicAer.get_backend("qasm_simulator") # Compile and run the Quantum circuit on a local simulator backend job_sim = execute(circ, sim_backend) sim_result = job_sim.result() # Show the results print("simulation: ", sim_result) print(sim_result.get_counts(circ))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Ripple adder example based on Cuccaro et al., quant-ph/0410184. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### backend = BasicAer.get_backend("qasm_simulator") coupling_map = [ [0, 1], [0, 8], [1, 2], [1, 9], [2, 3], [2, 10], [3, 4], [3, 11], [4, 5], [4, 12], [5, 6], [5, 13], [6, 7], [6, 14], [7, 15], [8, 9], [9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], ] ############################################################### # Make a quantum program for the n-bit ripple adder. ############################################################### n = 2 a = QuantumRegister(n, "a") b = QuantumRegister(n, "b") cin = QuantumRegister(1, "cin") cout = QuantumRegister(1, "cout") ans = ClassicalRegister(n + 1, "ans") qc = QuantumCircuit(a, b, cin, cout, ans, name="rippleadd") def majority(p, a, b, c): """Majority gate.""" p.cx(c, b) p.cx(c, a) p.ccx(a, b, c) def unmajority(p, a, b, c): """Unmajority gate.""" p.ccx(a, b, c) p.cx(c, a) p.cx(a, b) # Build a temporary subcircuit that adds a to b, # storing the result in b adder_subcircuit = QuantumCircuit(cin, a, b, cout) majority(adder_subcircuit, cin[0], b[0], a[0]) for j in range(n - 1): majority(adder_subcircuit, a[j], b[j + 1], a[j + 1]) adder_subcircuit.cx(a[n - 1], cout[0]) for j in reversed(range(n - 1)): unmajority(adder_subcircuit, a[j], b[j + 1], a[j + 1]) unmajority(adder_subcircuit, cin[0], b[0], a[0]) # Set the inputs to the adder qc.x(a[0]) # Set input a = 0...0001 qc.x(b) # Set input b = 1...1111 # Apply the adder qc &= adder_subcircuit # Measure the output register in the computational basis for j in range(n): qc.measure(b[j], ans[j]) qc.measure(cout[0], ans[n]) ############################################################### # execute the program. ############################################################### # First version: not mapped job = execute(qc, backend=backend, coupling_map=None, shots=1024) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph job = execute(qc, backend=backend, coupling_map=coupling_map, shots=1024) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution
https://github.com/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. """Example of using the StochasticSwap pass.""" from qiskit.transpiler.passes import StochasticSwap from qiskit.transpiler import CouplingMap from qiskit.converters import circuit_to_dag from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit coupling = CouplingMap([[0, 1], [1, 2], [1, 3]]) qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circ = QuantumCircuit(qr, cr) circ.cx(qr[1], qr[2]) circ.cx(qr[0], qr[3]) circ.measure(qr[0], cr[0]) circ.h(qr) circ.cx(qr[0], qr[1]) circ.cx(qr[2], qr[3]) circ.measure(qr[0], cr[0]) circ.measure(qr[1], cr[1]) circ.measure(qr[2], cr[2]) circ.measure(qr[3], cr[3]) dag = circuit_to_dag(circ) # β”Œβ”€β”β”Œβ”€β”€β”€β” β”Œβ”€β” # q_0: |0>─────────────────■───────────────────Mβ”œβ”€ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€Mβ”œ # β”Œβ”€β”€β”€β” β”‚ β””β•₯β”˜β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β”β”Œβ”€β”β””β•₯β”˜ # q_1: |0>──■──────── H β”œβ”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€Mβ”œβ”€β•«β”€ # β”Œβ”€β”΄β”€β”β”Œβ”€β”€β”€β”β””β”€β”€β”€β”˜ β”‚ β”Œβ”€β” β•‘ β””β”€β”€β”€β”˜β””β•₯β”˜ β•‘ # q_2: |0>─ X β”œβ”€ H β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€Mβ”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β•«β”€ # β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β”Œβ”€β”΄β”€β”β”Œβ”€β”€β”€β”β”Œβ”€β”΄β”€β”β”Œβ”€β”β””β•₯β”˜ β•‘ β•‘ β•‘ # q_3: |0>──────────────── X β”œβ”€ H β”œβ”€ X β”œβ”€Mβ”œβ”€β•«β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β•«β”€ # β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β•₯β”˜ β•‘ β•‘ β•‘ β•‘ # c_0: 0 ═══════════════════════════════╬══╬══╩════════════╬══╩═ # β•‘ β•‘ β•‘ # c_1: 0 ═══════════════════════════════╬══╬═══════════════╩════ # β•‘ β•‘ # c_2: 0 ═══════════════════════════════╬══╩════════════════════ # β•‘ # c_3: 0 ═══════════════════════════════╩═══════════════════════ # # β”Œβ”€β”β”Œβ”€β”€β”€β” β”Œβ”€β” # q_0: |0>────────────────────■───Mβ”œβ”€ H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β”Œβ”€β”΄β”€β”β””β•₯β”˜β””β”€β”€β”€β”˜β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β” β”Œβ”€β”΄β”€β”β””β•₯β”˜β”Œβ”€β” # q_1: |0>──■───X──────────── X β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€ H β”œβ”€ X β”œβ”€X───── X β”œβ”€β•«β”€β”€Mβ”œβ”€β”€β”€ # β”Œβ”€β”΄β”€β” β”‚ β”Œβ”€β”€β”€β”β””β”€β”€β”€β”˜ β•‘ β””β”€β”€β”€β”˜β””β”€β”¬β”€β”˜ β”‚ β””β”€β”€β”€β”˜ β•‘ β””β•₯β”˜β”Œβ”€β” # q_2: |0>─ X β”œβ”€β”Όβ”€β”€β”€β”€β”€β”€β”€ H β”œβ”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”β””β”€β”€β”€β”˜ β•‘ β”‚ β”Œβ”€β” β•‘ β•‘ β””β•₯β”˜ # q_3: |0>──────X── H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€X──Mβ”œβ”€β”€β”€β”€β”€β”€β•«β”€β”€β•«β”€β”€β•«β”€ # β””β”€β”€β”€β”˜ β•‘ β””β•₯β”˜ β•‘ β•‘ β•‘ # c_0: 0 ════════════════════════╩════════════════════╬═══════╩══╬══╬═ # β•‘ β•‘ β•‘ # c_1: 0 ═════════════════════════════════════════════╬══════════╩══╬═ # β•‘ β•‘ # c_2: 0 ═════════════════════════════════════════════╬═════════════╩═ # β•‘ # c_3: 0 ═════════════════════════════════════════════╩═══════════════ # # # 2 # | # 0 - 1 - 3 # Build the expected output to verify the pass worked expected = QuantumCircuit(qr, cr) expected.cx(qr[1], qr[2]) expected.h(qr[2]) expected.swap(qr[0], qr[1]) expected.h(qr[0]) expected.cx(qr[1], qr[3]) expected.h(qr[3]) expected.measure(qr[1], cr[0]) expected.swap(qr[1], qr[3]) expected.cx(qr[2], qr[1]) expected.h(qr[3]) expected.swap(qr[0], qr[1]) expected.measure(qr[2], cr[2]) expected.cx(qr[3], qr[1]) expected.measure(qr[0], cr[3]) expected.measure(qr[3], cr[0]) expected.measure(qr[1], cr[1]) expected_dag = circuit_to_dag(expected) # Run the pass on the dag from the input circuit pass_ = StochasticSwap(coupling, 20, 999) after = pass_.run(dag) # Verify the output of the pass matches our expectation assert expected_dag == after
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Quantum teleportation example. Note: if you have only cloned the Qiskit repository but not used `pip install`, the examples only work from the root directory. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]] backend = BasicAer.get_backend("qasm_simulator") ############################################################### # Make a quantum program for quantum teleportation. ############################################################### q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2, name="teleport") # Prepare an initial state qc.u(0.3, 0.2, 0.1, q[0]) # Prepare a Bell pair qc.h(q[1]) qc.cx(q[1], q[2]) # Barrier following state preparation qc.barrier(q) # Measure in the Bell basis qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) # Apply a correction qc.barrier(q) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.measure(q[2], c2[0]) ############################################################### # Execute. # Experiment does not support feedback, so we use the simulator ############################################################### # First version: not mapped initial_layout = {q[0]: 0, q[1]: 1, q[2]: 2} job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph job = execute( qc, backend=backend, coupling_map=coupling_map, shots=1024, initial_layout=initial_layout ) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Example showing how to use Qiskit-Terra at level 0 (novice). This example shows the most basic way to user Terra. It builds some circuits and runs them on both the BasicAer (local Qiskit provider) or IBMQ (remote IBMQ provider). To control the compile parameters we have provided a transpile function which can be used as a level 1 user. """ # Import the Qiskit modules from qiskit import QuantumCircuit from qiskit import execute, BasicAer # making first circuit: bell state qc1 = QuantumCircuit(2, 2) qc1.h(0) qc1.cx(0, 1) qc1.measure([0, 1], [0, 1]) # making another circuit: superpositions qc2 = QuantumCircuit(2, 2) qc2.h([0, 1]) qc2.measure([0, 1], [0, 1]) # setting up the backend print("(BasicAER Backends)") print(BasicAer.backends()) # running the job job_sim = execute([qc1, qc2], BasicAer.get_backend("qasm_simulator")) sim_result = job_sim.result() # Show the results print(sim_result.get_counts(qc1)) print(sim_result.get_counts(qc2))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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. """ Example showing how to use Qiskit at level 1 (intermediate). This example shows how an intermediate user interacts with Terra. It builds some circuits and transpiles them with transpile options. It then makes a qobj object which is just a container to be run on a backend. The same qobj can be submitted to many backends (as shown). It is the user's responsibility to make sure it can be run (i.e. it conforms to the restrictions of the backend, if any). This is useful when you want to compare the same circuit on different backends without recompiling the whole circuit, or just want to change some runtime parameters. To control the passes that transform the circuit, we have a pass manager for the level 2 user. """ import pprint, time # Import the Qiskit modules from qiskit import IBMQ, BasicAer from qiskit import QiskitError from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.compiler import transpile, assemble from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor try: IBMQ.load_accounts() except: print("""WARNING: There's no connection with the API for remote backends. Have you initialized a file with your personal token? For now, there's only access to local simulator backends...""") try: # Create a Quantum and Classical Register and give them names. qubit_reg = QuantumRegister(2, name='q') clbit_reg = ClassicalRegister(2, name='c') # Making first circuit: bell state qc1 = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc1.h(qubit_reg[0]) qc1.cx(qubit_reg[0], qubit_reg[1]) qc1.measure(qubit_reg, clbit_reg) # Making another circuit: superpositions qc2 = QuantumCircuit(qubit_reg, clbit_reg, name="superposition") qc2.h(qubit_reg) qc2.measure(qubit_reg, clbit_reg) # Setting up the backend print("(Aer Backends)") for backend in BasicAer.backends(): print(backend.status()) qasm_simulator = BasicAer.get_backend('qasm_simulator') # Compile and run the circuit on a real device backend # See a list of available remote backends print("\n(IBMQ Backends)") for backend in IBMQ.backends(): print(backend.status()) try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) except: print("All devices are currently unavailable.") print("Running on current least busy device: ", least_busy_device) # Transpile the circuits to make them compatible with the experimental backend [qc1_new, qc2_new] = transpile(circuits=[qc1, qc2], backend=least_busy_device) print("Bell circuit before transpile:") print(qc1.draw()) print("Bell circuit after transpile:") print(qc1_new.draw()) print("Superposition circuit before transpile:") print(qc2.draw()) print("Superposition circuit after transpile:") print(qc2_new.draw()) # Assemble the two circuits into a runnable qobj qobj = assemble([qc1_new, qc2_new], shots=1000) # Running qobj on the simulator sim_job = qasm_simulator.run(qobj) # Getting the result sim_result=sim_job.result() # Show the results print(sim_result.get_counts(qc1)) print(sim_result.get_counts(qc2)) # Running the job. exp_job = least_busy_device.run(qobj) job_monitor(exp_job) exp_result = exp_job.result() # Show the results print(exp_result.get_counts(qc1)) print(exp_result.get_counts(qc2)) except QiskitError as ex: print('There was an error in the circuit!. Error = {}'.format(ex))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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. """ Example showing how to use Qiskit at level 2 (advanced). This example shows how an advanced user interacts with Terra. It builds some circuits and transpiles them with the pass_manager. """ import pprint, time # Import the Qiskit modules from qiskit import IBMQ, BasicAer from qiskit import QiskitError from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.extensions import SwapGate from qiskit.compiler import assemble from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor from qiskit.transpiler import PassManager from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes import Unroller from qiskit.transpiler.passes import FullAncillaAllocation from qiskit.transpiler.passes import EnlargeWithAncilla from qiskit.transpiler.passes import TrivialLayout from qiskit.transpiler.passes import Decompose from qiskit.transpiler.passes import CXDirection from qiskit.transpiler.passes import LookaheadSwap try: IBMQ.load_accounts() except: print("""WARNING: There's no connection with the API for remote backends. Have you initialized a file with your personal token? For now, there's only access to local simulator backends...""") try: qubit_reg = QuantumRegister(4, name='q') clbit_reg = ClassicalRegister(4, name='c') # Making first circuit: superpositions qc1 = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc1.h(qubit_reg[0]) qc1.cx(qubit_reg[0], qubit_reg[1]) qc1.measure(qubit_reg, clbit_reg) # Making another circuit: GHZ State qc2 = QuantumCircuit(qubit_reg, clbit_reg, name="superposition") qc2.h(qubit_reg) qc2.cx(qubit_reg[0], qubit_reg[1]) qc2.cx(qubit_reg[0], qubit_reg[2]) qc2.cx(qubit_reg[0], qubit_reg[3]) qc2.measure(qubit_reg, clbit_reg) # Setting up the backend print("(Aer Backends)") for backend in BasicAer.backends(): print(backend.status()) qasm_simulator = BasicAer.get_backend('qasm_simulator') # Compile and run the circuit on a real device backend # See a list of available remote backends print("\n(IBMQ Backends)") for backend in IBMQ.backends(): print(backend.status()) try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) except: print("All devices are currently unavailable.") print("Running on current least busy device: ", least_busy_device) # making a pass manager to compile the circuits coupling_map = CouplingMap(least_busy_device.configuration().coupling_map) print("coupling map: ", coupling_map) pm = PassManager() pm.append(TrivialLayout(coupling_map)) pm.append(FullAncillaAllocation(coupling_map)) pm.append(EnlargeWithAncilla()) pm.append(LookaheadSwap(coupling_map)) pm.append(Decompose(SwapGate)) pm.append(CXDirection(coupling_map)) pm.append(Unroller(['u1', 'u2', 'u3', 'id', 'cx'])) qc1_new = pm.run(qc1) qc2_new = pm.run(qc2) print("Bell circuit before passes:") print(qc1.draw()) print("Bell circuit after passes:") print(qc1_new.draw()) print("Superposition circuit before passes:") print(qc2.draw()) print("Superposition circuit after passes:") print(qc2_new.draw()) # Assemble the two circuits into a runnable qobj qobj = assemble([qc1_new, qc2_new], shots=1000) # Running qobj on the simulator print("Running on simulator:") sim_job = qasm_simulator.run(qobj) # Getting the result sim_result=sim_job.result() # Show the results print(sim_result.get_counts(qc1)) print(sim_result.get_counts(qc2)) # Running the job. print("Running on device:") exp_job = least_busy_device.run(qobj) job_monitor(exp_job) exp_result = exp_job.result() # Show the results print(exp_result.get_counts(qc1)) print(exp_result.get_counts(qc2)) except QiskitError as ex: print('There was an error in the circuit!. Error = {}'.format(ex))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # 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. """Utils for reading a user preference config files.""" import configparser import os from qiskit import exceptions DEFAULT_FILENAME = os.path.join(os.path.expanduser("~"), '.qiskit', 'settings.conf') class UserConfig: """Class representing a user config file The config file format should look like: [default] circuit_drawer = mpl """ def __init__(self, filename=None): """Create a UserConfig Args: filename (str): The path to the user config file. If one isn't specified ~/.qiskit/settings.conf is used. """ if filename is None: self.filename = DEFAULT_FILENAME else: self.filename = filename self.settings = {} self.config_parser = configparser.ConfigParser() def read_config_file(self): """Read config file and parse the contents into the settings attr.""" if not os.path.isfile(self.filename): return self.config_parser.read(self.filename) if 'default' in self.config_parser.sections(): circuit_drawer = self.config_parser.get('default', 'circuit_drawer') if circuit_drawer: if circuit_drawer not in ['text', 'mpl', 'latex', 'latex_source']: raise exceptions.QiskitUserConfigError( "%s is not a valid circuit drawer backend. Must be " "either 'text', 'mpl', 'latex', or 'latex_source'" % circuit_drawer) self.settings['circuit_drawer'] = circuit_drawer def get_config(): """Read the config file from the default location or env var It will read a config file at either the default location ~/.qiskit/settings.conf or if set the value of the QISKIT_SETTINGS env var. It will return the parsed settings dict from the parsed config file. Returns: dict: The settings dict from the parsed config file. """ filename = os.getenv('QISKIT_SETTINGS', DEFAULT_FILENAME) if not os.path.isfile(filename): return {} user_config = UserConfig(filename) user_config.read_config_file() return user_config.settings
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Simulator command to snapshot internal simulator representation. """ import warnings from qiskit import QuantumCircuit from qiskit.circuit import CompositeGate from qiskit import QuantumRegister from qiskit.circuit import Instruction from qiskit.extensions.exceptions import ExtensionError class Snapshot(Instruction): """Simulator snapshot instruction.""" def __init__(self, label, snapshot_type='statevector', num_qubits=0, num_clbits=0, params=None): """Create new snapshot instruction. Args: label (str): the snapshot label for result data. snapshot_type (str): the type of the snapshot. num_qubits (int): the number of qubits for the snapshot type [Default: 0]. num_clbits (int): the number of classical bits for the snapshot type [Default: 0]. params (list or None): the parameters for snapshot_type [Default: None]. Raises: ExtensionError: if snapshot label is invalid. """ if not isinstance(label, str): raise ExtensionError('Snapshot label must be a string.') self._label = label self._snapshot_type = snapshot_type if params is None: params = [] super().__init__('snapshot', num_qubits, num_clbits, params) def assemble(self): """Assemble a QasmQobjInstruction""" instruction = super().assemble() instruction.label = self._label instruction.snapshot_type = self._snapshot_type return instruction def inverse(self): """Special case. Return self.""" return Snapshot(self.num_qubits, self.num_clbits, self.params[0], self.params[1]) @property def snapshot_type(self): """Return snapshot type""" return self._snapshot_type @property def label(self): """Return snapshot label""" return self._label @label.setter def label(self, name): """Set snapshot label to name Args: name (str or None): label to assign unitary Raises: TypeError: name is not string or None. """ if isinstance(name, str): self._label = name else: raise TypeError('label expects a string') def snapshot(self, label, snapshot_type='statevector', qubits=None, params=None): """Take a statevector snapshot of the internal simulator representation. Works on all qubits, and prevents reordering (like barrier). For other types of snapshots use the Snapshot extension directly. Args: label (str): a snapshot label to report the result snapshot_type (str): the type of the snapshot. qubits (list or None): the qubits to apply snapshot to [Default: None]. params (list or None): the parameters for snapshot_type [Default: None]. Returns: QuantumCircuit: with attached command Raises: ExtensionError: malformed command """ # Convert label to string for backwards compatibility if not isinstance(label, str): warnings.warn( "Snapshot label should be a string, " "implicit conversion is depreciated.", DeprecationWarning) label = str(label) # If no qubits are specified we add all qubits so it acts as a barrier # This is needed for full register snapshots like statevector if isinstance(qubits, QuantumRegister): qubits = qubits[:] if not qubits: tuples = [] if isinstance(self, QuantumCircuit): for register in self.qregs: tuples.append(register) if not tuples: raise ExtensionError('no qubits for snapshot') qubits = [] for tuple_element in tuples: if isinstance(tuple_element, QuantumRegister): for j in range(tuple_element.size): qubits.append((tuple_element, j)) else: qubits.append(tuple_element) return self.append( Snapshot( label, snapshot_type=snapshot_type, num_qubits=len(qubits), params=params), qubits) # Add to QuantumCircuit and CompositeGate classes QuantumCircuit.snapshot = snapshot CompositeGate.snapshot = snapshot
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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. """Decorator for using with Qiskit unit tests.""" import functools import os import sys import unittest from .utils import Path from .http_recorder import http_recorder from .testing_options import get_test_options def is_aer_provider_available(): """Check if the C++ simulator can be instantiated. Returns: bool: True if simulator executable is available """ # TODO: HACK FROM THE DEPTHS OF DESPAIR AS AER DOES NOT WORK ON MAC if sys.platform == 'darwin': return False try: import qiskit.providers.aer # pylint: disable=unused-import except ImportError: return False return True def requires_aer_provider(test_item): """Decorator that skips test if qiskit aer provider is not available Args: test_item (callable): function or class to be decorated. Returns: callable: the decorated function. """ reason = 'Aer provider not found, skipping test' return unittest.skipIf(not is_aer_provider_available(), reason)(test_item) def slow_test(func): """Decorator that signals that the test takes minutes to run. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(*args, **kwargs): skip_slow = not TEST_OPTIONS['run_slow'] if skip_slow: raise unittest.SkipTest('Skipping slow tests') return func(*args, **kwargs) return _wrapper def _get_credentials(test_object, test_options): """Finds the credentials for a specific test and options. Args: test_object (QiskitTestCase): The test object asking for credentials test_options (dict): Options after QISKIT_TESTS was parsed by get_test_options. Returns: Credentials: set of credentials Raises: ImportError: if the Exception: when the credential could not be set and they are needed for that set of options """ try: from qiskit.providers.ibmq.credentials import (Credentials, discover_credentials) except ImportError: raise ImportError('qiskit-ibmq-provider could not be found, and is ' 'required for mocking or executing online tests.') dummy_credentials = Credentials( 'dummyapiusersloginWithTokenid01', 'https://quantumexperience.ng.bluemix.net/api') if test_options['mock_online']: return dummy_credentials if os.getenv('USE_ALTERNATE_ENV_CREDENTIALS', ''): # Special case: instead of using the standard credentials mechanism, # load them from different environment variables. This assumes they # will always be in place, as is used by the Travis setup. return Credentials(os.getenv('IBMQ_TOKEN'), os.getenv('IBMQ_URL')) else: # Attempt to read the standard credentials. discovered_credentials = discover_credentials() if discovered_credentials: # Decide which credentials to use for testing. if len(discovered_credentials) > 1: try: # Attempt to use QE credentials. return discovered_credentials[dummy_credentials.unique_id()] except KeyError: pass # Use the first available credentials. return list(discovered_credentials.values())[0] # No user credentials were found. if test_options['rec']: raise Exception('Could not locate valid credentials. You need them for ' 'recording tests against the remote API.') test_object.log.warning('No user credentials were detected. ' 'Running with mocked data.') test_options['mock_online'] = True return dummy_credentials def requires_qe_access(func): """Decorator that signals that the test uses the online API: It involves: * determines if the test should be skipped by checking environment variables. * if the `USE_ALTERNATE_ENV_CREDENTIALS` environment variable is set, it reads the credentials from an alternative set of environment variables. * if the test is not skipped, it reads `qe_token` and `qe_url` from `Qconfig.py`, environment variables or qiskitrc. * if the test is not skipped, it appends `qe_token` and `qe_url` as arguments to the test function. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(self, *args, **kwargs): if TEST_OPTIONS['skip_online']: raise unittest.SkipTest('Skipping online tests') credentials = _get_credentials(self, TEST_OPTIONS) self.using_ibmq_credentials = credentials.is_ibmq() kwargs.update({'qe_token': credentials.token, 'qe_url': credentials.url}) decorated_func = func if TEST_OPTIONS['rec'] or TEST_OPTIONS['mock_online']: # For recording or for replaying existing cassettes, the test # should be decorated with @use_cassette. vcr_mode = 'new_episodes' if TEST_OPTIONS['rec'] else 'none' decorated_func = http_recorder( vcr_mode, Path.CASSETTES.value).use_cassette()(decorated_func) return decorated_func(self, *args, **kwargs) return _wrapper TEST_OPTIONS = get_test_options()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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. """Decorator for using with Qiskit unit tests.""" import functools import os import sys import unittest from .utils import Path from .http_recorder import http_recorder from .testing_options import get_test_options def is_aer_provider_available(): """Check if the C++ simulator can be instantiated. Returns: bool: True if simulator executable is available """ # TODO: HACK FROM THE DEPTHS OF DESPAIR AS AER DOES NOT WORK ON MAC if sys.platform == 'darwin': return False try: import qiskit.providers.aer # pylint: disable=unused-import except ImportError: return False return True def requires_aer_provider(test_item): """Decorator that skips test if qiskit aer provider is not available Args: test_item (callable): function or class to be decorated. Returns: callable: the decorated function. """ reason = 'Aer provider not found, skipping test' return unittest.skipIf(not is_aer_provider_available(), reason)(test_item) def slow_test(func): """Decorator that signals that the test takes minutes to run. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(*args, **kwargs): skip_slow = not TEST_OPTIONS['run_slow'] if skip_slow: raise unittest.SkipTest('Skipping slow tests') return func(*args, **kwargs) return _wrapper def _get_credentials(test_object, test_options): """Finds the credentials for a specific test and options. Args: test_object (QiskitTestCase): The test object asking for credentials test_options (dict): Options after QISKIT_TESTS was parsed by get_test_options. Returns: Credentials: set of credentials Raises: ImportError: if the Exception: when the credential could not be set and they are needed for that set of options """ try: from qiskit.providers.ibmq.credentials import (Credentials, discover_credentials) except ImportError: raise ImportError('qiskit-ibmq-provider could not be found, and is ' 'required for mocking or executing online tests.') dummy_credentials = Credentials( 'dummyapiusersloginWithTokenid01', 'https://quantumexperience.ng.bluemix.net/api') if test_options['mock_online']: return dummy_credentials if os.getenv('USE_ALTERNATE_ENV_CREDENTIALS', ''): # Special case: instead of using the standard credentials mechanism, # load them from different environment variables. This assumes they # will always be in place, as is used by the Travis setup. return Credentials(os.getenv('IBMQ_TOKEN'), os.getenv('IBMQ_URL')) else: # Attempt to read the standard credentials. discovered_credentials = discover_credentials() if discovered_credentials: # Decide which credentials to use for testing. if len(discovered_credentials) > 1: try: # Attempt to use QE credentials. return discovered_credentials[dummy_credentials.unique_id()] except KeyError: pass # Use the first available credentials. return list(discovered_credentials.values())[0] # No user credentials were found. if test_options['rec']: raise Exception('Could not locate valid credentials. You need them for ' 'recording tests against the remote API.') test_object.log.warning('No user credentials were detected. ' 'Running with mocked data.') test_options['mock_online'] = True return dummy_credentials def requires_qe_access(func): """Decorator that signals that the test uses the online API: It involves: * determines if the test should be skipped by checking environment variables. * if the `USE_ALTERNATE_ENV_CREDENTIALS` environment variable is set, it reads the credentials from an alternative set of environment variables. * if the test is not skipped, it reads `qe_token` and `qe_url` from `Qconfig.py`, environment variables or qiskitrc. * if the test is not skipped, it appends `qe_token` and `qe_url` as arguments to the test function. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(self, *args, **kwargs): if TEST_OPTIONS['skip_online']: raise unittest.SkipTest('Skipping online tests') credentials = _get_credentials(self, TEST_OPTIONS) self.using_ibmq_credentials = credentials.is_ibmq() kwargs.update({'qe_token': credentials.token, 'qe_url': credentials.url}) decorated_func = func if TEST_OPTIONS['rec'] or TEST_OPTIONS['mock_online']: # For recording or for replaying existing cassettes, the test # should be decorated with @use_cassette. vcr_mode = 'new_episodes' if TEST_OPTIONS['rec'] else 'none' decorated_func = http_recorder( vcr_mode, Path.CASSETTES.value).use_cassette()(decorated_func) return decorated_func(self, *args, **kwargs) return _wrapper TEST_OPTIONS = get_test_options()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Utils for using with Qiskit unit tests.""" import logging import os import unittest from enum import Enum from qiskit import __path__ as qiskit_path class Path(Enum): """Helper with paths commonly used during the tests.""" # Main SDK path: qiskit/ SDK = qiskit_path[0] # test.python path: qiskit/test/python/ TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python')) # Examples path: examples/ EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples')) # Schemas path: qiskit/schemas SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas')) # VCR cassettes path: qiskit/test/cassettes/ CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes')) # Sample QASMs path: qiskit/test/python/qasm QASMS = os.path.normpath(os.path.join(TEST, 'qasm')) def setup_test_logging(logger, log_level, filename): """Set logging to file and stdout for a logger. Args: logger (Logger): logger object to be updated. log_level (str): logging level. filename (str): name of the output file. """ # Set up formatter. log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:' ' %(message)s'.format(logger.name)) formatter = logging.Formatter(log_fmt) # Set up the file handler. file_handler = logging.FileHandler(filename) file_handler.setFormatter(formatter) logger.addHandler(file_handler) # Set the logging level from the environment variable, defaulting # to INFO if it is not a valid level. level = logging._nameToLevel.get(log_level, logging.INFO) logger.setLevel(level) class _AssertNoLogsContext(unittest.case._AssertLogsContext): """A context manager used to implement TestCase.assertNoLogs().""" # pylint: disable=inconsistent-return-statements def __exit__(self, exc_type, exc_value, tb): """ This is a modified version of TestCase._AssertLogsContext.__exit__(...) """ self.logger.handlers = self.old_handlers self.logger.propagate = self.old_propagate self.logger.setLevel(self.old_level) if exc_type is not None: # let unexpected exceptions pass through return False if self.watcher.records: msg = 'logs of level {} or higher triggered on {}:\n'.format( logging.getLevelName(self.level), self.logger.name) for record in self.watcher.records: msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname, record.lineno, record.getMessage()) self._raiseFailure(msg)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import Aer, IBMQ, execute from qiskit import transpile, assemble from qiskit.tools.monitor import job_monitor from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt from qiskit.visualization import plot_histogram, plot_state_city """ Qiskit backends to execute the quantum circuit """ def simulator(qc): """ Run on local simulator :param qc: quantum circuit :return: """ backend = Aer.get_backend("qasm_simulator") shots = 2048 tqc = transpile(qc, backend) qobj = assemble(tqc, shots=shots) job_sim = backend.run(qobj) qc_results = job_sim.result() return qc_results, shots def simulator_state_vector(qc): """ Select the StatevectorSimulator from the Aer provider :param qc: quantum circuit :return: statevector """ simulator = Aer.get_backend('statevector_simulator') # Execute and get counts result = execute(qc, simulator).result() state_vector = result.get_statevector(qc) return state_vector def real_quantum_device(qc): """ Use the IBMQ essex device :param qc: quantum circuit :return: """ provider = IBMQ.load_account() backend = provider.get_backend('ibmq_santiago') shots = 2048 TQC = transpile(qc, backend) qobj = assemble(TQC, shots=shots) job_exp = backend.run(qobj) job_monitor(job_exp) QC_results = job_exp.result() return QC_results, shots def counts(qc_results): """ Get counts representing the wave-function amplitudes :param qc_results: :return: dict keys are bit_strings and their counting values """ return qc_results.get_counts() def plot_results(qc_results): """ Visualizing wave-function amplitudes in a histogram :param qc_results: quantum circuit :return: """ plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False)) def plot_state_vector(state_vector): """Visualizing state vector in the density matrix representation""" plt.show(plot_state_city(state_vector))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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. # TODO: Remove after 0.7 and the deprecated methods are removed # pylint: disable=unused-argument """ Two quantum circuit drawers based on: 0. Ascii art 1. LaTeX 2. Matplotlib """ import errno import logging import os import subprocess import tempfile from PIL import Image from qiskit import user_config from qiskit.visualization import exceptions from qiskit.visualization import latex as _latex from qiskit.visualization import text as _text from qiskit.visualization import utils from qiskit.visualization import matplotlib as _matplotlib logger = logging.getLogger(__name__) def circuit_drawer(circuit, scale=0.7, filename=None, style=None, output=None, interactive=False, line_length=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit to different formats (set by output parameter): 0. text: ASCII art TextDrawing that can be printed in the console. 1. latex: high-quality images, but heavy external software dependencies 2. matplotlib: purely in Python with no external dependencies Args: circuit (QuantumCircuit): the quantum circuit to draw scale (float): scale of image to draw (shrink if < 1) filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file. This option is only used by the `mpl`, `latex`, and `latex_source` output types. If a str is passed in that is the path to a json file which contains that will be open, parsed, and then used just as the input dict. output (str): Select the output method to use for drawing the circuit. Valid choices are `text`, `latex`, `latex_source`, `mpl`. By default the 'text' drawer is used unless a user config file has an alternative backend set as the default. If the output is passed in that backend will always be used. interactive (bool): when set true show the circuit in a new window (for `mpl` this depends on the matplotlib backend being used supporting this). Note when used with either the `text` or the `latex_source` output type this has no effect and will be silently ignored. line_length (int): Sets the length of the lines generated by `text` output type. This useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using shutil.get_terminal_size(). However, if you're running in jupyter the default line length is set to 80 characters. If you don't want pagination at all, set `line_length=-1`. reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (string): Options are `left`, `right` or `none`, if anything else is supplied it defaults to left justified. It refers to where gates should be placed in the output circuit if there is an option. `none` results in each gate being placed in its own column. Currently only supported by text drawer. Returns: PIL.Image: (output `latex`) an in-memory representation of the image of the circuit diagram. matplotlib.figure: (output `mpl`) a matplotlib figure object for the circuit diagram. String: (output `latex_source`). The LaTeX source code. TextDrawing: (output `text`). A drawing that can be printed as ascii art Raises: VisualizationError: when an invalid output method is selected ImportError: when the output methods requieres non-installed libraries. .. _style-dict-doc: The style dict kwarg contains numerous options that define the style of the output circuit visualization. While the style dict is used by the `mpl`, `latex`, and `latex_source` outputs some options in that are only used by the `mpl` output. These options are defined below, if it is only used by the `mpl` output it is marked as such: textcolor (str): The color code to use for text. Defaults to `'#000000'` (`mpl` only) subtextcolor (str): The color code to use for subtext. Defaults to `'#000000'` (`mpl` only) linecolor (str): The color code to use for lines. Defaults to `'#000000'` (`mpl` only) creglinecolor (str): The color code to use for classical register lines `'#778899'`(`mpl` only) gatetextcolor (str): The color code to use for gate text `'#000000'` (`mpl` only) gatefacecolor (str): The color code to use for gates. Defaults to `'#ffffff'` (`mpl` only) barrierfacecolor (str): The color code to use for barriers. Defaults to `'#bdbdbd'` (`mpl` only) backgroundcolor (str): The color code to use for the background. Defaults to `'#ffffff'` (`mpl` only) fontsize (int): The font size to use for text. Defaults to 13 (`mpl` only) subfontsize (int): The font size to use for subtext. Defaults to 8 (`mpl` only) displaytext (dict): A dictionary of the text to use for each element type in the output visualization. The default values are: { 'id': 'id', 'u0': 'U_0', 'u1': 'U_1', 'u2': 'U_2', 'u3': 'U_3', 'x': 'X', 'y': 'Y', 'z': 'Z', 'h': 'H', 's': 'S', 'sdg': 'S^\\dagger', 't': 'T', 'tdg': 'T^\\dagger', 'rx': 'R_x', 'ry': 'R_y', 'rz': 'R_z', 'reset': '\\left|0\\right\\rangle' } You must specify all the necessary values if using this. There is no provision for passing an incomplete dict in. (`mpl` only) displaycolor (dict): The color codes to use for each circuit element. By default all values default to the value of `gatefacecolor` and the keys are the same as `displaytext`. Also, just like `displaytext` there is no provision for an incomplete dict passed in. (`mpl` only) latexdrawerstyle (bool): When set to True enable latex mode which will draw gates like the `latex` output modes. (`mpl` only) usepiformat (bool): When set to True use radians for output (`mpl` only) fold (int): The number of circuit elements to fold the circuit at. Defaults to 20 (`mpl` only) cregbundle (bool): If set True bundle classical registers (`mpl` only) showindex (bool): If set True draw an index. (`mpl` only) compress (bool): If set True draw a compressed circuit (`mpl` only) figwidth (int): The maximum width (in inches) for the output figure. (`mpl` only) dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl` only) margin (list): `mpl` only creglinestyle (str): The style of line to use for classical registers. Choices are `'solid'`, `'doublet'`, or any valid matplotlib `linestyle` kwarg value. Defaults to `doublet`(`mpl` only) """ image = None config = user_config.get_config() # Get default from config file else use text default_output = 'text' if config: default_output = config.get('circuit_drawer', 'text') if output is None: output = default_output if output == 'text': return _text_circuit_drawer(circuit, filename=filename, line_length=line_length, reverse_bits=reverse_bits, plotbarriers=plot_barriers, justify=justify) elif output == 'latex': image = _latex_circuit_drawer(circuit, scale=scale, filename=filename, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) elif output == 'latex_source': return _generate_latex_source(circuit, filename=filename, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) elif output == 'mpl': image = _matplotlib_circuit_drawer(circuit, scale=scale, filename=filename, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) else: raise exceptions.VisualizationError( 'Invalid output type %s selected. The only valid choices ' 'are latex, latex_source, text, and mpl' % output) if image and interactive: image.show() return image # ----------------------------------------------------------------------------- # Plot style sheet option # ----------------------------------------------------------------------------- def qx_color_scheme(): """Return default style for matplotlib_circuit_drawer (IBM QX style).""" return { "comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)", "textcolor": "#000000", "gatetextcolor": "#000000", "subtextcolor": "#000000", "linecolor": "#000000", "creglinecolor": "#b9b9b9", "gatefacecolor": "#ffffff", "barrierfacecolor": "#bdbdbd", "backgroundcolor": "#ffffff", "fold": 20, "fontsize": 13, "subfontsize": 8, "figwidth": -1, "dpi": 150, "displaytext": { "id": "id", "u0": "U_0", "u1": "U_1", "u2": "U_2", "u3": "U_3", "x": "X", "y": "Y", "z": "Z", "h": "H", "s": "S", "sdg": "S^\\dagger", "t": "T", "tdg": "T^\\dagger", "rx": "R_x", "ry": "R_y", "rz": "R_z", "reset": "\\left|0\\right\\rangle" }, "displaycolor": { "id": "#ffca64", "u0": "#f69458", "u1": "#f69458", "u2": "#f69458", "u3": "#f69458", "x": "#a6ce38", "y": "#a6ce38", "z": "#a6ce38", "h": "#00bff2", "s": "#00bff2", "sdg": "#00bff2", "t": "#ff6666", "tdg": "#ff6666", "rx": "#ffca64", "ry": "#ffca64", "rz": "#ffca64", "reset": "#d7ddda", "target": "#00bff2", "meas": "#f070aa" }, "latexdrawerstyle": True, "usepiformat": False, "cregbundle": False, "plotbarrier": False, "showindex": False, "compress": True, "margin": [2.0, 0.0, 0.0, 0.3], "creglinestyle": "solid", "reversebits": False } # ----------------------------------------------------------------------------- # _text_circuit_drawer # ----------------------------------------------------------------------------- def _text_circuit_drawer(circuit, filename=None, line_length=None, reverse_bits=False, plotbarriers=True, justify=None, vertically_compressed=True): """ Draws a circuit using ascii art. Args: circuit (QuantumCircuit): Input circuit filename (str): optional filename to write the result line_length (int): Optional. Breaks the circuit drawing to this length. This useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using shutil.get_terminal_size(). If you don't want pagination at all, set line_length=-1. reverse_bits (bool): Rearrange the bits in reverse order. plotbarriers (bool): Draws the barriers when they are there. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. vertically_compressed (bool): Default is `True`. It merges the lines so the drawing will take less vertical room. Returns: TextDrawing: An instances that, when printed, draws the circuit in ascii art. """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) text_drawing = _text.TextDrawing(qregs, cregs, ops) text_drawing.plotbarriers = plotbarriers text_drawing.line_length = line_length text_drawing.vertically_compressed = vertically_compressed if filename: text_drawing.dump(filename) return text_drawing # ----------------------------------------------------------------------------- # latex_circuit_drawer # ----------------------------------------------------------------------------- def _latex_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit based on latex (Qcircuit package) Requires version >=2.6.0 of the qcircuit LaTeX package. Args: circuit (QuantumCircuit): a quantum circuit scale (float): scaling factor filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: PIL.Image: an in-memory representation of the circuit diagram Raises: OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is missing. CalledProcessError: usually points errors during diagram creation. """ tmpfilename = 'circuit' with tempfile.TemporaryDirectory() as tmpdirname: tmppath = os.path.join(tmpdirname, tmpfilename + '.tex') _generate_latex_source(circuit, filename=tmppath, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) image = None try: subprocess.run(["pdflatex", "-halt-on-error", "-output-directory={}".format(tmpdirname), "{}".format(tmpfilename + '.tex')], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=True) except OSError as ex: if ex.errno == errno.ENOENT: logger.warning('WARNING: Unable to compile latex. ' 'Is `pdflatex` installed? ' 'Skipping latex circuit drawing...') raise except subprocess.CalledProcessError as ex: with open('latex_error.log', 'wb') as error_file: error_file.write(ex.stdout) logger.warning('WARNING Unable to compile latex. ' 'The output from the pdflatex command can ' 'be found in latex_error.log') raise else: try: base = os.path.join(tmpdirname, tmpfilename) subprocess.run(["pdftocairo", "-singlefile", "-png", "-q", base + '.pdf', base]) image = Image.open(base + '.png') image = utils._trim(image) os.remove(base + '.png') if filename: image.save(filename, 'PNG') except OSError as ex: if ex.errno == errno.ENOENT: logger.warning('WARNING: Unable to convert pdf to image. ' 'Is `poppler` installed? ' 'Skipping circuit drawing...') raise return image def _generate_latex_source(circuit, filename=None, scale=0.7, style=None, reverse_bits=False, plot_barriers=True, justify=None): """Convert QuantumCircuit to LaTeX string. Args: circuit (QuantumCircuit): input circuit scale (float): image scaling filename (str): optional filename to write latex style (dict or str): dictionary of style or file name of style file reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: str: Latex string appropriate for writing to file. """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits) latex = qcimg.latex() if filename: with open(filename, 'w') as latex_file: latex_file.write(latex) return latex # ----------------------------------------------------------------------------- # matplotlib_circuit_drawer # ----------------------------------------------------------------------------- def _matplotlib_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit based on matplotlib. If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline. We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization. Args: circuit (QuantumCircuit): a quantum circuit scale (float): scaling factor filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: matplotlib.figure: a matplotlib figure object for the circuit diagram """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) qcd = _matplotlib.MatplotlibDrawer(qregs, cregs, ops, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits) return qcd.draw(filename)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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=invalid-name,missing-docstring """mpl circuit visualization backend.""" import collections import fractions import itertools import json import logging import math import numpy as np try: from matplotlib import patches from matplotlib import pyplot as plt from matplotlib import pyplot as plt, gridspec HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False from qiskit.visualization import exceptions from qiskit.visualization import interpolation from qiskit.visualization.qcstyle import (OPStylePulse, OPStyleSched, DefaultStyle, BWStyle) from qiskit.pulse.channels import (DriveChannel, ControlChannel, MeasureChannel, AcquireChannel, SnapshotChannel) from qiskit.pulse import (SamplePulse, FrameChange, PersistentValue, Snapshot, Acquire, PulseError) from qiskit import user_config logger = logging.getLogger(__name__) Register = collections.namedtuple('Register', 'reg index') WID = 0.65 HIG = 0.65 DEFAULT_SCALE = 4.3 PORDER_GATE = 5 PORDER_LINE = 2 PORDER_GRAY = 3 PORDER_TEXT = 6 PORDER_SUBP = 4 class Anchor: def __init__(self, reg_num, yind, fold): self.__yind = yind self.__fold = fold self.__reg_num = reg_num self.__gate_placed = [] self.gate_anchor = 0 def plot_coord(self, index, gate_width): h_pos = index % self.__fold + 1 # check folding if self.__fold > 0: if h_pos + (gate_width - 1) > self.__fold: index += self.__fold - (h_pos - 1) x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1) y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1) else: x_pos = index + 1 + 0.5 * (gate_width - 1) y_pos = self.__yind # could have been updated, so need to store self.gate_anchor = index return x_pos, y_pos def is_locatable(self, index, gate_width): hold = [index + i for i in range(gate_width)] for p in hold: if p in self.__gate_placed: return False return True def set_index(self, index, gate_width): h_pos = index % self.__fold + 1 if h_pos + (gate_width - 1) > self.__fold: _index = index + self.__fold - (h_pos - 1) else: _index = index for ii in range(gate_width): if _index + ii not in self.__gate_placed: self.__gate_placed.append(_index + ii) self.__gate_placed.sort() def get_index(self): if self.__gate_placed: return self.__gate_placed[-1] + 1 return 0 class MatplotlibDrawer: def __init__(self, qregs, cregs, ops, scale=1.0, style=None, plot_barriers=True, reverse_bits=False): if not HAS_MATPLOTLIB: raise ImportError('The class MatplotlibDrawer needs matplotlib. ' 'Run "pip install matplotlib" before.') self._ast = None self._scale = DEFAULT_SCALE * scale self._creg = [] self._qreg = [] self._registers(cregs, qregs) self._ops = ops self._qreg_dict = collections.OrderedDict() self._creg_dict = collections.OrderedDict() self._cond = { 'n_lines': 0, 'xmax': 0, 'ymax': 0, } config = user_config.get_config() if config: config_style = config.get('circuit_mpl_style', 'default') if config_style == 'default': self._style = DefaultStyle() elif config_style == 'bw': self._style = BWStyle() elif style is False: self._style = BWStyle() else: self._style = DefaultStyle() self.plot_barriers = plot_barriers self.reverse_bits = reverse_bits if style: if isinstance(style, dict): self._style.set_style(style) elif isinstance(style, str): with open(style, 'r') as infile: dic = json.load(infile) self._style.set_style(dic) self.figure = plt.figure() self.figure.patch.set_facecolor(color=self._style.bg) self.ax = self.figure.add_subplot(111) self.ax.axis('off') self.ax.set_aspect('equal') self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False) def _registers(self, creg, qreg): self._creg = [] for r in creg: self._creg.append(Register(reg=r[0], index=r[1])) self._qreg = [] for r in qreg: self._qreg.append(Register(reg=r[0], index=r[1])) @property def ast(self): return self._ast def _custom_multiqubit_gate(self, xy, fc=None, wide=True, text=None, subtext=None): xpos = min([x[0] for x in xy]) ypos = min([y[1] for y in xy]) ypos_max = max([y[1] for y in xy]) if wide: if subtext: boxes_length = round(max([len(text), len(subtext)]) / 8) or 1 else: boxes_length = round(len(text) / 8) or 1 wid = WID * 2.8 * boxes_length else: wid = WID if fc: _fc = fc else: _fc = self._style.gc qubit_span = abs(ypos) - abs(ypos_max) + 1 height = HIG + (qubit_span - 1) box = patches.Rectangle( xy=(xpos - 0.5 * wid, ypos - .5 * HIG), width=wid, height=height, fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE) self.ax.add_patch(box) # Annotate inputs for bit, y in enumerate([x[1] for x in xy]): self.ax.text(xpos - 0.45 * wid, y, str(bit), ha='left', va='center', fontsize=self._style.fs, color=self._style.gt, clip_on=True, zorder=PORDER_TEXT) if text: disp_text = text if subtext: self.ax.text(xpos, ypos + 0.5 * height, disp_text, ha='center', va='center', fontsize=self._style.fs, color=self._style.gt, clip_on=True, zorder=PORDER_TEXT) self.ax.text(xpos, ypos + 0.3 * height, subtext, ha='center', va='center', fontsize=self._style.sfs, color=self._style.sc, clip_on=True, zorder=PORDER_TEXT) else: self.ax.text(xpos, ypos + .5 * (qubit_span - 1), disp_text, ha='center', va='center', fontsize=self._style.fs, color=self._style.gt, clip_on=True, zorder=PORDER_TEXT) def _gate(self, xy, fc=None, wide=False, text=None, subtext=None): xpos, ypos = xy if wide: if subtext: wid = WID * 2.8 else: boxes_wide = round(len(text) / 10) or 1 wid = WID * 2.8 * boxes_wide else: wid = WID if fc: _fc = fc elif text and text in self._style.dispcol: _fc = self._style.dispcol[text] else: _fc = self._style.gc box = patches.Rectangle( xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG, fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE) self.ax.add_patch(box) if text: if text in self._style.dispcol: disp_text = "${}$".format(self._style.disptex[text]) else: disp_text = text if subtext: self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center', fontsize=self._style.fs, color=self._style.gt, clip_on=True, zorder=PORDER_TEXT) self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center', fontsize=self._style.sfs, color=self._style.sc, clip_on=True, zorder=PORDER_TEXT) else: self.ax.text(xpos, ypos, disp_text, ha='center', va='center', fontsize=self._style.fs, color=self._style.gt, clip_on=True, zorder=PORDER_TEXT) def _subtext(self, xy, text): xpos, ypos = xy self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top', fontsize=self._style.sfs, color=self._style.tc, clip_on=True, zorder=PORDER_TEXT) def _sidetext(self, xy, text): xpos, ypos = xy # 0.15 = the initial gap, each char means it needs to move # another 0.0375 over xp = xpos + 0.15 + (0.0375 * len(text)) self.ax.text(xp, ypos+HIG, text, ha='center', va='top', fontsize=self._style.sfs, color=self._style.tc, clip_on=True, zorder=PORDER_TEXT) def _line(self, xy0, xy1, lc=None, ls=None): x0, y0 = xy0 x1, y1 = xy1 if lc is None: linecolor = self._style.lc else: linecolor = lc if ls is None: linestyle = 'solid' else: linestyle = ls if linestyle == 'doublet': theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0)) dx = 0.05 * WID * np.cos(theta) dy = 0.05 * WID * np.sin(theta) self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy], color=linecolor, linewidth=1.0, linestyle='solid', zorder=PORDER_LINE) self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy], color=linecolor, linewidth=1.0, linestyle='solid', zorder=PORDER_LINE) else: self.ax.plot([x0, x1], [y0, y1], color=linecolor, linewidth=1.0, linestyle=linestyle, zorder=PORDER_LINE) def _measure(self, qxy, cxy, cid): qx, qy = qxy cx, cy = cxy self._gate(qxy, fc=self._style.dispcol['meas']) # add measure symbol arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7, theta1=0, theta2=180, fill=False, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE) self.ax.add_patch(arc) self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG], color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE) # arrow self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc, ls=self._style.cline) arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID), (cx + 0.20 * WID, cy + 0.35 * WID), (cx, cy)), fc=self._style.cc, ec=None) self.ax.add_artist(arrowhead) # target if self._style.bundle: self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom', fontsize=0.8 * self._style.fs, color=self._style.tc, clip_on=True, zorder=PORDER_TEXT) def _conds(self, xy, istrue=False): xpos, ypos = xy if istrue: _fc = self._style.lc else: _fc = self._style.gc box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15, fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE) self.ax.add_patch(box) def _ctrl_qubit(self, xy): xpos, ypos = xy box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15, fc=self._style.lc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE) self.ax.add_patch(box) def _tgt_qubit(self, xy): xpos, ypos = xy box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35, fc=self._style.dispcol['target'], ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE) self.ax.add_patch(box) # add '+' symbol self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG], color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE) self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos], color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE) def _swap(self, xy): xpos, ypos = xy self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID], color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE) self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID], color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE) def _barrier(self, config, anc): xys = config['coord'] group = config['group'] y_reg = [] for qreg in self._qreg_dict.values(): if qreg['group'] in group: y_reg.append(qreg['y']) x0 = xys[0][0] box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5 box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5 box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0), width=0.6 * WID, height=box_y1 - box_y0, fc=self._style.bc, ec=None, alpha=0.6, linewidth=1.5, zorder=PORDER_GRAY) self.ax.add_patch(box) for xy in xys: xpos, ypos = xy self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5], linewidth=1, linestyle="dashed", color=self._style.lc, zorder=PORDER_TEXT) def _linefeed_mark(self, xy): xpos, ypos = xy self.ax.plot([xpos - .1, xpos - .1], [ypos, ypos - self._cond['n_lines'] + 1], color=self._style.lc, zorder=PORDER_LINE) self.ax.plot([xpos + .1, xpos + .1], [ypos, ypos - self._cond['n_lines'] + 1], color=self._style.lc, zorder=PORDER_LINE) def draw(self, filename=None, verbose=False): self._draw_regs() self._draw_ops(verbose) _xl = - self._style.margin[0] _xr = self._cond['xmax'] + self._style.margin[1] _yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5 _yt = self._style.margin[3] + 0.5 self.ax.set_xlim(_xl, _xr) self.ax.set_ylim(_yb, _yt) # update figure size fig_w = _xr - _xl fig_h = _yt - _yb if self._style.figwidth < 0.0: self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w) if filename: self.figure.savefig(filename, dpi=self._style.dpi, bbox_inches='tight') plt.close(self.figure) return self.figure def _draw_regs(self): # quantum register for ii, reg in enumerate(self._qreg): if len(self._qreg) > 1: label = '${}_{{{}}}$'.format(reg.reg.name, reg.index) else: label = '${}$'.format(reg.reg.name) pos = -ii self._qreg_dict[ii] = { 'y': pos, 'label': label, 'index': reg.index, 'group': reg.reg } self._cond['n_lines'] += 1 # classical register if self._creg: n_creg = self._creg.copy() n_creg.pop(0) idx = 0 y_off = -len(self._qreg) for ii, (reg, nreg) in enumerate(itertools.zip_longest( self._creg, n_creg)): pos = y_off - idx if self._style.bundle: label = '${}$'.format(reg.reg.name) self._creg_dict[ii] = { 'y': pos, 'label': label, 'index': reg.index, 'group': reg.reg } if not (not nreg or reg.reg != nreg.reg): continue else: label = '${}_{{{}}}$'.format(reg.reg.name, reg.index) self._creg_dict[ii] = { 'y': pos, 'label': label, 'index': reg.index, 'group': reg.reg } self._cond['n_lines'] += 1 idx += 1 def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False): # quantum register for qreg in self._qreg_dict.values(): if n_fold == 0: label = qreg['label'] + ' : $\\left|0\\right\\rangle$' else: label = qreg['label'] y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1) self.ax.text(-0.5, y, label, ha='right', va='center', fontsize=self._style.fs, color=self._style.tc, clip_on=True, zorder=PORDER_TEXT) self._line([0, y], [self._cond['xmax'], y]) # classical register this_creg_dict = {} for creg in self._creg_dict.values(): if n_fold == 0: label = creg['label'] + ' : 0 ' else: label = creg['label'] y = creg['y'] - n_fold * (self._cond['n_lines'] + 1) if y not in this_creg_dict.keys(): this_creg_dict[y] = {'val': 1, 'label': label} else: this_creg_dict[y]['val'] += 1 for y, this_creg in this_creg_dict.items(): # bundle if this_creg['val'] > 1: self.ax.plot([.6, .7], [y - .1, y + .1], color=self._style.cc, zorder=PORDER_LINE) self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom', fontsize=0.8 * self._style.fs, color=self._style.tc, clip_on=True, zorder=PORDER_TEXT) self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center', fontsize=self._style.fs, color=self._style.tc, clip_on=True, zorder=PORDER_TEXT) self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline) # lf line if feedline_r: self._linefeed_mark((self._style.fold + 1 - 0.1, - n_fold * (self._cond['n_lines'] + 1))) if feedline_l: self._linefeed_mark((0.1, - n_fold * (self._cond['n_lines'] + 1))) def _draw_ops(self, verbose=False): _wide_gate = ['u2', 'u3', 'cu2', 'cu3'] _barriers = {'coord': [], 'group': []} # # generate coordinate manager # q_anchors = {} for key, qreg in self._qreg_dict.items(): q_anchors[key] = Anchor(reg_num=self._cond['n_lines'], yind=qreg['y'], fold=self._style.fold) c_anchors = {} for key, creg in self._creg_dict.items(): c_anchors[key] = Anchor(reg_num=self._cond['n_lines'], yind=creg['y'], fold=self._style.fold) # # draw gates # prev_anc = -1 for layer in self._ops: layer_width = 1 for op in layer: if op.name in _wide_gate: if layer_width < 2: layer_width = 2 # if custom gate with a longer than standard name determine # width elif op.name not in ['barrier', 'snapshot', 'load', 'save', 'noise', 'cswap', 'swap', 'measure'] and len( op.name) >= 4: box_width = round(len(op.name) / 8) # handle params/subtext longer than op names if op.type == 'op' and hasattr(op.op, 'params'): param = self.param_parse(op.op.params, self._style.pimode) if len(param) > len(op.name): box_width = round(len(param) / 8) # If more than 4 characters min width is 2 if box_width <= 1: box_width = 2 if layer_width < box_width: if box_width > 2: layer_width = box_width * 2 else: layer_width = 2 continue # If more than 4 characters min width is 2 if box_width <= 1: box_width = 2 if layer_width < box_width: if box_width > 2: layer_width = box_width * 2 else: layer_width = 2 this_anc = prev_anc + 1 for op in layer: _iswide = op.name in _wide_gate if op.name not in ['barrier', 'snapshot', 'load', 'save', 'noise', 'cswap', 'swap', 'measure'] and len( op.name) >= 4: _iswide = True # get qreg index q_idxs = [] for qarg in op.qargs: for index, reg in self._qreg_dict.items(): if (reg['group'] == qarg[0] and reg['index'] == qarg[1]): q_idxs.append(index) break # get creg index c_idxs = [] for carg in op.cargs: for index, reg in self._creg_dict.items(): if (reg['group'] == carg[0] and reg['index'] == carg[1]): c_idxs.append(index) break # Only add the gate to the anchors if it is going to be plotted. # This prevents additional blank wires at the end of the line if # the last instruction is a barrier type if self.plot_barriers or \ op.name not in ['barrier', 'snapshot', 'load', 'save', 'noise']: for ii in q_idxs: q_anchors[ii].set_index(this_anc, layer_width) # qreg coordinate q_xy = [q_anchors[ii].plot_coord(this_anc, layer_width) for ii in q_idxs] # creg coordinate c_xy = [c_anchors[ii].plot_coord(this_anc, layer_width) for ii in c_idxs] # bottom and top point of qreg qreg_b = min(q_xy, key=lambda xy: xy[1]) qreg_t = max(q_xy, key=lambda xy: xy[1]) # update index based on the value from plotting this_anc = q_anchors[q_idxs[0]].gate_anchor if verbose: print(op) if op.type == 'op' and hasattr(op.op, 'params'): param = self.param_parse(op.op.params, self._style.pimode) else: param = None # conditional gate if op.condition: c_xy = [c_anchors[ii].plot_coord(this_anc, layer_width) for ii in self._creg_dict] mask = 0 for index, cbit in enumerate(self._creg): if cbit.reg == op.condition[0]: mask |= (1 << index) val = op.condition[1] # cbit list to consider fmt_c = '{{:0{}b}}'.format(len(c_xy)) cmask = list(fmt_c.format(mask))[::-1] # value fmt_v = '{{:0{}b}}'.format(cmask.count('1')) vlist = list(fmt_v.format(val))[::-1] # plot conditionals v_ind = 0 xy_plot = [] for xy, m in zip(c_xy, cmask): if m == '1': if xy not in xy_plot: if vlist[v_ind] == '1' or self._style.bundle: self._conds(xy, istrue=True) else: self._conds(xy, istrue=False) xy_plot.append(xy) v_ind += 1 creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0] self._subtext(creg_b, hex(val)) self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline) # # draw special gates # if op.name == 'measure': vv = self._creg_dict[c_idxs[0]]['index'] self._measure(q_xy[0], c_xy[0], vv) elif op.name in ['barrier', 'snapshot', 'load', 'save', 'noise']: _barriers = {'coord': [], 'group': []} for index, qbit in enumerate(q_idxs): q_group = self._qreg_dict[qbit]['group'] if q_group not in _barriers['group']: _barriers['group'].append(q_group) _barriers['coord'].append(q_xy[index]) if self.plot_barriers: self._barrier(_barriers, this_anc) else: # this stop there being blank lines plotted in place of barriers this_anc -= 1 elif op.name == 'initialize': vec = '[%s]' % param self._custom_multiqubit_gate(q_xy, wide=_iswide, text="|psi>", subtext=vec) elif op.name == 'unitary': # TODO(mtreinish): Look into adding the unitary to the # subtext self._custom_multiqubit_gate(q_xy, wide=_iswide, text="U") # # draw single qubit gates # elif len(q_xy) == 1: disp = op.name if param: prm = '({})'.format(param) if len(prm) < 20: self._gate(q_xy[0], wide=_iswide, text=disp, subtext=prm) else: self._gate(q_xy[0], wide=_iswide, text=disp) else: self._gate(q_xy[0], wide=_iswide, text=disp) # # draw multi-qubit gates (n=2) # elif len(q_xy) == 2: # cx if op.name == 'cx': self._ctrl_qubit(q_xy[0]) self._tgt_qubit(q_xy[1]) # add qubit-qubit wiring self._line(qreg_b, qreg_t) # cz for latexmode elif op.name == 'cz': if self._style.latexmode: self._ctrl_qubit(q_xy[0]) self._ctrl_qubit(q_xy[1]) else: disp = op.name.replace('c', '') self._ctrl_qubit(q_xy[0]) self._gate(q_xy[1], wide=_iswide, text=disp) # add qubit-qubit wiring self._line(qreg_b, qreg_t) # control gate elif op.name in ['cy', 'ch', 'cu3', 'crz']: disp = op.name.replace('c', '') self._ctrl_qubit(q_xy[0]) if param: self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param)) else: self._gate(q_xy[1], wide=_iswide, text=disp) # add qubit-qubit wiring self._line(qreg_b, qreg_t) # cu1 elif op.name == 'cu1': self._ctrl_qubit(q_xy[0]) self._ctrl_qubit(q_xy[1]) self._sidetext(qreg_b, param) # add qubit-qubit wiring self._line(qreg_b, qreg_t) # rzz gate elif op.name == 'rzz': self._ctrl_qubit(q_xy[0]) self._ctrl_qubit(q_xy[1]) self._sidetext(qreg_b, text='zz({})'.format(param)) # add qubit-qubit wiring self._line(qreg_b, qreg_t) # swap gate elif op.name == 'swap': self._swap(q_xy[0]) self._swap(q_xy[1]) # add qubit-qubit wiring self._line(qreg_b, qreg_t) # Custom gate else: self._custom_multiqubit_gate(q_xy, wide=_iswide, text=op.name) # # draw multi-qubit gates (n=3) # elif len(q_xy) == 3: # cswap gate if op.name == 'cswap': self._ctrl_qubit(q_xy[0]) self._swap(q_xy[1]) self._swap(q_xy[2]) # add qubit-qubit wiring self._line(qreg_b, qreg_t) # ccx gate elif op.name == 'ccx': self._ctrl_qubit(q_xy[0]) self._ctrl_qubit(q_xy[1]) self._tgt_qubit(q_xy[2]) # add qubit-qubit wiring self._line(qreg_b, qreg_t) # custom gate else: self._custom_multiqubit_gate(q_xy, wide=_iswide, text=op.name) # draw custom multi-qubit gate elif len(q_xy) > 3: self._custom_multiqubit_gate(q_xy, wide=_iswide, text=op.name) else: logger.critical('Invalid gate %s', op) raise exceptions.VisualizationError('invalid gate {}'.format(op)) prev_anc = this_anc + layer_width - 1 # # adjust window size and draw horizontal lines # anchors = [q_anchors[ii].get_index() for ii in self._qreg_dict] if anchors: max_anc = max(anchors) else: max_anc = 0 n_fold = max(0, max_anc - 1) // self._style.fold # window size if max_anc > self._style.fold > 0: self._cond['xmax'] = self._style.fold + 1 self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1 else: self._cond['xmax'] = max_anc + 1 self._cond['ymax'] = self._cond['n_lines'] # add horizontal lines for ii in range(n_fold + 1): feedline_r = (n_fold > 0 and n_fold > ii) feedline_l = (ii > 0) self._draw_regs_sub(ii, feedline_l, feedline_r) # draw gate number if self._style.index: for ii in range(max_anc): if self._style.fold > 0: x_coord = ii % self._style.fold + 1 y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7 else: x_coord = ii + 1 y_coord = 0.7 self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center', fontsize=self._style.sfs, color=self._style.tc, clip_on=True, zorder=PORDER_TEXT) @staticmethod def param_parse(v, pimode=False): # create an empty list to store the parameters in param_parts = [None] * len(v) for i, e in enumerate(v): if pimode: try: param_parts[i] = MatplotlibDrawer.format_pi(e) except TypeError: param_parts[i] = str(e) else: try: param_parts[i] = MatplotlibDrawer.format_numeric(e) except TypeError: param_parts[i] = str(e) if param_parts[i].startswith('-'): param_parts[i] = '$-$' + param_parts[i][1:] param_parts = ', '.join(param_parts) return param_parts @staticmethod def format_pi(val): fracvals = MatplotlibDrawer.fraction(val) buf = '' if fracvals: nmr, dnm = fracvals.numerator, fracvals.denominator if nmr == 1: buf += '$\\pi$' elif nmr == -1: buf += '-$\\pi$' else: buf += '{}$\\pi$'.format(nmr) if dnm > 1: buf += '/{}'.format(dnm) return buf else: coef = MatplotlibDrawer.format_numeric(val / np.pi) if coef == '0': return '0' return '{}$\\pi$'.format(coef) @staticmethod def format_numeric(val, tol=1e-5): if isinstance(val, complex): return str(val) elif complex(val).imag != 0: val = complex(val) abs_val = abs(val) if math.isclose(abs_val, 0.0, abs_tol=1e-100): return '0' if math.isclose(math.fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5: return str(int(val)) if 0.1 <= abs_val < 100.0: return '{:.2f}'.format(val) return '{:.1e}'.format(val) @staticmethod def fraction(val, base=np.pi, n=100, tol=1e-5): abs_val = abs(val) for i in range(1, n): for j in range(1, n): if math.isclose(abs_val, i / j * base, rel_tol=tol): if val < 0: i *= -1 return fractions.Fraction(i, j) return None class EventsOutputChannels: """Pulse dataset for channel.""" def __init__(self, t0, tf): """Create new channel dataset. Args: t0 (int): starting time of plot tf (int): ending time of plot """ self.pulses = {} self.t0 = t0 self.tf = tf self._waveform = None self._framechanges = None self._conditionals = None self._snapshots = None self._labels = None self.enable = False def add_instruction(self, start_time, pulse): """Add new pulse instruction to channel. Args: start_time (int): Starting time of instruction pulse (Instruction): Instruction object to be added """ if start_time in self.pulses.keys(): self.pulses[start_time].append(pulse.command) else: self.pulses[start_time] = [pulse.command] @property def waveform(self): """Get waveform.""" if self._waveform is None: self._build_waveform() return self._waveform[self.t0:self.tf] @property def framechanges(self): """Get frame changes.""" if self._framechanges is None: self._build_waveform() return self._trim(self._framechanges) @property def conditionals(self): """Get conditionals.""" if self._conditionals is None: self._build_waveform() return self._trim(self._conditionals) @property def snapshots(self): """Get snapshots.""" if self._snapshots is None: self._build_waveform() return self._trim(self._snapshots) @property def labels(self): """Get labels.""" if self._labels is None: self._build_waveform() return self._trim(self._labels) def is_empty(self): """Return if pulse is empty. Returns: bool: if the channel has nothing to plot """ if any(self.waveform) or self.framechanges or self.conditionals or self.snapshots: return False return True def to_table(self, name): """Get table contains. Args: name (str): name of channel Returns: dict: dictionary of events in the channel """ time_event = [] framechanges = self.framechanges conditionals = self.conditionals snapshots = self.snapshots for key, val in framechanges.items(): data_str = 'framechange: %.2f' % val time_event.append((key, name, data_str)) for key, val in conditionals.items(): data_str = 'conditional, %s' % val time_event.append((key, name, data_str)) for key, val in snapshots.items(): data_str = 'snapshot: %s' % val time_event.append((key, name, data_str)) return time_event def _build_waveform(self): """Create waveform from stored pulses. """ self._framechanges = {} self._conditionals = {} self._snapshots = {} self._labels = {} fc = 0 pv = np.zeros(self.tf + 1, dtype=np.complex128) wf = np.zeros(self.tf + 1, dtype=np.complex128) last_pv = None for time, commands in sorted(self.pulses.items()): if time > self.tf: break tmp_fc = 0 for command in commands: if isinstance(command, FrameChange): tmp_fc += command.phase pv[time:] = 0 elif isinstance(command, Snapshot): self._snapshots[time] = command.name if tmp_fc != 0: self._framechanges[time] = tmp_fc fc += tmp_fc for command in commands: if isinstance(command, PersistentValue): pv[time:] = np.exp(1j*fc) * command.value last_pv = (time, command) break for command in commands: duration = command.duration tf = min(time + duration, self.tf) if isinstance(command, SamplePulse): wf[time:tf] = np.exp(1j*fc) * command.samples[:tf-time] pv[time:] = 0 self._labels[time] = (tf, command) if last_pv is not None: pv_cmd = last_pv[1] self._labels[last_pv[0]] = (time, pv_cmd) last_pv = None elif isinstance(command, Acquire): wf[time:tf] = np.ones(command.duration) self._labels[time] = (tf, command) self._waveform = wf + pv def _trim(self, events): """Return events during given `time_range`. Args: events (dict): time and operation of events Returns: dict: dictionary of events within the time """ events_in_time_range = {} for k, v in events.items(): if self.t0 <= k <= self.tf: events_in_time_range[k] = v return events_in_time_range class SamplePulseDrawer: """A class to create figure for sample pulse.""" def __init__(self, style): """Create new figure. Args: style (OPStylePulse): style sheet """ self.style = style or OPStylePulse() def draw(self, pulse, dt, interp_method, scaling=1): """Draw figure. Args: pulse (SamplePulse): SamplePulse to draw dt (float): time interval interp_method (Callable): interpolation function See `qiskit.visualization.interpolation` for more information scaling (float): Relative visual scaling of waveform amplitudes Returns: matplotlib.figure: A matplotlib figure object of the pulse envelope """ figure = plt.figure() interp_method = interp_method or interpolation.step_wise figure.set_size_inches(self.style.figsize[0], self.style.figsize[1]) ax = figure.add_subplot(111) ax.set_facecolor(self.style.bg_color) samples = pulse.samples time = np.arange(0, len(samples) + 1, dtype=float) * dt time, re, im = interp_method(time, samples, self.style.num_points) # plot ax.fill_between(x=time, y1=re, y2=np.zeros_like(time), facecolor=self.style.wave_color[0], alpha=0.3, edgecolor=self.style.wave_color[0], linewidth=1.5, label='real part') ax.fill_between(x=time, y1=im, y2=np.zeros_like(time), facecolor=self.style.wave_color[1], alpha=0.3, edgecolor=self.style.wave_color[1], linewidth=1.5, label='imaginary part') ax.set_xlim(0, pulse.duration * dt) if scaling: ax.set_ylim(-scaling, scaling) else: v_max = max(max(np.abs(re)), max(np.abs(im))) ax.set_ylim(-1.2 * v_max, 1.2 * v_max) return figure class ScheduleDrawer: """A class to create figure for schedule and channel.""" def __init__(self, style): """Create new figure. Args: style (OPStyleSched): style sheet """ self.style = style or OPStyleSched() def _build_channels(self, schedule, t0, tf): # prepare waveform channels drive_channels = collections.OrderedDict() measure_channels = collections.OrderedDict() control_channels = collections.OrderedDict() acquire_channels = collections.OrderedDict() snapshot_channels = collections.OrderedDict() for chan in schedule.channels: if isinstance(chan, DriveChannel): try: drive_channels[chan] = EventsOutputChannels(t0, tf) except PulseError: pass elif isinstance(chan, MeasureChannel): try: measure_channels[chan] = EventsOutputChannels(t0, tf) except PulseError: pass elif isinstance(chan, ControlChannel): try: control_channels[chan] = EventsOutputChannels(t0, tf) except PulseError: pass elif isinstance(chan, AcquireChannel): try: acquire_channels[chan] = EventsOutputChannels(t0, tf) except PulseError: pass elif isinstance(chan, SnapshotChannel): try: snapshot_channels[chan] = EventsOutputChannels(t0, tf) except PulseError: pass output_channels = {**drive_channels, **measure_channels, **control_channels, **acquire_channels} channels = {**output_channels, **acquire_channels, **snapshot_channels} # sort by index then name to group qubits together. output_channels = collections.OrderedDict(sorted(output_channels.items(), key=lambda x: (x[0].index, x[0].name))) channels = collections.OrderedDict(sorted(channels.items(), key=lambda x: (x[0].index, x[0].name))) for start_time, instruction in schedule.instructions: for channel in instruction.channels: if channel in output_channels: output_channels[channel].add_instruction(start_time, instruction) elif channel in snapshot_channels: snapshot_channels[channel].add_instruction(start_time, instruction) return channels, output_channels, snapshot_channels def _count_valid_waveforms(self, channels, scaling=1, channels_to_plot=None, plot_all=False): # count numbers of valid waveform n_valid_waveform = 0 v_max = 0 for channel, events in channels.items(): if channels_to_plot: if channel in channels_to_plot: waveform = events.waveform v_max = max(v_max, max(np.abs(np.real(waveform))), max(np.abs(np.imag(waveform)))) n_valid_waveform += 1 events.enable = True else: if not events.is_empty() or plot_all: waveform = events.waveform v_max = max(v_max, max(np.abs(np.real(waveform))), max(np.abs(np.imag(waveform)))) n_valid_waveform += 1 events.enable = True if scaling: v_max = 0.5 * scaling else: v_max = 0.5 / (1.2 * v_max) return n_valid_waveform, v_max def _draw_table(self, figure, channels, dt, n_valid_waveform): del n_valid_waveform # unused # create table table_data = [] if self.style.use_table: for channel, events in channels.items(): if events.enable: table_data.extend(events.to_table(channel.name)) table_data = sorted(table_data, key=lambda x: x[0]) # plot table if table_data: # table area size ncols = self.style.table_columns nrows = int(np.ceil(len(table_data)/ncols)) # fig size h_table = nrows * self.style.fig_unit_h_table h_waves = (self.style.figsize[1] - h_table) # create subplots gs = gridspec.GridSpec(2, 1, height_ratios=[h_table, h_waves], hspace=0) tb = plt.subplot(gs[0]) ax = plt.subplot(gs[1]) # configure each cell tb.axis('off') cell_value = [['' for _kk in range(ncols * 3)] for _jj in range(nrows)] cell_color = [self.style.table_color * ncols for _jj in range(nrows)] cell_width = [*([0.2, 0.2, 0.5] * ncols)] for ii, data in enumerate(table_data): # pylint: disable=unbalanced-tuple-unpacking r, c = np.unravel_index(ii, (nrows, ncols), order='f') # pylint: enable=unbalanced-tuple-unpacking time, ch_name, data_str = data # item cell_value[r][3 * c + 0] = 't = %s' % time * dt cell_value[r][3 * c + 1] = 'ch %s' % ch_name cell_value[r][3 * c + 2] = data_str table = tb.table(cellText=cell_value, cellLoc='left', rowLoc='center', colWidths=cell_width, bbox=[0, 0, 1, 1], cellColours=cell_color) table.auto_set_font_size(False) table.set_fontsize = self.style.table_font_size else: ax = figure.add_subplot(111) figure.set_size_inches(self.style.figsize[0], self.style.figsize[1]) return ax def _draw_snapshots(self, ax, snapshot_channels, dt, y0): for events in snapshot_channels.values(): snapshots = events.snapshots if snapshots: for time in snapshots: ax.annotate(s="\u25D8", xy=(time*dt, y0), xytext=(time*dt, y0+0.08), arrowprops={'arrowstyle': 'wedge'}, ha='center') def _draw_framechanges(self, ax, fcs, dt, y0): framechanges_present = True for time in fcs.keys(): ax.text(x=time*dt, y=y0, s=r'$\circlearrowleft$', fontsize=self.style.icon_font_size, ha='center', va='center') return framechanges_present def _get_channel_color(self, channel): # choose color if isinstance(channel, DriveChannel): color = self.style.d_ch_color elif isinstance(channel, ControlChannel): color = self.style.u_ch_color elif isinstance(channel, MeasureChannel): color = self.style.m_ch_color elif isinstance(channel, AcquireChannel): color = self.style.a_ch_color else: color = 'black' return color def _prev_label_at_time(self, prev_labels, time): for _, labels in enumerate(prev_labels): for t0, (tf, _) in labels.items(): if time in (t0, tf): return True return False def _draw_labels(self, ax, labels, prev_labels, dt, y0): for t0, (tf, cmd) in labels.items(): if isinstance(cmd, PersistentValue): name = cmd.name if cmd.name else 'pv' elif isinstance(cmd, Acquire): name = cmd.name if cmd.name else 'acquire' else: name = cmd.name ax.annotate(r'%s' % name, xy=((t0+tf)//2*dt, y0), xytext=((t0+tf)//2*dt, y0-0.07), fontsize=self.style.label_font_size, ha='center', va='center') linestyle = self.style.label_ch_linestyle alpha = self.style.label_ch_alpha color = self.style.label_ch_color if not self._prev_label_at_time(prev_labels, t0): ax.axvline(t0*dt, -1, 1, color=color, linestyle=linestyle, alpha=alpha) if not (self._prev_label_at_time(prev_labels, tf) or tf in labels): ax.axvline(tf*dt, -1, 1, color=color, linestyle=linestyle, alpha=alpha) def _draw_channels(self, ax, output_channels, interp_method, t0, tf, dt, v_max, label=False, framechange=True): y0 = 0 prev_labels = [] for channel, events in output_channels.items(): if events.enable: # plot waveform waveform = events.waveform time = np.arange(t0, tf + 1, dtype=float) * dt time, re, im = interp_method(time, waveform, self.style.num_points) color = self._get_channel_color(channel) # scaling and offset re = v_max * re + y0 im = v_max * im + y0 offset = np.zeros_like(time) + y0 # plot ax.fill_between(x=time, y1=re, y2=offset, facecolor=color[0], alpha=0.3, edgecolor=color[0], linewidth=1.5, label='real part') ax.fill_between(x=time, y1=im, y2=offset, facecolor=color[1], alpha=0.3, edgecolor=color[1], linewidth=1.5, label='imaginary part') ax.plot((t0, tf), (y0, y0), color='#000000', linewidth=1.0) # plot frame changes fcs = events.framechanges if fcs and framechange: self._draw_framechanges(ax, fcs, dt, y0) # plot labels labels = events.labels if labels and label: self._draw_labels(ax, labels, prev_labels, dt, y0) prev_labels.append(labels) else: continue # plot label ax.text(x=0, y=y0, s=channel.name, fontsize=self.style.axis_font_size, ha='right', va='center') y0 -= 1 return y0 def draw(self, schedule, dt, interp_method, plot_range, scaling=1, channels_to_plot=None, plot_all=True, table=True, label=False, framechange=True): """Draw figure. Args: schedule (ScheduleComponent): Schedule to draw dt (float): time interval interp_method (Callable): interpolation function See `qiskit.visualization.interpolation` for more information plot_range (tuple[float]): plot range scaling (float): Relative visual scaling of waveform amplitudes channels_to_plot (list[OutputChannel]): channels to draw plot_all (bool): if plot all channels even it is empty table (bool): Draw event table label (bool): Label individual instructions framechange (bool): Add framechange indicators Returns: matplotlib.figure: A matplotlib figure object for the pulse schedule Raises: VisualizationError: when schedule cannot be drawn """ figure = plt.figure() if not channels_to_plot: channels_to_plot = [] interp_method = interp_method or interpolation.step_wise # setup plot range if plot_range: t0 = int(np.floor(plot_range[0]/dt)) tf = int(np.floor(plot_range[1]/dt)) else: t0 = 0 tf = schedule.stop_time # prepare waveform channels (channels, output_channels, snapshot_channels) = self._build_channels(schedule, t0, tf) # count numbers of valid waveform n_valid_waveform, v_max = self._count_valid_waveforms(output_channels, scaling=scaling, channels_to_plot=channels_to_plot, plot_all=plot_all) if table: ax = self._draw_table(figure, channels, dt, n_valid_waveform) else: ax = figure.add_subplot(111) figure.set_size_inches(self.style.figsize[0], self.style.figsize[1]) ax.set_facecolor(self.style.bg_color) y0 = self._draw_channels(ax, output_channels, interp_method, t0, tf, dt, v_max, label=label, framechange=framechange) self._draw_snapshots(ax, snapshot_channels, dt, y0) ax.set_xlim(t0 * dt, tf * dt) ax.set_ylim(y0, 1) ax.set_yticklabels([]) return figure
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-docstring,invalid-name,no-member,broad-except # pylint: disable=no-else-return, attribute-defined-outside-init # pylint: disable=import-error from qiskit_experiments.library import StateTomography import qiskit class StateTomographyBench: params = [2, 3, 4, 5] param_names = ["n_qubits"] version = "0.3.0" timeout = 120.0 def setup(self, _): self.qasm_backend = qiskit.BasicAer.get_backend("qasm_simulator") def time_state_tomography_bell(self, n_qubits): meas_qubits = [n_qubits - 2, n_qubits - 1] qr_full = qiskit.QuantumRegister(n_qubits) bell = qiskit.QuantumCircuit(qr_full) bell.h(qr_full[meas_qubits[0]]) bell.cx(qr_full[meas_qubits[0]], qr_full[meas_qubits[1]]) qst_exp = StateTomography(bell, measurement_qubits=meas_qubits) expdata = qst_exp.run(self.qasm_backend, shots=5000).block_for_results() expdata.analysis_results("state") expdata.analysis_results("state_fidelity") def time_state_tomography_cat(self, n_qubits): qr = qiskit.QuantumRegister(n_qubits, "qr") circ = qiskit.QuantumCircuit(qr, name="cat") circ.h(qr[0]) for i in range(1, n_qubits): circ.cx(qr[0], qr[i]) qst_exp = StateTomography(circ) expdata = qst_exp.run(self.qasm_backend, shots=5000).block_for_results() expdata.analysis_results("state") expdata.analysis_results("state_fidelity")
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. # pylint: disable=missing-docstring import os import configparser as cp from uuid import uuid4 from unittest import mock from qiskit import exceptions from qiskit.test import QiskitTestCase from qiskit import user_config class TestUserConfig(QiskitTestCase): def setUp(self): super().setUp() self.file_path = "test_%s.conf" % uuid4() def test_empty_file_read(self): config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({}, config.settings) def test_invalid_optimization_level(self): test_config = """ [default] transpile_optimization_level = 76 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_invalid_circuit_drawer(self): test_config = """ [default] circuit_drawer = MSPaint """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_circuit_drawer_valid(self): test_config = """ [default] circuit_drawer = latex """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"circuit_drawer": "latex"}, config.settings) def test_invalid_circuit_reverse_bits(self): test_config = """ [default] circuit_reverse_bits = Neither """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_circuit_reverse_bits_valid(self): test_config = """ [default] circuit_reverse_bits = false """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"circuit_reverse_bits": False}, config.settings) def test_optimization_level_valid(self): test_config = """ [default] transpile_optimization_level = 1 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"transpile_optimization_level": 1}, config.settings) def test_invalid_num_processes(self): test_config = """ [default] num_processes = -256 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_valid_num_processes(self): test_config = """ [default] num_processes = 31 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"num_processes": 31}, config.settings) def test_valid_parallel(self): test_config = """ [default] parallel = False """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"parallel_enabled": False}, config.settings) def test_all_options_valid(self): test_config = """ [default] circuit_drawer = latex circuit_mpl_style = default circuit_mpl_style_path = ~:~/.qiskit circuit_reverse_bits = false transpile_optimization_level = 3 suppress_packaging_warnings = true parallel = false num_processes = 15 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual( { "circuit_drawer": "latex", "circuit_mpl_style": "default", "circuit_mpl_style_path": ["~", "~/.qiskit"], "circuit_reverse_bits": False, "transpile_optimization_level": 3, "num_processes": 15, "parallel_enabled": False, }, config.settings, ) def test_set_config_all_options_valid(self): self.addCleanup(os.remove, self.file_path) user_config.set_config("circuit_drawer", "latex", file_path=self.file_path) user_config.set_config("circuit_mpl_style", "default", file_path=self.file_path) user_config.set_config("circuit_mpl_style_path", "~:~/.qiskit", file_path=self.file_path) user_config.set_config("circuit_reverse_bits", "false", file_path=self.file_path) user_config.set_config("transpile_optimization_level", "3", file_path=self.file_path) user_config.set_config("parallel", "false", file_path=self.file_path) user_config.set_config("num_processes", "15", file_path=self.file_path) config_settings = None with mock.patch.dict(os.environ, {"QISKIT_SETTINGS": self.file_path}, clear=True): config_settings = user_config.get_config() self.assertEqual( { "circuit_drawer": "latex", "circuit_mpl_style": "default", "circuit_mpl_style_path": ["~", "~/.qiskit"], "circuit_reverse_bits": False, "transpile_optimization_level": 3, "num_processes": 15, "parallel_enabled": False, }, config_settings, ) def test_set_config_multiple_sections(self): self.addCleanup(os.remove, self.file_path) user_config.set_config("circuit_drawer", "latex", file_path=self.file_path) user_config.set_config("circuit_mpl_style", "default", file_path=self.file_path) user_config.set_config("transpile_optimization_level", "3", file_path=self.file_path) user_config.set_config("circuit_drawer", "latex", section="test", file_path=self.file_path) user_config.set_config("parallel", "false", section="test", file_path=self.file_path) user_config.set_config("num_processes", "15", section="test", file_path=self.file_path) config = cp.ConfigParser() config.read(self.file_path) self.assertEqual(config.sections(), ["default", "test"]) self.assertEqual( { "circuit_drawer": "latex", "circuit_mpl_style": "default", "transpile_optimization_level": "3", }, dict(config.items("default")), )
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# Copyright 2022-2023 Ohad Lev. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0, # or in the root directory of this package("LICENSE.txt"). # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for `util.py` module.""" import unittest from datetime import datetime from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from sat_circuits_engine.util import flatten_circuit, timestamp class UtilTest(unittest.TestCase): def test_timestamp(self): """Test for the `timestamp` function.""" self.assertEqual(timestamp(datetime(2022, 12, 3, 17, 0, 45, 0)), "D03.12.22_T17.00.45") def test_flatten_circuit(self): """Test for the `flatten_circuit` function.""" bits_1 = 2 bits_2 = 3 qreg_1 = QuantumRegister(bits_1) qreg_2 = QuantumRegister(bits_2) creg_1 = ClassicalRegister(bits_1) creg_2 = ClassicalRegister(bits_2) circuit = QuantumCircuit(qreg_1, qreg_2, creg_1, creg_2) self.assertEqual(circuit.num_qubits, bits_1 + bits_2) self.assertEqual(circuit.num_clbits, bits_1 + bits_2) self.assertEqual(len(circuit.qregs), 2) self.assertEqual(len(circuit.cregs), 2) flat_circuit = flatten_circuit(circuit) self.assertEqual(flat_circuit.num_qubits, bits_1 + bits_2) self.assertEqual(flat_circuit.num_clbits, bits_1 + bits_2) self.assertEqual(len(flat_circuit.qregs), 1) self.assertEqual(len(flat_circuit.cregs), 1) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """BasicAer Backends Test.""" from qiskit import BasicAer from qiskit.providers.basicaer import BasicAerProvider from qiskit.providers.exceptions import QiskitBackendNotFoundError from qiskit.test import providers class TestBasicAerBackends(providers.ProviderTestCase): """Qiskit BasicAer Backends (Object) Tests.""" provider_cls = BasicAerProvider backend_name = "qasm_simulator" def test_deprecated(self): """Test that deprecated names map the same backends as the new names.""" def _get_first_available_backend(provider, backend_names): """Gets the first available backend.""" if isinstance(backend_names, str): backend_names = [backend_names] for backend_name in backend_names: try: return provider.get_backend(backend_name).name() except QiskitBackendNotFoundError: pass return None deprecated_names = BasicAer._deprecated_backend_names() for oldname, newname in deprecated_names.items(): expected = ( "WARNING:qiskit.providers.providerutils:Backend '%s' is deprecated. " "Use '%s'." % (oldname, newname) ) with self.subTest(oldname=oldname, newname=newname): with self.assertLogs("qiskit.providers.providerutils", level="WARNING") as context: resolved_newname = _get_first_available_backend(BasicAer, newname) real_backend = BasicAer.get_backend(resolved_newname) self.assertEqual(BasicAer.backends(oldname)[0], real_backend) self.assertEqual(context.output, [expected]) def test_aliases_fail(self): """Test a failing backend lookup.""" self.assertRaises(QiskitBackendNotFoundError, BasicAer.get_backend, "bad_name") def test_aliases_return_empty_list(self): """Test backends() return an empty list if name is unknown.""" self.assertEqual(BasicAer.backends("bad_name"), [])
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """BasicAer provider integration tests.""" import unittest from qiskit import BasicAer from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import execute from qiskit.result import Result from qiskit.providers.basicaer import BasicAerError from qiskit.test import QiskitTestCase class TestBasicAerIntegration(QiskitTestCase): """Qiskit BasicAer simulator integration tests.""" def setUp(self): super().setUp() qr = QuantumRegister(1) cr = ClassicalRegister(1) self._qc1 = QuantumCircuit(qr, cr, name="qc1") self._qc2 = QuantumCircuit(qr, cr, name="qc2") self._qc1.measure(qr[0], cr[0]) self.backend = BasicAer.get_backend("qasm_simulator") self._result1 = execute(self._qc1, self.backend).result() def test_builtin_simulator_result_fields(self): """Test components of a result from a local simulator.""" self.assertEqual("qasm_simulator", self._result1.backend_name) self.assertIsInstance(self._result1.job_id, str) self.assertEqual(self._result1.status, "COMPLETED") self.assertEqual(self._result1.results[0].status, "DONE") def test_basicaer_execute(self): """Test Compiler and run.""" qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) job = execute(qc, self.backend) result = job.result() self.assertIsInstance(result, Result) def test_basicaer_execute_two(self): """Test Compiler and run.""" qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qc_extra = QuantumCircuit(qubit_reg, clbit_reg, name="extra") qc_extra.measure(qubit_reg, clbit_reg) job = execute([qc, qc_extra], self.backend) result = job.result() self.assertIsInstance(result, Result) def test_basicaer_num_qubits(self): """Test BasicAerError is raised if num_qubits too large to simulate.""" qc = QuantumCircuit(50, 1) qc.x(0) qc.measure(0, 0) with self.assertRaises(BasicAerError): execute(qc, self.backend) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for all BasicAer simulators.""" import io from logging import StreamHandler, getLogger import sys from qiskit import BasicAer from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.compiler import transpile from qiskit.compiler import assemble from qiskit.qobj import QobjHeader from qiskit.test import QiskitTestCase class StreamHandlerRaiseException(StreamHandler): """Handler class that will raise an exception on formatting errors.""" def handleError(self, record): raise sys.exc_info() class TestBasicAerQobj(QiskitTestCase): """Tests for all the Terra simulators.""" 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)) qr = QuantumRegister(1) cr = ClassicalRegister(1) self.qc1 = QuantumCircuit(qr, cr, name="circuit0") self.qc1.h(qr[0]) def test_qobj_headers_in_result(self): """Test that the qobj headers are passed onto the results.""" custom_qobj_header = {"x": 1, "y": [1, 2, 3], "z": {"a": 4}} for backend in BasicAer.backends(): with self.subTest(backend=backend): new_circ = transpile(self.qc1, backend=backend) qobj = assemble(new_circ, shots=1024) # Update the Qobj header. qobj.header = QobjHeader.from_dict(custom_qobj_header) # Update the Qobj.experiment header. qobj.experiments[0].header.some_field = "extra info" result = backend.run(qobj).result() self.assertEqual(result.header.to_dict(), custom_qobj_header) self.assertEqual(result.results[0].header.some_field, "extra info")
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test executing multiple-register circuits on BasicAer.""" from qiskit import BasicAer, execute from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.quantum_info import Operator, Statevector, process_fidelity, state_fidelity from qiskit.test import QiskitTestCase class TestCircuitMultiRegs(QiskitTestCase): """QuantumCircuit Qasm tests.""" def test_circuit_multi(self): """Test circuit multi regs declared at start.""" qreg0 = QuantumRegister(2, "q0") creg0 = ClassicalRegister(2, "c0") qreg1 = QuantumRegister(2, "q1") creg1 = ClassicalRegister(2, "c1") circ = QuantumCircuit(qreg0, qreg1, creg0, creg1) circ.x(qreg0[1]) circ.x(qreg1[0]) meas = QuantumCircuit(qreg0, qreg1, creg0, creg1) meas.measure(qreg0, creg0) meas.measure(qreg1, creg1) qc = circ.compose(meas) backend_sim = BasicAer.get_backend("qasm_simulator") result = execute(qc, backend_sim, seed_transpiler=34342).result() counts = result.get_counts(qc) target = {"01 10": 1024} backend_sim = BasicAer.get_backend("statevector_simulator") result = execute(circ, backend_sim, seed_transpiler=3438).result() state = result.get_statevector(circ) backend_sim = BasicAer.get_backend("unitary_simulator") result = execute(circ, backend_sim, seed_transpiler=3438).result() unitary = Operator(result.get_unitary(circ)) self.assertEqual(counts, target) self.assertAlmostEqual(state_fidelity(Statevector.from_label("0110"), state), 1.0, places=7) self.assertAlmostEqual( process_fidelity(Operator.from_label("IXXI"), unitary), 1.0, places=7 )
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test QASM simulator.""" import os import unittest import io from logging import StreamHandler, getLogger import sys import numpy as np from qiskit import execute from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.compiler import transpile, assemble from qiskit.providers.basicaer import QasmSimulatorPy from qiskit.test import providers class StreamHandlerRaiseException(StreamHandler): """Handler class that will raise an exception on formatting errors.""" def handleError(self, record): raise sys.exc_info() class TestBasicAerQasmSimulator(providers.BackendTestCase): """Test the Basic qasm_simulator.""" backend_cls = QasmSimulatorPy def setUp(self): super().setUp() self.seed = 88 qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") qasm_filename = os.path.join(qasm_dir, "example.qasm") transpiled_circuit = QuantumCircuit.from_qasm_file(qasm_filename) transpiled_circuit.name = "test" transpiled_circuit = transpile(transpiled_circuit, backend=self.backend) self.qobj = assemble(transpiled_circuit, shots=1000, seed_simulator=self.seed) logger = getLogger() self.addCleanup(logger.setLevel, logger.level) logger.setLevel("DEBUG") self.log_output = io.StringIO() logger.addHandler(StreamHandlerRaiseException(self.log_output)) def assertExecuteLog(self, log_msg): """Runs execute and check for logs containing specified message""" shots = 100 qr = QuantumRegister(2, "qr") cr = ClassicalRegister(4, "cr") circuit = QuantumCircuit(qr, cr) execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed) self.log_output.seek(0) # Filter unrelated log lines output_lines = self.log_output.readlines() execute_log_lines = [x for x in output_lines if log_msg in x] self.assertTrue(len(execute_log_lines) > 0) def test_submission_log_time(self): """Check Total Job Submission Time is logged""" self.assertExecuteLog("Total Job Submission Time") def test_qasm_simulator_single_shot(self): """Test single shot run.""" shots = 1 self.qobj.config.shots = shots result = self.backend.run(self.qobj).result() self.assertEqual(result.success, True) def test_measure_sampler_repeated_qubits(self): """Test measure sampler if qubits measured more than once.""" shots = 100 qr = QuantumRegister(2, "qr") cr = ClassicalRegister(4, "cr") circuit = QuantumCircuit(qr, cr) circuit.x(qr[1]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) circuit.measure(qr[1], cr[2]) circuit.measure(qr[0], cr[3]) target = {"0110": shots} job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed) result = job.result() counts = result.get_counts(0) self.assertEqual(counts, target) def test_measure_sampler_single_qubit(self): """Test measure sampler if single-qubit is measured.""" shots = 100 num_qubits = 5 qr = QuantumRegister(num_qubits, "qr") cr = ClassicalRegister(1, "cr") for qubit in range(num_qubits): circuit = QuantumCircuit(qr, cr) circuit.x(qr[qubit]) circuit.measure(qr[qubit], cr[0]) target = {"1": shots} job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed) result = job.result() counts = result.get_counts(0) self.assertEqual(counts, target) def test_measure_sampler_partial_qubit(self): """Test measure sampler if single-qubit is measured.""" shots = 100 num_qubits = 5 qr = QuantumRegister(num_qubits, "qr") cr = ClassicalRegister(4, "cr") # β–‘ β–‘ β–‘ β”Œβ”€β” β–‘ # qr_0: ──────░─────░─────░──Mβ”œβ”€β–‘β”€β”€β”€β”€ # β”Œβ”€β”€β”€β” β–‘ β–‘ β”Œβ”€β” β–‘ β””β•₯β”˜ β–‘ # qr_1: ─ X β”œβ”€β–‘β”€β”€β”€β”€β”€β–‘β”€β”€Mβ”œβ”€β–‘β”€β”€β•«β”€β”€β–‘β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β–‘ β–‘ β””β•₯β”˜ β–‘ β•‘ β–‘ # qr_2: ──────░─────░──╫──░──╫──░──── # β”Œβ”€β”€β”€β” β–‘ β”Œβ”€β” β–‘ β•‘ β–‘ β•‘ β–‘ β”Œβ”€β” # qr_3: ─ X β”œβ”€β–‘β”€β”€Mβ”œβ”€β–‘β”€β”€β•«β”€β”€β–‘β”€β”€β•«β”€β”€β–‘β”€β”€Mβ”œ # β””β”€β”€β”€β”˜ β–‘ β””β•₯β”˜ β–‘ β•‘ β–‘ β•‘ β–‘ β””β•₯β”˜ # qr_4: ──────░──╫──░──╫──░──╫──░──╫─ # β–‘ β•‘ β–‘ β•‘ β–‘ β•‘ β–‘ β•‘ # cr: 4/═════════╩═════╩═════╩═════╩═ # 1 0 2 3 circuit = QuantumCircuit(qr, cr) circuit.x(qr[3]) circuit.x(qr[1]) circuit.barrier(qr) circuit.measure(qr[3], cr[1]) circuit.barrier(qr) circuit.measure(qr[1], cr[0]) circuit.barrier(qr) circuit.measure(qr[0], cr[2]) circuit.barrier(qr) circuit.measure(qr[3], cr[3]) target = {"1011": shots} job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed) result = job.result() counts = result.get_counts(0) self.assertEqual(counts, target) def test_qasm_simulator(self): """Test data counts output for single circuit run against reference.""" result = self.backend.run(self.qobj).result() shots = 1024 threshold = 0.04 * shots counts = result.get_counts("test") target = { "100 100": shots / 8, "011 011": shots / 8, "101 101": shots / 8, "111 111": shots / 8, "000 000": shots / 8, "010 010": shots / 8, "110 110": shots / 8, "001 001": shots / 8, } self.assertDictAlmostEqual(counts, target, threshold) def test_if_statement(self): """Test if statements.""" shots = 100 qr = QuantumRegister(3, "qr") cr = ClassicalRegister(3, "cr") # β”Œβ”€β”€β”€β”β”Œβ”€β” β”Œβ”€β” # qr_0: ─ X β”œβ”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β•₯β”˜β”Œβ”€β” β””β•₯β”˜β”Œβ”€β” # qr_1: ─ X β”œβ”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€ # β””β”€β”€β”€β”˜ β•‘ β””β•₯β”˜ β”Œβ”€β”€β”€β” β•‘ β””β•₯β”˜β”Œβ”€β” # qr_2: ──────╫──╫─── X β”œβ”€β”€β•«β”€β”€β•«β”€β”€Mβ”œ # β•‘ β•‘ └─β•₯β”€β”˜ β•‘ β•‘ β””β•₯β”˜ # β•‘ β•‘ β”Œβ”€β”€β•¨β”€β”€β” β•‘ β•‘ β•‘ # cr: 3/══════╩══╩═║ 0x3 β•žβ•β•©β•β•β•©β•β•β•©β• # 0 1 β””β”€β”€β”€β”€β”€β”˜ 0 1 2 circuit_if_true = QuantumCircuit(qr, cr) circuit_if_true.x(qr[0]) circuit_if_true.x(qr[1]) circuit_if_true.measure(qr[0], cr[0]) circuit_if_true.measure(qr[1], cr[1]) circuit_if_true.x(qr[2]).c_if(cr, 0x3) circuit_if_true.measure(qr[0], cr[0]) circuit_if_true.measure(qr[1], cr[1]) circuit_if_true.measure(qr[2], cr[2]) # β”Œβ”€β”€β”€β”β”Œβ”€β” β”Œβ”€β” # qr_0: ─ X β”œβ”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β””β”¬β”€β”¬β”˜β””β•₯β”˜ β””β•₯β”˜β”Œβ”€β” # qr_1: ──Mβ”œβ”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€ # β””β•₯β”˜ β•‘ β”Œβ”€β”€β”€β” β•‘ β””β•₯β”˜β”Œβ”€β” # qr_2: ──╫───╫─── X β”œβ”€β”€β•«β”€β”€β•«β”€β”€Mβ”œ # β•‘ β•‘ └─β•₯β”€β”˜ β•‘ β•‘ β””β•₯β”˜ # β•‘ β•‘ β”Œβ”€β”€β•¨β”€β”€β” β•‘ β•‘ β•‘ # cr: 3/══╩═══╩═║ 0x3 β•žβ•β•©β•β•β•©β•β•β•©β• # 1 0 β””β”€β”€β”€β”€β”€β”˜ 0 1 2 circuit_if_false = QuantumCircuit(qr, cr) circuit_if_false.x(qr[0]) circuit_if_false.measure(qr[0], cr[0]) circuit_if_false.measure(qr[1], cr[1]) circuit_if_false.x(qr[2]).c_if(cr, 0x3) circuit_if_false.measure(qr[0], cr[0]) circuit_if_false.measure(qr[1], cr[1]) circuit_if_false.measure(qr[2], cr[2]) job = execute( [circuit_if_true, circuit_if_false], backend=self.backend, shots=shots, seed_simulator=self.seed, ) result = job.result() counts_if_true = result.get_counts(circuit_if_true) counts_if_false = result.get_counts(circuit_if_false) self.assertEqual(counts_if_true, {"111": 100}) self.assertEqual(counts_if_false, {"001": 100}) def test_bit_cif_crossaffect(self): """Test if bits in a classical register other than the single conditional bit affect the conditioned operation.""" # β”Œβ”€β”€β”€β” β”Œβ”€β” # q0_0: ───────── H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€Mβ”œ # β”Œβ”€β”€β”€β” └─β•₯β”€β”˜ β”Œβ”€β” β””β•₯β”˜ # q0_1: ─ X β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β•«β”€ # β”œβ”€β”€β”€β”€ β•‘ β””β•₯β”˜β”Œβ”€β” β•‘ # q0_2: ─ X β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€Mβ”œβ”€β•«β”€ # β””β”€β”€β”€β”˜β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”€β” β•‘ β””β•₯β”˜ β•‘ # c0: 3/═════║ c0_0=0x1 β•žβ•β•©β•β•β•©β•β•β•¬β• # β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 1 2 β•‘ # c1: 1/════════════════════════╩═ # 0 shots = 100 qr = QuantumRegister(3) cr = ClassicalRegister(3) cr1 = ClassicalRegister(1) circuit = QuantumCircuit(qr, cr, cr1) circuit.x([qr[1], qr[2]]) circuit.measure(qr[1], cr[1]) circuit.measure(qr[2], cr[2]) circuit.h(qr[0]).c_if(cr[0], True) circuit.measure(qr[0], cr1[0]) job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed) result = job.result().get_counts() target = {"0 110": 100} self.assertEqual(result, target) def test_teleport(self): """Test teleportation as in tutorials""" # β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β” β–‘ β”Œβ”€β” # qr_0: ─ Ry(Ο€/4) β”œβ”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€ H β”œβ”€β–‘β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”˜ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ β–‘ β””β•₯β”˜β”Œβ”€β” # qr_1: ──── H β”œβ”€β”€β”€β”€β”€β– β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β–‘β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ β–‘ β•‘ β””β•₯β”˜ β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” β”Œβ”€β” # qr_2: ──────────── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€β•«β”€β”€β•«β”€β”€β”€ Z β”œβ”€β”€β”€ X β”œβ”€β”€Mβ”œ # β””β”€β”€β”€β”˜ β–‘ β•‘ β•‘ └─β•₯β”€β”˜ └─β•₯β”€β”˜ β””β•₯β”˜ # β•‘ β•‘ β”Œβ”€β”€β•¨β”€β”€β” β•‘ β•‘ # cr0: 1/═════════════════════════════╩══╬═║ 0x1 β•žβ•β•β•β•¬β•β•β•β•β•¬β• # 0 β•‘ β””β”€β”€β”€β”€β”€β”˜β”Œβ”€β”€β•¨β”€β”€β” β•‘ # cr1: 1/════════════════════════════════╩════════║ 0x1 β•žβ•β•¬β• # 0 β””β”€β”€β”€β”€β”€β”˜ β•‘ # cr2: 1/═════════════════════════════════════════════════╩═ # 0 self.log.info("test_teleport") pi = np.pi shots = 2000 qr = QuantumRegister(3, "qr") cr0 = ClassicalRegister(1, "cr0") cr1 = ClassicalRegister(1, "cr1") cr2 = ClassicalRegister(1, "cr2") circuit = QuantumCircuit(qr, cr0, cr1, cr2, name="teleport") circuit.h(qr[1]) circuit.cx(qr[1], qr[2]) circuit.ry(pi / 4, qr[0]) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.barrier(qr) circuit.measure(qr[0], cr0[0]) circuit.measure(qr[1], cr1[0]) circuit.z(qr[2]).c_if(cr0, 1) circuit.x(qr[2]).c_if(cr1, 1) circuit.measure(qr[2], cr2[0]) job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed) results = job.result() data = results.get_counts("teleport") alice = { "00": data["0 0 0"] + data["1 0 0"], "01": data["0 1 0"] + data["1 1 0"], "10": data["0 0 1"] + data["1 0 1"], "11": data["0 1 1"] + data["1 1 1"], } bob = { "0": data["0 0 0"] + data["0 1 0"] + data["0 0 1"] + data["0 1 1"], "1": data["1 0 0"] + data["1 1 0"] + data["1 0 1"] + data["1 1 1"], } self.log.info("test_teleport: circuit:") self.log.info(circuit.qasm()) self.log.info("test_teleport: data %s", data) self.log.info("test_teleport: alice %s", alice) self.log.info("test_teleport: bob %s", bob) alice_ratio = 1 / np.tan(pi / 8) ** 2 bob_ratio = bob["0"] / float(bob["1"]) error = abs(alice_ratio - bob_ratio) / alice_ratio self.log.info("test_teleport: relative error = %s", error) self.assertLess(error, 0.05) def test_memory(self): """Test memory.""" # β”Œβ”€β”€β”€β” β”Œβ”€β” # qr_0: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€ # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β””β•₯β”˜β”Œβ”€β” # qr_1: ────── X β”œβ”€β”€β”€β”€β•«β”€β”€Mβ”œ # β””β”¬β”€β”¬β”˜ β•‘ β””β•₯β”˜ # qr_2: ───────Mβ”œβ”€β”€β”€β”€β”€β•«β”€β”€β•«β”€ # β”Œβ”€β”€β”€β” β””β•₯β”˜ β”Œβ”€β” β•‘ β•‘ # qr_3: ─ X β”œβ”€β”€β•«β”€β”€β”€Mβ”œβ”€β•«β”€β”€β•«β”€ # β””β”€β”€β”€β”˜ β•‘ β””β•₯β”˜ β•‘ β•‘ # cr0: 2/══════╬═══╬══╩══╩═ # β•‘ β•‘ 0 1 # β•‘ β•‘ # cr1: 2/══════╩═══╩═══════ # 0 1 qr = QuantumRegister(4, "qr") cr0 = ClassicalRegister(2, "cr0") cr1 = ClassicalRegister(2, "cr1") circ = QuantumCircuit(qr, cr0, cr1) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.x(qr[3]) circ.measure(qr[0], cr0[0]) circ.measure(qr[1], cr0[1]) circ.measure(qr[2], cr1[0]) circ.measure(qr[3], cr1[1]) shots = 50 job = execute(circ, backend=self.backend, shots=shots, memory=True) result = job.result() memory = result.get_memory() self.assertEqual(len(memory), shots) for mem in memory: self.assertIn(mem, ["10 00", "10 11"]) def test_unitary(self): """Test unitary gate instruction""" max_qubits = 4 x_mat = np.array([[0, 1], [1, 0]]) # Test 1 to max_qubits for random n-qubit unitary gate for i in range(max_qubits): num_qubits = i + 1 # Apply X gate to all qubits multi_x = x_mat for _ in range(i): multi_x = np.kron(multi_x, x_mat) # Target counts shots = 1024 target_counts = {num_qubits * "1": shots} # Test circuit qr = QuantumRegister(num_qubits, "qr") cr = ClassicalRegister(num_qubits, "cr") circuit = QuantumCircuit(qr, cr) circuit.unitary(multi_x, qr) circuit.measure(qr, cr) job = execute(circuit, self.backend, shots=shots) result = job.result() counts = result.get_counts(0) self.assertEqual(counts, target_counts) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for unitary simulator.""" import unittest import numpy as np from qiskit import execute from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.providers.basicaer import UnitarySimulatorPy from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.test import ReferenceCircuits from qiskit.test import providers from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info import process_fidelity, Operator class BasicAerUnitarySimulatorPyTest(providers.BackendTestCase): """Test BasicAer unitary simulator.""" backend_cls = UnitarySimulatorPy circuit = ReferenceCircuits.bell_no_measure() def test_basicaer_unitary_simulator_py(self): """Test unitary simulator.""" circuits = self._test_circuits() job = execute(circuits, backend=self.backend) sim_unitaries = [job.result().get_unitary(circ) for circ in circuits] reference_unitaries = self._reference_unitaries() for u_sim, u_ref in zip(sim_unitaries, reference_unitaries): self.assertTrue(matrix_equal(u_sim, u_ref, ignore_phase=True)) def _test_circuits(self): """Return test circuits for unitary simulator""" qr = QuantumRegister(3) cr = ClassicalRegister(3) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc3 = QuantumCircuit(qr, cr) qc4 = QuantumCircuit(qr, cr) qc5 = QuantumCircuit(qr, cr) # Test circuit 1: HxHxH qc1.h(qr) # Test circuit 2: IxCX qc2.cx(qr[0], qr[1]) # Test circuit 3: CXxY qc3.y(qr[0]) qc3.cx(qr[1], qr[2]) # Test circuit 4: (CX.I).(IxCX).(IxIxX) qc4.h(qr[0]) qc4.cx(qr[0], qr[1]) qc4.cx(qr[1], qr[2]) # Test circuit 5 (X.Z)x(Z.Y)x(Y.X) qc5.x(qr[0]) qc5.y(qr[0]) qc5.y(qr[1]) qc5.z(qr[1]) qc5.z(qr[2]) qc5.x(qr[2]) return [qc1, qc2, qc3, qc4, qc5] def _reference_unitaries(self): """Return reference unitaries for test circuits""" # Gate matrices gate_h = np.array([[1, 1], [1, -1]]) / np.sqrt(2) gate_x = np.array([[0, 1], [1, 0]]) gate_y = np.array([[0, -1j], [1j, 0]]) gate_z = np.array([[1, 0], [0, -1]]) gate_cx = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0.0, 0, 1, 0], [0, 1, 0, 0]]) # Unitary matrices target_unitary1 = np.kron(np.kron(gate_h, gate_h), gate_h) target_unitary2 = np.kron(np.eye(2), gate_cx) target_unitary3 = np.kron(gate_cx, gate_y) target_unitary4 = np.dot( np.kron(gate_cx, np.eye(2)), np.dot(np.kron(np.eye(2), gate_cx), np.kron(np.eye(4), gate_h)), ) target_unitary5 = np.kron( np.kron(np.dot(gate_x, gate_z), np.dot(gate_z, gate_y)), np.dot(gate_y, gate_x) ) return [target_unitary1, target_unitary2, target_unitary3, target_unitary4, target_unitary5] def test_unitary(self): """Test unitary gate instruction""" num_trials = 10 max_qubits = 3 # Test 1 to max_qubits for random n-qubit unitary gate for i in range(max_qubits): num_qubits = i + 1 unitary_init = Operator(np.eye(2**num_qubits)) qr = QuantumRegister(num_qubits, "qr") for _ in range(num_trials): # Create random unitary unitary = random_unitary(2**num_qubits) # Compute expected output state unitary_target = unitary.dot(unitary_init) # Simulate output on circuit circuit = QuantumCircuit(qr) circuit.unitary(unitary, qr) job = execute(circuit, self.backend) result = job.result() unitary_out = Operator(result.get_unitary(0)) fidelity = process_fidelity(unitary_target, unitary_out) self.assertGreater(fidelity, 0.999) def test_global_phase(self): """Test global phase for XZH See https://github.com/Qiskit/qiskit-terra/issues/3083""" q = QuantumRegister(1) circuit = QuantumCircuit(q) circuit.h(q[0]) circuit.z(q[0]) circuit.x(q[0]) job = execute(circuit, self.backend) result = job.result() unitary_out = result.get_unitary(circuit) unitary_target = np.array( [[-1 / np.sqrt(2), 1 / np.sqrt(2)], [1 / np.sqrt(2), 1 / np.sqrt(2)]] ) self.assertTrue(np.allclose(unitary_out, unitary_target)) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test cases for the circuit qasm_file and qasm_string method.""" from qiskit import QiskitError from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit import Gate from qiskit.test import QiskitTestCase, Path class LoadFromQasmTest(QiskitTestCase): """Test circuit.from_qasm_* set of methods.""" def setUp(self): self.qasm_file_name = 'entangled_registers.qasm' self.qasm_file_path = self._get_resource_path( 'qasm/' + self.qasm_file_name, Path.EXAMPLES) def test_qasm_file(self): """Test qasm_file and get_circuit. If all is correct we should get the qasm file loaded in _qasm_file_path """ q_circuit = QuantumCircuit.from_qasm_file(self.qasm_file_path) qr_a = QuantumRegister(4, 'a') qr_b = QuantumRegister(4, 'b') cr_c = ClassicalRegister(4, 'c') cr_d = ClassicalRegister(4, 'd') q_circuit_2 = QuantumCircuit(qr_a, qr_b, cr_c, cr_d) q_circuit_2.h(qr_a) q_circuit_2.cx(qr_a, qr_b) q_circuit_2.barrier(qr_a) q_circuit_2.barrier(qr_b) q_circuit_2.measure(qr_a, cr_c) q_circuit_2.measure(qr_b, cr_d) self.assertEqual(q_circuit, q_circuit_2) def test_fail_qasm_file(self): """Test fail_qasm_file. If all is correct we should get a QiskitError """ self.assertRaises(QiskitError, QuantumCircuit.from_qasm_file, "") def test_fail_qasm_string(self): """Test fail_qasm_string. If all is correct we should get a QiskitError """ self.assertRaises(QiskitError, QuantumCircuit.from_qasm_str, "") def test_qasm_text(self): """Test qasm_text and get_circuit. If all is correct we should get the qasm file loaded from the string """ qasm_string = "// A simple 8 qubit example\nOPENQASM 2.0;\n" qasm_string += "include \"qelib1.inc\";\nqreg a[4];\n" qasm_string += "qreg b[4];\ncreg c[4];\ncreg d[4];\nh a;\ncx a, b;\n" qasm_string += "barrier a;\nbarrier b;\nmeasure a[0]->c[0];\n" qasm_string += "measure a[1]->c[1];\nmeasure a[2]->c[2];\n" qasm_string += "measure a[3]->c[3];\nmeasure b[0]->d[0];\n" qasm_string += "measure b[1]->d[1];\nmeasure b[2]->d[2];\n" qasm_string += "measure b[3]->d[3];" q_circuit = QuantumCircuit.from_qasm_str(qasm_string) qr_a = QuantumRegister(4, 'a') qr_b = QuantumRegister(4, 'b') cr_c = ClassicalRegister(4, 'c') cr_d = ClassicalRegister(4, 'd') ref = QuantumCircuit(qr_a, qr_b, cr_c, cr_d) ref.h(qr_a[3]) ref.cx(qr_a[3], qr_b[3]) ref.h(qr_a[2]) ref.cx(qr_a[2], qr_b[2]) ref.h(qr_a[1]) ref.cx(qr_a[1], qr_b[1]) ref.h(qr_a[0]) ref.cx(qr_a[0], qr_b[0]) ref.barrier(qr_b) ref.measure(qr_b, cr_d) ref.barrier(qr_a) ref.measure(qr_a, cr_c) self.assertEqual(len(q_circuit.cregs), 2) self.assertEqual(len(q_circuit.qregs), 2) self.assertEqual(q_circuit, ref) def test_qasm_text_conditional(self): """Test qasm_text and get_circuit when conditionals are present. """ qasm_string = '\n'.join(["OPENQASM 2.0;", "include \"qelib1.inc\";", "qreg q[1];", "creg c0[4];", "creg c1[4];", "x q[0];", "if(c1==4) x q[0];"]) + '\n' q_circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(1, 'q') cr0 = ClassicalRegister(4, 'c0') cr1 = ClassicalRegister(4, 'c1') ref = QuantumCircuit(qr, cr0, cr1) ref.x(qr[0]) ref.x(qr[0]).c_if(cr1, 4) self.assertEqual(len(q_circuit.cregs), 2) self.assertEqual(len(q_circuit.qregs), 1) self.assertEqual(q_circuit, ref) def test_opaque_gate(self): """Test parse an opaque gate See https://github.com/Qiskit/qiskit-terra/issues/1566""" qasm_string = '\n'.join(["OPENQASM 2.0;", "include \"qelib1.inc\";", "opaque my_gate(theta,phi,lambda) a,b;", "qreg q[3];", "my_gate(1,2,3) q[1],q[2];"]) + '\n' circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(3, 'q') expected = QuantumCircuit(qr) expected.append(Gate(name='my_gate', num_qubits=2, params=[1, 2, 3]), [qr[1], qr[2]]) self.assertEqual(circuit, expected) def test_qasm_example_file(self): """Loads qasm/example.qasm. """ qasm_filename = self._get_resource_path('example.qasm', Path.QASMS) expected_circuit = QuantumCircuit.from_qasm_str('\n'.join(["OPENQASM 2.0;", "include \"qelib1.inc\";", "qreg q[3];", "qreg r[3];", "creg c[3];", "creg d[3];", "h q[2];", "cx q[2],r[2];", "measure r[2] -> d[2];", "h q[1];", "cx q[1],r[1];", "measure r[1] -> d[1];", "h q[0];", "cx q[0],r[0];", "measure r[0] -> d[0];", "barrier q[0],q[1],q[2];", "measure q[2] -> c[2];", "measure q[1] -> c[1];", "measure q[0] -> c[0];"]) + '\n') q_circuit = QuantumCircuit.from_qasm_file(qasm_filename) self.assertEqual(q_circuit, expected_circuit) self.assertEqual(len(q_circuit.cregs), 2) self.assertEqual(len(q_circuit.qregs), 2) def test_qasm_qas_string_order(self): """ Test that gates are returned in qasm in ascending order""" expected_qasm = '\n'.join(["OPENQASM 2.0;", "include \"qelib1.inc\";", "qreg q[3];", "h q[0];", "h q[1];", "h q[2];"]) + '\n' qasm_string = """OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; h q;""" q_circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(q_circuit.qasm(), expected_qasm)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's QuantumCircuit class for multiple registers.""" from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.circuit.exceptions import CircuitError class TestCircuitMultiRegs(QiskitTestCase): """QuantumCircuit Qasm tests.""" def test_circuit_multi(self): """Test circuit multi regs declared at start.""" qreg0 = QuantumRegister(2, "q0") creg0 = ClassicalRegister(2, "c0") qreg1 = QuantumRegister(2, "q1") creg1 = ClassicalRegister(2, "c1") circ = QuantumCircuit(qreg0, qreg1, creg0, creg1) circ.x(qreg0[1]) circ.x(qreg1[0]) meas = QuantumCircuit(qreg0, qreg1, creg0, creg1) meas.measure(qreg0, creg0) meas.measure(qreg1, creg1) qc = circ.compose(meas) circ2 = QuantumCircuit() circ2.add_register(qreg0) circ2.add_register(qreg1) circ2.add_register(creg0) circ2.add_register(creg1) circ2.x(qreg0[1]) circ2.x(qreg1[0]) meas2 = QuantumCircuit() meas2.add_register(qreg0) meas2.add_register(qreg1) meas2.add_register(creg0) meas2.add_register(creg1) meas2.measure(qreg0, creg0) meas2.measure(qreg1, creg1) qc2 = circ2.compose(meas2) dag_qc = circuit_to_dag(qc) dag_qc2 = circuit_to_dag(qc2) dag_circ2 = circuit_to_dag(circ2) dag_circ = circuit_to_dag(circ) self.assertEqual(dag_qc, dag_qc2) self.assertEqual(dag_circ, dag_circ2) def test_circuit_multi_name_collision(self): """Test circuit multi regs, with name collision.""" qreg0 = QuantumRegister(2, "q") qreg1 = QuantumRegister(3, "q") self.assertRaises(CircuitError, QuantumCircuit, qreg0, qreg1)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's QuantumCircuit class.""" import numpy as np from ddt import data, ddt from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute from qiskit.circuit import Gate, Instruction, Measure, Parameter from qiskit.circuit.bit import Bit from qiskit.circuit.classicalregister import Clbit from qiskit.circuit.exceptions import CircuitError from qiskit.circuit.controlflow import IfElseOp from qiskit.circuit.library import CXGate, HGate from qiskit.circuit.library.standard_gates import SGate from qiskit.circuit.quantumcircuit import BitLocations from qiskit.circuit.quantumcircuitdata import CircuitInstruction from qiskit.circuit.quantumregister import AncillaQubit, AncillaRegister, Qubit from qiskit.pulse import DriveChannel, Gaussian, Play, Schedule from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase @ddt class TestCircuitOperations(QiskitTestCase): """QuantumCircuit Operations tests.""" @data(0, 1, -1, -2) def test_append_resolves_integers(self, index): """Test that integer arguments to append are correctly resolved.""" # We need to assume that appending ``Bit`` instances will always work, so we have something # to test against. qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] test = QuantumCircuit(qubits, clbits) test.append(Measure(), [index], [index]) expected = QuantumCircuit(qubits, clbits) expected.append(Measure(), [qubits[index]], [clbits[index]]) self.assertEqual(test, expected) @data(np.int32(0), np.int8(-1), np.uint64(1)) def test_append_resolves_numpy_integers(self, index): """Test that Numpy's integers can be used to reference qubits and clbits.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] test = QuantumCircuit(qubits, clbits) test.append(Measure(), [index], [index]) expected = QuantumCircuit(qubits, clbits) expected.append(Measure(), [qubits[int(index)]], [clbits[int(index)]]) self.assertEqual(test, expected) @data( slice(0, 2), slice(None, 1), slice(1, None), slice(None, None), slice(0, 2, 2), slice(2, -1, -1), slice(1000, 1003), ) def test_append_resolves_slices(self, index): """Test that slices can be used to reference qubits and clbits with the same semantics that they have on lists.""" qregs = [QuantumRegister(2), QuantumRegister(1)] cregs = [ClassicalRegister(1), ClassicalRegister(2)] test = QuantumCircuit(*qregs, *cregs) test.append(Measure(), [index], [index]) expected = QuantumCircuit(*qregs, *cregs) for qubit, clbit in zip(expected.qubits[index], expected.clbits[index]): expected.append(Measure(), [qubit], [clbit]) self.assertEqual(test, expected) def test_append_resolves_scalar_numpy_array(self): """Test that size-1 Numpy arrays can be used to index arguments. These arrays can be passed to ``int``, which means they sometimes might be involved in spurious casts.""" test = QuantumCircuit(1, 1) test.append(Measure(), [np.array([0])], [np.array([0])]) expected = QuantumCircuit(1, 1) expected.measure(0, 0) self.assertEqual(test, expected) @data([3], [-3], [0, 1, 3]) def test_append_rejects_out_of_range_input(self, specifier): """Test that append rejects an integer that's out of range.""" test = QuantumCircuit(2, 2) with self.subTest("qubit"), self.assertRaisesRegex(CircuitError, "out of range"): opaque = Instruction("opaque", len(specifier), 1, []) test.append(opaque, specifier, [0]) with self.subTest("clbit"), self.assertRaisesRegex(CircuitError, "out of range"): opaque = Instruction("opaque", 1, len(specifier), []) test.append(opaque, [0], specifier) def test_append_rejects_bits_not_in_circuit(self): """Test that append rejects bits that are not in the circuit.""" test = QuantumCircuit(2, 2) with self.subTest("qubit"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [Qubit()], [test.clbits[0]]) with self.subTest("clbit"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [test.qubits[0]], [Clbit()]) with self.subTest("qubit list"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [[test.qubits[0], Qubit()]], [test.clbits]) with self.subTest("clbit list"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [test.qubits], [[test.clbits[0], Clbit()]]) def test_append_rejects_bit_of_wrong_type(self): """Test that append rejects bits of the wrong type in an argument list.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] test = QuantumCircuit(qubits, clbits) with self.subTest("c to q"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [clbits[0]], [clbits[1]]) with self.subTest("q to c"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [qubits[0]], [qubits[1]]) with self.subTest("none to q"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [Bit()], [clbits[0]]) with self.subTest("none to c"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [qubits[0]], [Bit()]) with self.subTest("none list"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [[qubits[0], Bit()]], [[clbits[0], Bit()]]) @data(0.0, 1.0, 1.0 + 0.0j, "0") def test_append_rejects_wrong_types(self, specifier): """Test that various bad inputs are rejected, both given loose or in sublists.""" test = QuantumCircuit(2, 2) # Use a default Instruction to be sure that there's not overridden broadcasting. opaque = Instruction("opaque", 1, 1, []) with self.subTest("q"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [specifier], [0]) with self.subTest("c"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [0], [specifier]) with self.subTest("q list"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [[specifier]], [[0]]) with self.subTest("c list"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [[0]], [[specifier]]) @data([], [0], [0, 1, 2]) def test_append_rejects_bad_arguments_opaque(self, bad_arg): """Test that a suitable exception is raised when there is an argument mismatch.""" inst = QuantumCircuit(2, 2).to_instruction() qc = QuantumCircuit(3, 3) with self.assertRaisesRegex(CircuitError, "The amount of qubit arguments"): qc.append(inst, bad_arg, [0, 1]) with self.assertRaisesRegex(CircuitError, "The amount of clbit arguments"): qc.append(inst, [0, 1], bad_arg) def test_anding_self(self): """Test that qc &= qc finishes, which can be prone to infinite while-loops. This can occur e.g. when a user tries >>> other_qc = qc >>> other_qc &= qc # or qc2.compose(qc) """ qc = QuantumCircuit(1) qc.x(0) # must contain at least one operation to end up in a infinite while-loop # attempt addition, times out if qc is added via reference qc &= qc # finally, qc should contain two X gates self.assertEqual(["x", "x"], [x.operation.name for x in qc.data]) def test_compose_circuit(self): """Test composing two circuits""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr[0]) qc1.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc3 = qc1.compose(qc2) backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_compose_circuit_and(self): """Test composing two circuits using & operator""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr[0]) qc1.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc3 = qc1 & qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_compose_circuit_iand(self): """Test composing circuits using &= operator (in place)""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr[0]) qc1.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc1 &= qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc1, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 2}) # changes "in-place" self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_compose_circuit_fail_circ_size(self): """Test composing circuit fails when number of wires in circuit is not enough""" qr1 = QuantumRegister(2) qr2 = QuantumRegister(4) # Creating our circuits qc1 = QuantumCircuit(qr1) qc1.x(0) qc1.h(1) qc2 = QuantumCircuit(qr2) qc2.h([1, 2]) qc2.cx(2, 3) # Composing will fail because qc2 requires 4 wires self.assertRaises(CircuitError, qc1.compose, qc2) def test_compose_circuit_fail_arg_size(self): """Test composing circuit fails when arg size does not match number of wires""" qr1 = QuantumRegister(2) qr2 = QuantumRegister(2) qc1 = QuantumCircuit(qr1) qc1.h(0) qc2 = QuantumCircuit(qr2) qc2.cx(0, 1) self.assertRaises(CircuitError, qc1.compose, qc2, qubits=[0]) def test_tensor_circuit(self): """Test tensoring two circuits""" qc1 = QuantumCircuit(1, 1) qc2 = QuantumCircuit(1, 1) qc2.h(0) qc2.measure(0, 0) qc1.measure(0, 0) qc3 = qc1.tensor(qc2) backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc1.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_tensor_circuit_xor(self): """Test tensoring two circuits using ^ operator""" qc1 = QuantumCircuit(1, 1) qc2 = QuantumCircuit(1, 1) qc2.h(0) qc2.measure(0, 0) qc1.measure(0, 0) qc3 = qc1 ^ qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc1.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_tensor_circuit_ixor(self): """Test tensoring two circuits using ^= operator""" qc1 = QuantumCircuit(1, 1) qc2 = QuantumCircuit(1, 1) qc2.h(0) qc2.measure(0, 0) qc1.measure(0, 0) qc1 ^= qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc1, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 2}) # changes "in-place" self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_measure_args_type_cohesion(self): """Test for proper args types for measure function.""" quantum_reg = QuantumRegister(3) classical_reg_0 = ClassicalRegister(1) classical_reg_1 = ClassicalRegister(2) quantum_circuit = QuantumCircuit(quantum_reg, classical_reg_0, classical_reg_1) quantum_circuit.h(quantum_reg) with self.assertRaises(CircuitError) as ctx: quantum_circuit.measure(quantum_reg, classical_reg_1) self.assertEqual(ctx.exception.message, "register size error") def test_copy_circuit(self): """Test copy method makes a copy""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) self.assertEqual(qc, qc.copy()) def test_copy_copies_registers(self): """Test copy copies the registers not via reference.""" qc = QuantumCircuit(1, 1) copied = qc.copy() copied.add_register(QuantumRegister(1, "additional_q")) copied.add_register(ClassicalRegister(1, "additional_c")) self.assertEqual(len(qc.qregs), 1) self.assertEqual(len(copied.qregs), 2) self.assertEqual(len(qc.cregs), 1) self.assertEqual(len(copied.cregs), 2) def test_copy_empty_like_circuit(self): """Test copy_empty_like method makes a clear copy.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr, global_phase=1.0, name="qc", metadata={"key": "value"}) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) sched = Schedule(Play(Gaussian(160, 0.1, 40), DriveChannel(0))) qc.add_calibration("h", [0, 1], sched) copied = qc.copy_empty_like() qc.clear() self.assertEqual(qc, copied) self.assertEqual(qc.global_phase, copied.global_phase) self.assertEqual(qc.name, copied.name) self.assertEqual(qc.metadata, copied.metadata) self.assertEqual(qc.calibrations, copied.calibrations) copied = qc.copy_empty_like("copy") self.assertEqual(copied.name, "copy") def test_circuit_copy_rejects_invalid_types(self): """Test copy method rejects argument with type other than 'string' and 'None' type.""" qc = QuantumCircuit(1, 1) qc.h(0) with self.assertRaises(TypeError): qc.copy([1, "2", 3]) def test_circuit_copy_empty_like_rejects_invalid_types(self): """Test copy_empty_like method rejects argument with type other than 'string' and 'None' type.""" qc = QuantumCircuit(1, 1) qc.h(0) with self.assertRaises(TypeError): qc.copy_empty_like(123) def test_clear_circuit(self): """Test clear method deletes instructions in circuit.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.clear() self.assertEqual(len(qc.data), 0) self.assertEqual(len(qc._parameter_table), 0) def test_measure_active(self): """Test measure_active Applies measurements only to non-idle qubits. Creates a ClassicalRegister of size equal to the amount of non-idle qubits to store the measured values. """ qr = QuantumRegister(4) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[2]) circuit.measure_active() expected = QuantumCircuit(qr) expected.h(qr[0]) expected.h(qr[2]) expected.add_register(cr) expected.barrier() expected.measure([qr[0], qr[2]], [cr[0], cr[1]]) self.assertEqual(expected, circuit) def test_measure_active_copy(self): """Test measure_active copy Applies measurements only to non-idle qubits. Creates a ClassicalRegister of size equal to the amount of non-idle qubits to store the measured values. """ qr = QuantumRegister(4) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[2]) new_circuit = circuit.measure_active(inplace=False) expected = QuantumCircuit(qr) expected.h(qr[0]) expected.h(qr[2]) expected.add_register(cr) expected.barrier() expected.measure([qr[0], qr[2]], [cr[0], cr[1]]) self.assertEqual(expected, new_circuit) self.assertFalse("measure" in circuit.count_ops().keys()) def test_measure_active_repetition(self): """Test measure_active in a circuit with a 'measure' creg. measure_active should be aware that the creg 'measure' might exists. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.measure_active() self.assertEqual(len(circuit.cregs), 2) # Two cregs self.assertEqual(len(circuit.cregs[0]), 2) # Both length 2 self.assertEqual(len(circuit.cregs[1]), 2) def test_measure_all(self): """Test measure_all applies measurements to all qubits. Creates a ClassicalRegister of size equal to the total amount of qubits to store those measured values. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr) circuit.measure_all() expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr) self.assertEqual(expected, circuit) def test_measure_all_not_add_bits_equal(self): """Test measure_all applies measurements to all qubits. Does not create a new ClassicalRegister if the existing one is big enough. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure_all(add_bits=False) expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr) self.assertEqual(expected, circuit) def test_measure_all_not_add_bits_bigger(self): """Test measure_all applies measurements to all qubits. Does not create a new ClassicalRegister if the existing one is big enough. """ qr = QuantumRegister(2) cr = ClassicalRegister(3, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure_all(add_bits=False) expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr[0:2]) self.assertEqual(expected, circuit) def test_measure_all_not_add_bits_smaller(self): """Test measure_all applies measurements to all qubits. Raises an error if there are not enough classical bits to store the measurements. """ qr = QuantumRegister(3) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) with self.assertRaisesRegex(CircuitError, "The number of classical bits"): circuit.measure_all(add_bits=False) def test_measure_all_copy(self): """Test measure_all with inplace=False""" qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr) new_circuit = circuit.measure_all(inplace=False) expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr) self.assertEqual(expected, new_circuit) self.assertFalse("measure" in circuit.count_ops().keys()) def test_measure_all_repetition(self): """Test measure_all in a circuit with a 'measure' creg. measure_all should be aware that the creg 'measure' might exists. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr, cr) circuit.measure_all() self.assertEqual(len(circuit.cregs), 2) # Two cregs self.assertEqual(len(circuit.cregs[0]), 2) # Both length 2 self.assertEqual(len(circuit.cregs[1]), 2) def test_remove_final_measurements(self): """Test remove_final_measurements Removes all measurements at end of circuit. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) circuit.remove_final_measurements() expected = QuantumCircuit(qr) self.assertEqual(expected, circuit) def test_remove_final_measurements_copy(self): """Test remove_final_measurements on copy Removes all measurements at end of circuit. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) new_circuit = circuit.remove_final_measurements(inplace=False) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) self.assertTrue("measure" in circuit.count_ops().keys()) def test_remove_final_measurements_copy_with_parameters(self): """Test remove_final_measurements doesn't corrupt ParameterTable See https://github.com/Qiskit/qiskit-terra/issues/6108 for more details """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") theta = Parameter("theta") circuit = QuantumCircuit(qr, cr) circuit.rz(theta, qr) circuit.measure(qr, cr) circuit.remove_final_measurements() copy = circuit.copy() self.assertEqual(copy, circuit) def test_remove_final_measurements_multiple_measures(self): """Test remove_final_measurements only removes measurements at the end of the circuit remove_final_measurements should not remove measurements in the beginning or middle of the circuit. """ qr = QuantumRegister(2) cr = ClassicalRegister(1) circuit = QuantumCircuit(qr, cr) circuit.measure(qr[0], cr) circuit.h(0) circuit.measure(qr[0], cr) circuit.h(0) circuit.measure(qr[0], cr) circuit.remove_final_measurements() expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr) expected.h(0) expected.measure(qr[0], cr) expected.h(0) self.assertEqual(expected, circuit) def test_remove_final_measurements_5802(self): """Test remove_final_measurements removes classical bits https://github.com/Qiskit/qiskit-terra/issues/5802. """ qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) circuit.remove_final_measurements() self.assertEqual(circuit.cregs, []) self.assertEqual(circuit.clbits, []) def test_remove_final_measurements_7089(self): """Test remove_final_measurements removes resulting unused registers even if not all bits were measured into. https://github.com/Qiskit/qiskit-terra/issues/7089. """ circuit = QuantumCircuit(2, 5) circuit.measure(0, 0) circuit.measure(1, 1) circuit.remove_final_measurements(inplace=True) self.assertEqual(circuit.cregs, []) self.assertEqual(circuit.clbits, []) def test_remove_final_measurements_bit_locations(self): """Test remove_final_measurements properly recalculates clbit indicies and preserves order of remaining cregs and clbits. """ c0 = ClassicalRegister(1) c1_0 = Clbit() c2 = ClassicalRegister(1) c3 = ClassicalRegister(1) # add an individual bit that's not in any register of this circuit circuit = QuantumCircuit(QuantumRegister(1), c0, [c1_0], c2, c3) circuit.measure(0, c1_0) circuit.measure(0, c2[0]) # assert cregs and clbits before measure removal self.assertEqual(circuit.cregs, [c0, c2, c3]) self.assertEqual(circuit.clbits, [c0[0], c1_0, c2[0], c3[0]]) # assert clbit indices prior to measure removal self.assertEqual(circuit.find_bit(c0[0]), BitLocations(0, [(c0, 0)])) self.assertEqual(circuit.find_bit(c1_0), BitLocations(1, [])) self.assertEqual(circuit.find_bit(c2[0]), BitLocations(2, [(c2, 0)])) self.assertEqual(circuit.find_bit(c3[0]), BitLocations(3, [(c3, 0)])) circuit.remove_final_measurements() # after measure removal, creg c2 should be gone, as should lone bit c1_0 # and c0 should still come before c3 self.assertEqual(circuit.cregs, [c0, c3]) self.assertEqual(circuit.clbits, [c0[0], c3[0]]) # there should be no gaps in clbit indices # e.g. c3[0] is now the second clbit self.assertEqual(circuit.find_bit(c0[0]), BitLocations(0, [(c0, 0)])) self.assertEqual(circuit.find_bit(c3[0]), BitLocations(1, [(c3, 0)])) def test_reverse(self): """Test reverse method reverses but does not invert.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.s(1) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) qc.x(0) qc.y(1) expected = QuantumCircuit(2, 2) expected.y(1) expected.x(0) expected.measure([0, 1], [0, 1]) expected.cx(0, 1) expected.s(1) expected.h(0) self.assertEqual(qc.reverse_ops(), expected) def test_repeat(self): """Test repeating the circuit works.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.h(0).c_if(cr, 1) with self.subTest("repeat 0 times"): rep = qc.repeat(0) self.assertEqual(rep, QuantumCircuit(qr, cr)) with self.subTest("repeat 3 times"): inst = qc.to_instruction() ref = QuantumCircuit(qr, cr) for _ in range(3): ref.append(inst, ref.qubits, ref.clbits) rep = qc.repeat(3) self.assertEqual(rep, ref) @data(0, 1, 4) def test_repeat_global_phase(self, num): """Test the global phase is properly handled upon repeat.""" phase = 0.123 qc = QuantumCircuit(1, global_phase=phase) expected = np.exp(1j * phase * num) * np.identity(2) np.testing.assert_array_almost_equal(Operator(qc.repeat(num)).data, expected) def test_bind_global_phase(self): """Test binding global phase.""" x = Parameter("x") circuit = QuantumCircuit(1, global_phase=x) self.assertEqual(circuit.parameters, {x}) bound = circuit.bind_parameters({x: 2}) self.assertEqual(bound.global_phase, 2) self.assertEqual(bound.parameters, set()) def test_bind_parameter_in_phase_and_gate(self): """Test binding a parameter present in the global phase and the gates.""" x = Parameter("x") circuit = QuantumCircuit(1, global_phase=x) circuit.rx(x, 0) self.assertEqual(circuit.parameters, {x}) ref = QuantumCircuit(1, global_phase=2) ref.rx(2, 0) bound = circuit.bind_parameters({x: 2}) self.assertEqual(bound, ref) self.assertEqual(bound.parameters, set()) def test_power(self): """Test taking the circuit to a power works.""" qc = QuantumCircuit(2) qc.cx(0, 1) qc.rx(0.2, 1) gate = qc.to_gate() with self.subTest("power(int >= 0) equals repeat"): self.assertEqual(qc.power(4), qc.repeat(4)) with self.subTest("explicit matrix power"): self.assertEqual(qc.power(4, matrix_power=True).data[0].operation, gate.power(4)) with self.subTest("float power"): self.assertEqual(qc.power(1.23).data[0].operation, gate.power(1.23)) with self.subTest("negative power"): self.assertEqual(qc.power(-2).data[0].operation, gate.power(-2)) def test_power_parameterized_circuit(self): """Test taking a parameterized circuit to a power.""" theta = Parameter("th") qc = QuantumCircuit(2) qc.cx(0, 1) qc.rx(theta, 1) with self.subTest("power(int >= 0) equals repeat"): self.assertEqual(qc.power(4), qc.repeat(4)) with self.subTest("cannot to matrix power if parameterized"): with self.assertRaises(CircuitError): _ = qc.power(0.5) def test_control(self): """Test controlling the circuit.""" qc = QuantumCircuit(2, name="my_qc") qc.cry(0.2, 0, 1) c_qc = qc.control() with self.subTest("return type is circuit"): self.assertIsInstance(c_qc, QuantumCircuit) with self.subTest("test name"): self.assertEqual(c_qc.name, "c_my_qc") with self.subTest("repeated control"): cc_qc = c_qc.control() self.assertEqual(cc_qc.num_qubits, c_qc.num_qubits + 1) with self.subTest("controlled circuit has same parameter"): param = Parameter("p") qc.rx(param, 0) c_qc = qc.control() self.assertEqual(qc.parameters, c_qc.parameters) with self.subTest("non-unitary operation raises"): qc.reset(0) with self.assertRaises(CircuitError): _ = qc.control() def test_control_implementation(self): """Run a test case for controlling the circuit, which should use ``Gate.control``.""" qc = QuantumCircuit(3) qc.cx(0, 1) qc.cry(0.2, 0, 1) qc.t(0) qc.append(SGate().control(2), [0, 1, 2]) qc.iswap(2, 0) c_qc = qc.control(2, ctrl_state="10") cgate = qc.to_gate().control(2, ctrl_state="10") ref = QuantumCircuit(*c_qc.qregs) ref.append(cgate, ref.qubits) self.assertEqual(ref, c_qc) @data("gate", "instruction") def test_repeat_appended_type(self, subtype): """Test repeat appends Gate if circuit contains only gates and Instructions otherwise.""" sub = QuantumCircuit(2) sub.x(0) if subtype == "gate": sub = sub.to_gate() else: sub = sub.to_instruction() qc = QuantumCircuit(2) qc.append(sub, [0, 1]) rep = qc.repeat(3) if subtype == "gate": self.assertTrue(all(isinstance(op.operation, Gate) for op in rep.data)) else: self.assertTrue(all(isinstance(op.operation, Instruction) for op in rep.data)) def test_reverse_bits(self): """Test reversing order of bits.""" qc = QuantumCircuit(3, 2) qc.h(0) qc.s(1) qc.cx(0, 1) qc.measure(0, 1) qc.x(0) qc.y(1) qc.global_phase = -1 expected = QuantumCircuit(3, 2) expected.h(2) expected.s(1) expected.cx(2, 1) expected.measure(2, 0) expected.x(2) expected.y(1) expected.global_phase = -1 self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_boxed(self): """Test reversing order of bits in a hierarchical circuit.""" wide_cx = QuantumCircuit(3) wide_cx.cx(0, 1) wide_cx.cx(1, 2) wide_cxg = wide_cx.to_gate() cx_box = QuantumCircuit(3) cx_box.append(wide_cxg, [0, 1, 2]) expected = QuantumCircuit(3) expected.cx(2, 1) expected.cx(1, 0) self.assertEqual(cx_box.reverse_bits().decompose(), expected) self.assertEqual(cx_box.decompose().reverse_bits(), expected) # box one more layer to be safe. cx_box_g = cx_box.to_gate() cx_box_box = QuantumCircuit(4) cx_box_box.append(cx_box_g, [0, 1, 2]) cx_box_box.cx(0, 3) expected2 = QuantumCircuit(4) expected2.cx(3, 2) expected2.cx(2, 1) expected2.cx(3, 0) self.assertEqual(cx_box_box.reverse_bits().decompose().decompose(), expected2) def test_reverse_bits_with_registers(self): """Test reversing order of bits when registers are present.""" qr1 = QuantumRegister(3, "a") qr2 = QuantumRegister(2, "b") qc = QuantumCircuit(qr1, qr2) qc.h(qr1[0]) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr1[2]) qc.cx(qr1[2], qr2[0]) qc.cx(qr2[0], qr2[1]) expected = QuantumCircuit(qr2, qr1) expected.h(qr1[2]) expected.cx(qr1[2], qr1[1]) expected.cx(qr1[1], qr1[0]) expected.cx(qr1[0], qr2[1]) expected.cx(qr2[1], qr2[0]) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_overlapped_registers(self): """Test reversing order of bits when registers are overlapped.""" qr1 = QuantumRegister(2, "a") qr2 = QuantumRegister(bits=[qr1[0], qr1[1], Qubit()], name="b") qc = QuantumCircuit(qr1, qr2) qc.h(qr1[0]) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr2[2]) qr2 = QuantumRegister(bits=[Qubit(), qr1[0], qr1[1]], name="b") expected = QuantumCircuit(qr2, qr1) expected.h(qr1[1]) expected.cx(qr1[1], qr1[0]) expected.cx(qr1[0], qr2[0]) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_registerless_bits(self): """Test reversing order of registerless bits.""" q0 = Qubit() q1 = Qubit() c0 = Clbit() c1 = Clbit() qc = QuantumCircuit([q0, q1], [c0, c1]) qc.h(0) qc.cx(0, 1) qc.x(0).c_if(1, True) qc.measure(0, 0) expected = QuantumCircuit([c1, c0], [q1, q0]) expected.h(1) expected.cx(1, 0) expected.x(1).c_if(0, True) expected.measure(1, 1) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_registers_and_bits(self): """Test reversing order of bits with registers and registerless bits.""" qr = QuantumRegister(2, "a") q = Qubit() qc = QuantumCircuit(qr, [q]) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.cx(qr[1], q) expected = QuantumCircuit([q], qr) expected.h(qr[1]) expected.cx(qr[1], qr[0]) expected.cx(qr[0], q) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_mixed_overlapped_registers(self): """Test reversing order of bits with overlapped registers and registerless bits.""" q = Qubit() qr1 = QuantumRegister(bits=[q, Qubit()], name="qr1") qr2 = QuantumRegister(bits=[qr1[1], Qubit()], name="qr2") qc = QuantumCircuit(qr1, qr2, [Qubit()]) qc.h(q) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr2[1]) qc.cx(2, 3) qr2 = QuantumRegister(2, "qr2") qr1 = QuantumRegister(bits=[qr2[1], q], name="qr1") expected = QuantumCircuit([Qubit()], qr2, qr1) expected.h(qr1[1]) expected.cx(qr1[1], qr1[0]) expected.cx(qr1[0], qr2[0]) expected.cx(1, 0) self.assertEqual(qc.reverse_bits(), expected) def test_cnot_alias(self): """Test that the cnot method alias adds a cx gate.""" qc = QuantumCircuit(2) qc.cnot(0, 1) expected = QuantumCircuit(2) expected.cx(0, 1) self.assertEqual(qc, expected) def test_inverse(self): """Test inverse circuit.""" qr = QuantumRegister(2) qc = QuantumCircuit(qr, global_phase=0.5) qc.h(0) qc.barrier(qr) qc.t(1) expected = QuantumCircuit(qr) expected.tdg(1) expected.barrier(qr) expected.h(0) expected.global_phase = -0.5 self.assertEqual(qc.inverse(), expected) def test_compare_two_equal_circuits(self): """Test to compare that 2 circuits are equal.""" qc1 = QuantumCircuit(2, 2) qc1.h(0) qc2 = QuantumCircuit(2, 2) qc2.h(0) self.assertTrue(qc1 == qc2) def test_compare_two_different_circuits(self): """Test to compare that 2 circuits are different.""" qc1 = QuantumCircuit(2, 2) qc1.h(0) qc2 = QuantumCircuit(2, 2) qc2.x(0) self.assertFalse(qc1 == qc2) def test_compare_circuits_with_single_bit_conditions(self): """Test that circuits with single-bit conditions can be compared correctly.""" qreg = QuantumRegister(1, name="q") creg = ClassicalRegister(1, name="c") qc1 = QuantumCircuit(qreg, creg, [Clbit()]) qc1.x(0).c_if(qc1.cregs[0], 1) qc1.x(0).c_if(qc1.clbits[-1], True) qc2 = QuantumCircuit(qreg, creg, [Clbit()]) qc2.x(0).c_if(qc2.cregs[0], 1) qc2.x(0).c_if(qc2.clbits[-1], True) self.assertEqual(qc1, qc2) # Order of operations transposed. qc1 = QuantumCircuit(qreg, creg, [Clbit()]) qc1.x(0).c_if(qc1.cregs[0], 1) qc1.x(0).c_if(qc1.clbits[-1], True) qc2 = QuantumCircuit(qreg, creg, [Clbit()]) qc2.x(0).c_if(qc2.clbits[-1], True) qc2.x(0).c_if(qc2.cregs[0], 1) self.assertNotEqual(qc1, qc2) # Single-bit condition values not the same. qc1 = QuantumCircuit(qreg, creg, [Clbit()]) qc1.x(0).c_if(qc1.cregs[0], 1) qc1.x(0).c_if(qc1.clbits[-1], True) qc2 = QuantumCircuit(qreg, creg, [Clbit()]) qc2.x(0).c_if(qc2.cregs[0], 1) qc2.x(0).c_if(qc2.clbits[-1], False) self.assertNotEqual(qc1, qc2) def test_compare_a_circuit_with_none(self): """Test to compare that a circuit is different to None.""" qc1 = QuantumCircuit(2, 2) qc1.h(0) qc2 = None self.assertFalse(qc1 == qc2) def test_overlapped_add_bits_and_add_register(self): """Test add registers whose bits have already been added by add_bits.""" qc = QuantumCircuit() for bit_type, reg_type in ( [Qubit, QuantumRegister], [Clbit, ClassicalRegister], [AncillaQubit, AncillaRegister], ): bits = [bit_type() for _ in range(10)] reg = reg_type(bits=bits) qc.add_bits(bits) qc.add_register(reg) self.assertEqual(qc.num_qubits, 20) self.assertEqual(qc.num_clbits, 10) self.assertEqual(qc.num_ancillas, 10) def test_overlapped_add_register_and_add_register(self): """Test add registers whose bits have already been added by add_register.""" qc = QuantumCircuit() for bit_type, reg_type in ( [Qubit, QuantumRegister], [Clbit, ClassicalRegister], [AncillaQubit, AncillaRegister], ): bits = [bit_type() for _ in range(10)] reg1 = reg_type(bits=bits) reg2 = reg_type(bits=bits) qc.add_register(reg1) qc.add_register(reg2) self.assertEqual(qc.num_qubits, 20) self.assertEqual(qc.num_clbits, 10) self.assertEqual(qc.num_ancillas, 10) def test_from_instructions(self): """Test from_instructions method.""" qreg = QuantumRegister(4) creg = ClassicalRegister(3) a, b, c, d = qreg x, y, z = creg circuit_1 = QuantumCircuit(2, 1) circuit_1.x(0) circuit_2 = QuantumCircuit(2, 1) circuit_2.y(0) def instructions(): yield CircuitInstruction(HGate(), [a], []) yield CircuitInstruction(CXGate(), [a, b], []) yield CircuitInstruction(Measure(), [a], [x]) yield CircuitInstruction(Measure(), [b], [y]) yield CircuitInstruction(IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z]) def instruction_tuples(): yield HGate(), [a], [] yield CXGate(), [a, b], [] yield CircuitInstruction(Measure(), [a], [x]) yield Measure(), [b], [y] yield IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z] def instruction_tuples_partial(): yield HGate(), [a] yield CXGate(), [a, b], [] yield CircuitInstruction(Measure(), [a], [x]) yield Measure(), [b], [y] yield IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z] circuit = QuantumCircuit.from_instructions(instructions()) circuit_tuples = QuantumCircuit.from_instructions(instruction_tuples()) circuit_tuples_partial = QuantumCircuit.from_instructions(instruction_tuples_partial()) expected = QuantumCircuit([a, b, c, d], [x, y, z]) for instruction in instructions(): expected.append(instruction.operation, instruction.qubits, instruction.clbits) self.assertEqual(circuit, expected) self.assertEqual(circuit_tuples, expected) self.assertEqual(circuit_tuples_partial, expected) def test_from_instructions_bit_order(self): """Test from_instructions method bit order.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) a, b = qreg c, d = creg def instructions(): yield CircuitInstruction(HGate(), [b], []) yield CircuitInstruction(CXGate(), [a, b], []) yield CircuitInstruction(Measure(), [b], [d]) yield CircuitInstruction(Measure(), [a], [c]) circuit = QuantumCircuit.from_instructions(instructions()) self.assertEqual(circuit.qubits, [b, a]) self.assertEqual(circuit.clbits, [d, c]) circuit = QuantumCircuit.from_instructions(instructions(), qubits=qreg) self.assertEqual(circuit.qubits, [a, b]) self.assertEqual(circuit.clbits, [d, c]) circuit = QuantumCircuit.from_instructions(instructions(), clbits=creg) self.assertEqual(circuit.qubits, [b, a]) self.assertEqual(circuit.clbits, [c, d]) circuit = QuantumCircuit.from_instructions( instructions(), qubits=iter([a, b]), clbits=[c, d] ) self.assertEqual(circuit.qubits, [a, b]) self.assertEqual(circuit.clbits, [c, d]) def test_from_instructions_metadata(self): """Test from_instructions method passes metadata.""" qreg = QuantumRegister(2) a, b = qreg def instructions(): yield CircuitInstruction(HGate(), [a], []) yield CircuitInstruction(CXGate(), [a, b], []) circuit = QuantumCircuit.from_instructions(instructions(), name="test", global_phase=0.1) expected = QuantumCircuit([a, b], global_phase=0.1) for instruction in instructions(): expected.append(instruction.operation, instruction.qubits, instruction.clbits) self.assertEqual(circuit, expected) self.assertEqual(circuit.name, "test") class TestCircuitPrivateOperations(QiskitTestCase): """Direct tests of some of the private methods of QuantumCircuit. These do not represent functionality that we want to expose to users, but there are some cases where private methods are used internally (similar to "protected" access in .NET or "friend" access in C++), and we want to make sure they work in those cases.""" def test_previous_instruction_in_scope_failures(self): """Test the failure paths of the peek and pop methods for retrieving the most recent instruction in a scope.""" test = QuantumCircuit(1, 1) with self.assertRaisesRegex(CircuitError, r"This circuit contains no instructions\."): test._peek_previous_instruction_in_scope() with self.assertRaisesRegex(CircuitError, r"This circuit contains no instructions\."): test._pop_previous_instruction_in_scope() with test.for_loop(range(2)): with self.assertRaisesRegex(CircuitError, r"This scope contains no instructions\."): test._peek_previous_instruction_in_scope() with self.assertRaisesRegex(CircuitError, r"This scope contains no instructions\."): test._pop_previous_instruction_in_scope() def test_pop_previous_instruction_removes_parameters(self): """Test that the private "pop instruction" method removes parameters from the parameter table if that instruction is the only instance.""" x, y = Parameter("x"), Parameter("y") test = QuantumCircuit(1, 1) test.rx(y, 0) last_instructions = test.u(x, y, 0, 0) self.assertEqual({x, y}, set(test.parameters)) instruction = test._pop_previous_instruction_in_scope() self.assertEqual(list(last_instructions), [instruction]) self.assertEqual({y}, set(test.parameters)) def test_decompose_gate_type(self): """Test decompose specifying gate type.""" circuit = QuantumCircuit(1) circuit.append(SGate(label="s_gate"), [0]) decomposed = circuit.decompose(gates_to_decompose=SGate) self.assertNotIn("s", decomposed.count_ops())
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's inverse gate operation.""" import unittest import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, pulse from qiskit.circuit import Clbit from qiskit.circuit.library import RXGate, RYGate from qiskit.test import QiskitTestCase from qiskit.circuit.exceptions import CircuitError from qiskit.extensions.simulator import Snapshot class TestCircuitProperties(QiskitTestCase): """QuantumCircuit properties tests.""" def test_qarg_numpy_int(self): """Test castable to integer args for QuantumCircuit.""" n = np.int64(12) qc1 = QuantumCircuit(n) self.assertEqual(qc1.num_qubits, 12) self.assertEqual(type(qc1), QuantumCircuit) def test_carg_numpy_int(self): """Test castable to integer cargs for QuantumCircuit.""" n = np.int64(12) c1 = ClassicalRegister(n) qc1 = QuantumCircuit(c1) c_regs = qc1.cregs self.assertEqual(c_regs[0], c1) self.assertEqual(type(qc1), QuantumCircuit) def test_carg_numpy_int_2(self): """Test castable to integer cargs for QuantumCircuit.""" qc1 = QuantumCircuit(12, np.int64(12)) self.assertEqual(len(qc1.clbits), 12) self.assertTrue(all(isinstance(bit, Clbit) for bit in qc1.clbits)) self.assertEqual(type(qc1), QuantumCircuit) def test_qarg_numpy_int_exception(self): """Test attempt to pass non-castable arg to QuantumCircuit.""" self.assertRaises(CircuitError, QuantumCircuit, "string") def test_warning_on_noninteger_float(self): """Test warning when passing non-integer float to QuantumCircuit""" self.assertRaises(CircuitError, QuantumCircuit, 2.2) # but an integer float should pass qc = QuantumCircuit(2.0) self.assertEqual(qc.num_qubits, 2) def test_circuit_depth_empty(self): """Test depth of empty circuity""" q = QuantumRegister(5, "q") qc = QuantumCircuit(q) self.assertEqual(qc.depth(), 0) def test_circuit_depth_no_reg(self): """Test depth of no register circuits""" qc = QuantumCircuit() self.assertEqual(qc.depth(), 0) def test_circuit_depth_meas_only(self): """Test depth of measurement only""" q = QuantumRegister(1, "q") c = ClassicalRegister(1, "c") qc = QuantumCircuit(q, c) qc.measure(q, c) self.assertEqual(qc.depth(), 1) def test_circuit_depth_barrier(self): """Make sure barriers do not add to depth""" # β”Œβ”€β”€β”€β” β–‘ β”Œβ”€β” # q_0: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β”Œβ”€β”΄β”€β” β–‘ β””β•₯β”˜β”Œβ”€β” # q_1: ─ H β”œβ”€ X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β” β–‘ β•‘ β””β•₯β”˜β”Œβ”€β” # q_2: ─ H β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€ X β”œβ”€β”€β– β”€β”€β”€β–‘β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β”‚ β””β”€β”¬β”€β”˜β”Œβ”€β”΄β”€β” β–‘ β•‘ β•‘ β””β•₯β”˜β”Œβ”€β” # q_3: ─ H β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€β”€ X β”œβ”€β–‘β”€β”€β•«β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€ # β”œβ”€β”€β”€β”€ β”Œβ”€β”΄β”€β” β”‚ β””β”€β”€β”€β”˜ β–‘ β•‘ β•‘ β•‘ β””β•₯β”˜β”Œβ”€β” # q_4: ─ H β”œβ”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€β•«β”€β”€β•«β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ β–‘ β•‘ β•‘ β•‘ β•‘ β””β•₯β”˜ # c: 5/═════════════════════════════╩══╩══╩══╩══╩═ # 0 1 2 3 4 q = QuantumRegister(5, "q") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[4]) qc.cx(q[0], q[1]) qc.cx(q[1], q[4]) qc.cx(q[4], q[2]) qc.cx(q[2], q[3]) qc.barrier(q) qc.measure(q, c) self.assertEqual(qc.depth(), 6) def test_circuit_depth_simple(self): """Test depth for simple circuit""" # β”Œβ”€β”€β”€β” # q_0: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”β”Œβ”€β” # q_1: ───────┼───────────── X β”œβ”€Mβ”œ # β”Œβ”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β”β””β”€β”¬β”€β”˜β””β•₯β”˜ # q_2: ─ X β”œβ”€β”€β”Όβ”€β”€β”€ X β”œβ”€ X β”œβ”€β”€β”Όβ”€β”€β”€β•«β”€ # β””β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β”‚ β•‘ # q_3: ───────┼──────────────┼───╫─ # β”Œβ”€β”΄β”€β”β”Œβ”€β”€β”€β” β”‚ β•‘ # q_4: ────── X β”œβ”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β•«β”€ # β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β•‘ # c: 1/══════════════════════════╩═ # 0 q = QuantumRegister(5, "q") c = ClassicalRegister(1, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[4]) qc.x(q[2]) qc.x(q[2]) qc.x(q[2]) qc.x(q[4]) qc.cx(q[4], q[1]) qc.measure(q[1], c[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_multi_reg(self): """Test depth for multiple registers""" # β”Œβ”€β”€β”€β” # q1_0: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β”Œβ”€β”΄β”€β” # q1_1: ─ H β”œβ”€ X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β” # q1_2: ─ H β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€ X β”œβ”€β”€β– β”€β”€ # β”œβ”€β”€β”€β”€ β”‚ β””β”€β”¬β”€β”˜β”Œβ”€β”΄β”€β” # q2_0: ─ H β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€β”€ X β”œ # β”œβ”€β”€β”€β”€ β”Œβ”€β”΄β”€β” β”‚ β””β”€β”€β”€β”˜ # q2_1: ─ H β”œβ”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q1, q2, c) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_3q_gate(self): """Test depth for 3q gate""" # β”Œβ”€β”€β”€β” # q1_0: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β”‚ β”Œβ”€β”΄β”€β” # q1_1: ─ H β”œβ”€β”€β”Όβ”€β”€β”€ X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β”‚ β””β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β” # q1_2: ─ H β”œβ”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€ X β”œβ”€β”€β– β”€β”€ # β”œβ”€β”€β”€β”€β”Œβ”€β”΄β”€β” β”‚ β””β”€β”¬β”€β”˜β”Œβ”€β”΄β”€β” # q2_0: ─ H β”œβ”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€β”€ X β”œ # β”œβ”€β”€β”€β”€β””β”€β”¬β”€β”˜ β”Œβ”€β”΄β”€β” β”‚ β””β”€β”€β”€β”˜ # q2_1: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q1, q2, c) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.ccx(q2[1], q1[0], q2[0]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.depth(), 6) def test_circuit_depth_conditionals1(self): """Test circuit depth for conditional gates #1.""" # β”Œβ”€β”€β”€β” β”Œβ”€β” # q_0: ─ H β”œβ”€β”€β– β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β”Œβ”€β”΄β”€β”β””β•₯β”˜β”Œβ”€β” # q_1: ─ H β”œβ”€ X β”œβ”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β”€β”€β”€β”˜ β•‘ β””β•₯β”˜ β”Œβ”€β”€β”€β” # q_2: ─ H β”œβ”€β”€β– β”€β”€β”€β•«β”€β”€β•«β”€β”€β”€ H β”œβ”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β”Œβ”€β”΄β”€β” β•‘ β•‘ └─β•₯β”€β”˜ β”Œβ”€β”€β”€β” # q_3: ─ H β”œβ”€ X β”œβ”€β•«β”€β”€β•«β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€ H β”œβ”€ # β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ └─β•₯β”€β”˜ # β•‘ β•‘ β”Œβ”€β”€β•¨β”€β”€β”β”Œβ”€β”€β•¨β”€β”€β” # c: 4/═══════════╩══╩═║ 0x2 β•žβ•‘ 0x4 β•ž # 0 1 β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[0], q[1]) qc.cx(q[2], q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.h(q[2]).c_if(c, 2) qc.h(q[3]).c_if(c, 4) self.assertEqual(qc.depth(), 5) def test_circuit_depth_conditionals2(self): """Test circuit depth for conditional gates #2.""" # β”Œβ”€β”€β”€β” β”Œβ”€β”β”Œβ”€β” # q_0: ─ H β”œβ”€β”€β– β”€β”€β”€Mβ”œβ”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β”Œβ”€β”΄β”€β”β””β•₯β”˜β””β•₯β”˜ # q_1: ─ H β”œβ”€ X β”œβ”€β•«β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β”€β”€β”€β”˜ β•‘ β•‘ β”Œβ”€β”€β”€β” # q_2: ─ H β”œβ”€β”€β– β”€β”€β”€β•«β”€β”€β•«β”€β”€β”€ H β”œβ”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β”Œβ”€β”΄β”€β” β•‘ β•‘ └─β•₯β”€β”˜ β”Œβ”€β”€β”€β” # q_3: ─ H β”œβ”€ X β”œβ”€β•«β”€β”€β•«β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€ H β”œβ”€ # β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ └─β•₯β”€β”˜ # β•‘ β•‘ β”Œβ”€β”€β•¨β”€β”€β”β”Œβ”€β”€β•¨β”€β”€β” # c: 4/═══════════╩══╩═║ 0x2 β•žβ•‘ 0x4 β•ž # 0 0 β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[0], q[1]) qc.cx(q[2], q[3]) qc.measure(q[0], c[0]) qc.measure(q[0], c[0]) qc.h(q[2]).c_if(c, 2) qc.h(q[3]).c_if(c, 4) self.assertEqual(qc.depth(), 6) def test_circuit_depth_conditionals3(self): """Test circuit depth for conditional gates #3.""" # β”Œβ”€β”€β”€β”β”Œβ”€β” # q_0: ─ H β”œβ”€Mβ”œβ”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β•₯β”˜ β”‚ β”Œβ”€β” # q_1: ─ H β”œβ”€β•«β”€β”€β”€β”€β”Όβ”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β”‚ β””β•₯β”˜β”Œβ”€β” # q_2: ─ H β”œβ”€β•«β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β”Œβ”€β”΄β”€β” β•‘ β””β•₯β”˜β”Œβ”€β” # q_3: ─ H β”œβ”€β•«β”€β”€β”€ X β”œβ”€β”€β•«β”€β”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”˜ β•‘ └─β•₯β”€β”˜ β•‘ β•‘ β””β•₯β”˜ # β•‘ β”Œβ”€β”€β•¨β”€β”€β” β•‘ β•‘ β•‘ # c: 4/══════╩═║ 0x2 β•žβ•β•©β•β•β•©β•β•β•©β• # 0 β””β”€β”€β”€β”€β”€β”˜ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c, 2) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 4) def test_circuit_depth_bit_conditionals1(self): """Test circuit depth for single bit conditional gates #1.""" # β”Œβ”€β”€β”€β”β”Œβ”€β” # q_0: ─ H β”œβ”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β•₯β”˜ β”Œβ”€β”€β”€β” # q_1: ─ H β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€β”€ H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β”Œβ”€β” └─β•₯β”€β”˜ # q_2: ─ H β”œβ”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β””β•₯β”˜ β•‘ β”Œβ”€β”€β”€β” # q_3: ─ H β”œβ”€β•«β”€β”€β•«β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€ H β”œβ”€β”€β”€ # β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ └─β•₯β”€β”˜ # β•‘ β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” # c: 4/══════╩══╩═║ c_0=0x1 β•žβ•‘ c_2=0x0 β•ž # 0 2 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[2], c[2]) qc.h(q[1]).c_if(c[0], True) qc.h(q[3]).c_if(c[2], False) self.assertEqual(qc.depth(), 3) def test_circuit_depth_bit_conditionals2(self): """Test circuit depth for single bit conditional gates #2.""" # β”Œβ”€β”€β”€β”β”Œβ”€β” Β» # q_0: ─ H β”œβ”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€Β» # β”œβ”€β”€β”€β”€β””β•₯β”˜ β”Œβ”€β”€β”€β” β”Œβ”€β”΄β”€β” β”‚ Β» # q_1: ─ H β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€β”€ H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€Β» # β”œβ”€β”€β”€β”€ β•‘ β”Œβ”€β” └─β•₯β”€β”˜ └─β•₯β”€β”˜ β”Œβ”€β”΄β”€β” Β» # q_2: ─ H β”œβ”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€ H β”œβ”€β”€β”€Β» # β”œβ”€β”€β”€β”€ β•‘ β””β•₯β”˜ β•‘ β”Œβ”€β”€β”€β” β•‘ β”Œβ”€β”΄β”€β” └─β•₯β”€β”˜ Β» # q_3: ─ H β”œβ”€β•«β”€β”€β•«β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€ H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€Β» # β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ └─β•₯β”€β”˜ β•‘ └─β•₯β”€β”˜ β•‘ Β» # β•‘ β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”Β» # c: 4/══════╩══╩═║ c_1=0x1 β•žβ•‘ c_3=0x1 β•žβ•‘ c_0=0x0 β•žβ•‘ c_2=0x0 β•žβ•‘ c_1=0x1 β•žΒ» # 0 2 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜Β» # Β« # Β«q_0: ─────────── # Β« # Β«q_1: ─────■───── # Β« β”‚ # Β«q_2: ─────┼───── # Β« β”Œβ”€β”΄β”€β” # Β«q_3: ──── H β”œβ”€β”€β”€ # Β« └─β•₯β”€β”˜ # Β« β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” # Β«c: 4/β•‘ c_3=0x1 β•ž # Β« β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[2], c[2]) qc.h(q[1]).c_if(c[1], True) qc.h(q[3]).c_if(c[3], True) qc.cx(0, 1).c_if(c[0], False) qc.cx(2, 3).c_if(c[2], False) qc.ch(0, 2).c_if(c[1], True) qc.ch(1, 3).c_if(c[3], True) self.assertEqual(qc.depth(), 4) def test_circuit_depth_bit_conditionals3(self): """Test circuit depth for single bit conditional gates #3.""" # β”Œβ”€β”€β”€β”β”Œβ”€β” # q_0: ─ H β”œβ”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β•₯β”˜ β”Œβ”€β”€β”€β” β”Œβ”€β” # q_1: ─ H β”œβ”€β•«β”€β”€β”€β”€β”€ H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ └─β•₯β”€β”˜ β”Œβ”€β”€β”€β” β””β•₯β”˜β”Œβ”€β” # q_2: ─ H β”œβ”€β•«β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€ H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β•‘ └─β•₯β”€β”˜ β”Œβ”€β”€β”€β” β•‘ β””β•₯β”˜β”Œβ”€β” # q_3: ─ H β”œβ”€β•«β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€ H β”œβ”€β”€β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ └─β•₯β”€β”˜ β•‘ β•‘ β””β•₯β”˜ # β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”β”Œβ”€β”€β•¨β”€β”€β”β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” β•‘ β•‘ β•‘ # c: 4/══════╩═║ c_0=0x1 β•žβ•‘ 0x2 β•žβ•‘ c_3=0x1 β•žβ•β•©β•β•β•©β•β•β•©β• # 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.h(1).c_if(c[0], True) qc.h(q[2]).c_if(c, 2) qc.h(3).c_if(c[3], True) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 6) def test_circuit_depth_measurements1(self): """Test circuit depth for measurements #1.""" # β”Œβ”€β”€β”€β”β”Œβ”€β” # q_0: ─ H β”œβ”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β•₯β”˜β”Œβ”€β” # q_1: ─ H β”œβ”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β””β•₯β”˜β”Œβ”€β” # q_2: ─ H β”œβ”€β•«β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β•‘ β””β•₯β”˜β”Œβ”€β” # q_3: ─ H β”œβ”€β•«β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ β””β•₯β”˜ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 2) def test_circuit_depth_measurements2(self): """Test circuit depth for measurements #2.""" # β”Œβ”€β”€β”€β”β”Œβ”€β”β”Œβ”€β”β”Œβ”€β”β”Œβ”€β” # q_0: ─ H β”œβ”€Mβ”œβ”€Mβ”œβ”€Mβ”œβ”€Mβ”œ # β”œβ”€β”€β”€β”€β””β•₯β”˜β””β•₯β”˜β””β•₯β”˜β””β•₯β”˜ # q_1: ─ H β”œβ”€β•«β”€β”€β•«β”€β”€β•«β”€β”€β•«β”€ # β”œβ”€β”€β”€β”€ β•‘ β•‘ β•‘ β•‘ # q_2: ─ H β”œβ”€β•«β”€β”€β•«β”€β”€β•«β”€β”€β•«β”€ # β”œβ”€β”€β”€β”€ β•‘ β•‘ β•‘ β•‘ # q_3: ─ H β”œβ”€β•«β”€β”€β•«β”€β”€β•«β”€β”€β•«β”€ # β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ β•‘ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[0], c[1]) qc.measure(q[0], c[2]) qc.measure(q[0], c[3]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_measurements3(self): """Test circuit depth for measurements #3.""" # β”Œβ”€β”€β”€β”β”Œβ”€β” # q_0: ─ H β”œβ”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β•₯β”˜β”Œβ”€β” # q_1: ─ H β”œβ”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β””β•₯β”˜β”Œβ”€β” # q_2: ─ H β”œβ”€β•«β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β•‘ β””β•₯β”˜β”Œβ”€β” # q_3: ─ H β”œβ”€β•«β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ β””β•₯β”˜ # c: 4/══════╩══╩══╩══╩═ # 0 0 0 0 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[0]) qc.measure(q[2], c[0]) qc.measure(q[3], c[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_barriers1(self): """Test circuit depth for barriers #1.""" # β”Œβ”€β”€β”€β” β–‘ # q_0: ─ H β”œβ”€β”€β– β”€β”€β”€β–‘β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β–‘ # q_1: ────── X β”œβ”€β–‘β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β–‘ β”Œβ”€β”€β”€β” # q_2: ───────────░── H β”œβ”€β”€β– β”€β”€ # β–‘ β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” # q_3: ───────────░─────── X β”œ # β–‘ β””β”€β”€β”€β”˜ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.barrier(q) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_barriers2(self): """Test circuit depth for barriers #2.""" # β”Œβ”€β”€β”€β” β–‘ β–‘ β–‘ # q_0: ─ H β”œβ”€β–‘β”€β”€β”€β– β”€β”€β”€β–‘β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β–‘ β”Œβ”€β”΄β”€β” β–‘ β–‘ # q_1: ──────░── X β”œβ”€β–‘β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€β”€β”€β”€β”€ # β–‘ β””β”€β”€β”€β”˜ β–‘ β”Œβ”€β”€β”€β” β–‘ # q_2: ──────░───────░── H β”œβ”€β–‘β”€β”€β”€β– β”€β”€ # β–‘ β–‘ β””β”€β”€β”€β”˜ β–‘ β”Œβ”€β”΄β”€β” # q_3: ──────░───────░───────░── X β”œ # β–‘ β–‘ β–‘ β””β”€β”€β”€β”˜ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.barrier(q) circ.cx(0, 1) circ.barrier(q) circ.h(2) circ.barrier(q) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_barriers3(self): """Test circuit depth for barriers #3.""" # β”Œβ”€β”€β”€β” β–‘ β–‘ β–‘ β–‘ β–‘ # q_0: ─ H β”œβ”€β–‘β”€β”€β”€β– β”€β”€β”€β–‘β”€β”€β–‘β”€β”€β–‘β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β–‘ β”Œβ”€β”΄β”€β” β–‘ β–‘ β–‘ β–‘ # q_1: ──────░── X β”œβ”€β–‘β”€β”€β–‘β”€β”€β–‘β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€β”€β”€β”€β”€ # β–‘ β””β”€β”€β”€β”˜ β–‘ β–‘ β–‘ β”Œβ”€β”€β”€β” β–‘ # q_2: ──────░───────░──░──░── H β”œβ”€β–‘β”€β”€β”€β– β”€β”€ # β–‘ β–‘ β–‘ β–‘ β””β”€β”€β”€β”˜ β–‘ β”Œβ”€β”΄β”€β” # q_3: ──────░───────░──░──░───────░── X β”œ # β–‘ β–‘ β–‘ β–‘ β–‘ β””β”€β”€β”€β”˜ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.barrier(q) circ.cx(0, 1) circ.barrier(q) circ.barrier(q) circ.barrier(q) circ.h(2) circ.barrier(q) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap1(self): """Test circuit depth for snapshots #1.""" # β”Œβ”€β”€β”€β” β–‘ # q_0: ─ H β”œβ”€β”€β– β”€β”€β”€β–‘β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β–‘ # q_1: ────── X β”œβ”€β–‘β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β–‘ β”Œβ”€β”€β”€β” # q_2: ───────────░── H β”œβ”€β”€β– β”€β”€ # β–‘ β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” # q_3: ───────────░─────── X β”œ # β–‘ β””β”€β”€β”€β”˜ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.append(Snapshot("snap", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap2(self): """Test circuit depth for snapshots #2.""" # β”Œβ”€β”€β”€β” β–‘ β–‘ β–‘ # q_0: ─ H β”œβ”€β–‘β”€β”€β”€β– β”€β”€β”€β–‘β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β–‘ β”Œβ”€β”΄β”€β” β–‘ β–‘ # q_1: ──────░── X β”œβ”€β–‘β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€β”€β”€β”€β”€ # β–‘ β””β”€β”€β”€β”˜ β–‘ β”Œβ”€β”€β”€β” β–‘ # q_2: ──────░───────░── H β”œβ”€β–‘β”€β”€β”€β– β”€β”€ # β–‘ β–‘ β””β”€β”€β”€β”˜ β–‘ β”Œβ”€β”΄β”€β” # q_3: ──────░───────░───────░── X β”œ # β–‘ β–‘ β–‘ β””β”€β”€β”€β”˜ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.append(Snapshot("snap0", num_qubits=4), [0, 1, 2, 3]) circ.cx(0, 1) circ.append(Snapshot("snap1", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.append(Snapshot("snap2", num_qubits=4), [0, 1, 2, 3]) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap3(self): """Test circuit depth for snapshots #3.""" # β”Œβ”€β”€β”€β” β–‘ β–‘ # q_0: ─ H β”œβ”€β”€β– β”€β”€β”€β–‘β”€β”€β–‘β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β–‘ β–‘ # q_1: ────── X β”œβ”€β–‘β”€β”€β–‘β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β–‘ β–‘ β”Œβ”€β”€β”€β” # q_2: ───────────░──░── H β”œβ”€β”€β– β”€β”€ # β–‘ β–‘ β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” # q_3: ───────────░──░─────── X β”œ # β–‘ β–‘ β””β”€β”€β”€β”˜ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.append(Snapshot("snap0", num_qubits=4), [0, 1, 2, 3]) circ.append(Snapshot("snap1", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_2qubit(self): """Test finding depth of two-qubit gates only.""" # β”Œβ”€β”€β”€β” # q_0: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β” # q_1: ────── X β”œβ”€ Rz(0.1) β”œβ”€β– β”€β”€Mβ”œ # β”Œβ”€β”€β”€β”β””β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β•₯β”˜ # q_2: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β•«β”€ # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β”‚ β•‘ # q_3: ────── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β•«β”€ # β””β”€β”€β”€β”˜ β•‘ # c: 1/═════════════════════════╩═ # 0 circ = QuantumCircuit(4, 1) circ.h(0) circ.cx(0, 1) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) self.assertEqual(circ.depth(lambda x: x.operation.num_qubits == 2), 2) def test_circuit_depth_multiqubit_or_conditional(self): """Test finding depth of multi-qubit or conditional gates.""" # β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” # q_0: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€ # β””β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β” └─β•₯β”€β”˜ # q_1: ───────■─── Rz(0.1) β”œβ”€β”€β”€β”€β”€β”€β– β”€β”€Mβ”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€ # β”Œβ”€β”΄β”€β”β””β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”˜ β”‚ β””β•₯β”˜ β•‘ # q_2: ────── X β”œβ”€β”€β”€β”€ H β”œβ”€β”€β”€β”€β”€β– β”€β”€β”€β”Όβ”€β”€β•«β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ β”Œβ”€β”΄β”€β” β”‚ β•‘ β•‘ # q_3: ────────────────────── X β”œβ”€β– β”€β”€β•«β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” # c: 1/══════════════════════════════╩═║ c_0 = T β•ž # 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ circ = QuantumCircuit(4, 1) circ.h(0) circ.ccx(0, 1, 2) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) circ.x(0).c_if(0, 1) self.assertEqual( circ.depth(lambda x: x.operation.num_qubits >= 2 or x.operation.condition is not None), 4, ) def test_circuit_depth_first_qubit(self): """Test finding depth of gates touching q0 only.""" # β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” # q_0: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€ T β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β”β”Œβ”€β”€β”΄β”€β”€β”€β”΄β”€β”€β” β”Œβ”€β” # q_1: ────── X β”œβ”€ Rz(0.1) β”œβ”€β– β”€β”€Mβ”œ # β”Œβ”€β”€β”€β”β””β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β•₯β”˜ # q_2: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β•«β”€ # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β”‚ β•‘ # q_3: ────── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β•«β”€ # β””β”€β”€β”€β”˜ β•‘ # c: 1/═════════════════════════╩═ # 0 circ = QuantumCircuit(4, 1) circ.h(0) circ.cx(0, 1) circ.t(0) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) self.assertEqual(circ.depth(lambda x: circ.qubits[0] in x.qubits), 3) def test_circuit_size_empty(self): """Circuit.size should return 0 for an empty circuit.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) self.assertEqual(qc.size(), 0) def test_circuit_size_single_qubit_gates(self): """Circuit.size should increment for each added single qubit gate.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) self.assertEqual(qc.size(), 1) qc.h(q[1]) self.assertEqual(qc.size(), 2) def test_circuit_size_2qubit(self): """Circuit.size of only 2-qubit gates.""" size = 3 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.rz(0.1, q[1]) qc.rzz(0.1, q[1], q[2]) self.assertEqual(qc.size(lambda x: x.operation.num_qubits == 2), 2) def test_circuit_size_ignores_barriers_snapshots(self): """Circuit.size should not count barriers or snapshots.""" q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) self.assertEqual(qc.size(), 2) qc.barrier(q) self.assertEqual(qc.size(), 2) qc.append(Snapshot("snapshot_label", num_qubits=4), [0, 1, 2, 3]) self.assertEqual(qc.size(), 2) def test_circuit_count_ops(self): """Test circuit count ops.""" q = QuantumRegister(6, "q") qc = QuantumCircuit(q) qc.h(q) qc.x(q[1]) qc.y(q[2:4]) qc.z(q[3:]) result = qc.count_ops() expected = {"h": 6, "z": 3, "y": 2, "x": 1} self.assertIsInstance(result, dict) self.assertEqual(expected, result) def test_circuit_nonlocal_gates(self): """Test num_nonlocal_gates.""" # β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” # q_0: ─ H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€0 β”œ # β”œβ”€β”€β”€β”€ β”Œβ”€β”€β”€β” β”‚ β”‚ # q_1: ─ H β”œβ”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€ β”œ # β”œβ”€β”€β”€β”€ β””β”€β”€β”€β”˜ β”‚ β”‚ β”‚ # q_2: ─ H β”œβ”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€X── Iswap β”œ # β”œβ”€β”€β”€β”€ β”‚ β”Œβ”€β”€β”€β” β”‚ β”‚ β”‚ # q_3: ─ H β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€ Z β”œβ”€X── β”œ # β”œβ”€β”€β”€β”€β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”β”œβ”€β”€β”€β”€ β”‚ β”‚ # q_4: ─ H β”œβ”€ Ry(0.1) β”œβ”€ Z β”œβ”€β”€β”€β”€1 β”œ # β”œβ”€β”€β”€β”€β””β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”˜β””β”€β”€β”€β”˜ └───β•₯β”€β”€β”€β”€β”˜ # q_5: ─ H β”œβ”€β”€β”€β”€ Z β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ β”Œβ”€β”€β•¨β”€β”€β” # c: 2/═════════════════════════║ 0x2 β•žβ•β• # β””β”€β”€β”€β”€β”€β”˜ q = QuantumRegister(6, "q") c = ClassicalRegister(2, "c") qc = QuantumCircuit(q, c) qc.h(q) qc.x(q[1]) qc.cry(0.1, q[2], q[4]) qc.z(q[3:]) qc.cswap(q[1], q[2], q[3]) qc.iswap(q[0], q[4]).c_if(c, 2) result = qc.num_nonlocal_gates() expected = 3 self.assertEqual(expected, result) def test_circuit_nonlocal_gates_no_instruction(self): """Verify num_nunlocal_gates does not include barriers.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/4500 n = 3 qc = QuantumCircuit(n) qc.h(range(n)) qc.barrier() self.assertEqual(qc.num_nonlocal_gates(), 0) def test_circuit_connected_components_empty(self): """Verify num_connected_components is width for empty""" q = QuantumRegister(7, "q") qc = QuantumCircuit(q) self.assertEqual(7, qc.num_connected_components()) def test_circuit_connected_components_multi_reg(self): """Test tensor factors works over multi registers""" # β”Œβ”€β”€β”€β” # q1_0: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β”Œβ”€β”΄β”€β” # q1_1: ─ H β”œβ”€ X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β” # q1_2: ─ H β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€ X β”œβ”€β”€β– β”€β”€ # β”œβ”€β”€β”€β”€ β”‚ β””β”€β”¬β”€β”˜β”Œβ”€β”΄β”€β” # q2_0: ─ H β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€β”€ X β”œ # β”œβ”€β”€β”€β”€ β”Œβ”€β”΄β”€β” β”‚ β””β”€β”€β”€β”˜ # q2_1: ─ H β”œβ”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_multi_reg2(self): """Test tensor factors works over multi registers #2.""" # q1_0: ──■──────────── # β”‚ # q1_1: ──┼─────────■── # β”‚ β”Œβ”€β”€β”€β” β”‚ # q1_2: ──┼─── X β”œβ”€β”€β”Όβ”€β”€ # β”‚ β””β”€β”¬β”€β”˜β”Œβ”€β”΄β”€β” # q2_0: ──┼────■─── X β”œ # β”Œβ”€β”΄β”€β” β””β”€β”€β”€β”˜ # q2_1: ─ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[1]) qc.cx(q2[0], q1[2]) qc.cx(q1[1], q2[0]) self.assertEqual(qc.num_connected_components(), 2) def test_circuit_connected_components_disconnected(self): """Test tensor factors works with 2q subspaces.""" # q1_0: ──■────────────────────── # β”‚ # q1_1: ──┼────■───────────────── # β”‚ β”‚ # q1_2: ──┼────┼────■──────────── # β”‚ β”‚ β”‚ # q1_3: ──┼────┼────┼────■─────── # β”‚ β”‚ β”‚ β”‚ # q1_4: ──┼────┼────┼────┼────■── # β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”΄β”€β” # q2_0: ──┼────┼────┼────┼─── X β”œ # β”‚ β”‚ β”‚ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ # q2_1: ──┼────┼────┼─── X β”œβ”€β”€β”€β”€β”€ # β”‚ β”‚ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ # q2_2: ──┼────┼─── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”‚ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ # q2_3: ──┼─── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ # q2_4: ─ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ q1 = QuantumRegister(5, "q1") q2 = QuantumRegister(5, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[4]) qc.cx(q1[1], q2[3]) qc.cx(q1[2], q2[2]) qc.cx(q1[3], q2[1]) qc.cx(q1[4], q2[0]) self.assertEqual(qc.num_connected_components(), 5) def test_circuit_connected_components_with_clbits(self): """Test tensor components with classical register.""" # β”Œβ”€β”€β”€β”β”Œβ”€β” # q_0: ─ H β”œβ”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β•₯β”˜β”Œβ”€β” # q_1: ─ H β”œβ”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β””β•₯β”˜β”Œβ”€β” # q_2: ─ H β”œβ”€β•«β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β•‘ β””β•₯β”˜β”Œβ”€β” # q_3: ─ H β”œβ”€β•«β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ β””β•₯β”˜ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 4) def test_circuit_connected_components_with_cond(self): """Test tensor components with one conditional gate.""" # β”Œβ”€β”€β”€β”β”Œβ”€β” # q_0: ─ H β”œβ”€Mβ”œβ”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β•₯β”˜ β”‚ β”Œβ”€β” # q_1: ─ H β”œβ”€β•«β”€β”€β”€β”€β”Όβ”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β”‚ β””β•₯β”˜β”Œβ”€β” # q_2: ─ H β”œβ”€β•«β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β”Œβ”€β”΄β”€β” β•‘ β””β•₯β”˜β”Œβ”€β” # q_3: ─ H β”œβ”€β•«β”€β”€β”€ X β”œβ”€β”€β•«β”€β”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”˜ β•‘ └─β•₯β”€β”˜ β•‘ β•‘ β””β•₯β”˜ # β•‘ β”Œβ”€β”€β•¨β”€β”€β” β•‘ β•‘ β•‘ # c: 4/══════╩═║ 0x2 β•žβ•β•©β•β•β•©β•β•β•©β• # 0 β””β”€β”€β”€β”€β”€β”˜ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c, 2) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_with_cond2(self): """Test tensor components with two conditional gates.""" # β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” # q_0: ─ H β”œβ”€β”€ H β”œβ”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ └─β•₯β”€β”˜ # q_1: ─ H β”œβ”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β– β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β”Œβ”€β”΄β”€β” # q_2: ─ H β”œβ”€β”€β”€β•«β”€β”€β”€β”€β”€ X β”œβ”€ # β”œβ”€β”€β”€β”€ β•‘ └─β•₯β”€β”˜ # q_3: ─ H β”œβ”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€ # β””β”€β”€β”€β”˜β”Œβ”€β”€β•¨β”€β”€β”β”Œβ”€β”€β•¨β”€β”€β” # c: 8/═════║ 0x0 β•žβ•‘ 0x4 β•ž # β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(2 * size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(0).c_if(c, 0) qc.cx(1, 2).c_if(c, 4) self.assertEqual(qc.num_connected_components(), 2) def test_circuit_connected_components_with_cond3(self): """Test tensor components with three conditional gates and measurements.""" # β”Œβ”€β”€β”€β”β”Œβ”€β” β”Œβ”€β”€β”€β” # q0_0: ─ H β”œβ”€Mβ”œβ”€β”€ H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β•₯β”˜ └─β•₯β”€β”˜ # q0_1: ─ H β”œβ”€β•«β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β•‘ β”Œβ”€β”΄β”€β” β”Œβ”€β” # q0_2: ─ H β”œβ”€β•«β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€ X β”œβ”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β•‘ └─β•₯β”€β”˜ β””β•₯β”˜ β”Œβ”€β”€β”€β” # q0_3: ─ H β”œβ”€β•«β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β•«β”€β”€β”€ X β”œβ”€ # β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ β•‘ └─β•₯β”€β”˜ # β•‘ β”Œβ”€β”€β•¨β”€β”€β”β”Œβ”€β”€β•¨β”€β”€β” β•‘ β”Œβ”€β”€β•¨β”€β”€β” # c0: 4/══════╩═║ 0x0 β•žβ•‘ 0x1 β•žβ•β•©β•β•‘ 0x2 β•ž # 0 β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜ 2 β””β”€β”€β”€β”€β”€β”˜ size = 4 q = QuantumRegister(size) c = ClassicalRegister(size) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.h(q[0]).c_if(c, 0) qc.cx(q[1], q[2]).c_if(c, 1) qc.measure(q[2], c[2]) qc.x(q[3]).c_if(c, 2) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_with_bit_cond(self): """Test tensor components with one single bit conditional gate.""" # β”Œβ”€β”€β”€β”β”Œβ”€β” # q_0: ─ H β”œβ”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β•₯β”˜β”Œβ”€β” β”‚ # q_1: ─ H β”œβ”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β””β•₯β”˜β”Œβ”€β” β”‚ # q_2: ─ H β”œβ”€β•«β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β•‘ β””β•₯β”˜ β”Œβ”€β”΄β”€β” β”Œβ”€β” # q_3: ─ H β”œβ”€β•«β”€β”€β•«β”€β”€β•«β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€Mβ”œ # β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ └─β•₯β”€β”˜ β””β•₯β”˜ # β•‘ β•‘ β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” β•‘ # c: 4/══════╩══╩══╩═║ c_0=0x1 β•žβ•β•©β• # 0 1 2 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c[0], True) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 3) def test_circuit_connected_components_with_bit_cond2(self): """Test tensor components with two bit conditional gates.""" # β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” # q_0: ─ H β”œβ”€β”€β”€β”€ H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€ # β”œβ”€β”€β”€β”€ └─β•₯β”€β”˜ β””β”€β”¬β”€β”˜ # q_1: ─ H β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β•‘ # q_2: ─ H β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β”‚ β•‘ # q_3: ─ H β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” # c: 6/═════║ c_1=0x1 β•žβ•‘ c_0=0x1 β•žβ•‘ c_4=0x0 β•ž # β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size + 2, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(0).c_if(c[1], True) qc.cx(1, 0).c_if(c[4], False) qc.cz(2, 3).c_if(c[0], True) self.assertEqual(qc.num_connected_components(), 5) def test_circuit_connected_components_with_bit_cond3(self): """Test tensor components with register and bit conditional gates.""" # β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” # q0_0: ─ H β”œβ”€β”€β”€β”€ H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ └─β•₯β”€β”˜ # q0_1: ─ H β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β”Œβ”€β”΄β”€β” # q0_2: ─ H β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ └─β•₯β”€β”˜ β”Œβ”€β”€β”€β” # q0_3: ─ H β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β•‘ β•‘ └─β•₯β”€β”˜ # β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”€β”β”Œβ”€β”€β•¨β”€β”€β”β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”€β” # c0: 4/═════║ c0_0=0x1 β•žβ•‘ 0x1 β•žβ•‘ c0_2=0x1 β•ž # β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ size = 4 q = QuantumRegister(size) c = ClassicalRegister(size) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[0]).c_if(c[0], True) qc.cx(q[1], q[2]).c_if(c, 1) qc.x(q[3]).c_if(c[2], True) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_unitary_factors1(self): """Test unitary factors empty circuit.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) self.assertEqual(qc.num_unitary_factors(), 4) def test_circuit_unitary_factors2(self): """Test unitary factors multi qregs""" q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q1, q2, c) self.assertEqual(qc.num_unitary_factors(), 4) def test_circuit_unitary_factors3(self): """Test unitary factors measurements and conditionals.""" # β”Œβ”€β”€β”€β” β”Œβ”€β” # q_0: ─ H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€Mβ”œβ”€β”€β”€ # β”œβ”€β”€β”€β”€ β”‚ β”‚ β”‚ β”Œβ”€β” β”‚ β””β•₯β”˜ # q_1: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β•«β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β”Œβ”€β”΄β”€β” β”‚ β”Œβ”€β”΄β”€β” β”‚ β”‚ β””β•₯β”˜β”Œβ”€β” β”‚ β•‘ # q_2: ─ H β”œβ”€ X β”œβ”€β”€β”€β”Όβ”€β”€β”€β”€ X β”œβ”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”Όβ”€β”€β”€β•«β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β”€β”€β”€β”˜ β”Œβ”€β”΄β”€β” β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β”β”Œβ”€β”΄β”€β” β•‘ β””β•₯β”˜β”Œβ”€β”΄β”€β” β•‘ β”Œβ”€β” # q_3: ─ H β”œβ”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€ X β”œβ”€ X β”œβ”€β•«β”€β”€β•«β”€β”€ X β”œβ”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”˜ └─β•₯β”€β”˜ β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β•‘ β•‘ β””β”€β”€β”€β”˜ β•‘ β””β•₯β”˜ # β”Œβ”€β”€β•¨β”€β”€β” β•‘ β•‘ β•‘ β•‘ # c: 4/══════════║ 0x2 β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•©β•β•β•β•β•β•β•β•©β•β•β•©β• # β””β”€β”€β”€β”€β”€β”˜ 1 2 0 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[1], q[2]) qc.cx(q[1], q[2]) qc.cx(q[0], q[3]).c_if(c, 2) qc.cx(q[0], q[3]) qc.cx(q[0], q[3]) qc.cx(q[0], q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_unitary_factors(), 2) def test_circuit_unitary_factors4(self): """Test unitary factors measurements go to same cbit.""" # β”Œβ”€β”€β”€β”β”Œβ”€β” # q_0: ─ H β”œβ”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β””β•₯β”˜β”Œβ”€β” # q_1: ─ H β”œβ”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β””β•₯β”˜β”Œβ”€β” # q_2: ─ H β”œβ”€β•«β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€ # β”œβ”€β”€β”€β”€ β•‘ β•‘ β””β•₯β”˜β”Œβ”€β” # q_3: ─ H β”œβ”€β•«β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ β””β•₯β”˜ # q_4: ──────╫──╫──╫──╫─ # β•‘ β•‘ β•‘ β•‘ # c: 5/══════╩══╩══╩══╩═ # 0 0 0 0 size = 5 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[0]) qc.measure(q[2], c[0]) qc.measure(q[3], c[0]) self.assertEqual(qc.num_unitary_factors(), 5) def test_num_qubits_qubitless_circuit(self): """Check output in absence of qubits.""" c_reg = ClassicalRegister(3) circ = QuantumCircuit(c_reg) self.assertEqual(circ.num_qubits, 0) def test_num_qubits_qubitfull_circuit(self): """Check output in presence of qubits""" q_reg = QuantumRegister(4) c_reg = ClassicalRegister(3) circ = QuantumCircuit(q_reg, c_reg) self.assertEqual(circ.num_qubits, 4) def test_num_qubits_registerless_circuit(self): """Check output for circuits with direct argument for qubits.""" circ = QuantumCircuit(5) self.assertEqual(circ.num_qubits, 5) def test_num_qubits_multiple_register_circuit(self): """Check output for circuits with multiple quantum registers.""" q_reg1 = QuantumRegister(5) q_reg2 = QuantumRegister(6) q_reg3 = QuantumRegister(7) circ = QuantumCircuit(q_reg1, q_reg2, q_reg3) self.assertEqual(circ.num_qubits, 18) def test_calibrations_basis_gates(self): """Check if the calibrations for basis gates provided are added correctly.""" circ = QuantumCircuit(2) 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(RXGate(3.14), [0], q0_x180) circ.add_calibration(RYGate(1.57), [1], q1_y90) self.assertEqual(set(circ.calibrations.keys()), {"rx", "ry"}) self.assertEqual(set(circ.calibrations["rx"].keys()), {((0,), (3.14,))}) self.assertEqual(set(circ.calibrations["ry"].keys()), {((1,), (1.57,))}) self.assertEqual( circ.calibrations["rx"][((0,), (3.14,))].instructions, q0_x180.instructions ) self.assertEqual(circ.calibrations["ry"][((1,), (1.57,))].instructions, q1_y90.instructions) def test_calibrations_custom_gates(self): """Check if the calibrations for custom gates with params provided are added correctly.""" circ = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibrations with a custom gate 'rxt' circ.add_calibration("rxt", [0], q0_x180, params=[1.57, 3.14, 4.71]) self.assertEqual(set(circ.calibrations.keys()), {"rxt"}) self.assertEqual(set(circ.calibrations["rxt"].keys()), {((0,), (1.57, 3.14, 4.71))}) self.assertEqual( circ.calibrations["rxt"][((0,), (1.57, 3.14, 4.71))].instructions, q0_x180.instructions ) def test_calibrations_no_params(self): """Check calibrations if the no params is provided with just gate name.""" circ = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) circ.add_calibration("h", [0], q0_x180) self.assertEqual(set(circ.calibrations.keys()), {"h"}) self.assertEqual(set(circ.calibrations["h"].keys()), {((0,), ())}) self.assertEqual(circ.calibrations["h"][((0,), ())].instructions, q0_x180.instructions) def test_has_calibration_for(self): """Test that `has_calibration_for` returns a correct answer.""" qc = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("h", [0], q0_x180) qc.h(0) qc.h(1) self.assertTrue(qc.has_calibration_for(qc.data[0])) self.assertFalse(qc.has_calibration_for(qc.data[1])) def test_has_calibration_for_legacy(self): """Test that `has_calibration_for` returns a correct answer when presented with a legacy 3 tuple.""" qc = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("h", [0], q0_x180) qc.h(0) qc.h(1) self.assertTrue( qc.has_calibration_for( (qc.data[0].operation, list(qc.data[0].qubits), list(qc.data[0].clbits)) ) ) self.assertFalse( qc.has_calibration_for( (qc.data[1].operation, list(qc.data[1].qubits), list(qc.data[1].clbits)) ) ) def test_metadata_copy_does_not_share_state(self): """Verify mutating the metadata of a circuit copy does not impact original.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/6057 qc1 = QuantumCircuit(1) qc1.metadata = {"a": 0} qc2 = qc1.copy() qc2.metadata["a"] = 1000 self.assertEqual(qc1.metadata["a"], 0) def test_metadata_is_dict(self): """Verify setting metadata to None in the constructor results in an empty dict.""" qc = QuantumCircuit(1) metadata1 = qc.metadata self.assertEqual(metadata1, {}) def test_metadata_raises(self): """Test that we must set metadata to a dict.""" qc = QuantumCircuit(1) with self.assertRaises(TypeError): qc.metadata = 1 def test_metdata_deprectation(self): """Test that setting metadata to None emits a deprecation warning.""" qc = QuantumCircuit(1) with self.assertWarns(DeprecationWarning): qc.metadata = None self.assertEqual(qc.metadata, {}) def test_scheduling(self): """Test cannot return schedule information without scheduling.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) with self.assertRaises(AttributeError): # pylint: disable=pointless-statement qc.op_start_times if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's gates in QASM2.""" import unittest from math import pi import re from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.circuit import Parameter, Qubit, Clbit, Gate from qiskit.circuit.library import C3SXGate, CCZGate, CSGate, CSdgGate, PermutationGate from qiskit.qasm.exceptions import QasmError # Regex pattern to match valid OpenQASM identifiers VALID_QASM2_IDENTIFIER = re.compile("[a-z][a-zA-Z_0-9]*") class TestCircuitQasm(QiskitTestCase): """QuantumCircuit QASM2 tests.""" def test_circuit_qasm(self): """Test circuit qasm() method.""" qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") cr = ClassicalRegister(3, "cr") qc = QuantumCircuit(qr1, qr2, cr) qc.p(0.3, qr1[0]) qc.u(0.3, 0.2, 0.1, qr2[1]) qc.s(qr2[1]) qc.sdg(qr2[1]) qc.cx(qr1[0], qr2[1]) qc.barrier(qr2) qc.cx(qr2[1], qr1[0]) qc.h(qr2[1]) qc.x(qr2[1]).c_if(cr, 0) qc.y(qr1[0]).c_if(cr, 1) qc.z(qr1[0]).c_if(cr, 2) qc.barrier(qr1, qr2) qc.measure(qr1[0], cr[0]) qc.measure(qr2[0], cr[1]) qc.measure(qr2[1], cr[2]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg qr1[1]; qreg qr2[2]; creg cr[3]; p(0.3) qr1[0]; u(0.3,0.2,0.1) qr2[1]; s qr2[1]; sdg qr2[1]; cx qr1[0],qr2[1]; barrier qr2[0],qr2[1]; cx qr2[1],qr1[0]; h qr2[1]; if(cr==0) x qr2[1]; if(cr==1) y qr1[0]; if(cr==2) z qr1[0]; barrier qr1[0],qr2[0],qr2[1]; measure qr1[0] -> cr[0]; measure qr2[0] -> cr[1]; measure qr2[1] -> cr[2];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_composite_circuit(self): """Test circuit qasm() method when a composite circuit instruction is included within circuit. """ composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_instruction() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate composite_circ q0,q1 { h q0; x q1; cx q0,q1; } qreg qr[2]; creg cr[2]; h qr[0]; cx qr[0],qr[1]; barrier qr[0],qr[1]; composite_circ qr[0],qr[1]; measure qr[0] -> cr[0]; measure qr[1] -> cr[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_multiple_same_composite_circuits(self): """Test circuit qasm() method when a composite circuit is added to the circuit multiple times """ composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_instruction() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate composite_circ q0,q1 { h q0; x q1; cx q0,q1; } qreg qr[2]; creg cr[2]; h qr[0]; cx qr[0],qr[1]; barrier qr[0],qr[1]; composite_circ qr[0],qr[1]; composite_circ qr[0],qr[1]; measure qr[0] -> cr[0]; measure qr[1] -> cr[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_multiple_composite_circuits_with_same_name(self): """Test circuit qasm() method when multiple composite circuit instructions with the same circuit name are added to the circuit """ my_gate = QuantumCircuit(1, name="my_gate") my_gate.h(0) my_gate_inst1 = my_gate.to_instruction() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst2 = my_gate.to_instruction() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst3 = my_gate.to_instruction() qr = QuantumRegister(1, name="qr") circuit = QuantumCircuit(qr, name="circuit") circuit.append(my_gate_inst1, [qr[0]]) circuit.append(my_gate_inst2, [qr[0]]) my_gate_inst2_id = id(circuit.data[-1].operation) circuit.append(my_gate_inst3, [qr[0]]) my_gate_inst3_id = id(circuit.data[-1].operation) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate q0 {{ h q0; }} gate my_gate_{1} q0 {{ x q0; }} gate my_gate_{0} q0 {{ x q0; }} qreg qr[1]; my_gate qr[0]; my_gate_{1} qr[0]; my_gate_{0} qr[0];\n""".format( my_gate_inst3_id, my_gate_inst2_id ) self.assertEqual(circuit.qasm(), expected_qasm) def test_circuit_qasm_with_composite_circuit_with_children_composite_circuit(self): """Test circuit qasm() method when composite circuits with children composite circuits in the definitions are added to the circuit""" child_circ = QuantumCircuit(2, name="child_circ") child_circ.h(0) child_circ.cx(0, 1) parent_circ = QuantumCircuit(3, name="parent_circ") parent_circ.append(child_circ, range(2)) parent_circ.h(2) grandparent_circ = QuantumCircuit(4, name="grandparent_circ") grandparent_circ.append(parent_circ, range(3)) grandparent_circ.x(3) qc = QuantumCircuit(4) qc.append(grandparent_circ, range(4)) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate child_circ q0,q1 { h q0; cx q0,q1; } gate parent_circ q0,q1,q2 { child_circ q0,q1; h q2; } gate grandparent_circ q0,q1,q2,q3 { parent_circ q0,q1,q2; x q3; } qreg q[4]; grandparent_circ q[0],q[1],q[2],q[3];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_pi(self): """Test circuit qasm() method with pi params.""" circuit = QuantumCircuit(2) circuit.cz(0, 1) circuit.u(2 * pi, 3 * pi, -5 * pi, 0) qasm_str = circuit.qasm() circuit2 = QuantumCircuit.from_qasm_str(qasm_str) self.assertEqual(circuit, circuit2) def test_circuit_qasm_with_composite_circuit_with_one_param(self): """Test circuit qasm() method when a composite circuit instruction has one param """ original_str = """OPENQASM 2.0; include "qelib1.inc"; gate nG0(param0) q0 { h q0; } qreg q[3]; creg c[3]; nG0(pi) q[0];\n""" qc = QuantumCircuit.from_qasm_str(original_str) self.assertEqual(original_str, qc.qasm()) def test_circuit_qasm_with_composite_circuit_with_many_params_and_qubits(self): """Test circuit qasm() method when a composite circuit instruction has many params and qubits """ original_str = """OPENQASM 2.0; include "qelib1.inc"; gate nG0(param0,param1) q0,q1 { h q0; h q1; } qreg q[3]; qreg r[3]; creg c[3]; creg d[3]; nG0(pi,pi/2) q[0],r[0];\n""" qc = QuantumCircuit.from_qasm_str(original_str) self.assertEqual(original_str, qc.qasm()) def test_c3sxgate_roundtrips(self): """Test that C3SXGate correctly round trips. Qiskit gives this gate a different name ('c3sx') to the name in Qiskit's version of qelib1.inc ('c3sqrtx') gate, which can lead to resolution issues.""" qc = QuantumCircuit(4) qc.append(C3SXGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; c3sqrtx q[0],q[1],q[2],q[3]; """ self.assertEqual(qasm, expected) parsed = QuantumCircuit.from_qasm_str(qasm) self.assertIsInstance(parsed.data[0].operation, C3SXGate) def test_c3sxgate_qasm_deprecation_warning(self): """Test deprecation warning for C3SXGate.""" with self.assertWarnsRegex(DeprecationWarning, r"Correct exporting to OpenQASM 2"): C3SXGate().qasm() def test_cczgate_qasm(self): """Test that CCZ dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(3) qc.append(CCZGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate ccz q0,q1,q2 { h q2; ccx q0,q1,q2; h q2; } qreg q[3]; ccz q[0],q[1],q[2]; """ self.assertEqual(qasm, expected) def test_csgate_qasm(self): """Test that CS dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.append(CSGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate cs q0,q1 { p(pi/4) q0; cx q0,q1; p(-pi/4) q1; cx q0,q1; p(pi/4) q1; } qreg q[2]; cs q[0],q[1]; """ self.assertEqual(qasm, expected) def test_csdggate_qasm(self): """Test that CSdg dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.append(CSdgGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate csdg q0,q1 { p(-pi/4) q0; cx q0,q1; p(pi/4) q1; cx q0,q1; p(-pi/4) q1; } qreg q[2]; csdg q[0],q[1]; """ self.assertEqual(qasm, expected) def test_rzxgate_qasm(self): """Test that RZX dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.rzx(0, 0, 1) qc.rzx(pi / 2, 1, 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate rzx(param0) q0,q1 { h q1; cx q0,q1; rz(param0) q1; cx q0,q1; h q1; } qreg q[2]; rzx(0) q[0],q[1]; rzx(pi/2) q[1],q[0]; """ self.assertEqual(qasm, expected) def test_ecrgate_qasm(self): """Test that ECR dumps its definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.ecr(0, 1) qc.ecr(1, 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate rzx(param0) q0,q1 { h q1; cx q0,q1; rz(param0) q1; cx q0,q1; h q1; } gate ecr q0,q1 { rzx(pi/4) q0,q1; x q0; rzx(-pi/4) q0,q1; } qreg q[2]; ecr q[0],q[1]; ecr q[1],q[0]; """ self.assertEqual(qasm, expected) def test_unitary_qasm(self): """Test that UnitaryGate can be dumped to OQ2 correctly.""" qc = QuantumCircuit(1) qc.unitary([[1, 0], [0, 1]], 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate unitary q0 { u(0,0,0) q0; } qreg q[1]; unitary q[0]; """ self.assertEqual(qasm, expected) def test_multiple_unitary_qasm(self): """Test that multiple UnitaryGate instances can all dump successfully.""" custom = QuantumCircuit(1, name="custom") custom.unitary([[1, 0], [0, -1]], 0) qc = QuantumCircuit(2) qc.unitary([[1, 0], [0, 1]], 0) qc.unitary([[0, 1], [1, 0]], 1) qc.append(custom.to_gate(), [0], []) qasm = qc.qasm() expected = re.compile( r"""OPENQASM 2.0; include "qelib1.inc"; gate unitary q0 { u\(0,0,0\) q0; } gate (?P<u1>unitary_[0-9]*) q0 { u\(pi,-pi/2,pi/2\) q0; } gate (?P<u2>unitary_[0-9]*) q0 { u\(0,pi/2,pi/2\) q0; } gate custom q0 { (?P=u2) q0; } qreg q\[2\]; unitary q\[0\]; (?P=u1) q\[1\]; custom q\[0\]; """, re.MULTILINE, ) self.assertRegex(qasm, expected) def test_unbound_circuit_raises(self): """Test circuits with unbound parameters raises.""" qc = QuantumCircuit(1) theta = Parameter("ΞΈ") qc.rz(theta, 0) with self.assertRaises(QasmError): qc.qasm() def test_gate_qasm_with_ctrl_state(self): """Test gate qasm() with controlled gate that has ctrl_state setting.""" from qiskit.quantum_info import Operator qc = QuantumCircuit(2) qc.ch(0, 1, ctrl_state=0) qasm_str = qc.qasm() self.assertEqual(Operator(qc), Operator(QuantumCircuit.from_qasm_str(qasm_str))) def test_circuit_qasm_with_mcx_gate(self): """Test circuit qasm() method with MCXGate See https://github.com/Qiskit/qiskit-terra/issues/4943 """ qc = QuantumCircuit(4) qc.mcx([0, 1, 2], 3) # qasm output doesn't support parameterized gate yet. # param0 for "gate mcuq(param0) is not used inside the definition expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate mcx q0,q1,q2,q3 { h q3; p(pi/8) q0; p(pi/8) q1; p(pi/8) q2; p(pi/8) q3; cx q0,q1; p(-pi/8) q1; cx q0,q1; cx q1,q2; p(-pi/8) q2; cx q0,q2; p(pi/8) q2; cx q1,q2; p(-pi/8) q2; cx q0,q2; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; h q3; } qreg q[4]; mcx q[0],q[1],q[2],q[3];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_mcx_gate_variants(self): """Test circuit qasm() method with MCXGrayCode, MCXRecursive, MCXVChain""" import qiskit.circuit.library as cl n = 5 qc = QuantumCircuit(2 * n - 1) qc.append(cl.MCXGrayCode(n), range(n + 1)) qc.append(cl.MCXRecursive(n), range(n + 2)) qc.append(cl.MCXVChain(n), range(2 * n - 1)) # qasm output doesn't support parameterized gate yet. # param0 for "gate mcuq(param0) is not used inside the definition expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate mcu1(param0) q0,q1,q2,q3,q4,q5 { cu1(pi/16) q4,q5; cx q4,q3; cu1(-pi/16) q3,q5; cx q4,q3; cu1(pi/16) q3,q5; cx q3,q2; cu1(-pi/16) q2,q5; cx q4,q2; cu1(pi/16) q2,q5; cx q3,q2; cu1(-pi/16) q2,q5; cx q4,q2; cu1(pi/16) q2,q5; cx q2,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q3,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q2,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q3,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q1,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q2,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q1,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q2,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; } gate mcx_gray q0,q1,q2,q3,q4,q5 { h q5; mcu1(pi) q0,q1,q2,q3,q4,q5; h q5; } gate mcx q0,q1,q2,q3 { h q3; p(pi/8) q0; p(pi/8) q1; p(pi/8) q2; p(pi/8) q3; cx q0,q1; p(-pi/8) q1; cx q0,q1; cx q1,q2; p(-pi/8) q2; cx q0,q2; p(pi/8) q2; cx q1,q2; p(-pi/8) q2; cx q0,q2; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; h q3; } gate mcx_recursive q0,q1,q2,q3,q4,q5,q6 { mcx q0,q1,q2,q6; mcx q3,q4,q6,q5; mcx q0,q1,q2,q6; mcx q3,q4,q6,q5; } gate mcx_vchain q0,q1,q2,q3,q4,q5,q6,q7,q8 { rccx q0,q1,q6; rccx q2,q6,q7; rccx q3,q7,q8; ccx q4,q8,q5; rccx q3,q7,q8; rccx q2,q6,q7; rccx q0,q1,q6; } qreg q[9]; mcx_gray q[0],q[1],q[2],q[3],q[4],q[5]; mcx_recursive q[0],q[1],q[2],q[3],q[4],q[5],q[6]; mcx_vchain q[0],q[1],q[2],q[3],q[4],q[5],q[6],q[7],q[8];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_registerless_bits(self): """Test that registerless bits do not have naming collisions in their registers.""" initial_registers = [QuantumRegister(2), ClassicalRegister(2)] qc = QuantumCircuit(*initial_registers, [Qubit(), Clbit()]) # Match a 'qreg identifier[3];'-like QASM register declaration. register_regex = re.compile(r"\s*[cq]reg\s+(\w+)\s*\[\d+\]\s*", re.M) qasm_register_names = set() for statement in qc.qasm().split(";"): match = register_regex.match(statement) if match: qasm_register_names.add(match.group(1)) self.assertEqual(len(qasm_register_names), 4) # Check that no additional registers were added to the circuit. self.assertEqual(len(qc.qregs), 1) self.assertEqual(len(qc.cregs), 1) # Check that the registerless-register names are recalculated after adding more registers, # to avoid naming clashes in this case. generated_names = qasm_register_names - {register.name for register in initial_registers} for generated_name in generated_names: qc.add_register(QuantumRegister(1, name=generated_name)) qasm_register_names = set() for statement in qc.qasm().split(";"): match = register_regex.match(statement) if match: qasm_register_names.add(match.group(1)) self.assertEqual(len(qasm_register_names), 6) def test_circuit_qasm_with_repeated_instruction_names(self): """Test that qasm() doesn't change the name of the instructions that live in circuit.data, but a copy of them when there are repeated names.""" qc = QuantumCircuit(2) qc.h(0) qc.x(1) # Create some random custom gate and name it "custom" custom = QuantumCircuit(1) custom.h(0) custom.y(0) gate = custom.to_gate() gate.name = "custom" # Another random custom gate named "custom" as well custom2 = QuantumCircuit(2) custom2.x(0) custom2.z(1) gate2 = custom2.to_gate() gate2.name = "custom" # Append custom gates with same name to original circuit qc.append(gate, [0]) qc.append(gate2, [1, 0]) # Expected qasm string will append the id to the second gate with repeated name expected_qasm = f"""OPENQASM 2.0; include "qelib1.inc"; gate custom q0 {{ h q0; y q0; }} gate custom_{id(gate2)} q0,q1 {{ x q0; z q1; }} qreg q[2]; h q[0]; x q[1]; custom q[0]; custom_{id(gate2)} q[1],q[0];\n""" # Check qasm() produced the correct string self.assertEqual(expected_qasm, qc.qasm()) # Check instruction names were not changed by qasm() names = ["h", "x", "custom", "custom"] for idx, instruction in enumerate(qc._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_with_invalid_identifiers(self): """Test that qasm() detects and corrects invalid OpenQASM gate identifiers, while not changing the instructions on the original circuit""" qc = QuantumCircuit(2) # Create some gate and give it an invalid name custom = QuantumCircuit(1) custom.x(0) custom.u(0, 0, pi, 0) gate = custom.to_gate() gate.name = "A[$]" # Another gate also with invalid name custom2 = QuantumCircuit(2) custom2.x(0) custom2.append(gate, [1]) gate2 = custom2.to_gate() gate2.name = "invalid[name]" # Append gates qc.append(gate, [0]) qc.append(gate2, [1, 0]) # Expected qasm with valid identifiers expected_qasm = "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "gate gate_A___ q0 { x q0; u(0,0,pi) q0; }", "gate invalid_name_ q0,q1 { x q0; gate_A___ q1; }", "qreg q[2];", "gate_A___ q[0];", "invalid_name_ q[1],q[0];", "", ] ) # Check qasm() produces the correct string self.assertEqual(expected_qasm, qc.qasm()) # Check instruction names were not changed by qasm() names = ["A[$]", "invalid[name]"] for idx, instruction in enumerate(qc._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_with_duplicate_invalid_identifiers(self): """Test that qasm() corrects invalid identifiers and the de-duplication code runs correctly, without altering original instructions""" base = QuantumCircuit(1) # First gate with invalid name, escapes to "invalid__" clash1 = QuantumCircuit(1, name="invalid??") clash1.x(0) base.append(clash1, [0]) # Second gate with invalid name that also escapes to "invalid__" clash2 = QuantumCircuit(1, name="invalid[]") clash2.z(0) base.append(clash2, [0]) # Check qasm is correctly produced names = set() for match in re.findall(r"gate (\S+)", base.qasm()): self.assertTrue(VALID_QASM2_IDENTIFIER.fullmatch(match)) names.add(match) self.assertEqual(len(names), 2) # Check instruction names were not changed by qasm() names = ["invalid??", "invalid[]"] for idx, instruction in enumerate(base._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_escapes_register_names(self): """Test that registers that have invalid OpenQASM 2 names get correctly escaped, even when they would escape to the same value.""" qc = QuantumCircuit(QuantumRegister(2, "?invalid"), QuantumRegister(2, "!invalid")) qc.cx(0, 1) qc.cx(2, 3) qasm = qc.qasm() match = re.fullmatch( rf"""OPENQASM 2.0; include "qelib1.inc"; qreg ({VALID_QASM2_IDENTIFIER.pattern})\[2\]; qreg ({VALID_QASM2_IDENTIFIER.pattern})\[2\]; cx \1\[0\],\1\[1\]; cx \2\[0\],\2\[1\]; """, qasm, ) self.assertTrue(match) self.assertNotEqual(match.group(1), match.group(2)) def test_circuit_qasm_escapes_reserved(self): """Test that the OpenQASM 2 exporter won't export reserved names.""" qc = QuantumCircuit(QuantumRegister(1, "qreg")) gate = Gate("gate", 1, []) gate.definition = QuantumCircuit(1) qc.append(gate, [qc.qubits[0]]) qasm = qc.qasm() match = re.fullmatch( rf"""OPENQASM 2.0; include "qelib1.inc"; gate ({VALID_QASM2_IDENTIFIER.pattern}) q0 {{ }} qreg ({VALID_QASM2_IDENTIFIER.pattern})\[1\]; \1 \2\[0\]; """, qasm, ) self.assertTrue(match) self.assertNotEqual(match.group(1), "gate") self.assertNotEqual(match.group(1), "qreg") def test_circuit_qasm_with_double_precision_rotation_angle(self): """Test that qasm() emits high precision rotation angles per default.""" from qiskit.circuit.tools.pi_check import MAX_FRAC qc = QuantumCircuit(1) qc.p(0.123456789, 0) qc.p(pi * pi, 0) qc.p(MAX_FRAC * pi + 1, 0) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; p(0.123456789) q[0]; p(9.869604401089358) q[0]; p(51.26548245743669) q[0];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_rotation_angles_close_to_pi(self): """Test that qasm() properly rounds values closer than 1e-12 to pi.""" qc = QuantumCircuit(1) qc.p(pi + 1e-11, 0) qc.p(pi + 1e-12, 0) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; p(3.141592653599793) q[0]; p(pi) q[0];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_raises_on_single_bit_condition(self): """OpenQASM 2 can't represent single-bit conditions, so test that a suitable error is printed if this is attempted.""" qc = QuantumCircuit(1, 1) qc.x(0).c_if(0, True) with self.assertRaisesRegex(QasmError, "OpenQASM 2 can only condition on registers"): qc.qasm() def test_circuit_raises_invalid_custom_gate_no_qubits(self): """OpenQASM 2 exporter of custom gates with no qubits. See: https://github.com/Qiskit/qiskit-terra/issues/10435""" legit_circuit = QuantumCircuit(5, name="legit_circuit") empty_circuit = QuantumCircuit(name="empty_circuit") legit_circuit.append(empty_circuit) with self.assertRaisesRegex(QasmError, "acts on zero qubits"): legit_circuit.qasm() def test_circuit_raises_invalid_custom_gate_clbits(self): """OpenQASM 2 exporter of custom instruction. See: https://github.com/Qiskit/qiskit-terra/issues/7351""" instruction = QuantumCircuit(2, 2, name="inst") instruction.cx(0, 1) instruction.measure([0, 1], [0, 1]) custom_instruction = instruction.to_instruction() qc = QuantumCircuit(2, 2) qc.append(custom_instruction, [0, 1], [0, 1]) with self.assertRaisesRegex(QasmError, "acts on 2 classical bits"): qc.qasm() def test_circuit_qasm_with_permutations(self): """Test circuit qasm() method with Permutation gates.""" qc = QuantumCircuit(4) qc.append(PermutationGate([2, 1, 0]), [0, 1, 2]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate permutation__2_1_0_ q0,q1,q2 { swap q0,q2; } qreg q[4]; permutation__2_1_0_ q[0],q[1],q[2];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_multiple_permutation(self): """Test that multiple PermutationGates can be added to a circuit.""" custom = QuantumCircuit(3, name="custom") custom.append(PermutationGate([2, 1, 0]), [0, 1, 2]) custom.append(PermutationGate([0, 1, 2]), [0, 1, 2]) qc = QuantumCircuit(4) qc.append(PermutationGate([2, 1, 0]), [0, 1, 2], []) qc.append(PermutationGate([1, 2, 0]), [0, 1, 2], []) qc.append(custom.to_gate(), [1, 3, 2], []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate permutation__2_1_0_ q0,q1,q2 { swap q0,q2; } gate permutation__1_2_0_ q0,q1,q2 { swap q1,q2; swap q0,q2; } gate permutation__0_1_2_ q0,q1,q2 { } gate custom q0,q1,q2 { permutation__2_1_0_ q0,q1,q2; permutation__0_1_2_ q0,q1,q2; } qreg q[4]; permutation__2_1_0_ q[0],q[1],q[2]; permutation__1_2_0_ q[0],q[1],q[2]; custom q[1],q[3],q[2]; """ self.assertEqual(qasm, expected) def test_circuit_qasm_with_reset(self): """Test circuit qasm() method with Reset.""" qc = QuantumCircuit(2) qc.reset([0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; reset q[0]; reset q[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_nested_gate_naming_clashes(self): """Test that gates that have naming clashes but only appear in the body of another gate still get exported correctly.""" # pylint: disable=missing-class-docstring class Inner(Gate): def __init__(self, param): super().__init__("inner", 1, [param]) def _define(self): self._definition = QuantumCircuit(1) self._definition.rx(self.params[0], 0) class Outer(Gate): def __init__(self, param): super().__init__("outer", 1, [param]) def _define(self): self._definition = QuantumCircuit(1) self._definition.append(Inner(self.params[0]), [0], []) qc = QuantumCircuit(1) qc.append(Outer(1.0), [0], []) qc.append(Outer(2.0), [0], []) qasm = qc.qasm() expected = re.compile( r"""OPENQASM 2\.0; include "qelib1\.inc"; gate inner\(param0\) q0 { rx\(1\.0\) q0; } gate outer\(param0\) q0 { inner\(1\.0\) q0; } gate (?P<inner1>inner_[0-9]*)\(param0\) q0 { rx\(2\.0\) q0; } gate (?P<outer1>outer_[0-9]*)\(param0\) q0 { (?P=inner1)\(2\.0\) q0; } qreg q\[1\]; outer\(1\.0\) q\[0\]; (?P=outer1)\(2\.0\) q\[0\]; """, re.MULTILINE, ) self.assertRegex(qasm, expected) def test_opaque_output(self): """Test that gates with no definition are exported as `opaque`.""" custom = QuantumCircuit(1, name="custom") custom.append(Gate("my_c", 1, []), [0]) qc = QuantumCircuit(2) qc.append(Gate("my_a", 1, []), [0]) qc.append(Gate("my_a", 1, []), [1]) qc.append(Gate("my_b", 2, [1.0]), [1, 0]) qc.append(custom.to_gate(), [0], []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; opaque my_a q0; opaque my_b(param0) q0,q1; opaque my_c q0; gate custom q0 { my_c q0; } qreg q[2]; my_a q[0]; my_a q[1]; my_b(1.0) q[1],q[0]; custom q[0]; """ self.assertEqual(qasm, expected) def test_sequencial_inner_gates_with_same_name(self): """Test if inner gates sequentially added with the same name result in the correct qasm""" qubits_range = range(3) gate_a = QuantumCircuit(3, name="a") gate_a.h(qubits_range) gate_a = gate_a.to_instruction() gate_b = QuantumCircuit(3, name="a") gate_b.append(gate_a, qubits_range) gate_b.x(qubits_range) gate_b = gate_b.to_instruction() qc = QuantumCircuit(3) qc.append(gate_b, qubits_range) qc.z(qubits_range) gate_a_id = id(qc.data[0].operation) expected_output = f"""OPENQASM 2.0; include "qelib1.inc"; gate a q0,q1,q2 {{ h q0; h q1; h q2; }} gate a_{gate_a_id} q0,q1,q2 {{ a q0,q1,q2; x q0; x q1; x q2; }} qreg q[3]; a_{gate_a_id} q[0],q[1],q[2]; z q[0]; z q[1]; z q[2]; """ self.assertEqual(qc.qasm(), expected_output) def test_empty_barrier(self): """Test that a blank barrier statement in _Qiskit_ acts over all qubits, while an explicitly no-op barrier (assuming Qiskit continues to allow this) is not output to OQ2 at all, since the statement requires an argument in the spec.""" qc = QuantumCircuit(QuantumRegister(2, "qr1"), QuantumRegister(3, "qr2")) qc.barrier() # In Qiskit land, this affects _all_ qubits. qc.barrier([]) # This explicitly affects _no_ qubits (so is totally meaningless). expected = """\ OPENQASM 2.0; include "qelib1.inc"; qreg qr1[2]; qreg qr2[3]; barrier qr1[0],qr1[1],qr2[0],qr2[1],qr2[2]; """ self.assertEqual(qc.qasm(), expected) def test_small_angle_valid(self): """Test that small angles do not get converted to invalid OQ2 floating-point values.""" # OQ2 _technically_ requires a decimal point in all floating-point values, even ones that # are followed by an exponent. qc = QuantumCircuit(1) qc.rx(0.000001, 0) expected = """\ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; rx(1.e-06) q[0]; """ self.assertEqual(qc.qasm(), expected) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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=unused-import """Test Qiskit's QuantumCircuit class.""" import os import tempfile import unittest import numpy as np import qiskit.extensions.simulator from qiskit import BasicAer from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit, Qubit, Clbit from qiskit import execute from qiskit import QiskitError from qiskit.quantum_info import state_fidelity from qiskit.test import QiskitTestCase class TestCircuitRegisters(QiskitTestCase): """QuantumCircuit Registers tests.""" def test_qregs(self): """Test getting quantum registers from circuit. """ qr1 = QuantumRegister(10, "q") self.assertEqual(qr1.name, "q") self.assertEqual(qr1.size, 10) self.assertEqual(type(qr1), QuantumRegister) def test_cregs(self): """Test getting quantum registers from circuit. """ cr1 = ClassicalRegister(10, "c") self.assertEqual(cr1.name, "c") self.assertEqual(cr1.size, 10) self.assertEqual(type(cr1), ClassicalRegister) def test_qarg_negative_size(self): """Test attempt to create a negative size QuantumRegister. """ self.assertRaises(qiskit.exceptions.QiskitError, QuantumRegister, -1) def test_qarg_string_size(self): """Test attempt to create a non-integer size QuantumRegister. """ self.assertRaises(qiskit.exceptions.QiskitError, QuantumRegister, 'string') def test_qarg_numpy_int_size(self): """Test castable to integer size QuantumRegister. """ np_int = np.dtype('int').type(10) qr1 = QuantumRegister(np_int, "q") self.assertEqual(qr1.name, "q") self.assertEqual(qr1.size, 10) self.assertEqual(type(qr1), QuantumRegister) def test_numpy_array_of_registers(self): """Test numpy array of Registers . See https://github.com/Qiskit/qiskit-terra/issues/1898 """ qrs = [QuantumRegister(2, name='q%s' % i) for i in range(5)] qreg_array = np.array([], dtype=object, ndmin=1) qreg_array = np.append(qreg_array, qrs) expected = [qrs[0][0], qrs[0][1], qrs[1][0], qrs[1][1], qrs[2][0], qrs[2][1], qrs[3][0], qrs[3][1], qrs[4][0], qrs[4][1]] self.assertEqual(len(qreg_array), 10) self.assertEqual(qreg_array.tolist(), expected) def test_negative_index(self): """Test indexing from the back """ qr1 = QuantumRegister(10, "q") cr1 = ClassicalRegister(10, "c") self.assertEqual(qr1[-1], qr1[9]) self.assertEqual(qr1[-3:-1], [qr1[7], qr1[8]]) self.assertEqual(len(cr1[0:-2]), 8) def test_reg_equal(self): """Test getting quantum registers from circuit. """ qr1 = QuantumRegister(1, "q") qr2 = QuantumRegister(2, "q") cr1 = ClassicalRegister(1, "q") self.assertEqual(qr1, qr1) self.assertNotEqual(qr1, qr2) self.assertNotEqual(qr1, cr1) def test_qubits(self): """Test qubits() method. """ qr1 = QuantumRegister(1, "q1") cr1 = ClassicalRegister(3, "c1") qr2 = QuantumRegister(2, "q2") qc = QuantumCircuit(qr2, cr1, qr1) qubtis = qc.qubits self.assertEqual(qubtis[0], qr2[0]) self.assertEqual(qubtis[1], qr2[1]) self.assertEqual(qubtis[2], qr1[0]) def test_clbits(self): """Test clbits() method. """ qr1 = QuantumRegister(1, "q1") cr1 = ClassicalRegister(2, "c1") qr2 = QuantumRegister(2, "q2") cr2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(qr2, cr2, qr1, cr1) clbtis = qc.clbits self.assertEqual(clbtis[0], cr2[0]) self.assertEqual(clbtis[1], cr1[0]) self.assertEqual(clbtis[2], cr1[1]) def test_qregs_circuit(self): """Test getting quantum registers from circuit. """ qr1 = QuantumRegister(1) qr2 = QuantumRegister(2) qc = QuantumCircuit(qr1, qr2) q_regs = qc.qregs self.assertEqual(len(q_regs), 2) self.assertEqual(q_regs[0], qr1) self.assertEqual(q_regs[1], qr2) def test_cregs_circuit(self): """Test getting classical registers from circuit. """ cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(2) cr3 = ClassicalRegister(3) qc = QuantumCircuit(cr1, cr2, cr3) c_regs = qc.cregs self.assertEqual(len(c_regs), 3) self.assertEqual(c_regs[0], cr1) self.assertEqual(c_regs[1], cr2) def test_basic_slice(self): """simple slice test""" qr = QuantumRegister(5) cr = ClassicalRegister(5) self.assertEqual(len(qr[0:3]), 3) self.assertEqual(len(cr[0:3]), 3) def test_apply_gate_to_slice(self): """test applying gate to register slice""" sli = slice(0, 9, 2) qr = QuantumRegister(10) cr = ClassicalRegister(10) qc = QuantumCircuit(qr, cr) qc.h(qr[0:9:2]) for i, index in enumerate(range(*sli.indices(sli.stop))): self.assertEqual(qc.data[i][1][0].index, index) def test_apply_barrier_to_slice(self): """test applying barrier to register slice""" n_qubits = 10 qr = QuantumRegister(n_qubits) cr = ClassicalRegister(n_qubits) qc = QuantumCircuit(qr, cr) qc.barrier(qr) # barrier works a little different than normal gates for expansion # test full register self.assertEqual(len(qc.data), 1) self.assertEqual(qc.data[0][0].name, 'barrier') self.assertEqual(len(qc.data[0][1]), n_qubits) for i, bit in enumerate(qc.data[0][1]): self.assertEqual(bit.index, i) # test slice n_qubits = 2 qc = QuantumCircuit(qr, cr) qc.barrier(qr[0:n_qubits]) self.log.info(qc.qasm()) self.assertEqual(len(qc.data), 1) self.assertEqual(qc.data[0][0].name, 'barrier') self.assertEqual(len(qc.data[0][1]), n_qubits) for i in range(n_qubits): self.assertEqual(qc.data[0][1][i].index, i) def test_apply_ccx_to_slice(self): """test applying ccx to register slice""" qcontrol = QuantumRegister(10) qcontrol2 = QuantumRegister(10) qtarget = QuantumRegister(5) qtarget2 = QuantumRegister(10) qc = QuantumCircuit(qcontrol, qtarget) # test slice with skip and full register target qc.ccx(qcontrol[1::2], qcontrol[0::2], qtarget) self.assertEqual(len(qc.data), 5) for i, ictl, (gate, qargs, _) in zip(range(len(qc.data)), range(0, 10, 2), qc.data): self.assertEqual(gate.name, 'ccx') self.assertEqual(len(qargs), 3) self.assertIn(qargs[0].index, [ictl, ictl + 1]) self.assertIn(qargs[1].index, [ictl, ictl + 1]) self.assertEqual(qargs[2].index, i) # test decrementing slice qc = QuantumCircuit(qcontrol, qtarget) qc.ccx(qcontrol[2:0:-1], qcontrol[4:6], qtarget[0:2]) self.assertEqual(len(qc.data), 2) for (gate, qargs, _), ictl1, ictl2, itgt in zip(qc.data, range(2, 0, -1), range(4, 6), range(0, 2)): self.assertEqual(gate.name, 'ccx') self.assertEqual(len(qargs), 3) self.assertEqual(qargs[0].index, ictl1) self.assertEqual(qargs[1].index, ictl2) self.assertEqual(qargs[2].index, itgt) # test register expansion in ccx qc = QuantumCircuit(qcontrol, qcontrol2, qtarget2) qc.ccx(qcontrol, qcontrol2, qtarget2) for i, (gate, qargs, _) in enumerate(qc.data): self.assertEqual(gate.name, 'ccx') self.assertEqual(len(qargs), 3) self.assertEqual(qargs[0].index, i) self.assertEqual(qargs[1].index, i) self.assertEqual(qargs[2].index, i) def test_cswap_on_slice(self): """test applying cswap to register slice""" qr1 = QuantumRegister(10) qr2 = QuantumRegister(5) qc = QuantumCircuit(qr1, qr2) qc.cswap(qr2[3::-1], qr1[1:9:2], qr1[2:9:2]) qc.cswap(qr2[0], qr1[1], qr1[2]) qc.cswap([qr2[0]], [qr1[1]], [qr1[2]]) self.assertRaises(qiskit.exceptions.QiskitError, qc.cswap, qr2[4::-1], qr1[1:9:2], qr1[2:9:2]) def test_apply_ccx_to_empty_slice(self): """test applying ccx to non-register raises""" qr = QuantumRegister(10) cr = ClassicalRegister(10) qc = QuantumCircuit(qr, cr) self.assertRaises(qiskit.exceptions.QiskitError, qc.ccx, qr[2:0], qr[4:2], qr[7:5]) def test_apply_cx_to_non_register(self): """test applying ccx to non-register raises""" qr = QuantumRegister(10) cr = ClassicalRegister(10) qc = QuantumCircuit(qr, cr) self.assertRaises(qiskit.exceptions.QiskitError, qc.cx, qc[0:2], qc[2:4]) def test_apply_ch_to_slice(self): """test applying ch to slice""" qr = QuantumRegister(10) cr = ClassicalRegister(10) # test slice qc = QuantumCircuit(qr, cr) ctl_slice = slice(0, 2) tgt_slice = slice(2, 4) qc.ch(qr[ctl_slice], qr[tgt_slice]) for (gate, qargs, _), ictrl, itgt in zip(qc.data, range(0, 2), range(2, 4)): self.assertEqual(gate.name, 'ch') self.assertEqual(len(qargs), 2) self.assertEqual(qargs[0].index, ictrl) self.assertEqual(qargs[1].index, itgt) # test single qubit args qc = QuantumCircuit(qr, cr) qc.ch(qr[0], qr[1]) self.assertEqual(len(qc.data), 1) op, qargs, _ = qc.data[0] self.assertEqual(op.name, 'ch') self.assertEqual(qargs[0].index, 0) self.assertEqual(qargs[1].index, 1) def test_measure_slice(self): """test measure slice""" qr = QuantumRegister(10) cr = ClassicalRegister(10) cr2 = ClassicalRegister(5) qc = QuantumCircuit(qr, cr) qc.measure(qr[0:2], cr[2:4]) for (gate, qargs, cargs), ictrl, itgt in zip(qc.data, range(0, 2), range(2, 4)): self.assertEqual(gate.name, 'measure') self.assertEqual(len(qargs), 1) self.assertEqual(len(cargs), 1) self.assertEqual(qargs[0].index, ictrl) self.assertEqual(cargs[0].index, itgt) # test single element slice qc = QuantumCircuit(qr, cr) qc.measure(qr[0:1], cr[2:3]) for (gate, qargs, cargs), ictrl, itgt in zip(qc.data, range(0, 1), range(2, 3)): self.assertEqual(gate.name, 'measure') self.assertEqual(len(qargs), 1) self.assertEqual(len(cargs), 1) self.assertEqual(qargs[0].index, ictrl) self.assertEqual(cargs[0].index, itgt) # test tuple qc = QuantumCircuit(qr, cr) qc.measure(qr[0], cr[2]) self.assertEqual(len(qc.data), 1) op, qargs, cargs = qc.data[0] self.assertEqual(op.name, 'measure') self.assertEqual(len(qargs), 1) self.assertEqual(len(cargs), 1) self.assertTrue(isinstance(qargs[0], Qubit)) self.assertTrue(isinstance(cargs[0], Clbit)) self.assertEqual(qargs[0].index, 0) self.assertEqual(cargs[0].index, 2) # test full register qc = QuantumCircuit(qr, cr) qc.measure(qr, cr) for (gate, qargs, cargs), ictrl, itgt in zip(qc.data, range(len(qr)), range(len(cr))): self.assertEqual(gate.name, 'measure') self.assertEqual(len(qargs), 1) self.assertEqual(len(cargs), 1) self.assertEqual(qargs[0].index, ictrl) self.assertEqual(cargs[0].index, itgt) # test mix slice full register qc = QuantumCircuit(qr, cr2) qc.measure(qr[::2], cr2) for (gate, qargs, cargs), ictrl, itgt in zip(qc.data, range(0, 10, 2), range(len(cr2))): self.assertEqual(gate.name, 'measure') self.assertEqual(len(qargs), 1) self.assertEqual(len(cargs), 1) self.assertEqual(qargs[0].index, ictrl) self.assertEqual(cargs[0].index, itgt) def test_measure_slice_raises(self): """test raising exception for strange measures""" qr = QuantumRegister(10) cr = ClassicalRegister(10) qc = QuantumCircuit(qr, cr) with self.assertRaises(QiskitError): qc.measure(qr[0:2], cr[2]) # this is ok qc.measure(qr[0], cr[0:2]) def test_list_indexing(self): """test list indexing""" qr = QuantumRegister(10) cr = QuantumRegister(10) qc = QuantumCircuit(qr, cr) ind = [0, 1, 8, 9] qc.h(qr[ind]) self.assertEqual(len(qc.data), len(ind)) for (gate, qargs, _), index in zip(qc.data, ind): self.assertEqual(gate.name, 'h') self.assertEqual(len(qargs), 1) self.assertEqual(qargs[0].index, index) qc = QuantumCircuit(qr, cr) ind = [0, 1, 8, 9] qc.cx(qr[ind], qr[2:6]) for (gate, qargs, _), ind1, ind2 in zip(qc.data, ind, range(2, 6)): self.assertEqual(gate.name, 'cx') self.assertEqual(len(qargs), 2) self.assertEqual(qargs[0].index, ind1) self.assertEqual(qargs[1].index, ind2) class TestCircuitBit(QiskitTestCase): """QuantumCircuit Registers tests.""" def test_bit_getitem(self): """ Deprecated Bit.__getitem__. """ qubit = QuantumRegister(1, "q")[0] with self.assertWarns(DeprecationWarning): self.assertEqual(qubit[0], qubit.register) self.assertEqual(qubit[1], qubit.index) def test_gate_with_tuples(self): """ Deprecated gate parameters as tuples""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) expected = QuantumCircuit(qr) expected.h(qr[0]) with self.assertWarns(DeprecationWarning): qc.h((qr, 0)) self.assertEqual(qc, expected) def test_gate_with_tuple_list(self): """ Deprecated gate parameters as tuple list""" qr = QuantumRegister(2) qc = QuantumCircuit(qr) expected = QuantumCircuit(qr) expected.h([qr[0], qr[1]]) with self.assertWarns(DeprecationWarning): qc.h([(qr, 0), (qr, 1)]) self.assertEqual(qc, expected)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-function-docstring, missing-module-docstring import unittest from inspect import signature from math import pi import numpy as np from scipy.linalg import expm from ddt import data, ddt, unpack from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, execute from qiskit.exceptions import QiskitError from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase from qiskit.circuit import Gate, ControlledGate from qiskit.circuit.library import ( U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate, XXMinusYYGate, XXPlusYYGate, RZGate, XGate, YGate, GlobalPhaseGate, ) from qiskit import BasicAer from qiskit.quantum_info import Pauli from qiskit.quantum_info.operators.predicates import matrix_equal, is_unitary_matrix from qiskit.utils.optionals import HAS_TWEEDLEDUM from qiskit.quantum_info import Operator from qiskit import transpile class TestStandard1Q(QiskitTestCase): """Standard Extension Test. Gates with a single Qubit""" def setUp(self): super().setUp() self.qr = QuantumRegister(3, "q") self.qr2 = QuantumRegister(3, "r") self.cr = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.qr, self.qr2, self.cr) def test_barrier(self): self.circuit.barrier(self.qr[1]) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_barrier_wires(self): self.circuit.barrier(1) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_barrier_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.barrier, self.cr[0]) self.assertRaises(CircuitError, qc.barrier, self.cr) self.assertRaises(CircuitError, qc.barrier, (self.qr, "a")) self.assertRaises(CircuitError, qc.barrier, 0.0) def test_conditional_barrier_invalid(self): qc = self.circuit barrier = qc.barrier(self.qr) self.assertRaises(QiskitError, barrier.c_if, self.cr, 0) def test_barrier_reg(self): self.circuit.barrier(self.qr) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_barrier_none(self): self.circuit.barrier() self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual( self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2], self.qr2[0], self.qr2[1], self.qr2[2]), ) def test_ccx(self): self.circuit.ccx(self.qr[0], self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "ccx") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_ccx_wires(self): self.circuit.ccx(0, 1, 2) self.assertEqual(self.circuit[0].operation.name, "ccx") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_ccx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.ccx, self.cr[0], self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.ccx, self.qr[0], self.qr[0], self.qr[2]) self.assertRaises(CircuitError, qc.ccx, 0.0, self.qr[0], self.qr[2]) self.assertRaises(CircuitError, qc.ccx, self.cr, self.qr, self.qr) self.assertRaises(CircuitError, qc.ccx, "a", self.qr[1], self.qr[2]) def test_ch(self): self.circuit.ch(self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "ch") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_ch_wires(self): self.circuit.ch(0, 1) self.assertEqual(self.circuit[0].operation.name, "ch") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_ch_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.ch, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.ch, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.ch, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.ch, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.ch, self.cr, self.qr) self.assertRaises(CircuitError, qc.ch, "a", self.qr[1]) def test_cif_reg(self): self.circuit.h(self.qr[0]).c_if(self.cr, 7) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[0],)) self.assertEqual(self.circuit[0].operation.condition, (self.cr, 7)) def test_cif_single_bit(self): self.circuit.h(self.qr[0]).c_if(self.cr[0], True) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[0],)) self.assertEqual(self.circuit[0].operation.condition, (self.cr[0], True)) def test_crz(self): self.circuit.crz(1, self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "crz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_cry(self): self.circuit.cry(1, self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "cry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crx(self): self.circuit.crx(1, self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "crx") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crz_wires(self): self.circuit.crz(1, 0, 1) self.assertEqual(self.circuit[0].operation.name, "crz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_cry_wires(self): self.circuit.cry(1, 0, 1) self.assertEqual(self.circuit[0].operation.name, "cry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crx_wires(self): self.circuit.crx(1, 0, 1) self.assertEqual(self.circuit[0].operation.name, "crx") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.crz, 0, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.crz, 0, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.crz, 0, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.crz, self.qr[2], self.qr[1], self.qr[0]) self.assertRaises(CircuitError, qc.crz, 0, self.qr[1], self.cr[2]) self.assertRaises(CircuitError, qc.crz, 0, (self.qr, 3), self.qr[1]) self.assertRaises(CircuitError, qc.crz, 0, self.cr, self.qr) # TODO self.assertRaises(CircuitError, qc.crz, 'a', self.qr[1], self.qr[2]) def test_cry_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cry, 0, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.cry, 0, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cry, 0, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cry, self.qr[2], self.qr[1], self.qr[0]) self.assertRaises(CircuitError, qc.cry, 0, self.qr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cry, 0, (self.qr, 3), self.qr[1]) self.assertRaises(CircuitError, qc.cry, 0, self.cr, self.qr) # TODO self.assertRaises(CircuitError, qc.cry, 'a', self.qr[1], self.qr[2]) def test_crx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.crx, 0, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.crx, 0, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.crx, 0, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.crx, self.qr[2], self.qr[1], self.qr[0]) self.assertRaises(CircuitError, qc.crx, 0, self.qr[1], self.cr[2]) self.assertRaises(CircuitError, qc.crx, 0, (self.qr, 3), self.qr[1]) self.assertRaises(CircuitError, qc.crx, 0, self.cr, self.qr) # TODO self.assertRaises(CircuitError, qc.crx, 'a', self.qr[1], self.qr[2]) def test_cswap(self): self.circuit.cswap(self.qr[0], self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cswap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_cswap_wires(self): self.circuit.cswap(0, 1, 2) self.assertEqual(self.circuit[0].operation.name, "cswap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_cswap_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cswap, self.cr[0], self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cswap, self.qr[1], self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cswap, self.qr[1], 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cswap, self.cr[0], self.cr[1], self.qr[0]) self.assertRaises(CircuitError, qc.cswap, self.qr[0], self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, 0.0, self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, (self.qr, 3), self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, self.cr, self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, "a", self.qr[1], self.qr[2]) def test_cu1(self): self.circuit.append(CU1Gate(1), [self.qr[1], self.qr[2]]) self.assertEqual(self.circuit[0].operation.name, "cu1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cu1_wires(self): self.circuit.append(CU1Gate(1), [1, 2]) self.assertEqual(self.circuit[0].operation.name, "cu1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cu3(self): self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr[2]]) self.assertEqual(self.circuit[0].operation.name, "cu3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cu3_wires(self): self.circuit.append(CU3Gate(1, 2, 3), [1, 2]) self.assertEqual(self.circuit[0].operation.name, "cu3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cx(self): self.circuit.cx(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cx") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cx_wires(self): self.circuit.cx(1, 2) self.assertEqual(self.circuit[0].operation.name, "cx") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cx, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cx, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cx, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cx, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.cx, self.cr, self.qr) self.assertRaises(CircuitError, qc.cx, "a", self.qr[1]) def test_cy(self): self.circuit.cy(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cy") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cy_wires(self): self.circuit.cy(1, 2) self.assertEqual(self.circuit[0].operation.name, "cy") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cy_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cy, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cy, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cy, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cy, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.cy, self.cr, self.qr) self.assertRaises(CircuitError, qc.cy, "a", self.qr[1]) def test_cz(self): self.circuit.cz(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cz") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cz_wires(self): self.circuit.cz(1, 2) self.assertEqual(self.circuit[0].operation.name, "cz") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cz, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cz, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cz, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cz, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.cz, self.cr, self.qr) self.assertRaises(CircuitError, qc.cz, "a", self.qr[1]) def test_h(self): self.circuit.h(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_h_wires(self): self.circuit.h(1) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_h_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.h, self.cr[0]) self.assertRaises(CircuitError, qc.h, self.cr) self.assertRaises(CircuitError, qc.h, (self.qr, 3)) self.assertRaises(CircuitError, qc.h, (self.qr, "a")) self.assertRaises(CircuitError, qc.h, 0.0) def test_h_reg(self): instruction_set = self.circuit.h(self.qr) self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "h") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_h_reg_inv(self): instruction_set = self.circuit.h(self.qr).inverse() self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "h") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_iden(self): self.circuit.i(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "id") self.assertEqual(self.circuit[0].operation.params, []) def test_iden_wires(self): self.circuit.i(1) self.assertEqual(self.circuit[0].operation.name, "id") self.assertEqual(self.circuit[0].operation.params, []) def test_iden_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.i, self.cr[0]) self.assertRaises(CircuitError, qc.i, self.cr) self.assertRaises(CircuitError, qc.i, (self.qr, 3)) self.assertRaises(CircuitError, qc.i, (self.qr, "a")) self.assertRaises(CircuitError, qc.i, 0.0) def test_iden_reg(self): instruction_set = self.circuit.i(self.qr) self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "id") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_iden_reg_inv(self): instruction_set = self.circuit.i(self.qr).inverse() self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "id") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_rx(self): self.circuit.rx(1, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rx") self.assertEqual(self.circuit[0].operation.params, [1]) def test_rx_wires(self): self.circuit.rx(1, 1) self.assertEqual(self.circuit[0].operation.name, "rx") self.assertEqual(self.circuit[0].operation.params, [1]) def test_rx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.rx, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.rx, self.qr[1], 0) self.assertRaises(CircuitError, qc.rx, 0, self.cr[0]) self.assertRaises(CircuitError, qc.rx, 0, 0.0) self.assertRaises(CircuitError, qc.rx, self.qr[2], self.qr[1]) self.assertRaises(CircuitError, qc.rx, 0, (self.qr, 3)) self.assertRaises(CircuitError, qc.rx, 0, self.cr) # TODO self.assertRaises(CircuitError, qc.rx, 'a', self.qr[1]) self.assertRaises(CircuitError, qc.rx, 0, "a") def test_rx_reg(self): instruction_set = self.circuit.rx(1, self.qr) self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "rx") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1]) def test_rx_reg_inv(self): instruction_set = self.circuit.rx(1, self.qr).inverse() self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "rx") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_rx_pi(self): qc = self.circuit qc.rx(pi / 2, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rx") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_ry(self): self.circuit.ry(1, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "ry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_ry_wires(self): self.circuit.ry(1, 1) self.assertEqual(self.circuit[0].operation.name, "ry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_ry_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.ry, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.ry, self.qr[1], 0) self.assertRaises(CircuitError, qc.ry, 0, self.cr[0]) self.assertRaises(CircuitError, qc.ry, 0, 0.0) self.assertRaises(CircuitError, qc.ry, self.qr[2], self.qr[1]) self.assertRaises(CircuitError, qc.ry, 0, (self.qr, 3)) self.assertRaises(CircuitError, qc.ry, 0, self.cr) # TODO self.assertRaises(CircuitError, qc.ry, 'a', self.qr[1]) self.assertRaises(CircuitError, qc.ry, 0, "a") def test_ry_reg(self): instruction_set = self.circuit.ry(1, self.qr) self.assertEqual(instruction_set[0].operation.name, "ry") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1]) def test_ry_reg_inv(self): instruction_set = self.circuit.ry(1, self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "ry") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_ry_pi(self): qc = self.circuit qc.ry(pi / 2, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "ry") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) def test_rz(self): self.circuit.rz(1, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_rz_wires(self): self.circuit.rz(1, 1) self.assertEqual(self.circuit[0].operation.name, "rz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_rz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.rz, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.rz, self.qr[1], 0) self.assertRaises(CircuitError, qc.rz, 0, self.cr[0]) self.assertRaises(CircuitError, qc.rz, 0, 0.0) self.assertRaises(CircuitError, qc.rz, self.qr[2], self.qr[1]) self.assertRaises(CircuitError, qc.rz, 0, (self.qr, 3)) self.assertRaises(CircuitError, qc.rz, 0, self.cr) # TODO self.assertRaises(CircuitError, qc.rz, 'a', self.qr[1]) self.assertRaises(CircuitError, qc.rz, 0, "a") def test_rz_reg(self): instruction_set = self.circuit.rz(1, self.qr) self.assertEqual(instruction_set[0].operation.name, "rz") self.assertEqual(instruction_set[2].operation.params, [1]) def test_rz_reg_inv(self): instruction_set = self.circuit.rz(1, self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "rz") self.assertEqual(instruction_set[2].operation.params, [-1]) def test_rz_pi(self): self.circuit.rz(pi / 2, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rz") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_rzz(self): self.circuit.rzz(1, self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "rzz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_rzz_wires(self): self.circuit.rzz(1, 1, 2) self.assertEqual(self.circuit[0].operation.name, "rzz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_rzz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.rzz, 1, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.rzz, 1, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.rzz, 1, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.rzz, 1, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.rzz, 1, self.cr, self.qr) self.assertRaises(CircuitError, qc.rzz, 1, "a", self.qr[1]) self.assertRaises(CircuitError, qc.rzz, 0.1, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.rzz, 0.1, self.qr[0], self.qr[0]) def test_s(self): self.circuit.s(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "s") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_s_wires(self): self.circuit.s(1) self.assertEqual(self.circuit[0].operation.name, "s") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_s_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.s, self.cr[0]) self.assertRaises(CircuitError, qc.s, self.cr) self.assertRaises(CircuitError, qc.s, (self.qr, 3)) self.assertRaises(CircuitError, qc.s, (self.qr, "a")) self.assertRaises(CircuitError, qc.s, 0.0) def test_s_reg(self): instruction_set = self.circuit.s(self.qr) self.assertEqual(instruction_set[0].operation.name, "s") self.assertEqual(instruction_set[2].operation.params, []) def test_s_reg_inv(self): instruction_set = self.circuit.s(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "sdg") self.assertEqual(instruction_set[2].operation.params, []) def test_sdg(self): self.circuit.sdg(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "sdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_sdg_wires(self): self.circuit.sdg(1) self.assertEqual(self.circuit[0].operation.name, "sdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_sdg_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.sdg, self.cr[0]) self.assertRaises(CircuitError, qc.sdg, self.cr) self.assertRaises(CircuitError, qc.sdg, (self.qr, 3)) self.assertRaises(CircuitError, qc.sdg, (self.qr, "a")) self.assertRaises(CircuitError, qc.sdg, 0.0) def test_sdg_reg(self): instruction_set = self.circuit.sdg(self.qr) self.assertEqual(instruction_set[0].operation.name, "sdg") self.assertEqual(instruction_set[2].operation.params, []) def test_sdg_reg_inv(self): instruction_set = self.circuit.sdg(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "s") self.assertEqual(instruction_set[2].operation.params, []) def test_swap(self): self.circuit.swap(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "swap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_swap_wires(self): self.circuit.swap(1, 2) self.assertEqual(self.circuit[0].operation.name, "swap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_swap_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.swap, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.swap, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.swap, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.swap, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.swap, self.cr, self.qr) self.assertRaises(CircuitError, qc.swap, "a", self.qr[1]) self.assertRaises(CircuitError, qc.swap, self.qr, self.qr2[[1, 2]]) self.assertRaises(CircuitError, qc.swap, self.qr[:2], self.qr2) def test_t(self): self.circuit.t(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "t") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_t_wire(self): self.circuit.t(1) self.assertEqual(self.circuit[0].operation.name, "t") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_t_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.t, self.cr[0]) self.assertRaises(CircuitError, qc.t, self.cr) self.assertRaises(CircuitError, qc.t, (self.qr, 3)) self.assertRaises(CircuitError, qc.t, (self.qr, "a")) self.assertRaises(CircuitError, qc.t, 0.0) def test_t_reg(self): instruction_set = self.circuit.t(self.qr) self.assertEqual(instruction_set[0].operation.name, "t") self.assertEqual(instruction_set[2].operation.params, []) def test_t_reg_inv(self): instruction_set = self.circuit.t(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "tdg") self.assertEqual(instruction_set[2].operation.params, []) def test_tdg(self): self.circuit.tdg(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "tdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_tdg_wires(self): self.circuit.tdg(1) self.assertEqual(self.circuit[0].operation.name, "tdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_tdg_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.tdg, self.cr[0]) self.assertRaises(CircuitError, qc.tdg, self.cr) self.assertRaises(CircuitError, qc.tdg, (self.qr, 3)) self.assertRaises(CircuitError, qc.tdg, (self.qr, "a")) self.assertRaises(CircuitError, qc.tdg, 0.0) def test_tdg_reg(self): instruction_set = self.circuit.tdg(self.qr) self.assertEqual(instruction_set[0].operation.name, "tdg") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_tdg_reg_inv(self): instruction_set = self.circuit.tdg(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "t") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_u1(self): self.circuit.append(U1Gate(1), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u1_wires(self): self.circuit.append(U1Gate(1), [1]) self.assertEqual(self.circuit[0].operation.name, "u1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u1_reg(self): instruction_set = self.circuit.append(U1Gate(1), [self.qr]) self.assertEqual(instruction_set[0].operation.name, "u1") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1]) def test_u1_reg_inv(self): instruction_set = self.circuit.append(U1Gate(1), [self.qr]).inverse() self.assertEqual(instruction_set[0].operation.name, "u1") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_u1_pi(self): qc = self.circuit qc.append(U1Gate(pi / 2), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u1") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u2(self): self.circuit.append(U2Gate(1, 2), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u2") self.assertEqual(self.circuit[0].operation.params, [1, 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u2_wires(self): self.circuit.append(U2Gate(1, 2), [1]) self.assertEqual(self.circuit[0].operation.name, "u2") self.assertEqual(self.circuit[0].operation.params, [1, 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u2_reg(self): instruction_set = self.circuit.append(U2Gate(1, 2), [self.qr]) self.assertEqual(instruction_set[0].operation.name, "u2") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1, 2]) def test_u2_reg_inv(self): instruction_set = self.circuit.append(U2Gate(1, 2), [self.qr]).inverse() self.assertEqual(instruction_set[0].operation.name, "u2") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-pi - 2, -1 + pi]) def test_u2_pi(self): self.circuit.append(U2Gate(pi / 2, 0.3 * pi), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u2") self.assertEqual(self.circuit[0].operation.params, [pi / 2, 0.3 * pi]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u3(self): self.circuit.append(U3Gate(1, 2, 3), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u3_wires(self): self.circuit.append(U3Gate(1, 2, 3), [1]) self.assertEqual(self.circuit[0].operation.name, "u3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u3_reg(self): instruction_set = self.circuit.append(U3Gate(1, 2, 3), [self.qr]) self.assertEqual(instruction_set[0].operation.name, "u3") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_u3_reg_inv(self): instruction_set = self.circuit.append(U3Gate(1, 2, 3), [self.qr]).inverse() self.assertEqual(instruction_set[0].operation.name, "u3") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_u3_pi(self): self.circuit.append(U3Gate(pi, pi / 2, 0.3 * pi), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u3") self.assertEqual(self.circuit[0].operation.params, [pi, pi / 2, 0.3 * pi]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_x(self): self.circuit.x(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "x") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_x_wires(self): self.circuit.x(1) self.assertEqual(self.circuit[0].operation.name, "x") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_x_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.x, self.cr[0]) self.assertRaises(CircuitError, qc.x, self.cr) self.assertRaises(CircuitError, qc.x, (self.qr, "a")) self.assertRaises(CircuitError, qc.x, 0.0) def test_x_reg(self): instruction_set = self.circuit.x(self.qr) self.assertEqual(instruction_set[0].operation.name, "x") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_x_reg_inv(self): instruction_set = self.circuit.x(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "x") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_y(self): self.circuit.y(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "y") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_y_wires(self): self.circuit.y(1) self.assertEqual(self.circuit[0].operation.name, "y") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_y_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.y, self.cr[0]) self.assertRaises(CircuitError, qc.y, self.cr) self.assertRaises(CircuitError, qc.y, (self.qr, "a")) self.assertRaises(CircuitError, qc.y, 0.0) def test_y_reg(self): instruction_set = self.circuit.y(self.qr) self.assertEqual(instruction_set[0].operation.name, "y") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_y_reg_inv(self): instruction_set = self.circuit.y(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "y") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_z(self): self.circuit.z(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "z") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_z_wires(self): self.circuit.z(1) self.assertEqual(self.circuit[0].operation.name, "z") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_z_reg(self): instruction_set = self.circuit.z(self.qr) self.assertEqual(instruction_set[0].operation.name, "z") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_z_reg_inv(self): instruction_set = self.circuit.z(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "z") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_global_phase(self): qc = self.circuit qc.append(GlobalPhaseGate(0.1), []) self.assertEqual(self.circuit[0].operation.name, "global_phase") self.assertEqual(self.circuit[0].operation.params, [0.1]) self.assertEqual(self.circuit[0].qubits, ()) def test_global_phase_inv(self): instruction_set = self.circuit.append(GlobalPhaseGate(0.1), []).inverse() self.assertEqual(len(instruction_set), 1) self.assertEqual(instruction_set[0].operation.params, [-0.1]) def test_global_phase_matrix(self): """Test global_phase matrix.""" theta = 0.1 np.testing.assert_allclose( np.array(GlobalPhaseGate(theta)), np.array([[np.exp(1j * theta)]], dtype=complex), atol=1e-7, ) def test_global_phase_consistency(self): """Tests compatibility of GlobalPhaseGate with QuantumCircuit.global_phase""" theta = 0.1 qc1 = QuantumCircuit(0, global_phase=theta) qc2 = QuantumCircuit(0) qc2.append(GlobalPhaseGate(theta), []) np.testing.assert_allclose( Operator(qc1), Operator(qc2), atol=1e-7, ) def test_transpile_global_phase_consistency(self): """Tests compatibility of transpiled GlobalPhaseGate with QuantumCircuit.global_phase""" qc1 = QuantumCircuit(0, global_phase=0.3) qc2 = QuantumCircuit(0, global_phase=0.2) qc2.append(GlobalPhaseGate(0.1), []) np.testing.assert_allclose( Operator(transpile(qc1, basis_gates=["u"])), Operator(transpile(qc2, basis_gates=["u"])), atol=1e-7, ) @ddt class TestStandard2Q(QiskitTestCase): """Standard Extension Test. Gates with two Qubits""" def setUp(self): super().setUp() self.qr = QuantumRegister(3, "q") self.qr2 = QuantumRegister(3, "r") self.cr = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.qr, self.qr2, self.cr) def test_barrier_reg_bit(self): self.circuit.barrier(self.qr, self.qr2[0]) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2], self.qr2[0])) def test_ch_reg_reg(self): instruction_set = self.circuit.ch(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_reg_reg_inv(self): instruction_set = self.circuit.ch(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_reg_bit(self): instruction_set = self.circuit.ch(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual( instruction_set[1].qubits, ( self.qr[1], self.qr2[1], ), ) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_reg_bit_inv(self): instruction_set = self.circuit.ch(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual( instruction_set[1].qubits, ( self.qr[1], self.qr2[1], ), ) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_bit_reg(self): instruction_set = self.circuit.ch(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_crz_reg_reg(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crz_reg_reg_inv(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crz_reg_bit(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crz_reg_bit_inv(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crz_bit_reg(self): instruction_set = self.circuit.crz(1, self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crz_bit_reg_inv(self): instruction_set = self.circuit.crz(1, self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cry_reg_reg(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cry_reg_reg_inv(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cry_reg_bit(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cry_reg_bit_inv(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cry_bit_reg(self): instruction_set = self.circuit.cry(1, self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cry_bit_reg_inv(self): instruction_set = self.circuit.cry(1, self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crx_reg_reg(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crx_reg_reg_inv(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crx_reg_bit(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crx_reg_bit_inv(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crx_bit_reg(self): instruction_set = self.circuit.crx(1, self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crx_bit_reg_inv(self): instruction_set = self.circuit.crx(1, self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu1_reg_reg(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cu1_reg_reg_inv(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu1_reg_bit(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2[1]]) self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cu1_reg_bit_inv(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2[1]]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu1_bit_reg(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr[1], self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cu1_bit_reg_inv(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr[1], self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu3_reg_reg(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_cu3_reg_reg_inv(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_cu3_reg_bit(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2[1]]) self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_cu3_reg_bit_inv(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2[1]]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_cu3_bit_reg(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_cu3_bit_reg_inv(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_cx_reg_reg(self): instruction_set = self.circuit.cx(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_reg_reg_inv(self): instruction_set = self.circuit.cx(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_reg_bit(self): instruction_set = self.circuit.cx(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_reg_bit_inv(self): instruction_set = self.circuit.cx(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_bit_reg(self): instruction_set = self.circuit.cx(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_bit_reg_inv(self): instruction_set = self.circuit.cx(self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_reg(self): instruction_set = self.circuit.cy(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_reg_inv(self): instruction_set = self.circuit.cy(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_bit(self): instruction_set = self.circuit.cy(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_bit_inv(self): instruction_set = self.circuit.cy(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_bit_reg(self): instruction_set = self.circuit.cy(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_bit_reg_inv(self): instruction_set = self.circuit.cy(self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_reg(self): instruction_set = self.circuit.cz(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_reg_inv(self): instruction_set = self.circuit.cz(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_bit(self): instruction_set = self.circuit.cz(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_bit_inv(self): instruction_set = self.circuit.cz(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_bit_reg(self): instruction_set = self.circuit.cz(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_bit_reg_inv(self): instruction_set = self.circuit.cz(self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_swap_reg_reg(self): instruction_set = self.circuit.swap(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "swap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_swap_reg_reg_inv(self): instruction_set = self.circuit.swap(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "swap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) @unpack @data( (0, 0, np.eye(4)), ( np.pi / 2, np.pi / 2, np.array( [ [np.sqrt(2) / 2, 0, 0, -np.sqrt(2) / 2], [0, 1, 0, 0], [0, 0, 1, 0], [np.sqrt(2) / 2, 0, 0, np.sqrt(2) / 2], ] ), ), ( np.pi, np.pi / 2, np.array([[0, 0, 0, -1], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]), ), ( 2 * np.pi, np.pi / 2, np.array([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]), ), ( np.pi / 2, np.pi, np.array( [ [np.sqrt(2) / 2, 0, 0, 1j * np.sqrt(2) / 2], [0, 1, 0, 0], [0, 0, 1, 0], [1j * np.sqrt(2) / 2, 0, 0, np.sqrt(2) / 2], ] ), ), (4 * np.pi, 0, np.eye(4)), ) def test_xx_minus_yy_matrix(self, theta: float, beta: float, expected: np.ndarray): """Test XX-YY matrix.""" gate = XXMinusYYGate(theta, beta) np.testing.assert_allclose(np.array(gate), expected, atol=1e-7) def test_xx_minus_yy_exponential_formula(self): """Test XX-YY exponential formula.""" theta, beta = np.random.uniform(-10, 10, size=2) gate = XXMinusYYGate(theta, beta) x = np.array(XGate()) y = np.array(YGate()) xx = np.kron(x, x) yy = np.kron(y, y) rz1 = np.kron(np.array(RZGate(beta)), np.eye(2)) np.testing.assert_allclose( np.array(gate), rz1 @ expm(-0.25j * theta * (xx - yy)) @ rz1.T.conj(), atol=1e-7, ) def test_xx_plus_yy_exponential_formula(self): """Test XX+YY exponential formula.""" theta, beta = np.random.uniform(-10, 10, size=2) gate = XXPlusYYGate(theta, beta) x = np.array(XGate()) y = np.array(YGate()) xx = np.kron(x, x) yy = np.kron(y, y) rz0 = np.kron(np.eye(2), np.array(RZGate(beta))) np.testing.assert_allclose( np.array(gate), rz0.T.conj() @ expm(-0.25j * theta * (xx + yy)) @ rz0, atol=1e-7, ) class TestStandard3Q(QiskitTestCase): """Standard Extension Test. Gates with three Qubits""" def setUp(self): super().setUp() self.qr = QuantumRegister(3, "q") self.qr2 = QuantumRegister(3, "r") self.qr3 = QuantumRegister(3, "s") self.cr = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.qr, self.qr2, self.qr3, self.cr) def test_ccx_reg_reg_reg(self): instruction_set = self.circuit.ccx(self.qr, self.qr2, self.qr3) self.assertEqual(instruction_set[0].operation.name, "ccx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_ccx_reg_reg_inv(self): instruction_set = self.circuit.ccx(self.qr, self.qr2, self.qr3).inverse() self.assertEqual(instruction_set[0].operation.name, "ccx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cswap_reg_reg_reg(self): instruction_set = self.circuit.cswap(self.qr, self.qr2, self.qr3) self.assertEqual(instruction_set[0].operation.name, "cswap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cswap_reg_reg_inv(self): instruction_set = self.circuit.cswap(self.qr, self.qr2, self.qr3).inverse() self.assertEqual(instruction_set[0].operation.name, "cswap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) class TestStandardMethods(QiskitTestCase): """Standard Extension Test.""" @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") def test_to_matrix(self): """test gates implementing to_matrix generate matrix which matches definition.""" from qiskit.circuit.library.pauli_evolution import PauliEvolutionGate from qiskit.circuit.library.generalized_gates.pauli import PauliGate from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression params = [0.1 * (i + 1) for i in range(10)] gate_class_list = Gate.__subclasses__() + ControlledGate.__subclasses__() simulator = BasicAer.get_backend("unitary_simulator") for gate_class in gate_class_list: if hasattr(gate_class, "__abstractmethods__"): # gate_class is abstract continue sig = signature(gate_class) free_params = len(set(sig.parameters) - {"label", "ctrl_state"}) try: if gate_class == PauliGate: # special case due to PauliGate using string parameters gate = gate_class("IXYZ") elif gate_class == BooleanExpression: gate = gate_class("x") elif gate_class == PauliEvolutionGate: gate = gate_class(Pauli("XYZ")) else: gate = gate_class(*params[0:free_params]) except (CircuitError, QiskitError, AttributeError, TypeError): self.log.info("Cannot init gate with params only. Skipping %s", gate_class) continue if gate.name in ["U", "CX"]: continue circ = QuantumCircuit(gate.num_qubits) circ.append(gate, range(gate.num_qubits)) try: gate_matrix = gate.to_matrix() except CircuitError: # gate doesn't implement to_matrix method: skip self.log.info('to_matrix method FAILED for "%s" gate', gate.name) continue definition_unitary = execute([circ], simulator).result().get_unitary() with self.subTest(gate_class): # TODO check for exact equality once BasicAer can handle global phase self.assertTrue(matrix_equal(definition_unitary, gate_matrix, ignore_phase=True)) self.assertTrue(is_unitary_matrix(gate_matrix)) @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") def test_to_matrix_op(self): """test gates implementing to_matrix generate matrix which matches definition using Operator.""" from qiskit.circuit.library.generalized_gates.gms import MSGate from qiskit.circuit.library.generalized_gates.pauli import PauliGate from qiskit.circuit.library.pauli_evolution import PauliEvolutionGate from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression params = [0.1 * i for i in range(1, 11)] gate_class_list = Gate.__subclasses__() + ControlledGate.__subclasses__() for gate_class in gate_class_list: if hasattr(gate_class, "__abstractmethods__"): # gate_class is abstract continue sig = signature(gate_class) if gate_class == MSGate: # due to the signature (num_qubits, theta, *, n_qubits=Noe) the signature detects # 3 arguments but really its only 2. This if can be removed once the deprecated # n_qubits argument is no longer supported. free_params = 2 else: free_params = len(set(sig.parameters) - {"label", "ctrl_state"}) try: if gate_class == PauliGate: # special case due to PauliGate using string parameters gate = gate_class("IXYZ") elif gate_class == BooleanExpression: gate = gate_class("x") elif gate_class == PauliEvolutionGate: gate = gate_class(Pauli("XYZ")) else: gate = gate_class(*params[0:free_params]) except (CircuitError, QiskitError, AttributeError, TypeError): self.log.info("Cannot init gate with params only. Skipping %s", gate_class) continue if gate.name in ["U", "CX"]: continue try: gate_matrix = gate.to_matrix() except CircuitError: # gate doesn't implement to_matrix method: skip self.log.info('to_matrix method FAILED for "%s" gate', gate.name) continue if not hasattr(gate, "definition") or not gate.definition: continue definition_unitary = Operator(gate.definition).data self.assertTrue(matrix_equal(definition_unitary, gate_matrix)) self.assertTrue(is_unitary_matrix(gate_matrix)) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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=unused-import """Test Qiskit's inverse gate operation.""" import os import tempfile import unittest from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.extensions.standard import TGate, SGate class TestCircuitQasm(QiskitTestCase): """QuantumCircuit Qasm tests.""" def test_circuit_qasm(self): """Test circuit qasm() method. """ qr = QuantumRegister(1, 'qr') cr = ClassicalRegister(1, 'cr') circuit = QuantumCircuit(qr, cr) circuit.s(qr) circuit.s(qr) circuit.append(SGate().inverse(), qr[:]) circuit.s(qr) circuit.append(TGate().inverse(), qr[:]) circuit.t(qr) circuit.measure(qr, cr) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg qr[1]; creg cr[1]; s qr[0]; s qr[0]; sdg qr[0]; s qr[0]; tdg qr[0]; t qr[0]; measure qr[0] -> cr[0];\n""" self.assertEqual(circuit.qasm(), expected_qasm) if __name__ == '__main__': unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Non-string identifiers for circuit and record identifiers test""" import unittest from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase class TestAnonymousIds(QiskitTestCase): """Test the anonymous use of registers.""" def test_create_anonymous_classical_register(self): """ClassicalRegister with no name.""" cr = ClassicalRegister(size=3) self.assertIsInstance(cr, ClassicalRegister) def test_create_anonymous_quantum_register(self): """QuantumRegister with no name.""" qr = QuantumRegister(size=3) self.assertIsInstance(qr, QuantumRegister) def test_create_anonymous_classical_registers(self): """Several ClassicalRegister with no name.""" cr1 = ClassicalRegister(size=3) cr2 = ClassicalRegister(size=3) self.assertNotEqual(cr1.name, cr2.name) def test_create_anonymous_quantum_registers(self): """Several QuantumRegister with no name.""" qr1 = QuantumRegister(size=3) qr2 = QuantumRegister(size=3) self.assertNotEqual(qr1.name, qr2.name) def test_create_anonymous_mixed_registers(self): """Several Registers with no name.""" cr0 = ClassicalRegister(size=3) qr0 = QuantumRegister(size=3) # Get the current index count of the registers cr_index = int(cr0.name[1:]) qr_index = int(qr0.name[1:]) cr1 = ClassicalRegister(size=3) _ = QuantumRegister(size=3) qr2 = QuantumRegister(size=3) # Check that the counters for each kind are incremented separately. cr_current = int(cr1.name[1:]) qr_current = int(qr2.name[1:]) self.assertEqual(cr_current, cr_index + 1) self.assertEqual(qr_current, qr_index + 2) def test_create_circuit_noname(self): """Create_circuit with no name.""" qr = QuantumRegister(size=3) cr = ClassicalRegister(size=3) qc = QuantumCircuit(qr, cr) self.assertIsInstance(qc, QuantumCircuit) class TestInvalidIds(QiskitTestCase): """Circuits and records with invalid IDs""" def test_invalid_type_circuit_name(self): """QuantumCircuit() with invalid type name.""" qr = QuantumRegister(size=3) cr = ClassicalRegister(size=3) self.assertRaises(CircuitError, QuantumCircuit, qr, cr, name=1) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Initialize test. """ import math import unittest import numpy as np from ddt import ddt, data from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit import ClassicalRegister from qiskit import transpile from qiskit import execute, assemble, BasicAer from qiskit.quantum_info import state_fidelity, Statevector, Operator from qiskit.exceptions import QiskitError from qiskit.test import QiskitTestCase from qiskit.extensions.quantum_initializer import Initialize @ddt class TestInitialize(QiskitTestCase): """Qiskit Initialize tests.""" _desired_fidelity = 0.99 def test_uniform_superposition(self): """Initialize a uniform superposition on 2 qubits.""" desired_vector = [0.5, 0.5, 0.5, 0.5] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_deterministic_state(self): """Initialize a computational-basis state |01> on 2 qubits.""" desired_vector = [0, 1, 0, 0] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_statevector(self): """Initialize gates from a statevector.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/5134 (footnote) desired_vector = [0, 0, 0, 1] qc = QuantumCircuit(2) statevector = Statevector.from_label("11") qc.initialize(statevector, [0, 1]) self.assertEqual(qc.data[0].operation.params, desired_vector) def test_bell_state(self): """Initialize a Bell state on 2 qubits.""" desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_ghz_state(self): """Initialize a GHZ state on 3 qubits.""" 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]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_initialize_register(self): """Initialize one register out of two.""" desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") qr2 = QuantumRegister(2, "qr2") qc = QuantumCircuit(qr, qr2) qc.initialize(desired_vector, qr) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, np.kron([1, 0, 0, 0], desired_vector)) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_initialize_one_by_one(self): """Initializing qubits individually into product state same as initializing the pair.""" qubit_0_state = [1, 0] qubit_1_state = [1 / math.sqrt(2), 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") qc_a = QuantumCircuit(qr) qc_a.initialize(np.kron(qubit_1_state, qubit_0_state), qr) qc_b = QuantumCircuit(qr) qc_b.initialize(qubit_0_state, [qr[0]]) qc_b.initialize(qubit_1_state, [qr[1]]) job = execute([qc_a, qc_b], BasicAer.get_backend("statevector_simulator")) result = job.result() statevector_a = result.get_statevector(0) statevector_b = result.get_statevector(1) fidelity = state_fidelity(statevector_a, statevector_b) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_single_qubit(self): """Initialize a single qubit to a weighted superposition state.""" desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3)] qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_random_3qubit(self): """Initialize to a non-trivial 3-qubit state.""" desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0, ] qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_random_4qubit(self): """Initialize to a non-trivial 4-qubit state.""" desired_vector = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0), ] qr = QuantumRegister(4, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_malformed_amplitudes(self): """Initializing to a vector with 3 amplitudes fails.""" desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3), 0] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) self.assertRaises(QiskitError, qc.initialize, desired_vector, [qr[0], qr[1]]) def test_non_unit_probability(self): """Initializing to a vector with probabilities not summing to 1 fails.""" desired_vector = [1, 1] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) self.assertRaises(QiskitError, qc.initialize, desired_vector, [qr[0], qr[1]]) def test_normalize(self): """Test initializing with a non-normalized vector is normalized, if specified.""" desired_vector = [1, 1] normalized = np.asarray(desired_vector) / np.linalg.norm(desired_vector) qc = QuantumCircuit(1) qc.initialize(desired_vector, [0], normalize=True) op = qc.data[0].operation self.assertAlmostEqual(np.linalg.norm(op.params), 1) self.assertEqual(Statevector(qc), Statevector(normalized)) def test_wrong_vector_size(self): """Initializing to a vector with a size different to the qubit parameter length. See https://github.com/Qiskit/qiskit-terra/issues/2372""" qr = QuantumRegister(2) random_state = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0), ] qc = QuantumCircuit(qr) self.assertRaises(QiskitError, qc.initialize, random_state, qr[0:2]) def test_initialize_middle_circuit(self): """Reset + initialize gives the correct statevector.""" desired_vector = [0.5, 0.5, 0.5, 0.5] qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.reset(qr[0]) qc.reset(qr[1]) qc.initialize(desired_vector, [qr[0], qr[1]]) qc.measure(qr, cr) # statevector simulator does not support reset shots = 2000 threshold = 0.005 * shots job = execute(qc, BasicAer.get_backend("qasm_simulator"), shots=shots, seed_simulator=42) result = job.result() counts = result.get_counts() target = {"00": shots / 4, "01": shots / 4, "10": shots / 4, "11": shots / 4} self.assertDictAlmostEqual(counts, target, threshold) def test_math_amplitudes(self): """Initialize to amplitudes given by math expressions""" desired_vector = [ 0, math.cos(math.pi / 3) * complex(0, 1) / math.sqrt(4), math.sin(math.pi / 3) / math.sqrt(4), 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4), 1 / math.sqrt(4) * complex(0, 1), ] qr = QuantumRegister(4, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_combiner(self): """Combining two circuits containing initialize.""" desired_vector_1 = [1.0 / math.sqrt(2), 1.0 / math.sqrt(2)] desired_vector_2 = [1.0 / math.sqrt(2), -1.0 / math.sqrt(2)] qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") qc1 = QuantumCircuit(qr, cr) qc1.initialize(desired_vector_1, [qr[0]]) qc2 = QuantumCircuit(qr, cr) qc2.initialize(desired_vector_2, [qr[0]]) job = execute(qc1.compose(qc2), BasicAer.get_backend("statevector_simulator")) result = job.result() quantum_state = result.get_statevector() fidelity = state_fidelity(quantum_state, desired_vector_2) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_equivalence(self): """Test two similar initialize instructions evaluate to equal.""" desired_vector = [0.5, 0.5, 0.5, 0.5] qr = QuantumRegister(2, "qr") qc1 = QuantumCircuit(qr, name="circuit") qc1.initialize(desired_vector, [qr[0], qr[1]]) qc2 = QuantumCircuit(qr, name="circuit") qc2.initialize(desired_vector, [qr[0], qr[1]]) self.assertEqual(qc1, qc2) def test_max_number_cnots(self): """ Check if the number of cnots <= 2^(n+1) - 2n (arXiv:quant-ph/0406176) """ num_qubits = 4 _optimization_level = 0 vector = np.array( [ 0.1314346 + 0.0j, 0.32078572 - 0.01542775j, 0.13146466 + 0.0945312j, 0.21090852 + 0.07935982j, 0.1700122 - 0.07905648j, 0.15570757 - 0.12309154j, 0.18039667 + 0.04904504j, 0.22227187 - 0.05055569j, 0.23573255 - 0.09894111j, 0.27307292 - 0.10372994j, 0.24162792 + 0.1090791j, 0.3115577 + 0.1211683j, 0.1851788 + 0.08679141j, 0.36226463 - 0.09940202j, 0.13863395 + 0.10558225j, 0.30767986 + 0.02073838j, ] ) vector = vector / np.linalg.norm(vector) qr = QuantumRegister(num_qubits, "qr") circuit = QuantumCircuit(qr) circuit.initialize(vector, qr) b = transpile( circuit, basis_gates=["u1", "u2", "u3", "cx"], optimization_level=_optimization_level, seed_transpiler=42, ) number_cnots = b.count_ops()["cx"] max_cnots = 2 ** (num_qubits + 1) - 2 * num_qubits self.assertLessEqual(number_cnots, max_cnots) def test_from_labels(self): """Initialize from labels.""" desired_sv = Statevector.from_label("01+-lr") qc = QuantumCircuit(6) qc.initialize("01+-lr", range(6)) actual_sv = Statevector.from_instruction(qc) self.assertTrue(desired_sv == actual_sv) def test_from_int(self): """Initialize from int.""" desired_sv = Statevector.from_label("110101") qc = QuantumCircuit(6) qc.initialize(53, range(6)) actual_sv = Statevector.from_instruction(qc) self.assertTrue(desired_sv == actual_sv) def _remove_resets(self, circ): circ.data = [instr for instr in circ.data if instr.operation.name != "reset"] def test_global_phase_random(self): """Test global phase preservation with random state vectors""" from qiskit.quantum_info.random import random_statevector repeats = 5 for n_qubits in [1, 2, 4]: for irep in range(repeats): with self.subTest(i=f"{n_qubits}_{irep}"): dim = 2**n_qubits qr = QuantumRegister(n_qubits) initializer = QuantumCircuit(qr) target = random_statevector(dim) initializer.initialize(target, qr) uninit = initializer.data[0].operation.definition self._remove_resets(uninit) evolve = Statevector(uninit) self.assertEqual(target, evolve) def test_global_phase_1q(self): """Test global phase preservation with some simple 1q statevectors""" target_list = [ Statevector([1j, 0]), Statevector([0, 1j]), Statevector([1j / np.sqrt(2), 1j / np.sqrt(2)]), ] n_qubits = 1 dim = 2**n_qubits qr = QuantumRegister(n_qubits) for target in target_list: with self.subTest(i=target): initializer = QuantumCircuit(qr) initializer.initialize(target, qr) # need to get rid of the resets in order to use the Operator class disentangler = Operator(initializer.data[0].operation.definition.data[1].operation) zero = Statevector.from_int(0, dim) actual = zero & disentangler self.assertEqual(target, actual) @data(2, "11", [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) def test_decompose_contains_stateprep(self, state): """Test initialize decomposes to a StatePreparation and reset""" qc = QuantumCircuit(2) qc.initialize(state) decom_circ = qc.decompose() self.assertEqual(decom_circ.data[0].operation.name, "reset") self.assertEqual(decom_circ.data[1].operation.name, "reset") self.assertEqual(decom_circ.data[2].operation.name, "state_preparation") def test_mutating_params(self): """Test mutating Initialize params correctly updates StatePreparation params""" init = Initialize("11") init.params = "00" qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.append(init, qr) decom_circ = qc.decompose() self.assertEqual(decom_circ.data[2].operation.name, "state_preparation") self.assertEqual(decom_circ.data[2].operation.params, ["0", "0"]) class TestInstructionParam(QiskitTestCase): """Test conversion of numpy type parameters.""" def test_diag(self): """Verify diagonal gate converts numpy.complex to complex.""" # ref: https://github.com/Qiskit/qiskit-aer/issues/696 diag = np.array([1 + 0j, 1 + 0j]) qc = QuantumCircuit(1) qc.diagonal(list(diag), [0]) params = qc.data[0].operation.params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) qobj = assemble(qc) params = qobj.experiments[0].instructions[0].params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) def test_init(self): """Verify initialize gate converts numpy.complex to complex.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/4151 qc = QuantumCircuit(1) vec = np.array([0, 0 + 1j]) qc.initialize(vec, 0) params = qc.data[0].operation.params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) qobj = assemble(qc) params = qobj.experiments[0].instructions[0].params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) if __name__ == "__main__": unittest.main()
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. """Test circuits with variable parameters.""" import unittest import cmath import math import copy import pickle from operator import add, mul, sub, truediv from test import combine import numpy from ddt import data, ddt, named_data import qiskit import qiskit.circuit.library as circlib from qiskit.circuit.library.standard_gates.rz import RZGate from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.circuit import Gate, Instruction, Parameter, ParameterExpression, ParameterVector from qiskit.circuit.parametertable import ParameterReferences, ParameterTable, ParameterView from qiskit.circuit.exceptions import CircuitError from qiskit.compiler import assemble, transpile from qiskit.execute_function import execute from qiskit import pulse from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeOurense from qiskit.tools import parallel_map def raise_if_parameter_table_invalid(circuit): """Validates the internal consistency of a ParameterTable and its containing QuantumCircuit. Intended for use in testing. Raises: CircuitError: if QuantumCircuit and ParameterTable are inconsistent. """ table = circuit._parameter_table # Assert parameters present in circuit match those in table. circuit_parameters = { parameter for instruction in circuit._data for param in instruction.operation.params for parameter in param.parameters if isinstance(param, ParameterExpression) } table_parameters = set(table._table.keys()) if circuit_parameters != table_parameters: raise CircuitError( "Circuit/ParameterTable Parameter mismatch. " "Circuit parameters: {}. " "Table parameters: {}.".format(circuit_parameters, table_parameters) ) # Assert parameter locations in table are present in circuit. circuit_instructions = [instr.operation for instr in circuit._data] for parameter, instr_list in table.items(): for instr, param_index in instr_list: if instr not in circuit_instructions: raise CircuitError(f"ParameterTable instruction not present in circuit: {instr}.") if not isinstance(instr.params[param_index], ParameterExpression): raise CircuitError( "ParameterTable instruction does not have a " "ParameterExpression at param_index {}: {}." "".format(param_index, instr) ) if parameter not in instr.params[param_index].parameters: raise CircuitError( "ParameterTable instruction parameters does " "not match ParameterTable key. Instruction " "parameters: {} ParameterTable key: {}." "".format(instr.params[param_index].parameters, parameter) ) # Assert circuit has no other parameter locations other than those in table. for instruction in circuit._data: for param_index, param in enumerate(instruction.operation.params): if isinstance(param, ParameterExpression): parameters = param.parameters for parameter in parameters: if (instruction.operation, param_index) not in table[parameter]: raise CircuitError( "Found parameterized instruction not " "present in table. Instruction: {} " "param_index: {}".format(instruction.operation, param_index) ) @ddt class TestParameters(QiskitTestCase): """Test Parameters.""" def test_gate(self): """Test instantiating gate with variable parameters""" theta = Parameter("ΞΈ") theta_gate = Gate("test", 1, params=[theta]) self.assertEqual(theta_gate.name, "test") self.assertIsInstance(theta_gate.params[0], Parameter) def test_compile_quantum_circuit(self): """Test instantiating gate with variable parameters""" theta = Parameter("ΞΈ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) self.assertIn(theta, qc_aer.parameters) def test_duplicate_name_on_append(self): """Test adding a second parameter object with the same name fails.""" param_a = Parameter("a") param_a_again = Parameter("a") qc = QuantumCircuit(1) qc.rx(param_a, 0) self.assertRaises(CircuitError, qc.rx, param_a_again, 0) def test_get_parameters(self): """Test instantiating gate with variable parameters""" from qiskit.circuit.library.standard_gates.rx import RXGate theta = Parameter("ΞΈ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) rxg = RXGate(theta) qc.append(rxg, [qr[0]], []) vparams = qc._parameter_table self.assertEqual(len(vparams), 1) self.assertIs(theta, next(iter(vparams))) self.assertEqual(rxg, next(iter(vparams[theta]))[0]) def test_get_parameters_by_index(self): """Test getting parameters by index""" x = Parameter("x") y = Parameter("y") z = Parameter("z") v = ParameterVector("v", 3) qc = QuantumCircuit(1) qc.rx(x, 0) qc.rz(z, 0) qc.ry(y, 0) qc.u(*v, 0) self.assertEqual(x, qc.parameters[3]) self.assertEqual(y, qc.parameters[4]) self.assertEqual(z, qc.parameters[5]) for i, vi in enumerate(v): self.assertEqual(vi, qc.parameters[i]) def test_bind_parameters_anonymously(self): """Test setting parameters by insertion order anonymously""" phase = Parameter("phase") x = Parameter("x") y = Parameter("y") z = Parameter("z") v = ParameterVector("v", 3) qc = QuantumCircuit(1, global_phase=phase) qc.rx(x, 0) qc.rz(z, 0) qc.ry(y, 0) qc.u(*v, 0) params = [0.1 * i for i in range(len(qc.parameters))] order = [phase] + v[:] + [x, y, z] param_dict = dict(zip(order, params)) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bqc_anonymous = getattr(qc, assign_fun)(params) bqc_list = getattr(qc, assign_fun)(param_dict) self.assertEqual(bqc_anonymous, bqc_list) def test_bind_parameters_allow_unknown(self): """Test binding parameters allowing unknown parameters.""" a = Parameter("a") b = Parameter("b") c = a.bind({a: 1, b: 1}, allow_unknown_parameters=True) self.assertEqual(c, a.bind({a: 1})) @data(QuantumCircuit.assign_parameters, QuantumCircuit.bind_parameters) def test_bind_parameters_custom_definition_global_phase(self, assigner): """Test that a custom gate with a parametrised `global_phase` is assigned correctly.""" x = Parameter("x") custom = QuantumCircuit(1, global_phase=x).to_gate() base = QuantumCircuit(1) base.append(custom, [0], []) test = Operator(assigner(base, {x: math.pi})) expected = Operator(numpy.array([[-1, 0], [0, -1]])) self.assertEqual(test, expected) def test_bind_half_single_precision(self): """Test binding with 16bit and 32bit floats.""" phase = Parameter("phase") x = Parameter("x") y = Parameter("y") z = Parameter("z") v = ParameterVector("v", 3) for i in (numpy.float16, numpy.float32): with self.subTest(float_type=i): expr = (v[0] * (x + y + z) + phase) - (v[2] * v[1]) params = numpy.array([0.1 * j for j in range(8)], dtype=i) order = [phase] + v[:] + [x, y, z] param_dict = dict(zip(order, params)) bound_value = expr.bind(param_dict) self.assertAlmostEqual(float(bound_value), 0.09, delta=1e-4) def test_parameter_order(self): """Test the parameters are sorted by name but parameter vector order takes precedence. This means that the following set of parameters {a, z, x[0], x[1], x[2], x[3], x[10], x[11]} will be sorted as [a, x[0], x[1], x[2], x[3], x[10], x[11], z] """ a, b, some_name, z = (Parameter(name) for name in ["a", "b", "some_name", "z"]) x = ParameterVector("x", 12) a_vector = ParameterVector("a_vector", 15) qc = QuantumCircuit(2) qc.p(z, 0) for i, x_i in enumerate(reversed(x)): qc.rx(x_i, i % 2) qc.cry(a, 0, 1) qc.crz(some_name, 1, 0) for v_i in a_vector[::2]: qc.p(v_i, 0) for v_i in a_vector[1::2]: qc.p(v_i, 1) qc.p(b, 0) expected_order = [a] + a_vector[:] + [b, some_name] + x[:] + [z] actual_order = qc.parameters self.assertListEqual(expected_order, list(actual_order)) @data(True, False) def test_parameter_order_compose(self, front): """Test the parameter order is correctly maintained upon composing circuits.""" x = Parameter("x") y = Parameter("y") qc1 = QuantumCircuit(1) qc1.p(x, 0) qc2 = QuantumCircuit(1) qc2.rz(y, 0) order = [x, y] composed = qc1.compose(qc2, front=front) self.assertListEqual(list(composed.parameters), order) def test_parameter_order_append(self): """Test the parameter order is correctly maintained upon appending circuits.""" x = Parameter("x") y = Parameter("y") qc1 = QuantumCircuit(1) qc1.p(x, 0) qc2 = QuantumCircuit(1) qc2.rz(y, 0) qc1.append(qc2, [0]) self.assertListEqual(list(qc1.parameters), [x, y]) def test_parameter_order_composing_nested_circuit(self): """Test the parameter order after nesting circuits and instructions.""" x = ParameterVector("x", 5) inner = QuantumCircuit(1) inner.rx(x[0], [0]) mid = QuantumCircuit(2) mid.p(x[1], 1) mid.append(inner, [0]) mid.p(x[2], 0) mid.append(inner, [0]) outer = QuantumCircuit(2) outer.compose(mid, inplace=True) outer.ryy(x[3], 0, 1) outer.compose(inner, inplace=True) outer.rz(x[4], 0) order = [x[0], x[1], x[2], x[3], x[4]] self.assertListEqual(list(outer.parameters), order) def test_is_parameterized(self): """Test checking if a gate is parameterized (bound/unbound)""" from qiskit.circuit.library.standard_gates.h import HGate from qiskit.circuit.library.standard_gates.rx import RXGate theta = Parameter("ΞΈ") rxg = RXGate(theta) self.assertTrue(rxg.is_parameterized()) theta_bound = theta.bind({theta: 3.14}) rxg = RXGate(theta_bound) self.assertFalse(rxg.is_parameterized()) h_gate = HGate() self.assertFalse(h_gate.is_parameterized()) def test_fix_variable(self): """Test setting a variable to a constant value""" theta = Parameter("ΞΈ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, 0, qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bqc = getattr(qc, assign_fun)({theta: 0.5}) self.assertEqual(float(bqc.data[0].operation.params[0]), 0.5) self.assertEqual(float(bqc.data[1].operation.params[1]), 0.5) bqc = getattr(qc, assign_fun)({theta: 0.6}) self.assertEqual(float(bqc.data[0].operation.params[0]), 0.6) self.assertEqual(float(bqc.data[1].operation.params[1]), 0.6) def test_multiple_parameters(self): """Test setting multiple parameters""" theta = Parameter("ΞΈ") x = Parameter("x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) self.assertEqual(qc.parameters, {theta, x}) def test_multiple_named_parameters(self): """Test setting multiple named/keyword argument based parameters""" theta = Parameter(name="ΞΈ") x = Parameter(name="x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) self.assertEqual(theta.name, "ΞΈ") self.assertEqual(qc.parameters, {theta, x}) @named_data( ["int", 2, int], ["float", 2.5, float], ["float16", numpy.float16(2.5), float], ["float32", numpy.float32(2.5), float], ["float64", numpy.float64(2.5), float], ) def test_circuit_assignment_to_numeric(self, value, type_): """Test binding a numeric value to a circuit instruction""" x = Parameter("x") qc = QuantumCircuit(1) qc.append(Instruction("inst", 1, 0, [x]), (0,)) qc.assign_parameters({x: value}, inplace=True) bound = qc.data[0].operation.params[0] self.assertIsInstance(bound, type_) self.assertEqual(bound, value) def test_partial_binding(self): """Test that binding a subset of circuit parameters returns a new parameterized circuit.""" theta = Parameter("ΞΈ") x = Parameter("x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): pqc = getattr(qc, assign_fun)({theta: 2}) self.assertEqual(pqc.parameters, {x}) self.assertEqual(float(pqc.data[0].operation.params[0]), 2) self.assertEqual(float(pqc.data[1].operation.params[1]), 2) @data(True, False) def test_mixed_binding(self, inplace): """Test we can bind a mixed dict with Parameter objects and floats.""" theta = Parameter("ΞΈ") x, new_x = Parameter("x"), Parameter("new_x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) pqc = qc.assign_parameters({theta: 2, x: new_x}, inplace=inplace) if inplace: self.assertEqual(qc.parameters, {new_x}) else: self.assertEqual(pqc.parameters, {new_x}) def test_expression_partial_binding(self): """Test that binding a subset of expression parameters returns a new parameterized circuit.""" theta = Parameter("ΞΈ") phi = Parameter("phi") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta + phi, qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): pqc = getattr(qc, assign_fun)({theta: 2}) self.assertEqual(pqc.parameters, {phi}) self.assertTrue(isinstance(pqc.data[0].operation.params[0], ParameterExpression)) self.assertEqual(str(pqc.data[0].operation.params[0]), "phi + 2") fbqc = getattr(pqc, assign_fun)({phi: 1.0}) self.assertEqual(fbqc.parameters, set()) self.assertIsInstance(fbqc.data[0].operation.params[0], float) self.assertEqual(float(fbqc.data[0].operation.params[0]), 3) def test_two_parameter_expression_binding(self): """Verify that for a circuit with parameters theta and phi that we can correctly assign theta to -phi. """ theta = Parameter("theta") phi = Parameter("phi") qc = QuantumCircuit(1) qc.rx(theta, 0) qc.ry(phi, 0) self.assertEqual(len(qc._parameter_table[theta]), 1) self.assertEqual(len(qc._parameter_table[phi]), 1) qc.assign_parameters({theta: -phi}, inplace=True) self.assertEqual(len(qc._parameter_table[phi]), 2) def test_expression_partial_binding_zero(self): """Verify that binding remains possible even if a previous partial bind would reduce the expression to zero. """ theta = Parameter("theta") phi = Parameter("phi") qc = QuantumCircuit(1) qc.p(theta * phi, 0) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): pqc = getattr(qc, assign_fun)({theta: 0}) self.assertEqual(pqc.parameters, {phi}) self.assertTrue(isinstance(pqc.data[0].operation.params[0], ParameterExpression)) self.assertEqual(str(pqc.data[0].operation.params[0]), "0") fbqc = getattr(pqc, assign_fun)({phi: 1}) self.assertEqual(fbqc.parameters, set()) self.assertIsInstance(fbqc.data[0].operation.params[0], int) self.assertEqual(float(fbqc.data[0].operation.params[0]), 0) def test_raise_if_assigning_params_not_in_circuit(self): """Verify binding parameters which are not present in the circuit raises an error.""" x = Parameter("x") y = Parameter("y") z = ParameterVector("z", 3) qr = QuantumRegister(1) qc = QuantumCircuit(qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: qc = QuantumCircuit(qr) with self.subTest(assign_fun=assign_fun): qc.p(0.1, qr[0]) self.assertRaises(CircuitError, getattr(qc, assign_fun), {x: 1}) qc.p(x, qr[0]) self.assertRaises(CircuitError, getattr(qc, assign_fun), {x: 1, y: 2}) qc.p(z[1], qr[0]) self.assertRaises(CircuitError, getattr(qc, assign_fun), {z: [3, 4, 5]}) self.assertRaises(CircuitError, getattr(qc, assign_fun), {"a_str": 6}) self.assertRaises(CircuitError, getattr(qc, assign_fun), {None: 7}) def test_gate_multiplicity_binding(self): """Test binding when circuit contains multiple references to same gate""" qc = QuantumCircuit(1) theta = Parameter("theta") gate = RZGate(theta) qc.append(gate, [0], []) qc.append(gate, [0], []) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): qc2 = getattr(qc, assign_fun)({theta: 1.0}) self.assertEqual(len(qc2._parameter_table), 0) for instruction in qc2.data: self.assertEqual(float(instruction.operation.params[0]), 1.0) def test_calibration_assignment(self): """That that calibration mapping and the schedules they map are assigned together.""" theta = Parameter("theta") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [theta]), [0]) circ.measure(0, 0) rxt_q0 = pulse.Schedule( pulse.Play( pulse.library.Gaussian(duration=128, sigma=16, amp=0.2 * theta / 3.14), pulse.DriveChannel(0), ) ) circ.add_calibration("rxt", [0], rxt_q0, [theta]) circ = circ.assign_parameters({theta: 3.14}) instruction = circ.data[0] cal_key = ( tuple(circ.find_bit(q).index for q in instruction.qubits), tuple(instruction.operation.params), ) self.assertEqual(cal_key, ((0,), (3.14,))) # Make sure that key from instruction data matches the calibrations dictionary self.assertIn(cal_key, circ.calibrations["rxt"]) sched = circ.calibrations["rxt"][cal_key] self.assertEqual(sched.instructions[0][1].pulse.amp, 0.2) def test_calibration_assignment_doesnt_mutate(self): """That that assignment doesn't mutate the original circuit.""" theta = Parameter("theta") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [theta]), [0]) circ.measure(0, 0) rxt_q0 = pulse.Schedule( pulse.Play( pulse.library.Gaussian(duration=128, sigma=16, amp=0.2 * theta / 3.14), pulse.DriveChannel(0), ) ) circ.add_calibration("rxt", [0], rxt_q0, [theta]) circ_copy = copy.deepcopy(circ) assigned_circ = circ.assign_parameters({theta: 3.14}) self.assertEqual(circ.calibrations, circ_copy.calibrations) self.assertNotEqual(assigned_circ.calibrations, circ.calibrations) def test_calibration_assignment_w_expressions(self): """That calibrations with multiple parameters are assigned correctly""" theta = Parameter("theta") sigma = Parameter("sigma") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [theta / 2, sigma]), [0]) circ.measure(0, 0) rxt_q0 = pulse.Schedule( pulse.Play( pulse.library.Gaussian(duration=128, sigma=4 * sigma, amp=0.2 * theta / 3.14), pulse.DriveChannel(0), ) ) circ.add_calibration("rxt", [0], rxt_q0, [theta / 2, sigma]) circ = circ.assign_parameters({theta: 3.14, sigma: 4}) instruction = circ.data[0] cal_key = ( tuple(circ.find_bit(q).index for q in instruction.qubits), tuple(instruction.operation.params), ) self.assertEqual(cal_key, ((0,), (3.14 / 2, 4))) # Make sure that key from instruction data matches the calibrations dictionary self.assertIn(cal_key, circ.calibrations["rxt"]) sched = circ.calibrations["rxt"][cal_key] self.assertEqual(sched.instructions[0][1].pulse.amp, 0.2) self.assertEqual(sched.instructions[0][1].pulse.sigma, 16) def test_substitution(self): """Test Parameter substitution (vs bind).""" alpha = Parameter("⍺") beta = Parameter("beta") schedule = pulse.Schedule(pulse.ShiftPhase(alpha, pulse.DriveChannel(0))) circ = QuantumCircuit(3, 3) circ.append(Gate("my_rz", 1, [alpha]), [0]) circ.add_calibration("my_rz", [0], schedule, [alpha]) circ = circ.assign_parameters({alpha: 2 * beta}) circ = circ.assign_parameters({beta: 1.57}) cal_sched = circ.calibrations["my_rz"][((0,), (3.14,))] self.assertEqual(float(cal_sched.instructions[0][1].phase), 3.14) def test_partial_assignment(self): """Expressions of parameters with partial assignment.""" alpha = Parameter("⍺") beta = Parameter("beta") gamma = Parameter("Ξ³") phi = Parameter("Ο•") with pulse.build() as my_cal: pulse.set_frequency(alpha + beta, pulse.DriveChannel(0)) pulse.shift_frequency(gamma + beta, pulse.DriveChannel(0)) pulse.set_phase(phi, pulse.DriveChannel(1)) circ = QuantumCircuit(2, 2) circ.append(Gate("custom", 2, [alpha, beta, gamma, phi]), [0, 1]) circ.add_calibration("custom", [0, 1], my_cal, [alpha, beta, gamma, phi]) # Partial bind delta = 1e9 freq = 4.5e9 shift = 0.5e9 phase = 3.14 / 4 circ = circ.assign_parameters({alpha: freq - delta}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(cal_sched.instructions[0][1].frequency, freq - delta + beta) circ = circ.assign_parameters({beta: delta}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(float(cal_sched.instructions[0][1].frequency), freq) self.assertEqual(cal_sched.instructions[1][1].frequency, gamma + delta) circ = circ.assign_parameters({gamma: shift - delta}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(float(cal_sched.instructions[1][1].frequency), shift) self.assertEqual(cal_sched.instructions[2][1].phase, phi) circ = circ.assign_parameters({phi: phase}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(float(cal_sched.instructions[2][1].phase), phase) def test_circuit_generation(self): """Test creating a series of circuits parametrically""" theta = Parameter("ΞΈ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) # generate list of circuits for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): circs = [] theta_list = numpy.linspace(0, numpy.pi, 20) for theta_i in theta_list: circs.append(getattr(qc_aer, assign_fun)({theta: theta_i})) qobj = assemble(circs) for index, theta_i in enumerate(theta_list): res = float(qobj.experiments[index].instructions[0].params[0]) self.assertTrue(math.isclose(res, theta_i), f"{res} != {theta_i}") def test_circuit_composition(self): """Test preservation of parameters when combining circuits.""" theta = Parameter("ΞΈ") qr = QuantumRegister(1) cr = ClassicalRegister(1) qc1 = QuantumCircuit(qr, cr) qc1.rx(theta, qr) phi = Parameter("phi") qc2 = QuantumCircuit(qr, cr) qc2.ry(phi, qr) qc2.h(qr) qc2.measure(qr, cr) qc3 = qc1.compose(qc2) self.assertEqual(qc3.parameters, {theta, phi}) def test_composite_instruction(self): """Test preservation of parameters via parameterized instructions.""" theta = Parameter("ΞΈ") qr1 = QuantumRegister(1, name="qr1") qc1 = QuantumCircuit(qr1) qc1.rx(theta, qr1) qc1.rz(numpy.pi / 2, qr1) qc1.ry(theta, qr1) gate = qc1.to_instruction() self.assertEqual(gate.params, [theta]) phi = Parameter("phi") qr2 = QuantumRegister(3, name="qr2") qc2 = QuantumCircuit(qr2) qc2.ry(phi, qr2[0]) qc2.h(qr2) qc2.append(gate, qargs=[qr2[1]]) self.assertEqual(qc2.parameters, {theta, phi}) def test_parameter_name_conflicts_raises(self): """Verify attempting to add different parameters with matching names raises an error.""" theta1 = Parameter("theta") theta2 = Parameter("theta") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.p(theta1, 0) self.assertRaises(CircuitError, qc.p, theta2, 0) def test_bind_ryrz_vector(self): """Test binding a list of floats to a ParameterVector""" qc = QuantumCircuit(4) depth = 4 theta = ParameterVector("ΞΈ", length=len(qc.qubits) * depth * 2) theta_iter = iter(theta) for _ in range(depth): for q in qc.qubits: qc.ry(next(theta_iter), q) qc.rz(next(theta_iter), q) for i, q in enumerate(qc.qubits[:-1]): qc.cx(qc.qubits[i], qc.qubits[i + 1]) qc.barrier() theta_vals = numpy.linspace(0, 1, len(theta)) * numpy.pi self.assertEqual(set(qc.parameters), set(theta.params)) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bqc = getattr(qc, assign_fun)({theta: theta_vals}) for instruction in bqc.data: if hasattr(instruction.operation, "params") and instruction.operation.params: self.assertIn(float(instruction.operation.params[0]), theta_vals) def test_compile_vector(self): """Test compiling a circuit with an unbound ParameterVector""" qc = QuantumCircuit(4) depth = 4 theta = ParameterVector("ΞΈ", length=len(qc.qubits) * depth * 2) theta_iter = iter(theta) for _ in range(depth): for q in qc.qubits: qc.ry(next(theta_iter), q) qc.rz(next(theta_iter), q) for i, q in enumerate(qc.qubits[:-1]): qc.cx(qc.qubits[i], qc.qubits[i + 1]) qc.barrier() backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) for param in theta: self.assertIn(param, qc_aer.parameters) def test_instruction_ryrz_vector(self): """Test constructing a circuit from instructions with remapped ParameterVectors""" qubits = 5 depth = 4 ryrz = QuantumCircuit(qubits, name="ryrz") theta = ParameterVector("ΞΈ0", length=len(ryrz.qubits) * 2) theta_iter = iter(theta) for q in ryrz.qubits: ryrz.ry(next(theta_iter), q) ryrz.rz(next(theta_iter), q) cxs = QuantumCircuit(qubits - 1, name="cxs") for i, _ in enumerate(cxs.qubits[:-1:2]): cxs.cx(cxs.qubits[2 * i], cxs.qubits[2 * i + 1]) paramvecs = [] qc = QuantumCircuit(qubits) for i in range(depth): theta_l = ParameterVector(f"ΞΈ{i + 1}", length=len(ryrz.qubits) * 2) ryrz_inst = ryrz.to_instruction(parameter_map={theta: theta_l}) paramvecs += [theta_l] qc.append(ryrz_inst, qargs=qc.qubits) qc.append(cxs, qargs=qc.qubits[1:]) qc.append(cxs, qargs=qc.qubits[:-1]) qc.barrier() backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) for vec in paramvecs: for param in vec: self.assertIn(param, qc_aer.parameters) @data("single", "vector") def test_parameter_equality_through_serialization(self, ptype): """Verify parameters maintain their equality after serialization.""" if ptype == "single": x1 = Parameter("x") x2 = Parameter("x") else: x1 = ParameterVector("x", 2)[0] x2 = ParameterVector("x", 2)[0] x1_p = pickle.loads(pickle.dumps(x1)) x2_p = pickle.loads(pickle.dumps(x2)) self.assertEqual(x1, x1_p) self.assertEqual(x2, x2_p) self.assertNotEqual(x1, x2_p) self.assertNotEqual(x2, x1_p) def test_binding_parameterized_circuits_built_in_multiproc(self): """Verify subcircuits built in a subprocess can still be bound.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2429 num_processes = 4 qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) parameters = [Parameter(f"x{i}") for i in range(num_processes)] results = parallel_map( _construct_circuit, parameters, task_args=(qr,), num_processes=num_processes ) for qc in results: circuit.compose(qc, inplace=True) parameter_values = [{x: 1.0 for x in parameters}] qobj = assemble( circuit, backend=BasicAer.get_backend("qasm_simulator"), parameter_binds=parameter_values, ) self.assertEqual(len(qobj.experiments), 1) self.assertEqual(len(qobj.experiments[0].instructions), 4) self.assertTrue( all( len(inst.params) == 1 and isinstance(inst.params[0], float) and float(inst.params[0]) == 1 for inst in qobj.experiments[0].instructions ) ) def test_transpiling_multiple_parameterized_circuits(self): """Verify several parameterized circuits can be transpiled at once.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2864 qr = QuantumRegister(1) qc1 = QuantumCircuit(qr) qc2 = QuantumCircuit(qr) theta = Parameter("theta") qc1.u(theta, 0, 0, qr[0]) qc2.u(theta, 3.14, 0, qr[0]) circuits = [qc1, qc2] job = execute( circuits, BasicAer.get_backend("unitary_simulator"), shots=512, parameter_binds=[{theta: 1}], ) self.assertTrue(len(job.result().results), 2) @data(0, 1, 2, 3) def test_transpile_across_optimization_levels(self, opt_level): """Verify parameterized circuits can be transpiled with all default pass managers.""" qc = QuantumCircuit(5, 5) theta = Parameter("theta") phi = Parameter("phi") qc.rx(theta, 0) qc.x(0) for i in range(5 - 1): qc.rxx(phi, i, i + 1) qc.measure(range(5 - 1), range(5 - 1)) transpile(qc, FakeOurense(), optimization_level=opt_level) def test_repeated_gates_to_dag_and_back(self): """Verify circuits with repeated parameterized gates can be converted to DAG and back, maintaining consistency of circuit._parameter_table.""" from qiskit.converters import circuit_to_dag, dag_to_circuit qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") qc.p(theta, qr[0]) double_qc = qc.compose(qc) test_qc = dag_to_circuit(circuit_to_dag(double_qc)) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bound_test_qc = getattr(test_qc, assign_fun)({theta: 1}) self.assertEqual(len(bound_test_qc.parameters), 0) def test_rebinding_instruction_copy(self): """Test rebinding a copied instruction does not modify the original.""" theta = Parameter("th") qc = QuantumCircuit(1) qc.rx(theta, 0) instr = qc.to_instruction() qc1 = QuantumCircuit(1) qc1.append(instr, [0]) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): output1 = getattr(qc1, assign_fun)({theta: 0.1}).decompose() output2 = getattr(qc1, assign_fun)({theta: 0.2}).decompose() expected1 = QuantumCircuit(1) expected1.rx(0.1, 0) expected2 = QuantumCircuit(1) expected2.rx(0.2, 0) self.assertEqual(expected1, output1) self.assertEqual(expected2, output2) @combine(target_type=["gate", "instruction"], parameter_type=["numbers", "parameters"]) def test_decompose_propagates_bound_parameters(self, target_type, parameter_type): """Verify bind-before-decompose preserves bound values.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2482 theta = Parameter("th") qc = QuantumCircuit(1) qc.rx(theta, 0) if target_type == "gate": inst = qc.to_gate() elif target_type == "instruction": inst = qc.to_instruction() qc2 = QuantumCircuit(1) qc2.append(inst, [0]) if parameter_type == "numbers": bound_qc2 = qc2.assign_parameters({theta: 0.5}) expected_parameters = set() expected_qc2 = QuantumCircuit(1) expected_qc2.rx(0.5, 0) else: phi = Parameter("ph") bound_qc2 = qc2.assign_parameters({theta: phi}) expected_parameters = {phi} expected_qc2 = QuantumCircuit(1) expected_qc2.rx(phi, 0) decomposed_qc2 = bound_qc2.decompose() with self.subTest(msg="testing parameters of initial circuit"): self.assertEqual(qc2.parameters, {theta}) with self.subTest(msg="testing parameters of bound circuit"): self.assertEqual(bound_qc2.parameters, expected_parameters) with self.subTest(msg="testing parameters of deep decomposed bound circuit"): self.assertEqual(decomposed_qc2.parameters, expected_parameters) with self.subTest(msg="testing deep decomposed circuit"): self.assertEqual(decomposed_qc2, expected_qc2) @combine(target_type=["gate", "instruction"], parameter_type=["numbers", "parameters"]) def test_decompose_propagates_deeply_bound_parameters(self, target_type, parameter_type): """Verify bind-before-decompose preserves deeply bound values.""" theta = Parameter("th") qc1 = QuantumCircuit(1) qc1.rx(theta, 0) if target_type == "gate": inst = qc1.to_gate() elif target_type == "instruction": inst = qc1.to_instruction() qc2 = QuantumCircuit(1) qc2.append(inst, [0]) if target_type == "gate": inst = qc2.to_gate() elif target_type == "instruction": inst = qc2.to_instruction() qc3 = QuantumCircuit(1) qc3.append(inst, [0]) if parameter_type == "numbers": bound_qc3 = qc3.assign_parameters({theta: 0.5}) expected_parameters = set() expected_qc3 = QuantumCircuit(1) expected_qc3.rx(0.5, 0) else: phi = Parameter("ph") bound_qc3 = qc3.assign_parameters({theta: phi}) expected_parameters = {phi} expected_qc3 = QuantumCircuit(1) expected_qc3.rx(phi, 0) deep_decomposed_qc3 = bound_qc3.decompose().decompose() with self.subTest(msg="testing parameters of initial circuit"): self.assertEqual(qc3.parameters, {theta}) with self.subTest(msg="testing parameters of bound circuit"): self.assertEqual(bound_qc3.parameters, expected_parameters) with self.subTest(msg="testing parameters of deep decomposed bound circuit"): self.assertEqual(deep_decomposed_qc3.parameters, expected_parameters) with self.subTest(msg="testing deep decomposed circuit"): self.assertEqual(deep_decomposed_qc3, expected_qc3) @data("gate", "instruction") def test_executing_parameterized_instruction_bound_early(self, target_type): """Verify bind-before-execute preserves bound values.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2482 theta = Parameter("theta") sub_qc = QuantumCircuit(2) sub_qc.h(0) sub_qc.cx(0, 1) sub_qc.rz(theta, [0, 1]) sub_qc.cx(0, 1) sub_qc.h(0) if target_type == "gate": sub_inst = sub_qc.to_gate() elif target_type == "instruction": sub_inst = sub_qc.to_instruction() unbound_qc = QuantumCircuit(2, 1) unbound_qc.append(sub_inst, [0, 1], []) unbound_qc.measure(0, 0) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bound_qc = getattr(unbound_qc, assign_fun)({theta: numpy.pi / 2}) shots = 1024 job = execute(bound_qc, backend=BasicAer.get_backend("qasm_simulator"), shots=shots) self.assertDictAlmostEqual(job.result().get_counts(), {"1": shots}, 0.05 * shots) def test_num_parameters(self): """Test the num_parameters property.""" with self.subTest(msg="standard case"): theta = Parameter("ΞΈ") x = Parameter("x") qc = QuantumCircuit(1) qc.rx(theta, 0) qc.u(0, theta, x, 0) self.assertEqual(qc.num_parameters, 2) with self.subTest(msg="parameter vector"): params = ParameterVector("x", length=3) qc = QuantumCircuit(4) qc.rx(params[0], 2) qc.ry(params[1], 1) qc.rz(params[2], 3) self.assertEqual(qc.num_parameters, 3) with self.subTest(msg="no params"): qc = QuantumCircuit(1) qc.x(0) self.assertEqual(qc.num_parameters, 0) def test_execute_result_names(self): """Test unique names for list of parameter binds.""" theta = Parameter("ΞΈ") reps = 5 qc = QuantumCircuit(1, 1) qc.rx(theta, 0) qc.measure(0, 0) plist = [{theta: i} for i in range(reps)] simulator = BasicAer.get_backend("qasm_simulator") result = execute(qc, backend=simulator, parameter_binds=plist).result() result_names = {res.name for res in result.results} self.assertEqual(reps, len(result_names)) def test_to_instruction_after_inverse(self): """Verify converting an inverse generates a valid ParameterTable""" # ref: https://github.com/Qiskit/qiskit-terra/issues/4235 qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) inv_instr = qc.inverse().to_instruction() self.assertIsInstance(inv_instr, Instruction) def test_repeated_circuit(self): """Test repeating a circuit maintains the parameters.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) rep = qc.repeat(3) self.assertEqual(rep.parameters, {theta}) def test_copy_after_inverse(self): """Verify circuit.inverse generates a valid ParameterTable.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) inverse = qc.inverse() self.assertIn(theta, inverse.parameters) raise_if_parameter_table_invalid(inverse) def test_copy_after_reverse(self): """Verify circuit.reverse generates a valid ParameterTable.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) reverse = qc.reverse_ops() self.assertIn(theta, reverse.parameters) raise_if_parameter_table_invalid(reverse) def test_copy_after_dot_data_setter(self): """Verify setting circuit.data generates a valid ParameterTable.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) qc.data = [] self.assertEqual(qc.parameters, set()) raise_if_parameter_table_invalid(qc) def test_circuit_with_ufunc(self): """Test construction of circuit and binding of parameters after we apply universal functions.""" from math import pi phi = Parameter(name="phi") theta = Parameter(name="theta") qc = QuantumCircuit(2) qc.p(numpy.abs(-phi), 0) qc.p(numpy.cos(phi), 0) qc.p(numpy.sin(phi), 0) qc.p(numpy.tan(phi), 0) qc.rz(numpy.arccos(theta), 1) qc.rz(numpy.arctan(theta), 1) qc.rz(numpy.arcsin(theta), 1) qc.assign_parameters({phi: pi, theta: 1}, inplace=True) qc_ref = QuantumCircuit(2) qc_ref.p(pi, 0) qc_ref.p(-1, 0) qc_ref.p(0, 0) qc_ref.p(0, 0) qc_ref.rz(0, 1) qc_ref.rz(pi / 4, 1) qc_ref.rz(pi / 2, 1) self.assertEqual(qc, qc_ref) def test_compile_with_ufunc(self): """Test compiling of circuit with unbound parameters after we apply universal functions.""" from math import pi theta = ParameterVector("theta", length=7) qc = QuantumCircuit(7) qc.rx(numpy.abs(theta[0]), 0) qc.rx(numpy.cos(theta[1]), 1) qc.rx(numpy.sin(theta[2]), 2) qc.rx(numpy.tan(theta[3]), 3) qc.rx(numpy.arccos(theta[4]), 4) qc.rx(numpy.arctan(theta[5]), 5) qc.rx(numpy.arcsin(theta[6]), 6) # transpile to different basis transpiled = transpile(qc, basis_gates=["rz", "sx", "x", "cx"], optimization_level=0) for x in theta: self.assertIn(x, transpiled.parameters) bound = transpiled.bind_parameters({theta: [-1, pi, pi, pi, 1, 1, 1]}) expected = QuantumCircuit(7) expected.rx(1.0, 0) expected.rx(-1.0, 1) expected.rx(0.0, 2) expected.rx(0.0, 3) expected.rx(0.0, 4) expected.rx(pi / 4, 5) expected.rx(pi / 2, 6) expected = transpile(expected, basis_gates=["rz", "sx", "x", "cx"], optimization_level=0) self.assertEqual(expected, bound) def test_parametervector_resize(self): """Test the resize method of the parameter vector.""" vec = ParameterVector("x", 2) element = vec[1] # store an entry for instancecheck later on with self.subTest("shorten"): vec.resize(1) self.assertEqual(len(vec), 1) self.assertListEqual([param.name for param in vec], _paramvec_names("x", 1)) with self.subTest("enlargen"): vec.resize(3) self.assertEqual(len(vec), 3) # ensure we still have the same instance not a copy with the same name # this is crucial for adding parameters to circuits since we cannot use the same # name if the instance is not the same self.assertIs(element, vec[1]) self.assertListEqual([param.name for param in vec], _paramvec_names("x", 3)) def test_raise_if_sub_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") with self.assertRaisesRegex(CircuitError, "not present"): x.subs({y: z}) def test_sub_allow_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") subbed = x.subs({y: z}, allow_unknown_parameters=True) self.assertEqual(subbed, x) def _construct_circuit(param, qr): qc = QuantumCircuit(qr) qc.ry(param, qr[0]) return qc def _paramvec_names(prefix, length): return [f"{prefix}[{i}]" for i in range(length)] @ddt class TestParameterExpressions(QiskitTestCase): """Test expressions of Parameters.""" supported_operations = [add, sub, mul, truediv] def test_compare_to_value_when_bound(self): """Verify expression can be compared to a fixed value when fully bound.""" x = Parameter("x") bound_expr = x.bind({x: 2.3}) self.assertEqual(bound_expr, 2.3) def test_abs_function_when_bound(self): """Verify expression can be used with abs functions when bound.""" x = Parameter("x") xb_1 = x.bind({x: 2.0}) xb_2 = x.bind({x: 3.0 + 4.0j}) self.assertEqual(abs(xb_1), 2.0) self.assertEqual(abs(-xb_1), 2.0) self.assertEqual(abs(xb_2), 5.0) def test_abs_function_when_not_bound(self): """Verify expression can be used with abs functions when not bound.""" x = Parameter("x") y = Parameter("y") self.assertEqual(abs(x), abs(-x)) self.assertEqual(abs(x) * abs(y), abs(x * y)) self.assertEqual(abs(x) / abs(y), abs(x / y)) def test_cast_to_complex_when_bound(self): """Verify that the cast to complex works for bound objects.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 1.0, y: 1j}) self.assertEqual(complex(bound_expr), 1 + 1j) def test_raise_if_cast_to_complex_when_not_fully_bound(self): """Verify raises if casting to complex and not fully bound.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 1j}) with self.assertRaisesRegex(TypeError, "unbound parameters"): complex(bound_expr) def test_cast_to_float_when_bound(self): """Verify expression can be cast to a float when fully bound.""" x = Parameter("x") bound_expr = x.bind({x: 2.3}) self.assertEqual(float(bound_expr), 2.3) def test_cast_to_float_when_underlying_expression_bound(self): """Verify expression can be cast to a float when it still contains unbound parameters, but the underlying symbolic expression has a knowable value.""" x = Parameter("x") expr = x - x + 2.3 self.assertEqual(float(expr), 2.3) def test_cast_to_float_intermediate_complex_value(self): """Verify expression can be cast to a float when it is fully bound, but an intermediate part of the expression evaluation involved complex types. Sympy is generally more permissive than symengine here, and sympy's tends to be the expected behaviour for our users.""" x = Parameter("x") bound_expr = (x + 1.0 + 1.0j).bind({x: -1.0j}) self.assertEqual(float(bound_expr), 1.0) def test_cast_to_float_of_complex_fails(self): """Test that an attempt to produce a float from a complex value fails if there is an imaginary part, with a sensible error message.""" x = Parameter("x") bound_expr = (x + 1.0j).bind({x: 1.0}) with self.assertRaisesRegex(TypeError, "could not cast expression to float"): float(bound_expr) def test_raise_if_cast_to_float_when_not_fully_bound(self): """Verify raises if casting to float and not fully bound.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 2.3}) with self.assertRaisesRegex(TypeError, "unbound parameters"): float(bound_expr) def test_cast_to_int_when_bound(self): """Verify expression can be cast to an int when fully bound.""" x = Parameter("x") bound_expr = x.bind({x: 2.3}) self.assertEqual(int(bound_expr), 2) def test_cast_to_int_when_bound_truncates_after_evaluation(self): """Verify expression can be cast to an int when fully bound, but truncated only after evaluation.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 2.3, y: 0.8}) self.assertEqual(int(bound_expr), 3) def test_cast_to_int_when_underlying_expression_bound(self): """Verify expression can be cast to a int when it still contains unbound parameters, but the underlying symbolic expression has a knowable value.""" x = Parameter("x") expr = x - x + 2.3 self.assertEqual(int(expr), 2) def test_raise_if_cast_to_int_when_not_fully_bound(self): """Verify raises if casting to int and not fully bound.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 2.3}) with self.assertRaisesRegex(TypeError, "unbound parameters"): int(bound_expr) def test_raise_if_sub_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") expr = x + 2 y = Parameter("y") z = Parameter("z") with self.assertRaisesRegex(CircuitError, "not present"): expr.subs({y: z}) def test_sub_allow_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") expr = x + 2 y = Parameter("y") z = Parameter("z") subbed = expr.subs({y: z}, allow_unknown_parameters=True) self.assertEqual(subbed, expr) def test_raise_if_subbing_in_parameter_name_conflict(self): """Verify we raise if substituting in conflicting parameter names.""" x = Parameter("x") y_first = Parameter("y") expr = x + y_first y_second = Parameter("y") # Replacing an existing name is okay. expr.subs({y_first: y_second}) with self.assertRaisesRegex(CircuitError, "Name conflict"): expr.subs({x: y_second}) def test_expressions_of_parameter_with_constant(self): """Verify operating on a Parameter with a constant.""" good_constants = [2, 1.3, 0, -1, -1.0, numpy.pi, 1j] x = Parameter("x") for op in self.supported_operations: for const in good_constants: expr = op(const, x) bound_expr = expr.bind({x: 2.3}) self.assertEqual(complex(bound_expr), op(const, 2.3)) # Division by zero will raise. Tested elsewhere. if const == 0 and op == truediv: continue # Repeat above, swapping position of Parameter and constant. expr = op(x, const) bound_expr = expr.bind({x: 2.3}) res = complex(bound_expr) expected = op(2.3, const) self.assertTrue(cmath.isclose(res, expected), f"{res} != {expected}") def test_complex_parameter_bound_to_real(self): """Test a complex parameter expression can be real if bound correctly.""" x, y = Parameter("x"), Parameter("y") with self.subTest("simple 1j * x"): qc = QuantumCircuit(1) qc.rx(1j * x, 0) bound = qc.bind_parameters({x: 1j}) ref = QuantumCircuit(1) ref.rx(-1, 0) self.assertEqual(bound, ref) with self.subTest("more complex expression"): qc = QuantumCircuit(1) qc.rx(0.5j * x - y * y + 2 * y, 0) bound = qc.bind_parameters({x: -4, y: 1j}) ref = QuantumCircuit(1) ref.rx(1, 0) self.assertEqual(bound, ref) def test_complex_angle_raises_when_not_supported(self): """Test parameters are validated when fully bound and errors are raised accordingly.""" x = Parameter("x") qc = QuantumCircuit(1) qc.r(x, 1j * x, 0) with self.subTest("binding x to 0 yields real parameters"): bound = qc.bind_parameters({x: 0}) ref = QuantumCircuit(1) ref.r(0, 0, 0) self.assertEqual(bound, ref) with self.subTest("binding x to 1 yields complex parameters"): # RGate does not support complex parameters with self.assertRaises(CircuitError): bound = qc.bind_parameters({x: 1}) def test_operating_on_a_parameter_with_a_non_float_will_raise(self): """Verify operations between a Parameter and a non-float will raise.""" bad_constants = ["1", numpy.Inf, numpy.NaN, None, {}, []] x = Parameter("x") for op in self.supported_operations: for const in bad_constants: with self.subTest(op=op, const=const): with self.assertRaises(TypeError): _ = op(const, x) with self.assertRaises(TypeError): _ = op(x, const) def test_expressions_division_by_zero(self): """Verify dividing a Parameter by 0, or binding 0 as a denominator raises.""" x = Parameter("x") with self.assertRaises(ZeroDivisionError): _ = x / 0 with self.assertRaises(ZeroDivisionError): _ = x / 0.0 expr = 2 / x with self.assertRaises(ZeroDivisionError): _ = expr.bind({x: 0}) with self.assertRaises(ZeroDivisionError): _ = expr.bind({x: 0.0}) def test_expressions_of_parameter_with_parameter(self): """Verify operating on two Parameters.""" x = Parameter("x") y = Parameter("y") for op in self.supported_operations: expr = op(x, y) partially_bound_expr = expr.bind({x: 2.3}) self.assertEqual(partially_bound_expr.parameters, {y}) fully_bound_expr = partially_bound_expr.bind({y: -numpy.pi}) self.assertEqual(fully_bound_expr.parameters, set()) self.assertEqual(float(fully_bound_expr), op(2.3, -numpy.pi)) bound_expr = expr.bind({x: 2.3, y: -numpy.pi}) self.assertEqual(bound_expr.parameters, set()) self.assertEqual(float(bound_expr), op(2.3, -numpy.pi)) def test_expressions_operation_order(self): """Verify ParameterExpressions respect order of operations.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") # Parenthesis before multiplication/division expr = (x + y) * z bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 9) expr = x * (y + z) bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 5) # Multiplication/division before addition/subtraction expr = x + y * z bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 7) expr = x * y + z bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 5) def test_nested_expressions(self): """Verify ParameterExpressions can also be the target of operations.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") expr1 = x * y expr2 = expr1 + z bound_expr2 = expr2.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr2), 5) def test_negated_expression(self): """Verify ParameterExpressions can be negated.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") expr1 = -x + y expr2 = -expr1 * (-z) bound_expr2 = expr2.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr2), 3) def test_standard_cu3(self): """This tests parameter negation in standard extension gate cu3.""" from qiskit.circuit.library import CU3Gate x = Parameter("x") y = Parameter("y") z = Parameter("z") qc = qiskit.QuantumCircuit(2) qc.append(CU3Gate(x, y, z), [0, 1]) try: qc.decompose() except TypeError: self.fail("failed to decompose cu3 gate with negated parameter expression") def test_name_collision(self): """Verify Expressions of distinct Parameters of shared name raises.""" x = Parameter("p") y = Parameter("p") # Expression of the same Parameter are valid. _ = x + x _ = x - x _ = x * x _ = x / x with self.assertRaises(CircuitError): _ = x + y with self.assertRaises(CircuitError): _ = x - y with self.assertRaises(CircuitError): _ = x * y with self.assertRaises(CircuitError): _ = x / y @combine(target_type=["gate", "instruction"], order=["bind-decompose", "decompose-bind"]) def test_to_instruction_with_expression(self, target_type, order): """Test preservation of expressions via parameterized instructions. β”Œβ”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” qr1_0: |0>─ Rx(ΞΈ) β”œβ”€ Rz(pi/2) β”œβ”€ Ry(phi*ΞΈ) β”œ β””β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” qr2_0: |0>──── Ry(delta) β”œβ”€β”€β”€ β”Œβ”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β” qr2_1: |0>─ Circuit0(phi,ΞΈ) β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ qr2_2: |0>─────────────────── """ theta = Parameter("ΞΈ") phi = Parameter("phi") qr1 = QuantumRegister(1, name="qr1") qc1 = QuantumCircuit(qr1) qc1.rx(theta, qr1) qc1.rz(numpy.pi / 2, qr1) qc1.ry(theta * phi, qr1) if target_type == "gate": gate = qc1.to_gate() elif target_type == "instruction": gate = qc1.to_instruction() self.assertEqual(gate.params, [phi, theta]) delta = Parameter("delta") qr2 = QuantumRegister(3, name="qr2") qc2 = QuantumCircuit(qr2) qc2.ry(delta, qr2[0]) qc2.append(gate, qargs=[qr2[1]]) self.assertEqual(qc2.parameters, {delta, theta, phi}) binds = {delta: 1, theta: 2, phi: 3} expected_qc = QuantumCircuit(qr2) expected_qc.rx(2, 1) expected_qc.rz(numpy.pi / 2, 1) expected_qc.ry(3 * 2, 1) expected_qc.r(1, numpy.pi / 2, 0) if order == "bind-decompose": decomp_bound_qc = qc2.assign_parameters(binds).decompose() elif order == "decompose-bind": decomp_bound_qc = qc2.decompose().assign_parameters(binds) self.assertEqual(decomp_bound_qc.parameters, set()) self.assertEqual(decomp_bound_qc, expected_qc) @combine(target_type=["gate", "instruction"], order=["bind-decompose", "decompose-bind"]) def test_to_instruction_expression_parameter_map(self, target_type, order): """Test preservation of expressions via instruction parameter_map.""" theta = Parameter("ΞΈ") phi = Parameter("phi") qr1 = QuantumRegister(1, name="qr1") qc1 = QuantumCircuit(qr1) qc1.rx(theta, qr1) qc1.rz(numpy.pi / 2, qr1) qc1.ry(theta * phi, qr1) theta_p = Parameter("theta") phi_p = Parameter("phi") if target_type == "gate": gate = qc1.to_gate(parameter_map={theta: theta_p, phi: phi_p}) elif target_type == "instruction": gate = qc1.to_instruction(parameter_map={theta: theta_p, phi: phi_p}) self.assertListEqual(gate.params, [theta_p, phi_p]) delta = Parameter("delta") qr2 = QuantumRegister(3, name="qr2") qc2 = QuantumCircuit(qr2) qc2.ry(delta, qr2[0]) qc2.append(gate, qargs=[qr2[1]]) self.assertListEqual(list(qc2.parameters), [delta, phi_p, theta_p]) binds = {delta: 1, theta_p: 2, phi_p: 3} expected_qc = QuantumCircuit(qr2) expected_qc.rx(2, 1) expected_qc.rz(numpy.pi / 2, 1) expected_qc.ry(3 * 2, 1) expected_qc.r(1, numpy.pi / 2, 0) if order == "bind-decompose": decomp_bound_qc = qc2.assign_parameters(binds).decompose() elif order == "decompose-bind": decomp_bound_qc = qc2.decompose().assign_parameters(binds) self.assertEqual(decomp_bound_qc.parameters, set()) self.assertEqual(decomp_bound_qc, expected_qc) def test_binding_across_broadcast_instruction(self): """Bind a parameter which was included via a broadcast instruction.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/3008 theta = Parameter("ΞΈ") n = 5 qc = QuantumCircuit(n, 1) qc.h(0) for i in range(n - 1): qc.cx(i, i + 1) qc.barrier() qc.rz(theta, range(n)) qc.barrier() for i in reversed(range(n - 1)): qc.cx(i, i + 1) qc.h(0) qc.measure(0, 0) theta_range = numpy.linspace(0, 2 * numpy.pi, 128) circuits = [qc.assign_parameters({theta: theta_val}) for theta_val in theta_range] self.assertEqual(len(circuits), len(theta_range)) for theta_val, bound_circ in zip(theta_range, circuits): rz_gates = [ inst.operation for inst in bound_circ.data if isinstance(inst.operation, RZGate) ] self.assertEqual(len(rz_gates), n) self.assertTrue(all(float(gate.params[0]) == theta_val for gate in rz_gates)) def test_substituting_parameter_with_simple_expression(self): """Substitute a simple parameter expression for a parameter.""" x = Parameter("x") y = Parameter("y") sub_ = y / 2 updated_expr = x.subs({x: sub_}) expected = y / 2 self.assertEqual(updated_expr, expected) def test_substituting_parameter_with_compound_expression(self): """Substitute a simple parameter expression for a parameter.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") sub_ = y * z updated_expr = x.subs({x: sub_}) expected = y * z self.assertEqual(updated_expr, expected) def test_substituting_simple_with_simple_expression(self): """Substitute a simple parameter expression in a parameter expression.""" x = Parameter("x") expr = x * x y = Parameter("y") sub_ = y / 2 updated_expr = expr.subs({x: sub_}) expected = y * y / 4 self.assertEqual(updated_expr, expected) def test_substituting_compound_expression(self): """Substitute a compound parameter expression in a parameter expression.""" x = Parameter("x") expr = x * x y = Parameter("y") z = Parameter("z") sub_ = y + z updated_expr = expr.subs({x: sub_}) expected = (y + z) * (y + z) self.assertEqual(updated_expr, expected) def test_conjugate(self): """Test calling conjugate on a ParameterExpression.""" x = Parameter("x") self.assertEqual((x.conjugate() + 1j), (x - 1j).conjugate()) @data( circlib.RGate, circlib.RXGate, circlib.RYGate, circlib.RZGate, circlib.RXXGate, circlib.RYYGate, circlib.RZXGate, circlib.RZZGate, circlib.CRXGate, circlib.CRYGate, circlib.CRZGate, circlib.XXPlusYYGate, ) def test_bound_gate_to_matrix(self, gate_class): """Test to_matrix works if previously free parameters are bound. The conversion might fail, if trigonometric functions such as cos are called on the parameters and the parameters are still of type ParameterExpression. """ num_parameters = 2 if gate_class == circlib.RGate else 1 params = list(range(1, 1 + num_parameters)) free_params = ParameterVector("th", num_parameters) gate = gate_class(*params) num_qubits = gate.num_qubits circuit = QuantumCircuit(num_qubits) circuit.append(gate_class(*free_params), list(range(num_qubits))) bound_circuit = circuit.assign_parameters({free_params: params}) numpy.testing.assert_array_almost_equal(Operator(bound_circuit).data, gate.to_matrix()) def test_parameter_expression_grad(self): """Verify correctness of ParameterExpression gradients.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") with self.subTest(msg="first order gradient"): expr = (x + y) * z self.assertEqual(expr.gradient(x), z) self.assertEqual(expr.gradient(z), (x + y)) with self.subTest(msg="second order gradient"): expr = x * x self.assertEqual(expr.gradient(x), 2 * x) self.assertEqual(expr.gradient(x).gradient(x), 2) def test_bound_expression_is_real(self): """Test is_real on bound parameters.""" x = Parameter("x") self.assertEqual(x.is_real(), None) self.assertEqual((1j * x).is_real(), None) expr = 1j * x bound = expr.bind({x: 2}) self.assertEqual(bound.is_real(), False) bound = x.bind({x: 0 + 0j}) self.assertEqual(bound.is_real(), True) bound = x.bind({x: 0 + 1j}) self.assertEqual(bound.is_real(), False) bound = x.bind({x: 1 + 0j}) self.assertEqual(bound.is_real(), True) bound = x.bind({x: 1 + 1j}) self.assertEqual(bound.is_real(), False) class TestParameterEquality(QiskitTestCase): """Test equality of Parameters and ParameterExpressions.""" def test_parameter_equal_self(self): """Verify a parameter is equal to it self.""" theta = Parameter("theta") self.assertEqual(theta, theta) def test_parameter_not_equal_param_of_same_name(self): """Verify a parameter is not equal to a Parameter of the same name.""" theta1 = Parameter("theta") theta2 = Parameter("theta") self.assertNotEqual(theta1, theta2) def test_parameter_expression_equal_to_self(self): """Verify an expression is equal to itself.""" theta = Parameter("theta") expr = 2 * theta self.assertEqual(expr, expr) def test_parameter_expression_equal_to_identical(self): """Verify an expression is equal an identical expression.""" theta = Parameter("theta") expr1 = 2 * theta expr2 = 2 * theta self.assertEqual(expr1, expr2) def test_parameter_expression_equal_floats_to_ints(self): """Verify an expression with float and int is identical.""" theta = Parameter("theta") expr1 = 2.0 * theta expr2 = 2 * theta self.assertEqual(expr1, expr2) def test_parameter_expression_not_equal_if_params_differ(self): """Verify expressions not equal if parameters are different.""" theta1 = Parameter("theta") theta2 = Parameter("theta") expr1 = 2 * theta1 expr2 = 2 * theta2 self.assertNotEqual(expr1, expr2) def test_parameter_equal_to_identical_expression(self): """Verify parameters and ParameterExpressions can be equal if identical.""" theta = Parameter("theta") phi = Parameter("phi") expr = (theta + phi).bind({phi: 0}) self.assertEqual(expr, theta) self.assertEqual(theta, expr) def test_parameter_symbol_equal_after_ufunc(self): """Verfiy ParameterExpression phi and ParameterExpression cos(phi) have the same symbol map""" phi = Parameter("phi") cos_phi = numpy.cos(phi) self.assertEqual(phi._parameter_symbols, cos_phi._parameter_symbols) class TestParameterReferences(QiskitTestCase): """Test the ParameterReferences class.""" def test_equal_inst_diff_instance(self): """Different value equal instructions are treated as distinct.""" theta = Parameter("theta") gate1 = RZGate(theta) gate2 = RZGate(theta) self.assertIsNot(gate1, gate2) self.assertEqual(gate1, gate2) refs = ParameterReferences(((gate1, 0), (gate2, 0))) # test __contains__ self.assertIn((gate1, 0), refs) self.assertIn((gate2, 0), refs) gate_ids = {id(gate1), id(gate2)} self.assertEqual(gate_ids, {id(gate) for gate, _ in refs}) self.assertTrue(all(idx == 0 for _, idx in refs)) def test_pickle_unpickle(self): """Membership testing after pickle/unpickle.""" theta = Parameter("theta") gate1 = RZGate(theta) gate2 = RZGate(theta) self.assertIsNot(gate1, gate2) self.assertEqual(gate1, gate2) refs = ParameterReferences(((gate1, 0), (gate2, 0))) to_pickle = (gate1, refs) pickled = pickle.dumps(to_pickle) (gate1_new, refs_new) = pickle.loads(pickled) self.assertEqual(len(refs_new), len(refs)) self.assertNotIn((gate1, 0), refs_new) self.assertIn((gate1_new, 0), refs_new) def test_equal_inst_same_instance(self): """Referentially equal instructions are treated as same.""" theta = Parameter("theta") gate = RZGate(theta) refs = ParameterReferences(((gate, 0), (gate, 0))) self.assertIn((gate, 0), refs) self.assertEqual(len(refs), 1) self.assertIs(next(iter(refs))[0], gate) self.assertEqual(next(iter(refs))[1], 0) def test_extend_refs(self): """Extending references handles duplicates.""" theta = Parameter("theta") ref0 = (RZGate(theta), 0) ref1 = (RZGate(theta), 0) ref2 = (RZGate(theta), 0) refs = ParameterReferences((ref0,)) refs |= ParameterReferences((ref0, ref1, ref2, ref1, ref0)) self.assertEqual(refs, ParameterReferences((ref0, ref1, ref2))) def test_copy_param_refs(self): """Copy of parameter references is a shallow copy.""" theta = Parameter("theta") ref0 = (RZGate(theta), 0) ref1 = (RZGate(theta), 0) ref2 = (RZGate(theta), 0) ref3 = (RZGate(theta), 0) refs = ParameterReferences((ref0, ref1)) refs_copy = refs.copy() # Check same gate instances in copy gate_ids = {id(ref0[0]), id(ref1[0])} self.assertEqual({id(gate) for gate, _ in refs_copy}, gate_ids) # add new ref to original and check copy not modified refs.add(ref2) self.assertNotIn(ref2, refs_copy) self.assertEqual(refs_copy, ParameterReferences((ref0, ref1))) # add new ref to copy and check original not modified refs_copy.add(ref3) self.assertNotIn(ref3, refs) self.assertEqual(refs, ParameterReferences((ref0, ref1, ref2))) class TestParameterTable(QiskitTestCase): """Test the ParameterTable class.""" def test_init_param_table(self): """Parameter table init from mapping.""" p1 = Parameter("theta") p2 = Parameter("theta") ref0 = (RZGate(p1), 0) ref1 = (RZGate(p1), 0) ref2 = (RZGate(p2), 0) mapping = {p1: ParameterReferences((ref0, ref1)), p2: ParameterReferences((ref2,))} table = ParameterTable(mapping) # make sure editing mapping doesn't change `table` del mapping[p1] self.assertEqual(table[p1], ParameterReferences((ref0, ref1))) self.assertEqual(table[p2], ParameterReferences((ref2,))) def test_set_references(self): """References replacement by parameter key.""" p1 = Parameter("theta") ref0 = (RZGate(p1), 0) ref1 = (RZGate(p1), 0) table = ParameterTable() table[p1] = ParameterReferences((ref0, ref1)) self.assertEqual(table[p1], ParameterReferences((ref0, ref1))) table[p1] = ParameterReferences((ref1,)) self.assertEqual(table[p1], ParameterReferences((ref1,))) def test_set_references_from_iterable(self): """Parameter table init from iterable.""" p1 = Parameter("theta") ref0 = (RZGate(p1), 0) ref1 = (RZGate(p1), 0) ref2 = (RZGate(p1), 0) table = ParameterTable({p1: ParameterReferences((ref0, ref1))}) table[p1] = (ref2, ref1, ref0) self.assertEqual(table[p1], ParameterReferences((ref2, ref1, ref0))) class TestParameterView(QiskitTestCase): """Test the ParameterView object.""" def setUp(self): super().setUp() x, y, z = Parameter("x"), Parameter("y"), Parameter("z") self.params = [x, y, z] self.view1 = ParameterView([x, y]) self.view2 = ParameterView([y, z]) self.view3 = ParameterView([x]) def test_and(self): """Test __and__.""" self.assertEqual(self.view1 & self.view2, {self.params[1]}) def test_or(self): """Test __or__.""" self.assertEqual(self.view1 | self.view2, set(self.params)) def test_xor(self): """Test __xor__.""" self.assertEqual(self.view1 ^ self.view2, {self.params[0], self.params[2]}) def test_len(self): """Test __len__.""" self.assertEqual(len(self.view1), 2) def test_le(self): """Test __le__.""" self.assertTrue(self.view1 <= self.view1) self.assertFalse(self.view1 <= self.view3) def test_lt(self): """Test __lt__.""" self.assertTrue(self.view3 < self.view1) def test_ge(self): """Test __ge__.""" self.assertTrue(self.view1 >= self.view1) self.assertFalse(self.view3 >= self.view1) def test_gt(self): """Test __lt__.""" self.assertTrue(self.view1 > self.view3) def test_eq(self): """Test __eq__.""" self.assertTrue(self.view1 == self.view1) self.assertFalse(self.view3 == self.view1) def test_ne(self): """Test __eq__.""" self.assertTrue(self.view1 != self.view2) self.assertFalse(self.view3 != self.view3) if __name__ == "__main__": unittest.main()
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. """Test registerless QuantumCircuit and Gates on wires""" import numpy from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit, AncillaQubit from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase class TestRegisterlessCircuit(QiskitTestCase): """Test registerless QuantumCircuit.""" def test_circuit_constructor_qwires(self): """Create a QuantumCircuit directly with quantum wires""" circuit = QuantumCircuit(2) expected = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(circuit, expected) def test_circuit_constructor_wires_wrong(self): """Create a registerless QuantumCircuit wrongly""" self.assertRaises(CircuitError, QuantumCircuit, 1, 2, 3) # QuantumCircuit(1, 2, 3) def test_circuit_constructor_wires_wrong_mix(self): """Create an almost-registerless QuantumCircuit""" # QuantumCircuit(1, ClassicalRegister(2)) self.assertRaises(CircuitError, QuantumCircuit, 1, ClassicalRegister(2)) class TestAddingBitsWithoutRegisters(QiskitTestCase): """Test adding Bit instances outside of Registers.""" def test_circuit_constructor_on_bits(self): """Verify we can add bits directly to a circuit.""" qubits = [Qubit(), Qubit()] clbits = [Clbit()] ancillas = [AncillaQubit(), AncillaQubit()] qc = QuantumCircuit(qubits, clbits, ancillas) self.assertEqual(qc.qubits, qubits + ancillas) self.assertEqual(qc.clbits, clbits) self.assertEqual(qc.ancillas, ancillas) self.assertEqual(qc.qregs, []) self.assertEqual(qc.cregs, []) def test_circuit_constructor_on_invalid_bits(self): """Verify we raise if passed not a Bit.""" with self.assertRaisesRegex(CircuitError, "Expected an instance of"): _ = QuantumCircuit([3.14]) def test_raise_if_bits_already_present(self): """Verify we raise when attempting to add a Bit already in the circuit.""" qubits = [Qubit()] with self.assertRaisesRegex(CircuitError, "bits found already"): _ = QuantumCircuit(qubits, qubits) qc = QuantumCircuit(qubits) with self.assertRaisesRegex(CircuitError, "bits found already"): qc.add_bits(qubits) qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) with self.assertRaisesRegex(CircuitError, "bits found already"): qc.add_bits(qr[:]) def test_addding_individual_bit(self): """Verify we can add a single bit to a circuit.""" qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) new_bit = Qubit() qc.add_bits([new_bit]) self.assertEqual(qc.qubits, list(qr) + [new_bit]) self.assertEqual(qc.qregs, [qr]) def test_inserted_ancilla_bits_are_added_to_qubits(self): """Verify AncillaQubits added via .add_bits are added to .qubits.""" anc = AncillaQubit() qb = Qubit() qc = QuantumCircuit() qc.add_bits([anc, qb]) self.assertEqual(qc.qubits, [anc, qb]) class TestGatesOnWires(QiskitTestCase): """Test gates on wires.""" def test_circuit_single_wire_h(self): """Test circuit on wire (H gate).""" qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) circuit.h(1) expected = QuantumCircuit(qreg) expected.h(qreg[1]) self.assertEqual(circuit, expected) def test_circuit_two_wire_cx(self): """Test circuit two wires (CX gate).""" qreg = QuantumRegister(2) expected = QuantumCircuit(qreg) expected.cx(qreg[0], qreg[1]) circuit = QuantumCircuit(qreg) circuit.cx(0, 1) self.assertEqual(circuit, expected) def test_circuit_single_wire_measure(self): """Test circuit on wire (measure gate).""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg, creg) circuit.measure(1, 1) expected = QuantumCircuit(qreg, creg) expected.measure(qreg[1], creg[1]) self.assertEqual(circuit, expected) def test_circuit_multi_qregs_h(self): """Test circuit multi qregs and wires (H gate).""" qreg0 = QuantumRegister(2) qreg1 = QuantumRegister(2) circuit = QuantumCircuit(qreg0, qreg1) circuit.h(0) circuit.h(2) expected = QuantumCircuit(qreg0, qreg1) expected.h(qreg0[0]) expected.h(qreg1[0]) self.assertEqual(circuit, expected) def test_circuit_multi_qreg_cregs_measure(self): """Test circuit multi qregs/cregs and wires (measure).""" qreg0 = QuantumRegister(2) creg0 = ClassicalRegister(2) qreg1 = QuantumRegister(2) creg1 = ClassicalRegister(2) circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1) circuit.measure(0, 2) circuit.measure(2, 1) expected = QuantumCircuit(qreg0, qreg1, creg0, creg1) expected.measure(qreg0[0], creg1[0]) expected.measure(qreg1[0], creg0[1]) self.assertEqual(circuit, expected) def test_circuit_barrier(self): """Test barrier on wires.""" qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.barrier(0) circuit.barrier(2) expected = QuantumCircuit(qreg01, qreg23) expected.barrier(qreg01[0]) expected.barrier(qreg23[0]) self.assertEqual(circuit, expected) def test_circuit_conditional(self): """Test conditional on wires.""" qreg = QuantumRegister(2) creg = ClassicalRegister(4) circuit = QuantumCircuit(qreg, creg) circuit.h(0).c_if(creg, 3) expected = QuantumCircuit(qreg, creg) expected.h(qreg[0]).c_if(creg, 3) self.assertEqual(circuit, expected) def test_circuit_qwire_out_of_range(self): """Fail if quantum wire is out of range.""" qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) self.assertRaises(CircuitError, circuit.h, 99) # circuit.h(99) def test_circuit_cwire_out_of_range(self): """Fail if classical wire is out of range.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg, creg) self.assertRaises(CircuitError, circuit.measure, 1, 99) # circuit.measure(1, 99) def test_circuit_initialize(self): """Test initialize on wires.""" init_vector = [0.5, 0.5, 0.5, 0.5] qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.initialize(init_vector, [0, 2]) expected = QuantumCircuit(qreg01, qreg23) expected.initialize(init_vector, [qreg01[0], qreg23[0]]) self.assertEqual(circuit, expected) def test_circuit_initialize_single_qubit(self): """Test initialize on single qubit.""" init_vector = [numpy.sqrt(0.5), numpy.sqrt(0.5)] qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) circuit.initialize(init_vector, qreg[0]) expected = QuantumCircuit(qreg) expected.initialize(init_vector, [qreg[0]]) self.assertEqual(circuit, expected) def test_mixed_register_and_registerless_indexing(self): """Test indexing if circuit contains bits in and out of registers.""" bits = [Qubit(), Qubit()] qreg = QuantumRegister(3, "q") circuit = QuantumCircuit(bits, qreg) for i in range(len(circuit.qubits)): circuit.rz(i, i) expected_qubit_order = bits + qreg[:] expected_circuit = QuantumCircuit(bits, qreg) for i in range(len(expected_circuit.qubits)): expected_circuit.rz(i, expected_qubit_order[i]) self.assertEqual(circuit.data, expected_circuit.data) class TestGatesOnWireRange(QiskitTestCase): """Test gates on wire range.""" def test_wire_range(self): """Test gate wire range""" qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) circuit.h(range(0, 2)) expected = QuantumCircuit(qreg) expected.h(qreg[0:2]) self.assertEqual(circuit, expected) def test_circuit_multi_qregs_h(self): """Test circuit multi qregs in range of wires (H gate).""" qreg0 = QuantumRegister(2) qreg1 = QuantumRegister(2) circuit = QuantumCircuit(qreg0, qreg1) circuit.h(range(0, 3)) expected = QuantumCircuit(qreg0, qreg1) expected.h(qreg0[0]) expected.h(qreg0[1]) expected.h(qreg1[0]) self.assertEqual(circuit, expected) def test_circuit_multi_qreg_cregs_measure(self): """Test circuit multi qregs in range of wires (measure).""" qreg0 = QuantumRegister(2) creg0 = ClassicalRegister(2) qreg1 = QuantumRegister(2) creg1 = ClassicalRegister(2) circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1) circuit.measure(range(1, 3), range(0, 4, 2)) expected = QuantumCircuit(qreg0, qreg1, creg0, creg1) expected.measure(qreg0[1], creg0[0]) expected.measure(qreg1[0], creg1[0]) self.assertEqual(circuit, expected) def test_circuit_barrier(self): """Test barrier on range of wires with multi regs.""" qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.barrier(range(0, 3)) expected = QuantumCircuit(qreg01, qreg23) expected.barrier(qreg01[0], qreg01[1], qreg23[0]) self.assertEqual(circuit, expected) def test_circuit_initialize(self): """Test initialize on wires.""" init_vector = [0.5, 0.5, 0.5, 0.5] qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.initialize(init_vector, range(1, 3)) expected = QuantumCircuit(qreg01, qreg23) expected.initialize(init_vector, [qreg01[1], qreg23[0]]) self.assertEqual(circuit, expected) def test_circuit_conditional(self): """Test conditional on wires.""" qreg0 = QuantumRegister(2) qreg1 = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg0, qreg1, creg) circuit.h(range(1, 3)).c_if(creg, 3) expected = QuantumCircuit(qreg0, qreg1, creg) expected.h(qreg0[1]).c_if(creg, 3) expected.h(qreg1[0]).c_if(creg, 3) self.assertEqual(circuit, expected) def test_circuit_qwire_out_of_range(self): """Fail if quantum wire is out of range.""" qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) self.assertRaises(CircuitError, circuit.h, range(9, 99)) # circuit.h(range(9,99)) def test_circuit_cwire_out_of_range(self): """Fail if classical wire is out of range.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg, creg) # circuit.measure(1, range(9,99)) self.assertRaises(CircuitError, circuit.measure, 1, range(9, 99)) class TestGatesOnWireSlice(QiskitTestCase): """Test gates on wire slice.""" def test_wire_slice(self): """Test gate wire slice""" qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) circuit.h(slice(0, 2)) expected = QuantumCircuit(qreg) expected.h(qreg[0:2]) self.assertEqual(circuit, expected) def test_wire_list(self): """Test gate wire list of integers""" qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) circuit.h([0, 1]) expected = QuantumCircuit(qreg) expected.h(qreg[0:2]) self.assertEqual(circuit, expected) def test_wire_np_int(self): """Test gate wire with numpy int""" numpy_int = numpy.dtype("int").type(2) qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) circuit.h(numpy_int) expected = QuantumCircuit(qreg) expected.h(qreg[2]) self.assertEqual(circuit, expected) def test_wire_np_1d_array(self): """Test gate wire with numpy array (one-dimensional)""" numpy_arr = numpy.array([0, 1]) qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) circuit.h(numpy_arr) expected = QuantumCircuit(qreg) expected.h(qreg[0]) expected.h(qreg[1]) self.assertEqual(circuit, expected) def test_circuit_multi_qregs_h(self): """Test circuit multi qregs in slices of wires (H gate).""" qreg0 = QuantumRegister(2) qreg1 = QuantumRegister(2) circuit = QuantumCircuit(qreg0, qreg1) circuit.h(slice(0, 3)) expected = QuantumCircuit(qreg0, qreg1) expected.h(qreg0[0]) expected.h(qreg0[1]) expected.h(qreg1[0]) self.assertEqual(circuit, expected) def test_circuit_multi_qreg_cregs_measure(self): """Test circuit multi qregs in slices of wires (measure).""" qreg0 = QuantumRegister(2) creg0 = ClassicalRegister(2) qreg1 = QuantumRegister(2) creg1 = ClassicalRegister(2) circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1) circuit.measure(slice(1, 3), slice(0, 4, 2)) expected = QuantumCircuit(qreg0, qreg1, creg0, creg1) expected.measure(qreg0[1], creg0[0]) expected.measure(qreg1[0], creg1[0]) self.assertEqual(circuit, expected) def test_circuit_barrier(self): """Test barrier on slice of wires with multi regs.""" qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.barrier(slice(0, 3)) expected = QuantumCircuit(qreg01, qreg23) expected.barrier([qreg01[0], qreg01[1], qreg23[0]]) self.assertEqual(circuit, expected) def test_circuit_initialize(self): """Test initialize on wires.""" init_vector = [0.5, 0.5, 0.5, 0.5] qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.initialize(init_vector, slice(1, 3)) expected = QuantumCircuit(qreg01, qreg23) expected.initialize(init_vector, [qreg01[1], qreg23[0]]) self.assertEqual(circuit, expected) def test_circuit_conditional(self): """Test conditional on wires.""" qreg0 = QuantumRegister(2) qreg1 = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg0, qreg1, creg) circuit.h(slice(1, 3)).c_if(creg, 3) expected = QuantumCircuit(qreg0, qreg1, creg) expected.h(qreg0[1]).c_if(creg, 3) expected.h(qreg1[0]).c_if(creg, 3) self.assertEqual(circuit, expected) def test_circuit_qwire_out_of_range(self): """Fail if quantum wire is out of range.""" qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) self.assertRaises(CircuitError, circuit.h, slice(9, 99)) # circuit.h(slice(9,99)) def test_circuit_cwire_out_of_range(self): """Fail if classical wire is out of range.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg, creg) # circuit.measure(1, slice(9,99)) self.assertRaises(CircuitError, circuit.measure, 1, slice(9, 99)) def test_wire_np_2d_array(self): """Test gate wire with numpy array (two-dimensional). Raises.""" numpy_arr = numpy.array([[0, 1], [2, 3]]) qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) self.assertRaises(CircuitError, circuit.h, numpy_arr) # circuit.h(numpy_arr) class TestBitConditional(QiskitTestCase): """Test gates with single bit conditionals.""" def test_bit_conditional_single_gate(self): """Test circuit with a single gate conditioned on a bit.""" qreg = QuantumRegister(1) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg, creg) circuit.h(0).c_if(0, True) expected = QuantumCircuit(qreg, creg) expected.h(qreg[0]).c_if(creg[0], True) self.assertEqual(circuit, expected) def test_bit_conditional_multiple_gates(self): """Test circuit with multiple gates conditioned on individual bits.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) creg1 = ClassicalRegister(1) circuit = QuantumCircuit(qreg, creg, creg1) circuit.h(0).c_if(0, True) circuit.h(1).c_if(1, False) circuit.cx(1, 0).c_if(2, True) expected = QuantumCircuit(qreg, creg, creg1) expected.h(qreg[0]).c_if(creg[0], True) expected.h(qreg[1]).c_if(creg[1], False) expected.cx(qreg[1], qreg[0]).c_if(creg1[0], True) self.assertEqual(circuit, expected)
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. """UnitaryGate tests""" import json import numpy from numpy.testing import assert_allclose import qiskit from qiskit.extensions.unitary import UnitaryGate from qiskit.test import QiskitTestCase from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.transpiler import PassManager from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.operators import Operator from qiskit.transpiler.passes import CXCancellation class TestUnitaryGate(QiskitTestCase): """Tests for the Unitary class.""" def test_set_matrix(self): """Test instantiation""" try: UnitaryGate([[0, 1], [1, 0]]) # pylint: disable=broad-except except Exception as err: self.fail(f"unexpected exception in init of Unitary: {err}") def test_set_matrix_raises(self): """test non-unitary""" try: UnitaryGate([[1, 1], [1, 0]]) # pylint: disable=broad-except except Exception: pass else: self.fail("setting Unitary with non-unitary did not raise") def test_set_init_with_unitary(self): """test instantiation of new unitary with another one (copy)""" uni1 = UnitaryGate([[0, 1], [1, 0]]) uni2 = UnitaryGate(uni1) self.assertEqual(uni1, uni2) self.assertFalse(uni1 is uni2) def test_conjugate(self): """test conjugate""" ymat = numpy.array([[0, -1j], [1j, 0]]) uni = UnitaryGate([[0, 1j], [-1j, 0]]) self.assertTrue(numpy.array_equal(uni.conjugate().to_matrix(), ymat)) def test_adjoint(self): """test adjoint operation""" uni = UnitaryGate([[0, 1j], [-1j, 0]]) self.assertTrue(numpy.array_equal(uni.adjoint().to_matrix(), uni.to_matrix())) class TestUnitaryCircuit(QiskitTestCase): """Matrix gate circuit tests.""" def test_1q_unitary(self): """test 1 qubit unitary matrix""" qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) matrix = numpy.array([[1, 0], [0, 1]]) qc.x(qr[0]) qc.append(UnitaryGate(matrix), [qr[0]]) # test of qasm output self.log.info(qc.qasm()) # test of text drawer self.log.info(qc) dag = circuit_to_dag(qc) dag_nodes = dag.named_nodes("unitary") self.assertTrue(len(dag_nodes) == 1) dnode = dag_nodes[0] self.assertIsInstance(dnode.op, UnitaryGate) self.assertEqual(dnode.qargs, (qr[0],)) assert_allclose(dnode.op.to_matrix(), matrix) def test_2q_unitary(self): """test 2 qubit unitary matrix""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmax, sigmay) qc.x(qr[0]) uni2q = UnitaryGate(matrix) qc.append(uni2q, [qr[0], qr[1]]) passman = PassManager() passman.append(CXCancellation()) qc2 = passman.run(qc) # test of qasm output self.log.info(qc2.qasm()) # test of text drawer self.log.info(qc2) dag = circuit_to_dag(qc) nodes = dag.two_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, UnitaryGate) self.assertEqual(dnode.qargs, (qr[0], qr[1])) assert_allclose(dnode.op.to_matrix(), matrix) qc3 = dag_to_circuit(dag) self.assertEqual(qc2, qc3) def test_3q_unitary(self): """test 3 qubit unitary matrix on non-consecutive bits""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay)) qc.x(qr[0]) uni3q = UnitaryGate(matrix) qc.append(uni3q, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) # test of text drawer self.log.info(qc) dag = circuit_to_dag(qc) nodes = dag.multi_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, UnitaryGate) self.assertEqual(dnode.qargs, (qr[0], qr[1], qr[3])) assert_allclose(dnode.op.to_matrix(), matrix) def test_1q_unitary_int_qargs(self): """test single qubit unitary matrix with 'int' and 'list of ints' qubits argument""" sigmax = numpy.array([[0, 1], [1, 0]]) sigmaz = numpy.array([[1, 0], [0, -1]]) # new syntax qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.unitary(sigmax, 0) qc.unitary(sigmax, qr[1]) qc.unitary(sigmaz, [0, 1]) # expected circuit qc_target = QuantumCircuit(qr) qc_target.append(UnitaryGate(sigmax), [0]) qc_target.append(UnitaryGate(sigmax), [qr[1]]) qc_target.append(UnitaryGate(sigmaz), [[0, 1]]) self.assertEqual(qc, qc_target) def test_qobj_with_unitary_matrix(self): """test qobj output with unitary matrix""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay)) qc.rx(numpy.pi / 4, qr[0]) uni = UnitaryGate(matrix) qc.append(uni, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[1] self.assertEqual(instr.name, "unitary") assert_allclose(numpy.array(instr.params[0]).astype(numpy.complex64), matrix) # check conversion to dict qobj_dict = qobj.to_dict() class NumpyEncoder(json.JSONEncoder): """Class for encoding json str with complex and numpy arrays.""" def default(self, obj): if isinstance(obj, numpy.ndarray): return obj.tolist() if isinstance(obj, complex): return (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) # check json serialization self.assertTrue(isinstance(json.dumps(qobj_dict, cls=NumpyEncoder), str)) def test_labeled_unitary(self): """test qobj output with unitary matrix""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmax, sigmay) uni = UnitaryGate(matrix, label="xy") qc.append(uni, [qr[0], qr[1]]) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[0] self.assertEqual(instr.name, "unitary") self.assertEqual(instr.label, "xy") def test_qasm_unitary_only_one_def(self): """test that a custom unitary can be converted to qasm and the definition is only written once""" qr = QuantumRegister(2, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = numpy.array([[1, 0], [0, 1]]) unitary_gate = UnitaryGate(matrix) qc.x(qr[0]) qc.append(unitary_gate, [qr[0]]) qc.append(unitary_gate, [qr[1]]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0 { u(0,0,0) q0; }\n" "qreg q0[2];\ncreg c0[1];\n" "x q0[0];\n" "unitary q0[0];\n" "unitary q0[1];\n" ) self.assertEqual(expected_qasm, qc.qasm()) def test_qasm_unitary_twice(self): """test that a custom unitary can be converted to qasm and that if the qasm is called twice it is the same every time""" qr = QuantumRegister(2, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = numpy.array([[1, 0], [0, 1]]) unitary_gate = UnitaryGate(matrix) qc.x(qr[0]) qc.append(unitary_gate, [qr[0]]) qc.append(unitary_gate, [qr[1]]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0 { u(0,0,0) q0; }\n" "qreg q0[2];\ncreg c0[1];\n" "x q0[0];\n" "unitary q0[0];\n" "unitary q0[1];\n" ) self.assertEqual(expected_qasm, qc.qasm()) self.assertEqual(expected_qasm, qc.qasm()) def test_qasm_2q_unitary(self): """test that a 2 qubit custom unitary can be converted to qasm""" qr = QuantumRegister(2, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = numpy.asarray([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]) unitary_gate = UnitaryGate(matrix) qc.x(qr[0]) qc.append(unitary_gate, [qr[0], qr[1]]) qc.append(unitary_gate, [qr[1], qr[0]]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0,q1 { u(pi,-pi/2,pi/2) q0; u(pi,pi/2,-pi/2) q1; }\n" "qreg q0[2];\n" "creg c0[1];\n" "x q0[0];\n" "unitary q0[0],q0[1];\n" "unitary q0[1],q0[0];\n" ) self.assertEqual(expected_qasm, qc.qasm()) def test_qasm_unitary_noop(self): """Test that an identity unitary can be converted to OpenQASM 2""" qc = QuantumCircuit(QuantumRegister(3, "q0")) qc.unitary(numpy.eye(8), qc.qubits) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0,q1,q2 { }\n" "qreg q0[3];\n" "unitary q0[0],q0[1],q0[2];\n" ) self.assertEqual(expected_qasm, qc.qasm()) def test_unitary_decomposition(self): """Test decomposition for unitary gates over 2 qubits.""" qc = QuantumCircuit(3) qc.unitary(random_unitary(8, seed=42), [0, 1, 2]) self.assertTrue(Operator(qc).equiv(Operator(qc.decompose()))) def test_unitary_decomposition_via_definition(self): """Test decomposition for 1Q unitary via definition.""" mat = numpy.array([[0, 1], [1, 0]]) self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat)) def test_unitary_decomposition_via_definition_2q(self): """Test decomposition for 2Q unitary via definition.""" mat = numpy.array([[0, 0, 1, 0], [0, 0, 0, -1], [1, 0, 0, 0], [0, -1, 0, 0]]) self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat)) def test_unitary_control(self): """Test parameters of controlled - unitary.""" mat = numpy.array([[0, 1], [1, 0]]) gate = UnitaryGate(mat).control() self.assertTrue(numpy.allclose(gate.params, mat)) self.assertTrue(numpy.allclose(gate.base_gate.params, mat))
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. """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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Compiler Test.""" import os import unittest from qiskit import BasicAer from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.transpiler import PassManager from qiskit import execute from qiskit.circuit.library import U1Gate, U2Gate from qiskit.compiler import transpile, assemble from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeRueschlikon, FakeTenerife from qiskit.qobj import QasmQobj class TestCompiler(QiskitTestCase): """Qiskit Compiler Tests.""" def setUp(self): super().setUp() self.seed_simulator = 42 self.backend = BasicAer.get_backend("qasm_simulator") def test_example_multiple_compile(self): """Test a toy example compiling multiple circuits. Pass if the results are correct. """ backend = BasicAer.get_backend("qasm_simulator") coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]] qr = QuantumRegister(5) cr = ClassicalRegister(5) bell = QuantumCircuit(qr, cr) ghz = QuantumCircuit(qr, cr) # Create a GHZ state ghz.h(qr[0]) for i in range(4): ghz.cx(qr[i], qr[i + 1]) # Insert a barrier before measurement ghz.barrier() # Measure all of the qubits in the standard basis for i in range(5): ghz.measure(qr[i], cr[i]) # Create a Bell state bell.h(qr[0]) bell.cx(qr[0], qr[1]) bell.barrier() bell.measure(qr[0], cr[0]) bell.measure(qr[1], cr[1]) shots = 2048 bell_backend = transpile(bell, backend=backend) ghz_backend = transpile(ghz, backend=backend, coupling_map=coupling_map) bell_qobj = assemble(bell_backend, shots=shots, seed_simulator=10) ghz_qobj = assemble(ghz_backend, shots=shots, seed_simulator=10) bell_result = backend.run(bell_qobj).result() ghz_result = backend.run(ghz_qobj).result() threshold = 0.05 * shots counts_bell = bell_result.get_counts() target_bell = {"00000": shots / 2, "00011": shots / 2} self.assertDictAlmostEqual(counts_bell, target_bell, threshold) counts_ghz = ghz_result.get_counts() target_ghz = {"00000": shots / 2, "11111": shots / 2} self.assertDictAlmostEqual(counts_ghz, target_ghz, threshold) def test_compile_coupling_map(self): """Test compile_coupling_map. If all correct should return data with the same stats. The circuit may be different. """ backend = BasicAer.get_backend("qasm_simulator") qr = QuantumRegister(3, "qr") cr = ClassicalRegister(3, "cr") qc = QuantumCircuit(qr, cr, name="qccccccc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.cx(qr[0], qr[2]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) shots = 2048 coupling_map = [[0, 1], [1, 2]] initial_layout = [0, 1, 2] qc_b = transpile( qc, backend=backend, coupling_map=coupling_map, initial_layout=initial_layout ) qobj = assemble(qc_b, shots=shots, seed_simulator=88) job = backend.run(qobj) result = job.result() qasm_to_check = qc.qasm() self.assertEqual(len(qasm_to_check), 173) counts = result.get_counts(qc) target = {"000": shots / 2, "111": shots / 2} threshold = 0.05 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_example_swap_bits(self): """Test a toy example swapping a set bit around. Uses the mapper. Pass if results are correct. """ backend = BasicAer.get_backend("qasm_simulator") coupling_map = [ [0, 1], [0, 8], [1, 2], [1, 9], [2, 3], [2, 10], [3, 4], [3, 11], [4, 5], [4, 12], [5, 6], [5, 13], [6, 7], [6, 14], [7, 15], [8, 9], [9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], ] # β”Œβ”€β”€β”€β” β–‘ β”Œβ”€β” # q0_0: ─ X β”œβ”€X───────────░──Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β”‚ β–‘ β””β•₯β”˜ β”Œβ”€β” # q0_1: ──────┼─────X──X──░──╫─────Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”‚ β”‚ β”‚ β–‘ β•‘ β””β•₯β”˜ β”Œβ”€β” # q0_2: ──────X──X──┼──┼──░──╫─────╫─────Mβ”œβ”€β”€β”€ # β”‚ β”‚ β”‚ β–‘ β•‘ β”Œβ”€β” β•‘ β””β•₯β”˜ # q1_0: ─────────┼──┼──┼──░──╫──Mβ”œβ”€β•«β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€ # β”‚ β”‚ β”‚ β–‘ β•‘ β””β•₯β”˜ β•‘ β”Œβ”€β” β•‘ # q1_1: ─────────┼──┼──X──░──╫──╫──╫──Mβ”œβ”€β•«β”€β”€β”€β”€ # β”‚ β”‚ β–‘ β•‘ β•‘ β•‘ β””β•₯β”˜ β•‘ β”Œβ”€β” # q1_2: ─────────X──X─────░──╫──╫──╫──╫──╫──Mβ”œ # β–‘ β•‘ β•‘ β•‘ β•‘ β•‘ β””β•₯β”˜ # c0: 6/═════════════════════╩══╩══╩══╩══╩══╩═ # 0 3 1 4 2 5 n = 3 # make this at least 3 qr0 = QuantumRegister(n) qr1 = QuantumRegister(n) ans = ClassicalRegister(2 * n) qc = QuantumCircuit(qr0, qr1, ans) # Set the first bit of qr0 qc.x(qr0[0]) # Swap the set bit qc.swap(qr0[0], qr0[n - 1]) qc.swap(qr0[n - 1], qr1[n - 1]) qc.swap(qr1[n - 1], qr0[1]) qc.swap(qr0[1], qr1[1]) # Insert a barrier before measurement qc.barrier() # Measure all of the qubits in the standard basis for j in range(n): qc.measure(qr0[j], ans[j]) qc.measure(qr1[j], ans[j + n]) # First version: no mapping result = execute( qc, backend=backend, coupling_map=None, shots=1024, seed_simulator=14 ).result() self.assertEqual(result.get_counts(qc), {"010000": 1024}) # Second version: map to coupling graph result = execute( qc, backend=backend, coupling_map=coupling_map, shots=1024, seed_simulator=14 ).result() self.assertEqual(result.get_counts(qc), {"010000": 1024}) def test_parallel_compile(self): """Trigger parallel routines in compile.""" backend = FakeRueschlikon() qr = QuantumRegister(16) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) for k in range(1, 15): qc.cx(qr[0], qr[k]) qc.measure(qr[5], cr[0]) qlist = [qc for k in range(10)] qobj = assemble(transpile(qlist, backend=backend)) self.assertEqual(len(qobj.experiments), 10) def test_no_conflict_backend_passmanager(self): """execute(qc, backend=..., passmanager=...) See: https://github.com/Qiskit/qiskit-terra/issues/5037 """ backend = BasicAer.get_backend("qasm_simulator") qc = QuantumCircuit(2) qc.append(U1Gate(0), [0]) qc.measure_all() job = execute(qc, backend=backend, pass_manager=PassManager()) result = job.result().get_counts() self.assertEqual(result, {"00": 1024}) def test_compile_single_qubit(self): """Compile a single-qubit circuit in a non-trivial layout""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) layout = {qr[0]: 12} cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit2 = transpile( circuit, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout ) qobj = assemble(circuit2) compiled_instruction = qobj.experiments[0].instructions[0] self.assertEqual(compiled_instruction.name, "u2") self.assertEqual(compiled_instruction.qubits, [12]) self.assertEqual(compiled_instruction.params, [0, 3.141592653589793]) def test_compile_pass_manager(self): """Test compile with and without an empty pass manager.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.append(U1Gate(3.14), [qr[0]]) qc.append(U2Gate(3.14, 1.57), [qr[0]]) qc.barrier(qr) qc.measure(qr, cr) backend = BasicAer.get_backend("qasm_simulator") qrtrue = assemble(transpile(qc, backend, seed_transpiler=8), seed_simulator=42) rtrue = backend.run(qrtrue).result() qrfalse = assemble(PassManager().run(qc), seed_simulator=42) rfalse = backend.run(qrfalse).result() self.assertEqual(rtrue.get_counts(), rfalse.get_counts()) def test_mapper_overoptimization(self): """Check mapper overoptimization. The mapper should not change the semantics of the input. An overoptimization introduced issue #81: https://github.com/Qiskit/qiskit-terra/issues/81 """ # β”Œβ”€β”€β”€β” β”Œβ”€β” # q0_0: ─ X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β”Œβ”€β”΄β”€β”β”Œβ”€β”€β”€β”β””β•₯β”˜ β”Œβ”€β” # q0_1: ─ Y β”œβ”€ X β”œβ”€ S β”œβ”€β•«β”€β”€β”€β– β”€β”€β”€Mβ”œβ”€β”€β”€ # β”œβ”€β”€β”€β”€β””β”€β”€β”€β”˜β”œβ”€β”€β”€β”€ β•‘ β”Œβ”€β”΄β”€β”β””β•₯β”˜β”Œβ”€β” # q0_2: ─ Z β”œβ”€β”€β– β”€β”€β”€ T β”œβ”€β•«β”€β”€ X β”œβ”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β”β”œβ”€β”€β”€β”€ β•‘ β””β”¬β”€β”¬β”˜ β•‘ β””β•₯β”˜ # q0_3: ────── X β”œβ”€ H β”œβ”€β•«β”€β”€β”€Mβ”œβ”€β”€β•«β”€β”€β•«β”€ # β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β•‘ β””β•₯β”˜ β•‘ β•‘ # c0: 4/════════════════╩═══╩═══╩══╩═ # 0 3 1 2 qr = QuantumRegister(4) cr = ClassicalRegister(4) circ = QuantumCircuit(qr, cr) circ.x(qr[0]) circ.y(qr[1]) circ.z(qr[2]) circ.cx(qr[0], qr[1]) circ.cx(qr[2], qr[3]) circ.s(qr[1]) circ.t(qr[2]) circ.h(qr[3]) circ.cx(qr[1], qr[2]) circ.measure(qr[0], cr[0]) circ.measure(qr[1], cr[1]) circ.measure(qr[2], cr[2]) circ.measure(qr[3], cr[3]) coupling_map = [[0, 2], [1, 2], [2, 3]] shots = 1000 result1 = execute( circ, backend=self.backend, coupling_map=coupling_map, seed_simulator=self.seed_simulator, seed_transpiler=8, shots=shots, ) count1 = result1.result().get_counts() result2 = execute( circ, backend=self.backend, coupling_map=None, seed_simulator=self.seed_simulator, seed_transpiler=8, shots=shots, ) count2 = result2.result().get_counts() self.assertDictAlmostEqual(count1, count2, shots * 0.02) def test_grovers_circuit(self): """Testing a circuit originated in the Grover algorithm""" shots = 1000 coupling_map = None # 6-qubit grovers # # β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β” β–‘ β”Œβ”€β” # q0_0: ─ H β”œβ”€ X β”œβ”€β”€β– β”€β”€β”€ X β”œβ”€ X β”œβ”€β”€β– β”€β”€β”€ X β”œβ”€β”€β– β”€β”€β”€ X β”œβ”€ H β”œβ”€β”€β”€β”€β”€β”€β–‘β”€β”€Mβ”œβ”€β”€β”€ # β”œβ”€β”€β”€β”€β””β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β”‚ β”œβ”€β”€β”€β”€ β”‚ β”œβ”€β”€β”€β”€β”œβ”€β”€β”€β”€ β–‘ β””β•₯β”˜β”Œβ”€β” # q0_1: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”Όβ”€β”€β”€ X β”œβ”€β”€β– β”€β”€β”€ X β”œβ”€ H β”œβ”€β”€β”€β”€β”€β”€β–‘β”€β”€β•«β”€β”€Mβ”œ # β”œβ”€β”€β”€β”€ β”‚ β”Œβ”€β”΄β”€β” β”‚ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β–‘ β•‘ β””β•₯β”˜ # q0_2: ─ X β”œβ”€β”€β”Όβ”€β”€β”€ X β”œβ”€β”€β– β”€β”€β”€β”€β”Όβ”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€β•«β”€β”€β•«β”€ # β”œβ”€β”€β”€β”€β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ β”‚ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ β”‚ β–‘ β•‘ β•‘ # q0_3: ─ X β”œβ”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€β•«β”€β”€β•«β”€ # β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β”Œβ”€β”΄β”€β”β”œβ”€β”€β”€β”€β”Œβ”€β”€β”€β” β”Œβ”€β”΄β”€β”β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β” β–‘ β•‘ β•‘ # q0_4: ──────────────── X β”œβ”€ X β”œβ”€ H β”œβ”€β”€β”€β”€β”€β”€ X β”œβ”€ H β”œβ”€ X β”œβ”€ H β”œβ”€β–‘β”€β”€β•«β”€β”€β•«β”€ # β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β–‘ β•‘ β•‘ # q0_5: ────────────────────────────────────────────────────────░──╫──╫─ # β–‘ β•‘ β•‘ # c0: 2/═══════════════════════════════════════════════════════════╩══╩═ # 0 1 qr = QuantumRegister(6) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr, name="grovers") circuit.h(qr[0]) circuit.h(qr[1]) circuit.x(qr[2]) circuit.x(qr[3]) circuit.x(qr[0]) circuit.cx(qr[0], qr[2]) circuit.x(qr[0]) circuit.cx(qr[1], qr[3]) circuit.ccx(qr[2], qr[3], qr[4]) circuit.cx(qr[1], qr[3]) circuit.x(qr[0]) circuit.cx(qr[0], qr[2]) circuit.x(qr[0]) circuit.x(qr[1]) circuit.x(qr[4]) circuit.h(qr[4]) circuit.ccx(qr[0], qr[1], qr[4]) circuit.h(qr[4]) circuit.x(qr[0]) circuit.x(qr[1]) circuit.x(qr[4]) circuit.h(qr[0]) circuit.h(qr[1]) circuit.h(qr[4]) circuit.barrier(qr) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) result = execute( circuit, backend=self.backend, coupling_map=coupling_map, seed_simulator=self.seed_simulator, shots=shots, ) counts = result.result().get_counts() expected_probs = {"00": 0.64, "01": 0.117, "10": 0.113, "11": 0.13} target = {key: shots * val for key, val in expected_probs.items()} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_math_domain_error(self): """Check for floating point errors. The math library operates over floats and introduces floating point errors that should be avoided. See: https://github.com/Qiskit/qiskit-terra/issues/111 """ # β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β” β”Œβ”€β” # q0_0: ─ Y β”œβ”€ X β”œβ”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜β””β”€β”¬β”€β”˜ β””β•₯β”˜ β”Œβ”€β” # q0_1: ───────■────────╫─────────────■───Mβ”œβ”€β”€β”€ # β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β” β•‘ β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β”β”Œβ”€β”΄β”€β”β””β•₯β”˜β”Œβ”€β” # q0_2: ─ Z β”œβ”€ H β”œβ”€ Y β”œβ”€β•«β”€β”€ T β”œβ”€ Z β”œβ”€ X β”œβ”€β•«β”€β”€Mβ”œ # β””β”¬β”€β”¬β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β•‘ β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β•‘ β””β•₯β”˜ # q0_3: ──Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β•«β”€ # β””β•₯β”˜ β•‘ β•‘ β•‘ # c0: 4/══╩═════════════╩═════════════════╩══╩═ # 3 0 1 2 qr = QuantumRegister(4) cr = ClassicalRegister(4) circ = QuantumCircuit(qr, cr) circ.y(qr[0]) circ.z(qr[2]) circ.h(qr[2]) circ.cx(qr[1], qr[0]) circ.y(qr[2]) circ.t(qr[2]) circ.z(qr[2]) circ.cx(qr[1], qr[2]) circ.measure(qr[0], cr[0]) circ.measure(qr[1], cr[1]) circ.measure(qr[2], cr[2]) circ.measure(qr[3], cr[3]) coupling_map = [[0, 2], [1, 2], [2, 3]] shots = 2000 job = execute( circ, backend=self.backend, coupling_map=coupling_map, seed_simulator=self.seed_simulator, shots=shots, ) counts = job.result().get_counts() target = {"0001": shots / 2, "0101": shots / 2} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_random_parameter_circuit(self): """Run a circuit with randomly generated parameters.""" qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "random_n5_d5.qasm")) coupling_map = [[0, 1], [1, 2], [2, 3], [3, 4]] shots = 1024 qobj = execute( circ, backend=self.backend, coupling_map=coupling_map, shots=shots, seed_simulator=self.seed_simulator, ) counts = qobj.result().get_counts() expected_probs = { "00000": 0.079239867254200971, "00001": 0.032859032998526903, "00010": 0.10752610993531816, "00011": 0.018818532050952699, "00100": 0.054830807251011054, "00101": 0.0034141983951965164, "00110": 0.041649309748902276, "00111": 0.039967731207338125, "01000": 0.10516937819949743, "01001": 0.026635620063700002, "01010": 0.0053475143548793866, "01011": 0.01940513314416064, "01100": 0.0044028405481225047, "01101": 0.057524760052126644, "01110": 0.010795354134597078, "01111": 0.026491296821535528, "10000": 0.094827455395274859, "10001": 0.0008373965072688836, "10010": 0.029082297894094441, "10011": 0.012386622870598416, "10100": 0.018739140061148799, "10101": 0.01367656456536896, "10110": 0.039184170706009248, "10111": 0.062339335178438288, "11000": 0.00293674365989009, "11001": 0.012848433960739968, "11010": 0.018472497159499782, "11011": 0.0088903691234912003, "11100": 0.031305389080034329, "11101": 0.0004788556283690458, "11110": 0.002232419390471667, "11111": 0.017684822659235985, } target = {key: shots * val for key, val in expected_probs.items()} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_yzy_zyz_cases(self): """yzy_to_zyz works in previously failed cases. See: https://github.com/Qiskit/qiskit-terra/issues/607 """ backend = FakeTenerife() qr = QuantumRegister(2) circ1 = QuantumCircuit(qr) circ1.cx(qr[0], qr[1]) circ1.rz(0.7, qr[1]) circ1.rx(1.570796, qr[1]) qobj1 = assemble(transpile(circ1, backend)) self.assertIsInstance(qobj1, QasmQobj) circ2 = QuantumCircuit(qr) circ2.y(qr[0]) circ2.h(qr[0]) circ2.s(qr[0]) circ2.h(qr[0]) qobj2 = assemble(transpile(circ2, backend)) self.assertIsInstance(qobj2, QasmQobj) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for the converters.""" import os import unittest from qiskit.converters import ast_to_dag, circuit_to_dag from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import qasm from qiskit.test import QiskitTestCase class TestAstToDag(QiskitTestCase): """Test AST to DAG.""" def setUp(self): super().setUp() qr = QuantumRegister(3) cr = ClassicalRegister(3) self.circuit = QuantumCircuit(qr, cr) self.circuit.ccx(qr[0], qr[1], qr[2]) self.circuit.measure(qr, cr) self.dag = circuit_to_dag(self.circuit) def test_from_ast_to_dag(self): """Test Unroller.execute()""" qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") ast = qasm.Qasm(os.path.join(qasm_dir, "example.qasm")).parse() dag_circuit = ast_to_dag(ast) expected_result = """\ OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; qreg r[3]; creg c[3]; creg d[3]; h q[0]; h q[1]; h q[2]; cx q[0],r[0]; cx q[1],r[1]; cx q[2],r[2]; barrier q[0],q[1],q[2]; measure q[0] -> c[0]; measure q[1] -> c[1]; measure q[2] -> c[2]; measure r[0] -> d[0]; measure r[1] -> d[1]; measure r[2] -> d[2]; """ expected_dag = circuit_to_dag(QuantumCircuit.from_qasm_str(expected_result)) self.assertEqual(dag_circuit, expected_dag) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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. """Tests for the converters.""" import unittest from qiskit.converters import dag_to_circuit, circuit_to_dag from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase class TestCircuitToDag(QiskitTestCase): """Test Circuit to DAG.""" def test_circuit_and_dag(self): """Check convert to dag and back""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag = circuit_to_dag(circuit_in) circuit_out = dag_to_circuit(dag) self.assertEqual(circuit_out, circuit_in) if __name__ == '__main__': unittest.main(verbosity=2)
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 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import os import sys cwd = os.getcwd() qiskit_dir = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(cwd)))) sys.path.append(qiskit_dir) from qiskit import IBMQ from qiskit.tools.jupyter import * IBMQ.load_account() %qiskit_backend_overview
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import os import sys cwd = os.getcwd() qiskit_dir = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(cwd)))) sys.path.append(qiskit_dir) from qiskit import BasicAer, execute from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.compiler import transpile from qiskit.tools.parallel import parallel_map from qiskit.tools.monitor import job_monitor from qiskit.tools.events import TextProgressBar from qiskit.tools.jupyter import * sim_backend = BasicAer.get_backend("qasm_simulator") import time def func(_): time.sleep(0.1) return 0 HTMLProgressBar() parallel_map(func, list(range(10))); %qiskit_progress_bar parallel_map(func, list(range(10))); TextProgressBar() parallel_map(func, list(range(10))); %qiskit_progress_bar -t text parallel_map(func, list(range(10))); q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) HTMLProgressBar() qobj = transpile([qc] * 20, backend=sim_backend) job_sim2 = execute([qc] * 10, backend=sim_backend) job_monitor(job_sim2)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-docstring """BasicAerJob creation and test suite.""" import uuid from contextlib import contextmanager from os import path import unittest from unittest.mock import patch from qiskit.test import QiskitTestCase from qiskit.test.mock import new_fake_qobj, FakeRueschlikon class TestSimulatorsJob(QiskitTestCase): """Test how backends create BasicAerJob objects and the BasicAerJob class.""" def test_multiple_execution(self): # Notice that it is Python responsibility to test the executors # can run several tasks at the same time. It is our responsibility to # use the executor correctly. That is what this test checks. taskcount = 10 target_tasks = [lambda: None for _ in range(taskcount)] job_id = str(uuid.uuid4()) backend = FakeRueschlikon() with mocked_executor() as (SimulatorJob, executor): for index in range(taskcount): job = SimulatorJob(backend, job_id, target_tasks[index], new_fake_qobj()) job.submit() self.assertEqual(executor.submit.call_count, taskcount) for index in range(taskcount): _, callargs, _ = executor.submit.mock_calls[index] submitted_task = callargs[0] target_task = target_tasks[index] self.assertEqual(submitted_task, target_task) def test_cancel(self): # Again, cancelling jobs is beyond our responsibility. In this test # we only check if we delegate on the proper method of the underlaying # future object. job_id = str(uuid.uuid4()) backend = FakeRueschlikon() with mocked_executor() as (BasicAerJob, executor): job = BasicAerJob(backend, job_id, lambda: None, new_fake_qobj()) job.submit() job.cancel() self.assertCalledOnce(executor.submit) mocked_future = executor.submit.return_value self.assertCalledOnce(mocked_future.cancel) def assertCalledOnce(self, mocked_callable): """Assert a mocked callable has been called once.""" call_count = mocked_callable.call_count self.assertEqual( call_count, 1, 'Callable object has been called more than once ({})'.format( call_count)) @contextmanager def mocked_executor(): """Context that patches the derived executor classes to return the same executor object. Also patches the future object returned by executor's submit().""" import importlib import concurrent.futures as futures import qiskit.providers.basicaer.basicaerjob as basicaerjob executor = unittest.mock.MagicMock(spec=futures.Executor) executor.submit.return_value = unittest.mock.MagicMock(spec=futures.Future) mock_options = {'return_value': executor, 'autospec': True} with patch.object(futures, 'ProcessPoolExecutor', **mock_options),\ patch.object(futures, 'ThreadPoolExecutor', **mock_options): importlib.reload(basicaerjob) yield basicaerjob.BasicAerJob, executor @contextmanager def mocked_simulator_binaries(): """Context to force binary-based simulators to think the simulators exist. """ with patch.object(path, 'exists', return_value=True, autospec=True),\ patch.object(path, 'getsize', return_value=1000, autospec=True): yield if __name__ == '__main__': unittest.main(verbosity=2)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # 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 """Tests continuous pulse functions.""" import numpy as np from qiskit.test import QiskitTestCase import qiskit.pulse.pulse_lib.continuous as continuous class TestContinuousPulses(QiskitTestCase): """Test continuous pulses.""" def test_constant(self): """Test constant pulse.""" amp = 0.5j samples = 50 times = np.linspace(0, 10, samples) constant_arr = continuous.constant(times, amp=amp) self.assertEqual(constant_arr.dtype, np.complex_) np.testing.assert_equal(constant_arr, amp) self.assertEqual(len(constant_arr), samples) def test_zero(self): """Test constant pulse.""" times = np.linspace(0, 10, 50) zero_arr = continuous.zero(times) self.assertEqual(zero_arr.dtype, np.complex_) np.testing.assert_equal(zero_arr, 0.0) self.assertEqual(len(zero_arr), 50) def test_square(self): """Test square wave.""" amp = 0.5 period = 5 samples = 100 times = np.linspace(0, 10, samples) square_arr = continuous.square(times, amp=amp, period=period) # with new phase square_arr_phased = continuous.square(times, amp=amp, period=period, phase=np.pi/2) self.assertEqual(square_arr.dtype, np.complex_) self.assertAlmostEqual(square_arr[0], amp) # test constant self.assertAlmostEqual(square_arr[1]-square_arr[0], 0.0) self.assertAlmostEqual(square_arr[25], -amp) self.assertAlmostEqual(square_arr_phased[0], -amp) # Assert bounded between -amp and amp self.assertTrue(np.all((-amp <= square_arr) & (square_arr <= amp))) self.assertEqual(len(square_arr), samples) def test_sawtooth(self): """Test sawtooth wave.""" amp = 0.5 period = 5 samples = 101 times, dt = np.linspace(0, 10, samples, retstep=True) sawtooth_arr = continuous.sawtooth(times, amp=amp, period=period) # with new phase sawtooth_arr_phased = continuous.sawtooth(times, amp=amp, period=period, phase=np.pi/2) self.assertEqual(sawtooth_arr.dtype, np.complex_) self.assertAlmostEqual(sawtooth_arr[0], 0.0) # test slope self.assertAlmostEqual((sawtooth_arr[1]-sawtooth_arr[0])/dt, 2*amp/period) self.assertAlmostEqual(sawtooth_arr[24], 0.48) self.assertAlmostEqual(sawtooth_arr[50], 0.) self.assertAlmostEqual(sawtooth_arr[75], -amp) self.assertAlmostEqual(sawtooth_arr_phased[0], -amp) # Assert bounded between -amp and amp self.assertTrue(np.all((-amp <= sawtooth_arr) & (sawtooth_arr <= amp))) self.assertEqual(len(sawtooth_arr), samples) def test_triangle(self): """Test triangle wave.""" amp = 0.5 period = 5 samples = 101 times, dt = np.linspace(0, 10, samples, retstep=True) triangle_arr = continuous.triangle(times, amp=amp, period=period) # with new phase triangle_arr_phased = continuous.triangle(times, amp=amp, period=period, phase=np.pi/2) self.assertEqual(triangle_arr.dtype, np.complex_) self.assertAlmostEqual(triangle_arr[0], 0.0) # test slope self.assertAlmostEqual((triangle_arr[1]-triangle_arr[0])/dt, 4*amp/period) self.assertAlmostEqual(triangle_arr[12], 0.48) self.assertAlmostEqual(triangle_arr[13], 0.48) self.assertAlmostEqual(triangle_arr[50], 0.) self.assertAlmostEqual(triangle_arr_phased[0], amp) # Assert bounded between -amp and amp self.assertTrue(np.all((-amp <= triangle_arr) & (triangle_arr <= amp))) self.assertEqual(len(triangle_arr), samples) def test_cos(self): """Test cosine wave.""" amp = 0.5 period = 5 freq = 1/period samples = 101 times = np.linspace(0, 10, samples) cos_arr = continuous.cos(times, amp=amp, freq=freq) # with new phase cos_arr_phased = continuous.cos(times, amp=amp, freq=freq, phase=np.pi/2) self.assertEqual(cos_arr.dtype, np.complex_) # Assert starts at 1 self.assertAlmostEqual(cos_arr[0], amp) self.assertAlmostEqual(cos_arr[6], 0.3644, places=2) self.assertAlmostEqual(cos_arr[25], -amp) self.assertAlmostEqual(cos_arr[50], amp) self.assertAlmostEqual(cos_arr_phased[0], 0.0) # Assert bounded between -amp and amp self.assertTrue(np.all((-amp <= cos_arr) & (cos_arr <= amp))) self.assertEqual(len(cos_arr), samples) def test_sin(self): """Test sine wave.""" amp = 0.5 period = 5 freq = 1/period samples = 101 times = np.linspace(0, 10, samples) sin_arr = continuous.sin(times, amp=amp, freq=freq) # with new phase sin_arr_phased = continuous.sin(times, amp=0.5, freq=1/5, phase=np.pi/2) self.assertEqual(sin_arr.dtype, np.complex_) # Assert starts at 1 self.assertAlmostEqual(sin_arr[0], 0.0) self.assertAlmostEqual(sin_arr[6], 0.3427, places=2) self.assertAlmostEqual(sin_arr[25], 0.0) self.assertAlmostEqual(sin_arr[13], amp, places=2) self.assertAlmostEqual(sin_arr_phased[0], amp) # Assert bounded between -amp and amp self.assertTrue(np.all((-amp <= sin_arr) & (sin_arr <= amp))) self.assertEqual(len(sin_arr), samples) def test_gaussian(self): """Test gaussian pulse.""" amp = 0.5 center = 10 sigma = 2 times, dt = np.linspace(0, 20, 1001, retstep=True) gaussian_arr = continuous.gaussian(times, amp, center, sigma) gaussian_arr_zeroed = continuous.gaussian(np.array([-1, 10]), amp, center, sigma, zeroed_width=2*(center+1), rescale_amp=True) self.assertEqual(gaussian_arr.dtype, np.complex_) center_time = np.argmax(gaussian_arr) self.assertAlmostEqual(times[center_time], center) self.assertAlmostEqual(gaussian_arr[center_time], amp) self.assertAlmostEqual(gaussian_arr_zeroed[0], 0., places=6) self.assertAlmostEqual(gaussian_arr_zeroed[1], amp) self.assertAlmostEqual(np.sum(gaussian_arr*dt), amp*np.sqrt(2*np.pi*sigma**2), places=3) def test_gaussian_deriv(self): """Test gaussian derivative pulse.""" amp = 0.5 center = 10 sigma = 2 times, dt = np.linspace(0, 20, 1000, retstep=True) deriv_prefactor = -sigma**2/(times-center) gaussian_deriv_arr = continuous.gaussian_deriv(times, amp, center, sigma) gaussian_arr = gaussian_deriv_arr*deriv_prefactor self.assertEqual(gaussian_deriv_arr.dtype, np.complex_) self.assertAlmostEqual(continuous.gaussian_deriv(np.array([0]), amp, center, sigma)[0], 0, places=5) self.assertAlmostEqual(np.sum(gaussian_arr*dt), amp*np.sqrt(2*np.pi*sigma**2), places=3) def test_gaussian_square(self): """Test gaussian square pulse.""" amp = 0.5 center = 10 width = 2 sigma = 0.1 times, dt = np.linspace(0, 20, 2001, retstep=True) gaussian_square_arr = continuous.gaussian_square(times, amp, center, width, sigma) self.assertEqual(gaussian_square_arr.dtype, np.complex_) self.assertEqual(gaussian_square_arr[1000], amp) # test half gaussian rise/fall self.assertAlmostEqual(np.sum(gaussian_square_arr[:900]*dt)*2, amp*np.sqrt(2*np.pi*sigma**2), places=2) self.assertAlmostEqual(np.sum(gaussian_square_arr[1100:]*dt)*2, amp*np.sqrt(2*np.pi*sigma**2), places=2) # test for continuity at gaussian/square boundaries gauss_rise_end_time = center-width/2 gauss_fall_start_time = center+width/2 epsilon = 0.01 rise_times, dt_rise = np.linspace(gauss_rise_end_time-epsilon, gauss_rise_end_time+epsilon, 1001, retstep=True) fall_times, dt_fall = np.linspace(gauss_fall_start_time-epsilon, gauss_fall_start_time+epsilon, 1001, retstep=True) gaussian_square_rise_arr = continuous.gaussian_square(rise_times, amp, center, width, sigma) gaussian_square_fall_arr = continuous.gaussian_square(fall_times, amp, center, width, sigma) # should be locally approximated by amp*dt^2/(2*sigma^2) self.assertAlmostEqual(amp*dt_rise**2/(2*sigma**2), gaussian_square_rise_arr[500]-gaussian_square_rise_arr[499]) self.assertAlmostEqual(amp*dt_fall**2/(2*sigma**2), gaussian_square_fall_arr[501]-gaussian_square_fall_arr[500]) def test_drag(self): """Test drag pulse.""" amp = 0.5 center = 10 sigma = 0.1 beta = 0 times = np.linspace(0, 20, 2001) # test that we recover gaussian for beta=0 gaussian_arr = continuous.gaussian(times, amp, center, sigma, zeroed_width=2*(center+1), rescale_amp=True) drag_arr = continuous.drag(times, amp, center, sigma, beta=beta, zeroed_width=2*(center+1), rescale_amp=True) self.assertEqual(drag_arr.dtype, np.complex_) np.testing.assert_equal(drag_arr, gaussian_arr)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # 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 discrete sampled pulse functions.""" import numpy as np from qiskit.test import QiskitTestCase from qiskit.pulse import SamplePulse import qiskit.pulse.pulse_lib as pulse_lib import qiskit.pulse.pulse_lib.continuous as continuous class TestDiscretePulses(QiskitTestCase): """Test discreted sampled pulses.""" def test_constant(self): """Test discrete sampled constant pulse.""" amp = 0.5j duration = 10 times = np.arange(0, duration) constant_ref = continuous.constant(times, amp=amp) constant_pulse = pulse_lib.constant(duration, amp=amp) self.assertIsInstance(constant_pulse, SamplePulse) np.testing.assert_array_almost_equal(constant_pulse.samples, constant_ref) def test_zero(self): """Test discrete sampled constant pulse.""" duration = 10 times = np.arange(0, duration) zero_ref = continuous.zero(times) zero_pulse = pulse_lib.zero(duration) self.assertIsInstance(zero_pulse, SamplePulse) np.testing.assert_array_almost_equal(zero_pulse.samples, zero_ref) def test_square(self): """Test discrete sampled square wave.""" amp = 0.5 period = 5 duration = 10 times = np.arange(0, duration) square_ref = continuous.square(times, amp=amp, period=period) square_pulse = pulse_lib.square(duration, amp=amp, period=period) self.assertIsInstance(square_pulse, SamplePulse) np.testing.assert_array_almost_equal(square_pulse.samples, square_ref) # test single cycle cycle_period = duration square_cycle_ref = continuous.square(times, amp=amp, period=cycle_period) square_cycle_pulse = pulse_lib.square(duration, amp=amp) np.testing.assert_array_almost_equal(square_cycle_pulse.samples, square_cycle_ref) def test_sawtooth(self): """Test discrete sampled sawtooth wave.""" amp = 0.5 period = 5 duration = 10 times = np.arange(0, duration) sawtooth_ref = continuous.sawtooth(times, amp=amp, period=period) sawtooth_pulse = pulse_lib.sawtooth(duration, amp=amp, period=period) self.assertIsInstance(sawtooth_pulse, SamplePulse) np.testing.assert_array_equal(sawtooth_pulse.samples, sawtooth_ref) # test single cycle cycle_period = duration sawtooth_cycle_ref = continuous.sawtooth(times, amp=amp, period=cycle_period) sawtooth_cycle_pulse = pulse_lib.sawtooth(duration, amp=amp) np.testing.assert_array_almost_equal(sawtooth_cycle_pulse.samples, sawtooth_cycle_ref) def test_triangle(self): """Test discrete sampled triangle wave.""" amp = 0.5 period = 5 duration = 10 times = np.arange(0, duration) triangle_ref = continuous.triangle(times, amp=amp, period=period) triangle_pulse = pulse_lib.triangle(duration, amp=amp, period=period) self.assertIsInstance(triangle_pulse, SamplePulse) np.testing.assert_array_almost_equal(triangle_pulse.samples, triangle_ref) # test single cycle cycle_period = duration triangle_cycle_ref = continuous.triangle(times, amp=amp, period=cycle_period) triangle_cycle_pulse = pulse_lib.triangle(duration, amp=amp) np.testing.assert_array_equal(triangle_cycle_pulse.samples, triangle_cycle_ref) def test_cos(self): """Test discrete sampled cosine wave.""" amp = 0.5 period = 5 freq = 1/period duration = 10 times = np.arange(0, duration) cos_ref = continuous.cos(times, amp=amp, freq=freq) cos_pulse = pulse_lib.cos(duration, amp=amp, freq=freq) self.assertIsInstance(cos_pulse, SamplePulse) np.testing.assert_array_almost_equal(cos_pulse.samples, cos_ref) # test single cycle cycle_freq = 1/duration cos_cycle_ref = continuous.cos(times, amp=amp, freq=cycle_freq) cos_cycle_pulse = pulse_lib.cos(duration, amp=amp) np.testing.assert_array_almost_equal(cos_cycle_pulse.samples, cos_cycle_ref) def test_sin(self): """Test discrete sampled sine wave.""" amp = 0.5 period = 5 freq = 1/period duration = 10 times = np.arange(0, duration) sin_ref = continuous.sin(times, amp=amp, freq=freq) sin_pulse = pulse_lib.sin(duration, amp=amp, freq=freq) self.assertIsInstance(sin_pulse, SamplePulse) np.testing.assert_array_equal(sin_pulse.samples, sin_ref) # test single cycle cycle_freq = 1/duration sin_cycle_ref = continuous.sin(times, amp=amp, freq=cycle_freq) sin_cycle_pulse = pulse_lib.sin(duration, amp=amp) np.testing.assert_array_almost_equal(sin_cycle_pulse.samples, sin_cycle_ref) def test_gaussian(self): """Test gaussian pulse.""" amp = 0.5 sigma = 2 duration = 10 center = duration/2 times = np.arange(0, duration) gaussian_ref = continuous.gaussian(times, amp, center, sigma, zeroed_width=2*(center+1), rescale_amp=True) gaussian_pulse = pulse_lib.gaussian(duration, amp, sigma) self.assertIsInstance(gaussian_pulse, SamplePulse) np.testing.assert_array_almost_equal(gaussian_pulse.samples, gaussian_ref) def test_gaussian_deriv(self): """Test discrete sampled gaussian derivative pulse.""" amp = 0.5 sigma = 2 duration = 10 center = duration/2 times = np.arange(0, duration) gaussian_deriv_ref = continuous.gaussian_deriv(times, amp, center, sigma) gaussian_deriv_pulse = pulse_lib.gaussian_deriv(duration, amp, sigma) self.assertIsInstance(gaussian_deriv_pulse, SamplePulse) np.testing.assert_array_almost_equal(gaussian_deriv_pulse.samples, gaussian_deriv_ref) def test_gaussian_square(self): """Test discrete sampled gaussian square pulse.""" amp = 0.5 sigma = 0.1 risefall = 2 duration = 10 center = duration/2 width = duration-2*risefall center = duration/2 times = np.arange(0, duration) gaussian_square_ref = continuous.gaussian_square(times, amp, center, width, sigma) gaussian_square_pulse = pulse_lib.gaussian_square(duration, amp, sigma, risefall) self.assertIsInstance(gaussian_square_pulse, SamplePulse) np.testing.assert_array_almost_equal(gaussian_square_pulse.samples, gaussian_square_ref) def test_drag(self): """Test discrete sampled drag pulse.""" amp = 0.5 sigma = 0.1 beta = 0 duration = 10 center = 10/2 times = np.arange(0, duration) # reference drag pulse drag_ref = continuous.drag(times, amp, center, sigma, beta=beta, zeroed_width=2*(center+1), rescale_amp=True) drag_pulse = pulse_lib.drag(duration, amp, sigma, beta=beta) self.assertIsInstance(drag_pulse, SamplePulse) np.testing.assert_array_almost_equal(drag_pulse.samples, drag_ref)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # 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 pulse function samplers.""" import numpy as np from qiskit.test import QiskitTestCase import qiskit.pulse.commands as commands import qiskit.pulse.samplers as samplers def linear(times: np.ndarray, m: float, b: float = 0.1) -> np.ndarray: """Linear test function Args: times: Input times. m: Slope. b: Intercept Returns: np.ndarray """ return m*times+b class TestSampler(QiskitTestCase): """Test continuous pulse function samplers.""" def test_left_sampler(self): """Test left sampler.""" m = 0.1 b = 0.1 duration = 2 left_linear_pulse_fun = samplers.left(linear) reference = np.array([0.1, 0.2], dtype=np.complex) pulse = left_linear_pulse_fun(duration, m=m, b=b) self.assertIsInstance(pulse, commands.SamplePulse) np.testing.assert_array_almost_equal(pulse.samples, reference) def test_right_sampler(self): """Test right sampler.""" m = 0.1 b = 0.1 duration = 2 right_linear_pulse_fun = samplers.right(linear) reference = np.array([0.2, 0.3], dtype=np.complex) pulse = right_linear_pulse_fun(duration, m=m, b=b) self.assertIsInstance(pulse, commands.SamplePulse) np.testing.assert_array_almost_equal(pulse.samples, reference) def test_midpoint_sampler(self): """Test midpoint sampler.""" m = 0.1 b = 0.1 duration = 2 midpoint_linear_pulse_fun = samplers.midpoint(linear) reference = np.array([0.15, 0.25], dtype=np.complex) pulse = midpoint_linear_pulse_fun(duration, m=m, b=b) self.assertIsInstance(pulse, commands.SamplePulse) np.testing.assert_array_almost_equal(pulse.samples, reference) def test_sampler_name(self): """Test that sampler setting of pulse name works.""" m = 0.1 b = 0.1 duration = 2 left_linear_pulse_fun = samplers.left(linear) pulse = left_linear_pulse_fun(duration, m=m, b=b, name='test') self.assertIsInstance(pulse, commands.SamplePulse) self.assertEqual(pulse.name, 'test') def test_default_arg_sampler(self): """Test that default arguments work with sampler.""" m = 0.1 duration = 2 left_linear_pulse_fun = samplers.left(linear) reference = np.array([0.1, 0.2], dtype=np.complex) pulse = left_linear_pulse_fun(duration, m=m) self.assertIsInstance(pulse, commands.SamplePulse) np.testing.assert_array_almost_equal(pulse.samples, reference)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Qobj tests.""" import copy from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.compiler import assemble from qiskit.qobj import ( QasmQobj, PulseQobj, QobjHeader, PulseQobjInstruction, PulseQobjExperiment, PulseQobjConfig, QobjMeasurementOption, PulseLibraryItem, QasmQobjInstruction, QasmQobjExperiment, QasmQobjConfig, QasmExperimentCalibrations, GateCalibration, ) from qiskit.test import QiskitTestCase class TestQASMQobj(QiskitTestCase): """Tests for QasmQobj.""" def setUp(self): super().setUp() self.valid_qobj = QasmQobj( qobj_id="12345", header=QobjHeader(), config=QasmQobjConfig(shots=1024, memory_slots=2), experiments=[ QasmQobjExperiment( instructions=[ QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]), QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]), ] ) ], ) self.valid_dict = { "qobj_id": "12345", "type": "QASM", "schema_version": "1.2.0", "header": {}, "config": {"memory_slots": 2, "shots": 1024}, "experiments": [ { "instructions": [ {"name": "u1", "params": [0.4], "qubits": [1]}, {"name": "u2", "params": [0.4, 0.2], "qubits": [1]}, ] } ], } self.bad_qobj = copy.deepcopy(self.valid_qobj) self.bad_qobj.experiments = [] def test_from_dict_per_class(self): """Test Qobj and its subclass representations given a dictionary.""" test_parameters = { QasmQobj: (self.valid_qobj, self.valid_dict), QasmQobjConfig: ( QasmQobjConfig(shots=1, memory_slots=2), {"shots": 1, "memory_slots": 2}, ), QasmQobjExperiment: ( QasmQobjExperiment( instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])] ), {"instructions": [{"name": "u1", "qubits": [1], "params": [0.4]}]}, ), QasmQobjInstruction: ( QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]), {"name": "u1", "qubits": [1], "params": [0.4]}, ), } for qobj_class, (qobj_item, expected_dict) in test_parameters.items(): with self.subTest(msg=str(qobj_class)): self.assertEqual(qobj_item, qobj_class.from_dict(expected_dict)) def test_snapshot_instruction_to_dict(self): """Test snapshot instruction to dict.""" valid_qobj = QasmQobj( qobj_id="12345", header=QobjHeader(), config=QasmQobjConfig(shots=1024, memory_slots=2), experiments=[ QasmQobjExperiment( instructions=[ QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]), QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]), QasmQobjInstruction( name="snapshot", qubits=[1], snapshot_type="statevector", label="my_snap", ), ] ) ], ) res = valid_qobj.to_dict() expected_dict = { "qobj_id": "12345", "type": "QASM", "schema_version": "1.3.0", "header": {}, "config": {"memory_slots": 2, "shots": 1024}, "experiments": [ { "instructions": [ {"name": "u1", "params": [0.4], "qubits": [1]}, {"name": "u2", "params": [0.4, 0.2], "qubits": [1]}, { "name": "snapshot", "qubits": [1], "snapshot_type": "statevector", "label": "my_snap", }, ], "config": {}, "header": {}, } ], } self.assertEqual(expected_dict, res) def test_snapshot_instruction_from_dict(self): """Test snapshot instruction from dict.""" expected_qobj = QasmQobj( qobj_id="12345", header=QobjHeader(), config=QasmQobjConfig(shots=1024, memory_slots=2), experiments=[ QasmQobjExperiment( instructions=[ QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]), QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]), QasmQobjInstruction( name="snapshot", qubits=[1], snapshot_type="statevector", label="my_snap", ), ] ) ], ) qobj_dict = { "qobj_id": "12345", "type": "QASM", "schema_version": "1.2.0", "header": {}, "config": {"memory_slots": 2, "shots": 1024}, "experiments": [ { "instructions": [ {"name": "u1", "params": [0.4], "qubits": [1]}, {"name": "u2", "params": [0.4, 0.2], "qubits": [1]}, { "name": "snapshot", "qubits": [1], "snapshot_type": "statevector", "label": "my_snap", }, ] } ], } self.assertEqual(expected_qobj, QasmQobj.from_dict(qobj_dict)) def test_change_qobj_after_compile(self): """Test modifying Qobj parameters after compile.""" qr = QuantumRegister(3) cr = ClassicalRegister(3) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr[0]) qc1.cx(qr[0], qr[1]) qc1.cx(qr[0], qr[2]) qc2.h(qr) qc1.measure(qr, cr) qc2.measure(qr, cr) circuits = [qc1, qc2] qobj1 = assemble(circuits, shots=1024, seed=88) qobj1.experiments[0].config.shots = 50 qobj1.experiments[1].config.shots = 1 self.assertTrue(qobj1.experiments[0].config.shots == 50) self.assertTrue(qobj1.experiments[1].config.shots == 1) self.assertTrue(qobj1.config.shots == 1024) def test_gate_calibrations_to_dict(self): """Test gate calibrations to dict.""" pulse_library = [PulseLibraryItem(name="test", samples=[1j, 1j])] valid_qobj = QasmQobj( qobj_id="12345", header=QobjHeader(), config=QasmQobjConfig(shots=1024, memory_slots=2, pulse_library=pulse_library), experiments=[ QasmQobjExperiment( instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])], config=QasmQobjConfig( calibrations=QasmExperimentCalibrations( gates=[ GateCalibration( name="u1", qubits=[1], params=[0.4], instructions=[] ) ] ) ), ) ], ) res = valid_qobj.to_dict() expected_dict = { "qobj_id": "12345", "type": "QASM", "schema_version": "1.3.0", "header": {}, "config": { "memory_slots": 2, "shots": 1024, "pulse_library": [{"name": "test", "samples": [1j, 1j]}], }, "experiments": [ { "instructions": [{"name": "u1", "params": [0.4], "qubits": [1]}], "config": { "calibrations": { "gates": [ {"name": "u1", "qubits": [1], "params": [0.4], "instructions": []} ] } }, "header": {}, } ], } self.assertEqual(expected_dict, res) class TestPulseQobj(QiskitTestCase): """Tests for PulseQobj.""" def setUp(self): super().setUp() self.valid_qobj = PulseQobj( qobj_id="12345", header=QobjHeader(), config=PulseQobjConfig( shots=1024, memory_slots=2, meas_level=1, memory_slot_size=8192, meas_return="avg", pulse_library=[ PulseLibraryItem(name="pulse0", samples=[0.0 + 0.0j, 0.5 + 0.0j, 0.0 + 0.0j]) ], qubit_lo_freq=[4.9], meas_lo_freq=[6.9], rep_time=1000, ), experiments=[ PulseQobjExperiment( instructions=[ PulseQobjInstruction(name="pulse0", t0=0, ch="d0"), PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=1.57), PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=0.0), PulseQobjInstruction(name="fc", t0=5, ch="d0", phase="P1"), PulseQobjInstruction(name="setp", t0=10, ch="d0", phase=3.14), PulseQobjInstruction(name="setf", t0=10, ch="d0", frequency=8.0), PulseQobjInstruction(name="shiftf", t0=10, ch="d0", frequency=4.0), PulseQobjInstruction( name="acquire", t0=15, duration=5, qubits=[0], memory_slot=[0], kernels=[ QobjMeasurementOption( name="boxcar", params={"start_window": 0, "stop_window": 5} ) ], ), ] ) ], ) self.valid_dict = { "qobj_id": "12345", "type": "PULSE", "schema_version": "1.2.0", "header": {}, "config": { "memory_slots": 2, "shots": 1024, "meas_level": 1, "memory_slot_size": 8192, "meas_return": "avg", "pulse_library": [{"name": "pulse0", "samples": [0, 0.5, 0]}], "qubit_lo_freq": [4.9], "meas_lo_freq": [6.9], "rep_time": 1000, }, "experiments": [ { "instructions": [ {"name": "pulse0", "t0": 0, "ch": "d0"}, {"name": "fc", "t0": 5, "ch": "d0", "phase": 1.57}, {"name": "fc", "t0": 5, "ch": "d0", "phase": 0}, {"name": "fc", "t0": 5, "ch": "d0", "phase": "P1"}, {"name": "setp", "t0": 10, "ch": "d0", "phase": 3.14}, {"name": "setf", "t0": 10, "ch": "d0", "frequency": 8.0}, {"name": "shiftf", "t0": 10, "ch": "d0", "frequency": 4.0}, { "name": "acquire", "t0": 15, "duration": 5, "qubits": [0], "memory_slot": [0], "kernels": [ {"name": "boxcar", "params": {"start_window": 0, "stop_window": 5}} ], }, ] } ], } def test_from_dict_per_class(self): """Test converting to Qobj and its subclass representations given a dictionary.""" test_parameters = { PulseQobj: (self.valid_qobj, self.valid_dict), PulseQobjConfig: ( PulseQobjConfig( meas_level=1, memory_slot_size=8192, meas_return="avg", pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])], qubit_lo_freq=[4.9], meas_lo_freq=[6.9], rep_time=1000, ), { "meas_level": 1, "memory_slot_size": 8192, "meas_return": "avg", "pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}], "qubit_lo_freq": [4.9], "meas_lo_freq": [6.9], "rep_time": 1000, }, ), PulseLibraryItem: ( PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]), {"name": "pulse0", "samples": [0.1 + 0j]}, ), PulseQobjExperiment: ( PulseQobjExperiment( instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")] ), {"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]}, ), PulseQobjInstruction: ( PulseQobjInstruction(name="pulse0", t0=0, ch="d0"), {"name": "pulse0", "t0": 0, "ch": "d0"}, ), } for qobj_class, (qobj_item, expected_dict) in test_parameters.items(): with self.subTest(msg=str(qobj_class)): self.assertEqual(qobj_item, qobj_class.from_dict(expected_dict)) def test_to_dict_per_class(self): """Test converting from Qobj and its subclass representations given a dictionary.""" test_parameters = { PulseQobj: (self.valid_qobj, self.valid_dict), PulseQobjConfig: ( PulseQobjConfig( meas_level=1, memory_slot_size=8192, meas_return="avg", pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])], qubit_lo_freq=[4.9], meas_lo_freq=[6.9], rep_time=1000, ), { "meas_level": 1, "memory_slot_size": 8192, "meas_return": "avg", "pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}], "qubit_lo_freq": [4.9], "meas_lo_freq": [6.9], "rep_time": 1000, }, ), PulseLibraryItem: ( PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]), {"name": "pulse0", "samples": [0.1 + 0j]}, ), PulseQobjExperiment: ( PulseQobjExperiment( instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")] ), {"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]}, ), PulseQobjInstruction: ( PulseQobjInstruction(name="pulse0", t0=0, ch="d0"), {"name": "pulse0", "t0": 0, "ch": "d0"}, ), } for qobj_class, (qobj_item, expected_dict) in test_parameters.items(): with self.subTest(msg=str(qobj_class)): self.assertEqual(qobj_item.to_dict(), expected_dict) def _nop(): pass
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for qiskit.quantum_info.analysis""" import unittest import qiskit from qiskit import BasicAer from qiskit.quantum_info.analysis.average import average_data from qiskit.quantum_info.analysis.make_observable import make_dict_observable from qiskit.quantum_info.analysis import hellinger_fidelity from qiskit.test import QiskitTestCase class TestAnalyzation(QiskitTestCase): """Test qiskit.Result API""" def test_average_data_dict_observable(self): """Test average_data for dictionary observable input""" qr = qiskit.QuantumRegister(2) cr = qiskit.ClassicalRegister(2) qc = qiskit.QuantumCircuit(qr, cr, name="qc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) shots = 10000 backend = BasicAer.get_backend("qasm_simulator") result = qiskit.execute(qc, backend, shots=shots).result() counts = result.get_counts(qc) observable = {"00": 1, "11": 1, "01": -1, "10": -1} mean_zz = average_data(counts=counts, observable=observable) observable = {"00": 1, "11": -1, "01": 1, "10": -1} mean_zi = average_data(counts, observable) observable = {"00": 1, "11": -1, "01": -1, "10": 1} mean_iz = average_data(counts, observable) self.assertAlmostEqual(mean_zz, 1, places=1) self.assertAlmostEqual(mean_zi, 0, places=1) self.assertAlmostEqual(mean_iz, 0, places=1) def test_average_data_list_observable(self): """Test average_data for list observable input.""" qr = qiskit.QuantumRegister(3) cr = qiskit.ClassicalRegister(3) qc = qiskit.QuantumCircuit(qr, cr, name="qc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.cx(qr[0], qr[2]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) shots = 10000 backend = BasicAer.get_backend("qasm_simulator") result = qiskit.execute(qc, backend, shots=shots).result() counts = result.get_counts(qc) observable = [1, -1, -1, 1, -1, 1, 1, -1] mean_zzz = average_data(counts=counts, observable=observable) observable = [1, 1, 1, 1, -1, -1, -1, -1] mean_zii = average_data(counts, observable) observable = [1, 1, -1, -1, 1, 1, -1, -1] mean_izi = average_data(counts, observable) observable = [1, 1, -1, -1, -1, -1, 1, 1] mean_zzi = average_data(counts, observable) self.assertAlmostEqual(mean_zzz, 0, places=1) self.assertAlmostEqual(mean_zii, 0, places=1) self.assertAlmostEqual(mean_izi, 0, places=1) self.assertAlmostEqual(mean_zzi, 1, places=1) def test_average_data_matrix_observable(self): """Test average_data for matrix observable input.""" qr = qiskit.QuantumRegister(2) cr = qiskit.ClassicalRegister(2) qc = qiskit.QuantumCircuit(qr, cr, name="qc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) shots = 10000 backend = BasicAer.get_backend("qasm_simulator") result = qiskit.execute(qc, backend, shots=shots).result() counts = result.get_counts(qc) observable = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]] mean_zz = average_data(counts=counts, observable=observable) observable = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]] mean_zi = average_data(counts, observable) observable = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]] mean_iz = average_data(counts, observable) self.assertAlmostEqual(mean_zz, 1, places=1) self.assertAlmostEqual(mean_zi, 0, places=1) self.assertAlmostEqual(mean_iz, 0, places=1) def test_make_dict_observable(self): """Test make_dict_observable.""" list_in = [1, 1, -1, -1] list_out = make_dict_observable(list_in) list_expected = {"00": 1, "01": 1, "10": -1, "11": -1} matrix_in = [[4, 0, 0, 0], [0, -3, 0, 0], [0, 0, 2, 0], [0, 0, 0, -1]] matrix_out = make_dict_observable(matrix_in) matrix_expected = {"00": 4, "01": -3, "10": 2, "11": -1} long_list_in = [1, 1, -1, -1, -1, -1, 1, 1] long_list_out = make_dict_observable(long_list_in) long_list_expected = { "000": 1, "001": 1, "010": -1, "011": -1, "100": -1, "101": -1, "110": 1, "111": 1, } self.assertEqual(list_out, list_expected) self.assertEqual(matrix_out, matrix_expected) self.assertEqual(long_list_out, long_list_expected) def test_hellinger_fidelity_same(self): """Test hellinger fidelity is one for same dist.""" qc = qiskit.QuantumCircuit(5, 5) qc.h(2) qc.cx(2, 1) qc.cx(2, 3) qc.cx(3, 4) qc.cx(1, 0) qc.measure(range(5), range(5)) sim = BasicAer.get_backend("qasm_simulator") res = qiskit.execute(qc, sim).result() ans = hellinger_fidelity(res.get_counts(), res.get_counts()) self.assertEqual(ans, 1.0) def test_hellinger_fidelity_no_overlap(self): """Test hellinger fidelity is zero for no overlap.""" # β”Œβ”€β”€β”€β” β”Œβ”€β” # q_0: ─────────── X β”œβ”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”Œβ”€β”€β”€β”β””β”€β”¬β”€β”˜ β””β•₯β”˜β”Œβ”€β” # q_1: ────── X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”Œβ”€β”€β”€β”β””β”€β”¬β”€β”˜ β•‘ β””β•₯β”˜β”Œβ”€β” # q_2: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β”Œβ”€β”΄β”€β” β•‘ β•‘ β””β•₯β”˜β”Œβ”€β” # q_3: ─────────── X β”œβ”€β”€β– β”€β”€β”€β•«β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€ # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β•‘ β•‘ β•‘ β””β•₯β”˜β”Œβ”€β” # q_4: ──────────────── X β”œβ”€β•«β”€β”€β•«β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ β•‘ β””β•₯β”˜ # c: 5/═════════════════════╩══╩══╩══╩══╩═ # 0 1 2 3 4 qc = qiskit.QuantumCircuit(5, 5) qc.h(2) qc.cx(2, 1) qc.cx(2, 3) qc.cx(3, 4) qc.cx(1, 0) qc.measure(range(5), range(5)) # β”Œβ”€β”€β”€β” β”Œβ”€β” # q_0: ─────────── X β”œβ”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”Œβ”€β”€β”€β”β””β”€β”¬β”€β”˜ β””β•₯β”˜β”Œβ”€β” # q_1: ────── X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β”Œβ”€β”€β”€β”β””β”€β”¬β”€β”˜β”Œβ”€β”€β”€β” β•‘ β””β•₯β”˜β”Œβ”€β” # q_2: ─ H β”œβ”€β”€β– β”€β”€β”€ Y β”œβ”€β”€β– β”€β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€ # β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β•‘ β•‘ β””β•₯β”˜β”Œβ”€β” # q_3: ──────────────── X β”œβ”€β•«β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œ # β”Œβ”€β” β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ β””β•₯β”˜ # q_4: ──Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β•«β”€β”€β•«β”€β”€β•«β”€ # β””β•₯β”˜ β•‘ β•‘ β•‘ β•‘ # c: 5/══╩══════════════════╩══╩══╩══╩═ # 4 0 1 2 3 qc2 = qiskit.QuantumCircuit(5, 5) qc2.h(2) qc2.cx(2, 1) qc2.y(2) qc2.cx(2, 3) qc2.cx(1, 0) qc2.measure(range(5), range(5)) sim = BasicAer.get_backend("qasm_simulator") res1 = qiskit.execute(qc, sim).result() res2 = qiskit.execute(qc2, sim).result() ans = hellinger_fidelity(res1.get_counts(), res2.get_counts()) self.assertEqual(ans, 0.0) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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=invalid-name,missing-docstring """Quick program to test the quantum information states modules.""" import unittest import numpy as np from qiskit import execute, QuantumRegister, QuantumCircuit, BasicAer from qiskit.quantum_info import basis_state, random_state from qiskit.quantum_info import state_fidelity from qiskit.quantum_info import projector from qiskit.quantum_info import purity from qiskit.test import QiskitTestCase class TestStates(QiskitTestCase): """Tests for qi.py""" def test_state_fidelity(self): psi1 = [0.70710678118654746, 0, 0, 0.70710678118654746] psi2 = [0., 0.70710678118654746, 0.70710678118654746, 0.] rho1 = [[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]] mix = [[0.25, 0, 0, 0], [0, 0.25, 0, 0], [0, 0, 0.25, 0], [0, 0, 0, 0.25]] self.assertAlmostEqual(state_fidelity(psi1, psi1), 1.0, places=7, msg='vector-vector input') self.assertAlmostEqual(state_fidelity(psi1, psi2), 0.0, places=7, msg='vector-vector input') self.assertAlmostEqual(state_fidelity(psi1, rho1), 1.0, places=7, msg='vector-matrix input') self.assertAlmostEqual(state_fidelity(psi1, mix), 0.25, places=7, msg='vector-matrix input') self.assertAlmostEqual(state_fidelity(psi2, rho1), 0.0, places=7, msg='vector-matrix input') self.assertAlmostEqual(state_fidelity(psi2, mix), 0.25, places=7, msg='vector-matrix input') self.assertAlmostEqual(state_fidelity(rho1, psi1), 1.0, places=7, msg='matrix-vector input') self.assertAlmostEqual(state_fidelity(rho1, rho1), 1.0, places=7, msg='matrix-matrix input') self.assertAlmostEqual(state_fidelity(mix, mix), 1.0, places=7, msg='matrix-matrix input') def test_state_fidelity_qubit(self): state0 = np.array([1.+0.j, 0.+0.j]) state1 = np.array([0.+0.j, 1.+0.j]) self.assertEqual(state_fidelity(state0, state0), 1.0) self.assertEqual(state_fidelity(state1, state1), 1.0) self.assertEqual(state_fidelity(state0, state1), 0.0) def test_projector(self): state0 = np.array([1.+0.j, 0.+0.j]) state1 = projector(np.array([0.+0.j, 1.+0.j])) self.assertEqual(state_fidelity(state0, state0), 1.0) self.assertEqual(state_fidelity(state1, state1), 1.0) self.assertEqual(state_fidelity(state0, state1), 0.0) def test_basis(self): # reference state = basis_state('010', 3) state_ideal = np.array([0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j]) state_fidelity(state, state_ideal) self.assertEqual(state_fidelity(state, state_ideal), 1.0) def test_basis_state_circuit(self): state = state = (basis_state('001', 3)+basis_state('111', 3))/np.sqrt(2) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.initialize(state, [q[0], q[1], q[2]]) backend = BasicAer.get_backend('statevector_simulator') qc_state = execute(qc, backend).result().get_statevector(qc) self.assertAlmostEqual(state_fidelity(qc_state, state), 1.0, places=7) def test_random_state(self): # this test that a random state converges to 1/d number = 100000 E_P0_last = 0 for ii in range(number): state = basis_state(bin(3)[2:].zfill(3), 3) E_P0 = (E_P0_last*ii)/(ii+1)+state_fidelity(state, random_state(2**3, seed=ii))/(ii+1) E_P0_last = E_P0 self.assertAlmostEqual(E_P0, 1/8, places=2) def test_random_state_circuit(self): state = random_state(2**3, seed=40) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.initialize(state, [q[0], q[1], q[2]]) backend = BasicAer.get_backend('statevector_simulator') qc_state = execute(qc, backend).result().get_statevector(qc) self.assertAlmostEqual(state_fidelity(qc_state, state), 1.0, places=7) def test_purity_list_input(self): rho1 = [[1, 0], [0, 0]] rho2 = [[0.5, 0], [0, 0.5]] rho3 = 0.7 * np.array(rho1) + 0.3 * np.array(rho2) test_pass = (purity(rho1) == 1.0 and purity(rho2) == 0.5 and round(purity(rho3), 10) == 0.745) self.assertTrue(test_pass) def test_purity_1d_list_input(self): input_state = [1, 0] res = purity(input_state) self.assertEqual(1, res) def test_purity_basis_state_input(self): state_1 = basis_state('0', 1) state_2 = basis_state('11', 2) state_3 = basis_state('010', 3) self.assertEqual(purity(state_1), 1.0) self.assertEqual(purity(state_2), 1.0) self.assertEqual(purity(state_3), 1.0) def test_purity_pure_state(self): state_1 = (1/np.sqrt(2))*(basis_state('0', 1) + basis_state('1', 1)) state_2 = (1/np.sqrt(3))*(basis_state('00', 2) + basis_state('01', 2) + basis_state('11', 2)) state_3 = 0.5*(basis_state('000', 3) + basis_state('001', 3) + basis_state('010', 3) + basis_state('100', 3)) self.assertEqual(purity(state_1), 1.0) self.assertEqual(purity(state_2), 1.0) self.assertEqual(purity(state_3), 1.0) def test_purity_pure_matrix_state(self): state_1 = (1/np.sqrt(2))*(basis_state('0', 1) + basis_state('1', 1)) state_1 = projector(state_1) state_2 = (1/np.sqrt(3))*(basis_state('00', 2) + basis_state('01', 2) + basis_state('11', 2)) state_2 = projector(state_2) state_3 = 0.5*(basis_state('000', 3) + basis_state('001', 3) + basis_state('010', 3) + basis_state('100', 3)) state_3 = projector(state_3) self.assertAlmostEqual(purity(state_1), 1.0, places=10) self.assertAlmostEqual(purity(state_2), 1.0, places=10) self.assertEqual(purity(state_3), 1.0) def test_purity_mixed_state(self): state_1 = 0.5*(projector(basis_state('0', 1)) + projector(basis_state('1', 1))) state_2 = (1/3.0)*(projector(basis_state('00', 2)) + projector(basis_state('01', 2)) + projector(basis_state('10', 2))) self.assertEqual(purity(state_1), 0.5) self.assertEqual(purity(state_2), 1.0/3) if __name__ == '__main__': unittest.main()
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. """Randomized tests of quantum synthesis.""" import unittest from test.python.quantum_info.test_synthesis import CheckDecompositions from hypothesis import given, strategies, settings import numpy as np from qiskit import execute from qiskit.circuit import QuantumCircuit, QuantumRegister from qiskit.extensions import UnitaryGate from qiskit.providers.basicaer import UnitarySimulatorPy from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.synthesis.two_qubit_decompose import ( two_qubit_cnot_decompose, TwoQubitBasisDecomposer, Ud, ) class TestSynthesis(CheckDecompositions): """Test synthesis""" seed = strategies.integers(min_value=0, max_value=2**32 - 1) rotation = strategies.floats(min_value=-np.pi * 10, max_value=np.pi * 10) @given(seed) def test_1q_random(self, seed): """Checks one qubit decompositions""" unitary = random_unitary(2, seed=seed) self.check_one_qubit_euler_angles(unitary) self.check_one_qubit_euler_angles(unitary, "U3") self.check_one_qubit_euler_angles(unitary, "U1X") self.check_one_qubit_euler_angles(unitary, "PSX") self.check_one_qubit_euler_angles(unitary, "ZSX") self.check_one_qubit_euler_angles(unitary, "ZYZ") self.check_one_qubit_euler_angles(unitary, "ZXZ") self.check_one_qubit_euler_angles(unitary, "XYX") self.check_one_qubit_euler_angles(unitary, "RR") @settings(deadline=None) @given(seed) def test_2q_random(self, seed): """Checks two qubit decompositions""" unitary = random_unitary(4, seed=seed) self.check_exact_decomposition(unitary.data, two_qubit_cnot_decompose) @given(strategies.tuples(*[seed] * 5)) def test_exact_supercontrolled_decompose_random(self, seeds): """Exact decomposition for random supercontrolled basis and random target""" k1 = np.kron(random_unitary(2, seed=seeds[0]).data, random_unitary(2, seed=seeds[1]).data) k2 = np.kron(random_unitary(2, seed=seeds[2]).data, random_unitary(2, seed=seeds[3]).data) basis_unitary = k1 @ Ud(np.pi / 4, 0, 0) @ k2 decomposer = TwoQubitBasisDecomposer(UnitaryGate(basis_unitary)) self.check_exact_decomposition(random_unitary(4, seed=seeds[4]).data, decomposer) @given(strategies.tuples(*[rotation] * 6), seed) def test_cx_equivalence_0cx_random(self, rnd, seed): """Check random circuits with 0 cx gates locally equivalent to identity.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 0) @given(strategies.tuples(*[rotation] * 12), seed) def test_cx_equivalence_1cx_random(self, rnd, seed): """Check random circuits with 1 cx gates locally equivalent to a cx.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[6], rnd[7], rnd[8], qr[0]) qc.u(rnd[9], rnd[10], rnd[11], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 1) @given(strategies.tuples(*[rotation] * 18), seed) def test_cx_equivalence_2cx_random(self, rnd, seed): """Check random circuits with 2 cx gates locally equivalent to some circuit with 2 cx.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[6], rnd[7], rnd[8], qr[0]) qc.u(rnd[9], rnd[10], rnd[11], qr[1]) qc.cx(qr[0], qr[1]) qc.u(rnd[12], rnd[13], rnd[14], qr[0]) qc.u(rnd[15], rnd[16], rnd[17], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 2) @given(strategies.tuples(*[rotation] * 24), seed) def test_cx_equivalence_3cx_random(self, rnd, seed): """Check random circuits with 3 cx gates are outside the 0, 1, and 2 qubit regions.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[6], rnd[7], rnd[8], qr[0]) qc.u(rnd[9], rnd[10], rnd[11], qr[1]) qc.cx(qr[0], qr[1]) qc.u(rnd[12], rnd[13], rnd[14], qr[0]) qc.u(rnd[15], rnd[16], rnd[17], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[18], rnd[19], rnd[20], qr[0]) qc.u(rnd[21], rnd[22], rnd[23], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 3) if __name__ == "__main__": unittest.main()
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. # pylint: disable=invalid-name """Tests for Operator matrix linear operator class.""" import unittest import logging import copy from test import combine import numpy as np from ddt import ddt from numpy.testing import assert_allclose import scipy.linalg as la from qiskit import QiskitError from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit.library import HGate, CHGate, CXGate, QFT from qiskit.test import QiskitTestCase from qiskit.transpiler.layout import Layout, TranspileLayout from qiskit.quantum_info.operators import Operator, ScalarOp from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.compiler.transpiler import transpile from qiskit.circuit import Qubit from qiskit.circuit.library import Permutation, PermutationGate logger = logging.getLogger(__name__) class OperatorTestCase(QiskitTestCase): """Test utils for Operator""" # Pauli-matrix unitaries UI = np.eye(2) UX = np.array([[0, 1], [1, 0]]) UY = np.array([[0, -1j], [1j, 0]]) UZ = np.diag([1, -1]) UH = np.array([[1, 1], [1, -1]]) / np.sqrt(2) @classmethod def rand_rho(cls, n): """Return random density matrix""" seed = np.random.randint(0, np.iinfo(np.int32).max) logger.debug("rand_rho default_rng seeded with seed=%s", seed) rng = np.random.default_rng(seed) psi = rng.random(n) + 1j * rng.random(n) rho = np.outer(psi, psi.conj()) rho /= np.trace(rho) return rho @classmethod def rand_matrix(cls, rows, cols=None, real=False): """Return a random matrix.""" seed = np.random.randint(0, np.iinfo(np.int32).max) logger.debug("rand_matrix default_rng seeded with seed=%s", seed) rng = np.random.default_rng(seed) if cols is None: cols = rows if real: return rng.random(size=(rows, cols)) return rng.random(size=(rows, cols)) + 1j * rng.random(size=(rows, cols)) def simple_circuit_no_measure(self): """Return a unitary circuit and the corresponding unitary array.""" qr = QuantumRegister(3) circ = QuantumCircuit(qr) circ.h(qr[0]) circ.x(qr[1]) circ.ry(np.pi / 2, qr[2]) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = Operator(np.kron(y90, np.kron(self.UX, self.UH))) return circ, target def simple_circuit_with_measure(self): """Return a unitary circuit with measurement.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) circ = QuantumCircuit(qr, cr) circ.h(qr[0]) circ.x(qr[1]) circ.measure(qr, cr) return circ @ddt class TestOperator(OperatorTestCase): """Tests for Operator linear operator class.""" def test_init_array_qubit(self): """Test subsystem initialization from N-qubit array.""" # Test automatic inference of qubit subsystems mat = self.rand_matrix(8, 8) op = Operator(mat) assert_allclose(op.data, mat) self.assertEqual(op.dim, (8, 8)) self.assertEqual(op.input_dims(), (2, 2, 2)) self.assertEqual(op.output_dims(), (2, 2, 2)) self.assertEqual(op.num_qubits, 3) op = Operator(mat, input_dims=8, output_dims=8) assert_allclose(op.data, mat) self.assertEqual(op.dim, (8, 8)) self.assertEqual(op.input_dims(), (2, 2, 2)) self.assertEqual(op.output_dims(), (2, 2, 2)) self.assertEqual(op.num_qubits, 3) def test_init_array(self): """Test initialization from array.""" mat = np.eye(3) op = Operator(mat) assert_allclose(op.data, mat) self.assertEqual(op.dim, (3, 3)) self.assertEqual(op.input_dims(), (3,)) self.assertEqual(op.output_dims(), (3,)) self.assertIsNone(op.num_qubits) mat = self.rand_matrix(2 * 3 * 4, 4 * 5) op = Operator(mat, input_dims=[4, 5], output_dims=[2, 3, 4]) assert_allclose(op.data, mat) self.assertEqual(op.dim, (4 * 5, 2 * 3 * 4)) self.assertEqual(op.input_dims(), (4, 5)) self.assertEqual(op.output_dims(), (2, 3, 4)) self.assertIsNone(op.num_qubits) def test_init_array_except(self): """Test initialization exception from array.""" mat = self.rand_matrix(4, 4) self.assertRaises(QiskitError, Operator, mat, input_dims=[4, 2]) self.assertRaises(QiskitError, Operator, mat, input_dims=[2, 4]) self.assertRaises(QiskitError, Operator, mat, input_dims=5) def test_init_operator(self): """Test initialization from Operator.""" op1 = Operator(self.rand_matrix(4, 4)) op2 = Operator(op1) self.assertEqual(op1, op2) def test_circuit_init(self): """Test initialization from a circuit.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) op = Operator(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 0, 1) op = Operator(circuit) target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(0, 1) op = Operator(circuit) target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_instruction_init(self): """Test initialization from a circuit.""" gate = CXGate() op = Operator(gate).data target = gate.to_matrix() global_phase_equivalent = matrix_equal(op, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) gate = CHGate() op = Operator(gate).data had = HGate().to_matrix() target = np.kron(had, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0])) global_phase_equivalent = matrix_equal(op, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, Operator, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(2, 2, real=True) self.assertEqual(Operator(np.array(mat, dtype=complex)), Operator(mat)) mat = self.rand_matrix(4, 4) self.assertEqual(Operator(mat.tolist()), Operator(mat)) def test_data(self): """Test Operator representation string property.""" mat = self.rand_matrix(2, 2) op = Operator(mat) assert_allclose(mat, op.data) def test_to_matrix(self): """Test Operator to_matrix method.""" mat = self.rand_matrix(2, 2) op = Operator(mat) assert_allclose(mat, op.to_matrix()) def test_dim(self): """Test Operator dim property.""" mat = self.rand_matrix(4, 4) self.assertEqual(Operator(mat).dim, (4, 4)) self.assertEqual(Operator(mat, input_dims=[4], output_dims=[4]).dim, (4, 4)) self.assertEqual(Operator(mat, input_dims=[2, 2], output_dims=[2, 2]).dim, (4, 4)) def test_input_dims(self): """Test Operator input_dims method.""" op = Operator(self.rand_matrix(2 * 3 * 4, 4 * 5), input_dims=[4, 5], output_dims=[2, 3, 4]) self.assertEqual(op.input_dims(), (4, 5)) self.assertEqual(op.input_dims(qargs=[0, 1]), (4, 5)) self.assertEqual(op.input_dims(qargs=[1, 0]), (5, 4)) self.assertEqual(op.input_dims(qargs=[0]), (4,)) self.assertEqual(op.input_dims(qargs=[1]), (5,)) def test_output_dims(self): """Test Operator output_dims method.""" op = Operator(self.rand_matrix(2 * 3 * 4, 4 * 5), input_dims=[4, 5], output_dims=[2, 3, 4]) self.assertEqual(op.output_dims(), (2, 3, 4)) self.assertEqual(op.output_dims(qargs=[0, 1, 2]), (2, 3, 4)) self.assertEqual(op.output_dims(qargs=[2, 1, 0]), (4, 3, 2)) self.assertEqual(op.output_dims(qargs=[2, 0, 1]), (4, 2, 3)) self.assertEqual(op.output_dims(qargs=[0]), (2,)) self.assertEqual(op.output_dims(qargs=[1]), (3,)) self.assertEqual(op.output_dims(qargs=[2]), (4,)) self.assertEqual(op.output_dims(qargs=[0, 2]), (2, 4)) self.assertEqual(op.output_dims(qargs=[2, 0]), (4, 2)) def test_reshape(self): """Test Operator reshape method.""" op = Operator(self.rand_matrix(8, 8)) reshaped1 = op.reshape(input_dims=[8], output_dims=[8]) reshaped2 = op.reshape(input_dims=[4, 2], output_dims=[2, 4]) self.assertEqual(op.output_dims(), (2, 2, 2)) self.assertEqual(op.input_dims(), (2, 2, 2)) self.assertEqual(reshaped1.output_dims(), (8,)) self.assertEqual(reshaped1.input_dims(), (8,)) self.assertEqual(reshaped2.output_dims(), (2, 4)) self.assertEqual(reshaped2.input_dims(), (4, 2)) def test_reshape_num_qubits(self): """Test Operator reshape method with num_qubits.""" op = Operator(self.rand_matrix(8, 8), input_dims=(4, 2), output_dims=(2, 4)) reshaped = op.reshape(num_qubits=3) self.assertEqual(reshaped.num_qubits, 3) self.assertEqual(reshaped.output_dims(), (2, 2, 2)) self.assertEqual(reshaped.input_dims(), (2, 2, 2)) def test_reshape_raise(self): """Test Operator reshape method with invalid args.""" op = Operator(self.rand_matrix(3, 3)) self.assertRaises(QiskitError, op.reshape, num_qubits=2) def test_copy(self): """Test Operator copy method""" mat = np.eye(2) with self.subTest("Deep copy"): orig = Operator(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = Operator(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_unitary(self): """Test is_unitary method.""" # X-90 rotation X90 = la.expm(-1j * 0.5 * np.pi * np.array([[0, 1], [1, 0]]) / 2) self.assertTrue(Operator(X90).is_unitary()) # Non-unitary should return false self.assertFalse(Operator([[1, 0], [0, 0]]).is_unitary()) def test_to_operator(self): """Test to_operator method.""" op1 = Operator(self.rand_matrix(4, 4)) op2 = op1.to_operator() self.assertEqual(op1, op2) def test_conjugate(self): """Test conjugate method.""" matr = self.rand_matrix(2, 4, real=True) mati = self.rand_matrix(2, 4, real=True) op = Operator(matr + 1j * mati) uni_conj = op.conjugate() self.assertEqual(uni_conj, Operator(matr - 1j * mati)) def test_transpose(self): """Test transpose method.""" matr = self.rand_matrix(2, 4, real=True) mati = self.rand_matrix(2, 4, real=True) op = Operator(matr + 1j * mati) uni_t = op.transpose() self.assertEqual(uni_t, Operator(matr.T + 1j * mati.T)) def test_adjoint(self): """Test adjoint method.""" matr = self.rand_matrix(2, 4, real=True) mati = self.rand_matrix(2, 4, real=True) op = Operator(matr + 1j * mati) uni_adj = op.adjoint() self.assertEqual(uni_adj, Operator(matr.T - 1j * mati.T)) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, Operator(np.eye(2)).compose, Operator(np.eye(3))) self.assertRaises(QiskitError, Operator(np.eye(2)).compose, 2) def test_compose(self): """Test compose method.""" op1 = Operator(self.UX) op2 = Operator(self.UY) targ = Operator(np.dot(self.UY, self.UX)) self.assertEqual(op1.compose(op2), targ) self.assertEqual(op1 & op2, targ) targ = Operator(np.dot(self.UX, self.UY)) self.assertEqual(op2.compose(op1), targ) self.assertEqual(op2 & op1, targ) def test_dot(self): """Test dot method.""" op1 = Operator(self.UY) op2 = Operator(self.UX) targ = Operator(np.dot(self.UY, self.UX)) self.assertEqual(op1.dot(op2), targ) self.assertEqual(op1 @ op2, targ) targ = Operator(np.dot(self.UX, self.UY)) self.assertEqual(op2.dot(op1), targ) self.assertEqual(op2 @ op1, targ) def test_compose_front(self): """Test front compose method.""" opYX = Operator(self.UY).compose(Operator(self.UX), front=True) matYX = np.dot(self.UY, self.UX) self.assertEqual(opYX, Operator(matYX)) opXY = Operator(self.UX).compose(Operator(self.UY), front=True) matXY = np.dot(self.UX, self.UY) self.assertEqual(opXY, Operator(matXY)) def test_compose_subsystem(self): """Test subsystem compose method.""" # 3-qubit operator mat = self.rand_matrix(8, 8) mat_a = self.rand_matrix(2, 2) mat_b = self.rand_matrix(2, 2) mat_c = self.rand_matrix(2, 2) op = Operator(mat) op1 = Operator(mat_a) op2 = Operator(np.kron(mat_b, mat_a)) op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a))) # op3 qargs=[0, 1, 2] targ = np.dot(np.kron(mat_c, np.kron(mat_b, mat_a)), mat) self.assertEqual(op.compose(op3, qargs=[0, 1, 2]), Operator(targ)) self.assertEqual(op.compose(op3([0, 1, 2])), Operator(targ)) self.assertEqual(op & op3([0, 1, 2]), Operator(targ)) # op3 qargs=[2, 1, 0] targ = np.dot(np.kron(mat_a, np.kron(mat_b, mat_c)), mat) self.assertEqual(op.compose(op3, qargs=[2, 1, 0]), Operator(targ)) self.assertEqual(op & op3([2, 1, 0]), Operator(targ)) # op2 qargs=[0, 1] targ = np.dot(np.kron(np.eye(2), np.kron(mat_b, mat_a)), mat) self.assertEqual(op.compose(op2, qargs=[0, 1]), Operator(targ)) self.assertEqual(op & op2([0, 1]), Operator(targ)) # op2 qargs=[2, 0] targ = np.dot(np.kron(mat_a, np.kron(np.eye(2), mat_b)), mat) self.assertEqual(op.compose(op2, qargs=[2, 0]), Operator(targ)) self.assertEqual(op & op2([2, 0]), Operator(targ)) # op1 qargs=[0] targ = np.dot(np.kron(np.eye(4), mat_a), mat) self.assertEqual(op.compose(op1, qargs=[0]), Operator(targ)) self.assertEqual(op & op1([0]), Operator(targ)) # op1 qargs=[1] targ = np.dot(np.kron(np.eye(2), np.kron(mat_a, np.eye(2))), mat) self.assertEqual(op.compose(op1, qargs=[1]), Operator(targ)) self.assertEqual(op & op1([1]), Operator(targ)) # op1 qargs=[2] targ = np.dot(np.kron(mat_a, np.eye(4)), mat) self.assertEqual(op.compose(op1, qargs=[2]), Operator(targ)) self.assertEqual(op & op1([2]), Operator(targ)) def test_dot_subsystem(self): """Test subsystem dot method.""" # 3-qubit operator mat = self.rand_matrix(8, 8) mat_a = self.rand_matrix(2, 2) mat_b = self.rand_matrix(2, 2) mat_c = self.rand_matrix(2, 2) op = Operator(mat) op1 = Operator(mat_a) op2 = Operator(np.kron(mat_b, mat_a)) op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a))) # op3 qargs=[0, 1, 2] targ = np.dot(mat, np.kron(mat_c, np.kron(mat_b, mat_a))) self.assertEqual(op.dot(op3, qargs=[0, 1, 2]), Operator(targ)) self.assertEqual(op.dot(op3([0, 1, 2])), Operator(targ)) # op3 qargs=[2, 1, 0] targ = np.dot(mat, np.kron(mat_a, np.kron(mat_b, mat_c))) self.assertEqual(op.dot(op3, qargs=[2, 1, 0]), Operator(targ)) self.assertEqual(op.dot(op3([2, 1, 0])), Operator(targ)) # op2 qargs=[0, 1] targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_b, mat_a))) self.assertEqual(op.dot(op2, qargs=[0, 1]), Operator(targ)) self.assertEqual(op.dot(op2([0, 1])), Operator(targ)) # op2 qargs=[2, 0] targ = np.dot(mat, np.kron(mat_a, np.kron(np.eye(2), mat_b))) self.assertEqual(op.dot(op2, qargs=[2, 0]), Operator(targ)) self.assertEqual(op.dot(op2([2, 0])), Operator(targ)) # op1 qargs=[0] targ = np.dot(mat, np.kron(np.eye(4), mat_a)) self.assertEqual(op.dot(op1, qargs=[0]), Operator(targ)) self.assertEqual(op.dot(op1([0])), Operator(targ)) # op1 qargs=[1] targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_a, np.eye(2)))) self.assertEqual(op.dot(op1, qargs=[1]), Operator(targ)) self.assertEqual(op.dot(op1([1])), Operator(targ)) # op1 qargs=[2] targ = np.dot(mat, np.kron(mat_a, np.eye(4))) self.assertEqual(op.dot(op1, qargs=[2]), Operator(targ)) self.assertEqual(op.dot(op1([2])), Operator(targ)) def test_compose_front_subsystem(self): """Test subsystem front compose method.""" # 3-qubit operator mat = self.rand_matrix(8, 8) mat_a = self.rand_matrix(2, 2) mat_b = self.rand_matrix(2, 2) mat_c = self.rand_matrix(2, 2) op = Operator(mat) op1 = Operator(mat_a) op2 = Operator(np.kron(mat_b, mat_a)) op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a))) # op3 qargs=[0, 1, 2] targ = np.dot(mat, np.kron(mat_c, np.kron(mat_b, mat_a))) self.assertEqual(op.compose(op3, qargs=[0, 1, 2], front=True), Operator(targ)) # op3 qargs=[2, 1, 0] targ = np.dot(mat, np.kron(mat_a, np.kron(mat_b, mat_c))) self.assertEqual(op.compose(op3, qargs=[2, 1, 0], front=True), Operator(targ)) # op2 qargs=[0, 1] targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_b, mat_a))) self.assertEqual(op.compose(op2, qargs=[0, 1], front=True), Operator(targ)) # op2 qargs=[2, 0] targ = np.dot(mat, np.kron(mat_a, np.kron(np.eye(2), mat_b))) self.assertEqual(op.compose(op2, qargs=[2, 0], front=True), Operator(targ)) # op1 qargs=[0] targ = np.dot(mat, np.kron(np.eye(4), mat_a)) self.assertEqual(op.compose(op1, qargs=[0], front=True), Operator(targ)) # op1 qargs=[1] targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_a, np.eye(2)))) self.assertEqual(op.compose(op1, qargs=[1], front=True), Operator(targ)) # op1 qargs=[2] targ = np.dot(mat, np.kron(mat_a, np.eye(4))) self.assertEqual(op.compose(op1, qargs=[2], front=True), Operator(targ)) def test_power(self): """Test power method.""" X90 = la.expm(-1j * 0.5 * np.pi * np.array([[0, 1], [1, 0]]) / 2) op = Operator(X90) self.assertEqual(op.power(2), Operator([[0, -1j], [-1j, 0]])) self.assertEqual(op.power(4), Operator(-1 * np.eye(2))) self.assertEqual(op.power(8), Operator(np.eye(2))) def test_expand(self): """Test expand method.""" mat1 = self.UX mat2 = np.eye(3, dtype=complex) mat21 = np.kron(mat2, mat1) op21 = Operator(mat1).expand(Operator(mat2)) self.assertEqual(op21.dim, (6, 6)) assert_allclose(op21.data, Operator(mat21).data) mat12 = np.kron(mat1, mat2) op12 = Operator(mat2).expand(Operator(mat1)) self.assertEqual(op12.dim, (6, 6)) assert_allclose(op12.data, Operator(mat12).data) def test_tensor(self): """Test tensor method.""" mat1 = self.UX mat2 = np.eye(3, dtype=complex) mat21 = np.kron(mat2, mat1) op21 = Operator(mat2).tensor(Operator(mat1)) self.assertEqual(op21.dim, (6, 6)) assert_allclose(op21.data, Operator(mat21).data) mat12 = np.kron(mat1, mat2) op12 = Operator(mat1).tensor(Operator(mat2)) self.assertEqual(op12.dim, (6, 6)) assert_allclose(op12.data, Operator(mat12).data) def test_power_except(self): """Test power method raises exceptions if not square.""" op = Operator(self.rand_matrix(2, 3)) # Non-integer power raises error self.assertRaises(QiskitError, op.power, 0.5) def test_add(self): """Test add method.""" mat1 = self.rand_matrix(4, 4) mat2 = self.rand_matrix(4, 4) op1 = Operator(mat1) op2 = Operator(mat2) self.assertEqual(op1._add(op2), Operator(mat1 + mat2)) self.assertEqual(op1 + op2, Operator(mat1 + mat2)) self.assertEqual(op1 - op2, Operator(mat1 - mat2)) def test_add_except(self): """Test add method raises exceptions.""" op1 = Operator(self.rand_matrix(2, 2)) op2 = Operator(self.rand_matrix(3, 3)) self.assertRaises(QiskitError, op1._add, op2) def test_add_qargs(self): """Test add method with qargs.""" mat = self.rand_matrix(8, 8) mat0 = self.rand_matrix(2, 2) mat1 = self.rand_matrix(2, 2) op = Operator(mat) op0 = Operator(mat0) op01 = Operator(np.kron(mat1, mat0)) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + Operator(np.kron(np.eye(4), mat0)) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + Operator(np.kron(np.kron(np.eye(2), mat0), np.eye(2))) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + Operator(np.kron(mat0, np.eye(4))) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op + op01([0, 1]) target = op + Operator(np.kron(np.eye(2), np.kron(mat1, mat0))) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op + op01([1, 0]) target = op + Operator(np.kron(np.eye(2), np.kron(mat0, mat1))) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op + op01([0, 2]) target = op + Operator(np.kron(mat1, np.kron(np.eye(2), mat0))) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op + op01([2, 0]) target = op + Operator(np.kron(mat0, np.kron(np.eye(2), mat1))) self.assertEqual(value, target) def test_sub_qargs(self): """Test subtract method with qargs.""" mat = self.rand_matrix(8, 8) mat0 = self.rand_matrix(2, 2) mat1 = self.rand_matrix(2, 2) op = Operator(mat) op0 = Operator(mat0) op01 = Operator(np.kron(mat1, mat0)) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - Operator(np.kron(np.eye(4), mat0)) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - Operator(np.kron(np.kron(np.eye(2), mat0), np.eye(2))) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - Operator(np.kron(mat0, np.eye(4))) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op - op01([0, 1]) target = op - Operator(np.kron(np.eye(2), np.kron(mat1, mat0))) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op - op01([1, 0]) target = op - Operator(np.kron(np.eye(2), np.kron(mat0, mat1))) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op - op01([0, 2]) target = op - Operator(np.kron(mat1, np.kron(np.eye(2), mat0))) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op - op01([2, 0]) target = op - Operator(np.kron(mat0, np.kron(np.eye(2), mat1))) self.assertEqual(value, target) def test_multiply(self): """Test multiply method.""" mat = self.rand_matrix(4, 4) val = np.exp(5j) op = Operator(mat) self.assertEqual(op._multiply(val), Operator(val * mat)) self.assertEqual(val * op, Operator(val * mat)) self.assertEqual(op * val, Operator(mat * val)) def test_multiply_except(self): """Test multiply method raises exceptions.""" op = Operator(self.rand_matrix(2, 2)) self.assertRaises(QiskitError, op._multiply, "s") self.assertRaises(QiskitError, op.__rmul__, "s") self.assertRaises(QiskitError, op._multiply, op) self.assertRaises(QiskitError, op.__rmul__, op) def test_negate(self): """Test negate method""" mat = self.rand_matrix(4, 4) op = Operator(mat) self.assertEqual(-op, Operator(-1 * mat)) def test_equiv(self): """Test negate method""" mat = np.diag([1, np.exp(1j * np.pi / 2)]) phase = np.exp(-1j * np.pi / 4) op = Operator(mat) self.assertTrue(op.equiv(phase * mat)) self.assertTrue(op.equiv(Operator(phase * mat))) self.assertFalse(op.equiv(2 * mat)) def test_reverse_qargs(self): """Test reverse_qargs method""" circ1 = QFT(5) circ2 = circ1.reverse_bits() state1 = Operator(circ1) state2 = Operator(circ2) self.assertEqual(state1.reverse_qargs(), state2) def test_drawings(self): """Test draw method""" qc1 = QFT(5) op = Operator.from_circuit(qc1) with self.subTest(msg="str(operator)"): str(op) for drawtype in ["repr", "text", "latex_source"]: with self.subTest(msg=f"draw('{drawtype}')"): op.draw(drawtype) with self.subTest(msg=" draw('latex')"): op.draw("latex") def test_from_circuit_constructor_no_layout(self): """Test initialization from a circuit using the from_circuit constructor.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) op = Operator.from_circuit(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 0, 1) op = Operator.from_circuit(circuit) target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(0, 1) op = Operator.from_circuit(circuit) target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout(self): """Test initialization from a circuit with an embedded reverse layout.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 1, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit) target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(1, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit) target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout_from_transpile(self): """Test initialization from a circuit with an embedded final layout.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) output = transpile(circuit, initial_layout=[2, 1, 0]) op = Operator.from_circuit(output) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout_from_transpile_with_registers(self): """Test initialization from a circuit with an embedded final layout.""" # Test tensor product of 1-qubit gates qr = QuantumRegister(3, name="test_reg") circuit = QuantumCircuit(qr) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) output = transpile(circuit, initial_layout=[2, 1, 0]) op = Operator.from_circuit(output) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout_and_final_layout(self): """Test initialization from a circuit with an embedded final layout.""" # Test tensor product of 1-qubit gates qr = QuantumRegister(3, name="test_reg") circuit = QuantumCircuit(qr) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, Layout({circuit.qubits[0]: 1, circuit.qubits[1]: 2, circuit.qubits[2]: 0}), ) circuit.swap(0, 1) circuit.swap(1, 2) op = Operator.from_circuit(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout_and_manual_final_layout(self): """Test initialization from a circuit with an embedded final layout.""" # Test tensor product of 1-qubit gates qr = QuantumRegister(3, name="test_reg") circuit = QuantumCircuit(qr) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) final_layout = Layout({circuit.qubits[0]: 1, circuit.qubits[1]: 2, circuit.qubits[2]: 0}) circuit.swap(0, 1) circuit.swap(1, 2) op = Operator.from_circuit(circuit, final_layout=final_layout) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout_ignore_set_layout(self): """Test initialization from a circuit with an ignored embedded reverse layout.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs() y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 1, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs() target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(1, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs() target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_user_specified_layout(self): """Test initialization from a circuit with a user specified reverse layout.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) layout = Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}) op = Operator.from_circuit(circuit, layout=layout) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 1, 0) layout = Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}) op = Operator.from_circuit(circuit, layout=layout) target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(1, 0) layout = Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}) op = Operator.from_circuit(circuit, layout=layout) target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_ghz_out_of_order_layout(self): """Test an out of order ghz state with a layout set.""" circuit = QuantumCircuit(5) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) circuit._layout = TranspileLayout( Layout( { circuit.qubits[3]: 0, circuit.qubits[4]: 1, circuit.qubits[2]: 2, circuit.qubits[0]: 3, circuit.qubits[1]: 4, } ), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) result = Operator.from_circuit(circuit) expected = QuantumCircuit(5) expected.h(0) expected.cx(0, 1) expected.cx(0, 2) expected.cx(0, 3) expected.cx(0, 4) expected_op = Operator(expected) self.assertTrue(expected_op.equiv(result)) def test_from_circuit_empty_circuit_empty_layout(self): """Test an out of order ghz state with a layout set.""" circuit = QuantumCircuit() circuit._layout = TranspileLayout(Layout(), {}) op = Operator.from_circuit(circuit) self.assertEqual(Operator([1]), op) def test_from_circuit_constructor_empty_layout(self): """Test an out of order ghz state with a layout set.""" circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) layout = Layout() with self.assertRaises(IndexError): Operator.from_circuit(circuit, layout=layout) def test_compose_scalar(self): """Test that composition works with a scalar-valued operator over no qubits.""" base = Operator(np.eye(2, dtype=np.complex128)) scalar = Operator(np.array([[-1.0 + 0.0j]])) composed = base.compose(scalar, qargs=[]) self.assertEqual(composed, Operator(-np.eye(2, dtype=np.complex128))) def test_compose_scalar_op(self): """Test that composition works with an explicit scalar operator over no qubits.""" base = Operator(np.eye(2, dtype=np.complex128)) scalar = ScalarOp(coeff=-1.0 + 0.0j) composed = base.compose(scalar, qargs=[]) self.assertEqual(composed, Operator(-np.eye(2, dtype=np.complex128))) def test_from_circuit_single_flat_default_register_transpiled(self): """Test a transpiled circuit with layout set from default register.""" circuit = QuantumCircuit(5) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) init_layout = Layout( { circuit.qubits[0]: 3, circuit.qubits[1]: 4, circuit.qubits[2]: 1, circuit.qubits[3]: 2, circuit.qubits[4]: 0, } ) tqc = transpile(circuit, initial_layout=init_layout) result = Operator.from_circuit(tqc) self.assertTrue(Operator.from_circuit(circuit).equiv(result)) def test_from_circuit_loose_bits_transpiled(self): """Test a transpiled circuit with layout set from loose bits.""" bits = [Qubit() for _ in range(5)] circuit = QuantumCircuit() circuit.add_bits(bits) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) init_layout = Layout( { circuit.qubits[0]: 3, circuit.qubits[1]: 4, circuit.qubits[2]: 1, circuit.qubits[3]: 2, circuit.qubits[4]: 0, } ) tqc = transpile(circuit, initial_layout=init_layout) result = Operator.from_circuit(tqc) self.assertTrue(Operator(circuit).equiv(result)) def test_from_circuit_multiple_registers_bits_transpiled(self): """Test a transpiled circuit with layout set from loose bits.""" regs = [QuantumRegister(1, name=f"custom_reg-{i}") for i in range(5)] circuit = QuantumCircuit() for reg in regs: circuit.add_register(reg) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) tqc = transpile(circuit, initial_layout=[3, 4, 1, 2, 0]) result = Operator.from_circuit(tqc) self.assertTrue(Operator(circuit).equiv(result)) def test_from_circuit_single_flat_custom_register_transpiled(self): """Test a transpiled circuit with layout set from loose bits.""" circuit = QuantumCircuit(QuantumRegister(5, name="custom_reg")) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) tqc = transpile(circuit, initial_layout=[3, 4, 1, 2, 0]) result = Operator.from_circuit(tqc) self.assertTrue(Operator(circuit).equiv(result)) def test_from_circuit_mixed_reg_loose_bits_transpiled(self): """Test a transpiled circuit with layout set from loose bits.""" bits = [Qubit(), Qubit()] circuit = QuantumCircuit() circuit.add_bits(bits) circuit.add_register(QuantumRegister(3, name="a_reg")) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) init_layout = Layout( { circuit.qubits[0]: 3, circuit.qubits[1]: 4, circuit.qubits[2]: 1, circuit.qubits[3]: 2, circuit.qubits[4]: 0, } ) tqc = transpile(circuit, initial_layout=init_layout) result = Operator.from_circuit(tqc) self.assertTrue(Operator(circuit).equiv(result)) def test_apply_permutation_back(self): """Test applying permutation to the operator, where the operator is applied first and the permutation second.""" op = Operator(self.rand_matrix(64, 64)) pattern = [1, 2, 0, 3, 5, 4] # Consider several methods of computing this operator and show # they all lead to the same result. # Compose the operator with the operator constructed from the # permutation circuit. op2 = op.copy() perm_op = Operator(Permutation(6, pattern)) op2 &= perm_op # Compose the operator with the operator constructed from the # permutation gate. op3 = op.copy() perm_op = Operator(PermutationGate(pattern)) op3 &= perm_op # Modify the operator using apply_permutation method. op4 = op.copy() op4 = op4.apply_permutation(pattern, front=False) self.assertEqual(op2, op3) self.assertEqual(op2, op4) def test_apply_permutation_front(self): """Test applying permutation to the operator, where the permutation is applied first and the operator second""" op = Operator(self.rand_matrix(64, 64)) pattern = [1, 2, 0, 3, 5, 4] # Consider several methods of computing this operator and show # they all lead to the same result. # Compose the operator with the operator constructed from the # permutation circuit. op2 = op.copy() perm_op = Operator(Permutation(6, pattern)) op2 = perm_op & op2 # Compose the operator with the operator constructed from the # permutation gate. op3 = op.copy() perm_op = Operator(PermutationGate(pattern)) op3 = perm_op & op3 # Modify the operator using apply_permutation method. op4 = op.copy() op4 = op4.apply_permutation(pattern, front=True) self.assertEqual(op2, op3) self.assertEqual(op2, op4) def test_apply_permutation_qudits_back(self): """Test applying permutation to the operator with heterogeneous qudit spaces, where the operator O is applied first and the permutation P second. The matrix of the resulting operator is the product [P][O] and corresponds to suitably permuting the rows of O's matrix. """ mat = np.array(range(6 * 6)).reshape((6, 6)) op = Operator(mat, input_dims=(2, 3), output_dims=(2, 3)) perm = [1, 0] actual = op.apply_permutation(perm, front=False) # Rows of mat are ordered to 00, 01, 02, 10, 11, 12; # perm maps these to 00, 10, 20, 01, 11, 21, # while the default ordering is 00, 01, 10, 11, 20, 21. permuted_mat = mat.copy()[[0, 2, 4, 1, 3, 5]] expected = Operator(permuted_mat, input_dims=(2, 3), output_dims=(3, 2)) self.assertEqual(actual, expected) def test_apply_permutation_qudits_front(self): """Test applying permutation to the operator with heterogeneous qudit spaces, where the permutation P is applied first and the operator O is applied second. The matrix of the resulting operator is the product [O][P] and corresponds to suitably permuting the columns of O's matrix. """ mat = np.array(range(6 * 6)).reshape((6, 6)) op = Operator(mat, input_dims=(2, 3), output_dims=(2, 3)) perm = [1, 0] actual = op.apply_permutation(perm, front=True) # Columns of mat are ordered to 00, 01, 02, 10, 11, 12; # perm maps these to 00, 10, 20, 01, 11, 21, # while the default ordering is 00, 01, 10, 11, 20, 21. permuted_mat = mat.copy()[:, [0, 2, 4, 1, 3, 5]] expected = Operator(permuted_mat, input_dims=(3, 2), output_dims=(2, 3)) self.assertEqual(actual, expected) @combine( dims=((2, 3, 4, 5), (5, 2, 4, 3), (3, 5, 2, 4), (5, 3, 4, 2), (4, 5, 2, 3), (4, 3, 2, 5)) ) def test_reverse_qargs_as_apply_permutation(self, dims): """Test reversing qargs by pre- and post-composing with reversal permutation. """ perm = [3, 2, 1, 0] op = Operator( np.array(range(120 * 120)).reshape((120, 120)), input_dims=dims, output_dims=dims ) op2 = op.reverse_qargs() op3 = op.apply_permutation(perm, front=True).apply_permutation(perm, front=False) self.assertEqual(op2, op3) def test_apply_permutation_exceptions(self): """Checks that applying permutation raises an error when dimensions do not match.""" op = Operator( np.array(range(24 * 30)).reshape((24, 30)), input_dims=(6, 5), output_dims=(2, 3, 4) ) with self.assertRaises(QiskitError): op.apply_permutation([1, 0], front=False) with self.assertRaises(QiskitError): op.apply_permutation([2, 1, 0], front=True) def test_apply_permutation_dimensions(self): """Checks the dimensions of the operator after applying permutation.""" op = Operator( np.array(range(24 * 30)).reshape((24, 30)), input_dims=(6, 5), output_dims=(2, 3, 4) ) op2 = op.apply_permutation([1, 2, 0], front=False) self.assertEqual(op2.output_dims(), (4, 2, 3)) op = Operator( np.array(range(24 * 30)).reshape((30, 24)), input_dims=(2, 3, 4), output_dims=(6, 5) ) op2 = op.apply_permutation([2, 0, 1], front=True) self.assertEqual(op2.input_dims(), (4, 2, 3)) if __name__ == "__main__": unittest.main()
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 for Chi quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.operators.channel import Chi from .channel_test_case import ChannelTestCase class TestChi(ChannelTestCase): """Tests for Chi channel representation.""" def test_init(self): """Test initialization""" mat4 = np.eye(4) / 2.0 chan = Chi(mat4) assert_allclose(chan.data, mat4) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) mat16 = np.eye(16) / 4 chan = Chi(mat16) assert_allclose(chan.data, mat16) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan.num_qubits, 2) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, Chi, mat16, input_dims=2, output_dims=4) # Non multi-qubit dimensions should raise exception self.assertRaises(QiskitError, Chi, np.eye(6) / 2, input_dims=3, output_dims=2) def test_circuit_init(self): """Test initialization from a circuit.""" circuit, target = self.simple_circuit_no_measure() op = Chi(circuit) target = Chi(target) self.assertEqual(op, target) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, Chi, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(4, 4, real=True) self.assertEqual(Chi(mat), Chi(mat)) def test_copy(self): """Test copy method""" mat = np.eye(4) with self.subTest("Deep copy"): orig = Chi(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = Chi(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(Chi(self.depol_chi(0.25)).is_cptp()) # Non-CPTP should return false self.assertFalse(Chi(1.25 * self.chiI - 0.25 * self.depol_chi(1)).is_cptp()) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, Chi(np.eye(4)).compose, Chi(np.eye(16))) self.assertRaises(QiskitError, Chi(np.eye(4)).compose, 2) def test_compose(self): """Test compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Chi(self.chiX) chan2 = Chi(self.chiY) chan = chan1.compose(chan2) target = rho.evolve(Chi(self.chiZ)) output = rho.evolve(chan) self.assertEqual(output, target) # 50% depolarizing channel chan1 = Chi(self.depol_chi(0.5)) chan = chan1.compose(chan1) target = rho.evolve(Chi(self.depol_chi(0.75))) output = rho.evolve(chan) self.assertEqual(output, target) # Compose random chi1 = self.rand_matrix(4, 4, real=True) chi2 = self.rand_matrix(4, 4, real=True) chan1 = Chi(chi1, input_dims=2, output_dims=2) chan2 = Chi(chi2, input_dims=2, output_dims=2) target = rho.evolve(chan1).evolve(chan2) chan = chan1.compose(chan2) output = rho.evolve(chan) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(output, target) chan = chan1 & chan2 output = rho.evolve(chan) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(output, target) def test_dot(self): """Test dot method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Chi(self.chiX) chan2 = Chi(self.chiY) target = rho.evolve(Chi(self.chiZ)) output = rho.evolve(chan2.dot(chan1)) self.assertEqual(output, target) # Compose random chi1 = self.rand_matrix(4, 4, real=True) chi2 = self.rand_matrix(4, 4, real=True) chan1 = Chi(chi1, input_dims=2, output_dims=2) chan2 = Chi(chi2, input_dims=2, output_dims=2) target = rho.evolve(chan1).evolve(chan2) chan = chan2.dot(chan1) output = rho.evolve(chan) self.assertEqual(output, target) chan = chan2 @ chan1 output = rho.evolve(chan) self.assertEqual(output, target) def test_compose_front(self): """Test front compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Chi(self.chiX) chan2 = Chi(self.chiY) chan = chan2.compose(chan1, front=True) target = rho.evolve(Chi(self.chiZ)) output = rho.evolve(chan) self.assertEqual(output, target) # Compose random chi1 = self.rand_matrix(4, 4, real=True) chi2 = self.rand_matrix(4, 4, real=True) chan1 = Chi(chi1, input_dims=2, output_dims=2) chan2 = Chi(chi2, input_dims=2, output_dims=2) target = rho.evolve(chan1).evolve(chan2) chan = chan2.compose(chan1, front=True) output = rho.evolve(chan) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(output, target) def test_expand(self): """Test expand method.""" # Pauli channels paulis = [self.chiI, self.chiX, self.chiY, self.chiZ] targs = 4 * np.eye(16) # diagonals of Pauli channel Chi mats for i, chi1 in enumerate(paulis): for j, chi2 in enumerate(paulis): chan1 = Chi(chi1) chan2 = Chi(chi2) chan = chan1.expand(chan2) # Target for diagonal Pauli channel targ = Chi(np.diag(targs[i + 4 * j])) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan, targ) # Completely depolarizing rho = DensityMatrix(np.diag([1, 0, 0, 0])) chan_dep = Chi(self.depol_chi(1)) chan = chan_dep.expand(chan_dep) target = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) output = rho.evolve(chan) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(output, target) def test_tensor(self): """Test tensor method.""" # Pauli channels paulis = [self.chiI, self.chiX, self.chiY, self.chiZ] targs = 4 * np.eye(16) # diagonals of Pauli channel Chi mats for i, chi1 in enumerate(paulis): for j, chi2 in enumerate(paulis): chan1 = Chi(chi1) chan2 = Chi(chi2) chan = chan2.tensor(chan1) # Target for diagonal Pauli channel targ = Chi(np.diag(targs[i + 4 * j])) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan, targ) # Test overload chan = chan2 ^ chan1 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan, targ) # Completely depolarizing rho = DensityMatrix(np.diag([1, 0, 0, 0])) chan_dep = Chi(self.depol_chi(1)) chan = chan_dep.tensor(chan_dep) target = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) output = rho.evolve(chan) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(output, target) # Test operator overload chan = chan_dep ^ chan_dep output = rho.evolve(chan) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(output, target) def test_power(self): """Test power method.""" # 10% depolarizing channel p_id = 0.9 depol = Chi(self.depol_chi(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = depol.power(3) targ3 = Chi(self.depol_chi(1 - p_id3)) self.assertEqual(chan3, targ3) def test_add(self): """Test add method.""" mat1 = 0.5 * self.chiI mat2 = 0.5 * self.depol_chi(1) chan1 = Chi(mat1) chan2 = Chi(mat2) targ = Chi(mat1 + mat2) self.assertEqual(chan1._add(chan2), targ) self.assertEqual(chan1 + chan2, targ) targ = Chi(mat1 - mat2) self.assertEqual(chan1 - chan2, targ) def test_add_qargs(self): """Test add method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = Chi(mat) op0 = Chi(mat0) op1 = Chi(mat1) op01 = op1.tensor(op0) eye = Chi(self.chiI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op + op01([0, 1]) target = op + eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op + op01([1, 0]) target = op + eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op + op01([0, 2]) target = op + op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op + op01([2, 0]) target = op + op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_sub_qargs(self): """Test subtract method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = Chi(mat) op0 = Chi(mat0) op1 = Chi(mat1) op01 = op1.tensor(op0) eye = Chi(self.chiI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op - op01([0, 1]) target = op - eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op - op01([1, 0]) target = op - eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op - op01([0, 2]) target = op - op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op - op01([2, 0]) target = op - op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_add_except(self): """Test add method raises exceptions.""" chan1 = Chi(self.chiI) chan2 = Chi(np.eye(16)) self.assertRaises(QiskitError, chan1._add, chan2) self.assertRaises(QiskitError, chan1._add, 5) def test_multiply(self): """Test multiply method.""" chan = Chi(self.chiI) val = 0.5 targ = Chi(val * self.chiI) self.assertEqual(chan._multiply(val), targ) self.assertEqual(val * chan, targ) targ = Chi(self.chiI * val) self.assertEqual(chan * val, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = Chi(self.chiI) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" chan = Chi(self.chiI) targ = Chi(-self.chiI) self.assertEqual(-chan, targ) if __name__ == "__main__": unittest.main()
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. # pylint: disable=invalid-name """Tests for Choi quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.operators.channel import Choi from .channel_test_case import ChannelTestCase class TestChoi(ChannelTestCase): """Tests for Choi channel representation.""" def test_init(self): """Test initialization""" mat4 = np.eye(4) / 2.0 chan = Choi(mat4) assert_allclose(chan.data, mat4) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) mat8 = np.eye(8) / 2.0 chan = Choi(mat8, input_dims=4) assert_allclose(chan.data, mat8) self.assertEqual(chan.dim, (4, 2)) self.assertIsNone(chan.num_qubits) chan = Choi(mat8, input_dims=2) assert_allclose(chan.data, mat8) self.assertEqual(chan.dim, (2, 4)) self.assertIsNone(chan.num_qubits) mat16 = np.eye(16) / 4 chan = Choi(mat16) assert_allclose(chan.data, mat16) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan.num_qubits, 2) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, Choi, mat8, input_dims=[4], output_dims=[4]) def test_circuit_init(self): """Test initialization from a circuit.""" circuit, target = self.simple_circuit_no_measure() op = Choi(circuit) target = Choi(target) self.assertEqual(op, target) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, Choi, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(4, 4) self.assertEqual(Choi(mat), Choi(mat)) def test_copy(self): """Test copy method""" mat = np.eye(2) with self.subTest("Deep copy"): orig = Choi(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = Choi(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_clone(self): """Test clone method""" mat = np.eye(4) orig = Choi(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(Choi(self.depol_choi(0.25)).is_cptp()) # Non-CPTP should return false self.assertFalse(Choi(1.25 * self.choiI - 0.25 * self.depol_choi(1)).is_cptp()) def test_conjugate(self): """Test conjugate method.""" # Test channel measures in Z basis and prepares in Y basis # Zp -> Yp, Zm -> Ym Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2 chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym)) # Conjugate channel swaps Y-basis states targ = Choi(np.kron(Zp, Ym) + np.kron(Zm, Yp)) chan_conj = chan.conjugate() self.assertEqual(chan_conj, targ) def test_transpose(self): """Test transpose method.""" # Test channel measures in Z basis and prepares in Y basis # Zp -> Yp, Zm -> Ym Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2 chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym)) # Transpose channel swaps basis targ = Choi(np.kron(Yp, Zp) + np.kron(Ym, Zm)) chan_t = chan.transpose() self.assertEqual(chan_t, targ) def test_adjoint(self): """Test adjoint method.""" # Test channel measures in Z basis and prepares in Y basis # Zp -> Yp, Zm -> Ym Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2 chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym)) # Ajoint channel swaps Y-basis elements and Z<->Y bases targ = Choi(np.kron(Ym, Zp) + np.kron(Yp, Zm)) chan_adj = chan.adjoint() self.assertEqual(chan_adj, targ) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, Choi(np.eye(4)).compose, Choi(np.eye(8))) self.assertRaises(QiskitError, Choi(np.eye(4)).compose, 2) def test_compose(self): """Test compose method.""" # UnitaryChannel evolution chan1 = Choi(self.choiX) chan2 = Choi(self.choiY) chan = chan1.compose(chan2) targ = Choi(self.choiZ) self.assertEqual(chan, targ) # 50% depolarizing channel chan1 = Choi(self.depol_choi(0.5)) chan = chan1.compose(chan1) targ = Choi(self.depol_choi(0.75)) self.assertEqual(chan, targ) # Measure and rotation Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2 chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) chan2 = Choi(self.choiX) # X-gate second does nothing targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) self.assertEqual(chan1.compose(chan2), targ) self.assertEqual(chan1 & chan2, targ) # X-gate first swaps Z states targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm)) self.assertEqual(chan2.compose(chan1), targ) self.assertEqual(chan2 & chan1, targ) # Compose different dimensions chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4) chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2) chan = chan1.compose(chan2) self.assertEqual(chan.dim, (2, 2)) chan = chan2.compose(chan1) self.assertEqual(chan.dim, (4, 4)) def test_dot(self): """Test dot method.""" # UnitaryChannel evolution chan1 = Choi(self.choiX) chan2 = Choi(self.choiY) targ = Choi(self.choiZ) self.assertEqual(chan1.dot(chan2), targ) self.assertEqual(chan1 @ chan2, targ) # 50% depolarizing channel chan1 = Choi(self.depol_choi(0.5)) targ = Choi(self.depol_choi(0.75)) self.assertEqual(chan1.dot(chan1), targ) self.assertEqual(chan1 @ chan1, targ) # Measure and rotation Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2 chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) chan2 = Choi(self.choiX) # X-gate second does nothing targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) self.assertEqual(chan2.dot(chan1), targ) self.assertEqual(chan2 @ chan1, targ) # X-gate first swaps Z states targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm)) self.assertEqual(chan1.dot(chan2), targ) self.assertEqual(chan1 @ chan2, targ) # Compose different dimensions chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4) chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2) chan = chan1.dot(chan2) self.assertEqual(chan.dim, (4, 4)) chan = chan1 @ chan2 self.assertEqual(chan.dim, (4, 4)) chan = chan2.dot(chan1) self.assertEqual(chan.dim, (2, 2)) chan = chan2 @ chan1 self.assertEqual(chan.dim, (2, 2)) def test_compose_front(self): """Test front compose method.""" # UnitaryChannel evolution chan1 = Choi(self.choiX) chan2 = Choi(self.choiY) chan = chan1.compose(chan2, front=True) targ = Choi(self.choiZ) self.assertEqual(chan, targ) # 50% depolarizing channel chan1 = Choi(self.depol_choi(0.5)) chan = chan1.compose(chan1, front=True) targ = Choi(self.depol_choi(0.75)) self.assertEqual(chan, targ) # Measure and rotation Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2 chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) chan2 = Choi(self.choiX) # X-gate second does nothing chan = chan2.compose(chan1, front=True) targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) self.assertEqual(chan, targ) # X-gate first swaps Z states chan = chan1.compose(chan2, front=True) targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm)) self.assertEqual(chan, targ) # Compose different dimensions chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4) chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2) chan = chan1.compose(chan2, front=True) self.assertEqual(chan.dim, (4, 4)) chan = chan2.compose(chan1, front=True) self.assertEqual(chan.dim, (2, 2)) def test_expand(self): """Test expand method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Choi(self.choiI) chan2 = Choi(self.choiX) # X \otimes I chan = chan1.expand(chan2) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan2.expand(chan1) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing chan_dep = Choi(self.depol_choi(1)) chan = chan_dep.expand(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_tensor(self): """Test tensor method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Choi(self.choiI) chan2 = Choi(self.choiX) # X \otimes I rho_targ = DensityMatrix(np.kron(rho1, rho0)) chan = chan2.tensor(chan1) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan2 ^ chan1 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X rho_targ = DensityMatrix(np.kron(rho0, rho1)) chan = chan1.tensor(chan2) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan1 ^ chan2 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) chan_dep = Choi(self.depol_choi(1)) chan = chan_dep.tensor(chan_dep) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan_dep ^ chan_dep self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_power(self): """Test power method.""" # 10% depolarizing channel p_id = 0.9 depol = Choi(self.depol_choi(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = depol.power(3) targ3 = Choi(self.depol_choi(1 - p_id3)) self.assertEqual(chan3, targ3) def test_add(self): """Test add method.""" mat1 = 0.5 * self.choiI mat2 = 0.5 * self.depol_choi(1) chan1 = Choi(mat1) chan2 = Choi(mat2) targ = Choi(mat1 + mat2) self.assertEqual(chan1._add(chan2), targ) self.assertEqual(chan1 + chan2, targ) targ = Choi(mat1 - mat2) self.assertEqual(chan1 - chan2, targ) def test_add_qargs(self): """Test add method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = Choi(mat) op0 = Choi(mat0) op1 = Choi(mat1) op01 = op1.tensor(op0) eye = Choi(self.choiI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op + op01([0, 1]) target = op + eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op + op01([1, 0]) target = op + eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op + op01([0, 2]) target = op + op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op + op01([2, 0]) target = op + op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_sub_qargs(self): """Test subtract method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = Choi(mat) op0 = Choi(mat0) op1 = Choi(mat1) op01 = op1.tensor(op0) eye = Choi(self.choiI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op - op01([0, 1]) target = op - eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op - op01([1, 0]) target = op - eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op - op01([0, 2]) target = op - op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op - op01([2, 0]) target = op - op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_add_except(self): """Test add method raises exceptions.""" chan1 = Choi(self.choiI) chan2 = Choi(np.eye(8)) self.assertRaises(QiskitError, chan1._add, chan2) self.assertRaises(QiskitError, chan1._add, 5) def test_multiply(self): """Test multiply method.""" chan = Choi(self.choiI) val = 0.5 targ = Choi(val * self.choiI) self.assertEqual(chan._multiply(val), targ) self.assertEqual(val * chan, targ) targ = Choi(self.choiI * val) self.assertEqual(chan * val, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = Choi(self.choiI) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" chan = Choi(self.choiI) targ = Choi(-1 * self.choiI) self.assertEqual(-chan, targ) if __name__ == "__main__": unittest.main()
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 for Kraus quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info import Kraus from .channel_test_case import ChannelTestCase class TestKraus(ChannelTestCase): """Tests for Kraus channel representation.""" def test_init(self): """Test initialization""" # Initialize from unitary chan = Kraus(self.UI) assert_allclose(chan.data, [self.UI]) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize from Kraus chan = Kraus(self.depol_kraus(0.5)) assert_allclose(chan.data, self.depol_kraus(0.5)) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize from Non-CPTP kraus_l, kraus_r = [self.UI, self.UX], [self.UY, self.UZ] chan = Kraus((kraus_l, kraus_r)) assert_allclose(chan.data, (kraus_l, kraus_r)) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize with redundant second op chan = Kraus((kraus_l, kraus_l)) assert_allclose(chan.data, kraus_l) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize from rectangular kraus = [np.zeros((4, 2))] chan = Kraus(kraus) assert_allclose(chan.data, kraus) self.assertEqual(chan.dim, (2, 4)) self.assertIsNone(chan.num_qubits) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, Kraus, kraus, input_dims=4, output_dims=4) def test_circuit_init(self): """Test initialization from a circuit.""" circuit, target = self.simple_circuit_no_measure() op = Kraus(circuit) target = Kraus(target) self.assertEqual(op, target) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, Kraus, circuit) def test_equal(self): """Test __eq__ method""" kraus = [self.rand_matrix(2, 2) for _ in range(2)] self.assertEqual(Kraus(kraus), Kraus(kraus)) def test_copy(self): """Test copy method""" mat = np.eye(2) with self.subTest("Deep copy"): orig = Kraus(mat) cpy = orig.copy() cpy._data[0][0][0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = Kraus(mat) clone = copy.copy(orig) clone._data[0][0][0, 0] = 0.0 self.assertTrue(clone == orig) def test_clone(self): """Test clone method""" mat = np.eye(4) orig = Kraus(mat) clone = copy.copy(orig) clone._data[0][0][0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(Kraus(self.depol_kraus(0.5)).is_cptp()) self.assertTrue(Kraus(self.UX).is_cptp()) # Non-CPTP should return false self.assertFalse(Kraus(([self.UI], [self.UX])).is_cptp()) self.assertFalse(Kraus([self.UI, self.UX]).is_cptp()) def test_conjugate(self): """Test conjugate method.""" kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Single Kraus list targ = Kraus([np.conjugate(k) for k in kraus_l]) chan1 = Kraus(kraus_l) chan = chan1.conjugate() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (2, 4)) # Double Kraus list targ = Kraus(([np.conjugate(k) for k in kraus_l], [np.conjugate(k) for k in kraus_r])) chan1 = Kraus((kraus_l, kraus_r)) chan = chan1.conjugate() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (2, 4)) def test_transpose(self): """Test transpose method.""" kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Single Kraus list targ = Kraus([np.transpose(k) for k in kraus_l]) chan1 = Kraus(kraus_l) chan = chan1.transpose() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) # Double Kraus list targ = Kraus(([np.transpose(k) for k in kraus_l], [np.transpose(k) for k in kraus_r])) chan1 = Kraus((kraus_l, kraus_r)) chan = chan1.transpose() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) def test_adjoint(self): """Test adjoint method.""" kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Single Kraus list targ = Kraus([np.transpose(k).conj() for k in kraus_l]) chan1 = Kraus(kraus_l) chan = chan1.adjoint() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) # Double Kraus list targ = Kraus( ([np.transpose(k).conj() for k in kraus_l], [np.transpose(k).conj() for k in kraus_r]) ) chan1 = Kraus((kraus_l, kraus_r)) chan = chan1.adjoint() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, Kraus(np.eye(2)).compose, Kraus(np.eye(4))) self.assertRaises(QiskitError, Kraus(np.eye(2)).compose, 2) def test_compose(self): """Test compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Kraus(self.UX) chan2 = Kraus(self.UY) chan = chan1.compose(chan2) targ = rho & Kraus(self.UZ) self.assertEqual(rho & chan, targ) # 50% depolarizing channel chan1 = Kraus(self.depol_kraus(0.5)) chan = chan1.compose(chan1) targ = rho & Kraus(self.depol_kraus(0.75)) self.assertEqual(rho & chan, targ) # Compose different dimensions kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4) chan1 = Kraus(kraus1) chan2 = Kraus(kraus2) targ = rho & chan1 & chan2 chan = chan1.compose(chan2) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho & chan, targ) chan = chan1 & chan2 self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho & chan, targ) def test_dot(self): """Test dot method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Kraus(self.UX) chan2 = Kraus(self.UY) targ = rho.evolve(Kraus(self.UZ)) self.assertEqual(rho.evolve(chan1.dot(chan2)), targ) self.assertEqual(rho.evolve(chan1 @ chan2), targ) # 50% depolarizing channel chan1 = Kraus(self.depol_kraus(0.5)) targ = rho & Kraus(self.depol_kraus(0.75)) self.assertEqual(rho.evolve(chan1.dot(chan1)), targ) self.assertEqual(rho.evolve(chan1 @ chan1), targ) # Compose different dimensions kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4) chan1 = Kraus(kraus1) chan2 = Kraus(kraus2) targ = rho & chan1 & chan2 self.assertEqual(rho.evolve(chan2.dot(chan1)), targ) self.assertEqual(rho.evolve(chan2 @ chan1), targ) def test_compose_front(self): """Test deprecated front compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Kraus(self.UX) chan2 = Kraus(self.UY) chan = chan1.compose(chan2, front=True) targ = rho & Kraus(self.UZ) self.assertEqual(rho & chan, targ) # 50% depolarizing channel chan1 = Kraus(self.depol_kraus(0.5)) chan = chan1.compose(chan1, front=True) targ = rho & Kraus(self.depol_kraus(0.75)) self.assertEqual(rho & chan, targ) # Compose different dimensions kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4) chan1 = Kraus(kraus1) chan2 = Kraus(kraus2) targ = rho & chan1 & chan2 chan = chan2.compose(chan1, front=True) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho & chan, targ) def test_expand(self): """Test expand method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Kraus(self.UI) chan2 = Kraus(self.UX) # X \otimes I chan = chan1.expand(chan2) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) # I \otimes X chan = chan2.expand(chan1) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) # Completely depolarizing chan_dep = Kraus(self.depol_kraus(1)) chan = chan_dep.expand(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) def test_tensor(self): """Test tensor method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Kraus(self.UI) chan2 = Kraus(self.UX) # X \otimes I chan = chan2.tensor(chan1) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) # I \otimes X chan = chan1.tensor(chan2) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) # Completely depolarizing chan_dep = Kraus(self.depol_kraus(1)) chan = chan_dep.tensor(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) def test_power(self): """Test power method.""" # 10% depolarizing channel rho = DensityMatrix(np.diag([1, 0])) p_id = 0.9 chan = Kraus(self.depol_kraus(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = chan.power(3) targ3a = rho & chan & chan & chan self.assertEqual(rho & chan3, targ3a) targ3b = rho & Kraus(self.depol_kraus(1 - p_id3)) self.assertEqual(rho & chan3, targ3b) def test_add(self): """Test add method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Random Single-Kraus maps chan1 = Kraus(kraus1) chan2 = Kraus(kraus2) targ = (rho & chan1) + (rho & chan2) chan = chan1._add(chan2) self.assertEqual(rho & chan, targ) chan = chan1 + chan2 self.assertEqual(rho & chan, targ) # Random Single-Kraus maps chan = Kraus((kraus1, kraus2)) targ = 2 * (rho & chan) chan = chan._add(chan) self.assertEqual(rho & chan, targ) def test_add_qargs(self): """Test add method with qargs.""" rho = DensityMatrix(self.rand_rho(8)) kraus = self.rand_kraus(8, 8, 4) kraus0 = self.rand_kraus(2, 2, 4) op = Kraus(kraus) op0 = Kraus(kraus0) eye = Kraus(self.UI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(rho & value, rho & target) def test_sub_qargs(self): """Test sub method with qargs.""" rho = DensityMatrix(self.rand_rho(8)) kraus = self.rand_kraus(8, 8, 4) kraus0 = self.rand_kraus(2, 2, 4) op = Kraus(kraus) op0 = Kraus(kraus0) eye = Kraus(self.UI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(rho & value, rho & target) def test_subtract(self): """Test subtract method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Random Single-Kraus maps chan1 = Kraus(kraus1) chan2 = Kraus(kraus2) targ = (rho & chan1) - (rho & chan2) chan = chan1 - chan2 self.assertEqual(rho & chan, targ) # Random Single-Kraus maps chan = Kraus((kraus1, kraus2)) targ = 0 * (rho & chan) chan = chan - chan self.assertEqual(rho & chan, targ) def test_multiply(self): """Test multiply method.""" # Random initial state and Kraus ops rho = DensityMatrix(self.rand_rho(2)) val = 0.5 kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Single Kraus set chan1 = Kraus(kraus1) targ = val * (rho & chan1) chan = chan1._multiply(val) self.assertEqual(rho & chan, targ) chan = val * chan1 self.assertEqual(rho & chan, targ) targ = (rho & chan1) * val chan = chan1 * val self.assertEqual(rho & chan, targ) # Double Kraus set chan2 = Kraus((kraus1, kraus2)) targ = val * (rho & chan2) chan = chan2._multiply(val) self.assertEqual(rho & chan, targ) chan = val * chan2 self.assertEqual(rho & chan, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = Kraus(self.depol_kraus(1)) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" rho = DensityMatrix(np.diag([1, 0])) targ = DensityMatrix(np.diag([-0.5, -0.5])) chan = -Kraus(self.depol_kraus(1)) self.assertEqual(rho & chan, targ) if __name__ == "__main__": unittest.main()
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 for PTM quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.operators.channel import PTM from .channel_test_case import ChannelTestCase class TestPTM(ChannelTestCase): """Tests for PTM channel representation.""" def test_init(self): """Test initialization""" mat4 = np.eye(4) / 2.0 chan = PTM(mat4) assert_allclose(chan.data, mat4) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) mat16 = np.eye(16) / 4 chan = PTM(mat16) assert_allclose(chan.data, mat16) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan.num_qubits, 2) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, PTM, mat16, input_dims=2, output_dims=4) # Non multi-qubit dimensions should raise exception self.assertRaises(QiskitError, PTM, np.eye(6) / 2, input_dims=3, output_dims=2) def test_circuit_init(self): """Test initialization from a circuit.""" circuit, target = self.simple_circuit_no_measure() op = PTM(circuit) target = PTM(target) self.assertEqual(op, target) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, PTM, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(4, 4, real=True) self.assertEqual(PTM(mat), PTM(mat)) def test_copy(self): """Test copy method""" mat = np.eye(4) with self.subTest("Deep copy"): orig = PTM(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = PTM(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_clone(self): """Test clone method""" mat = np.eye(4) orig = PTM(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(PTM(self.depol_ptm(0.25)).is_cptp()) # Non-CPTP should return false self.assertFalse(PTM(1.25 * self.ptmI - 0.25 * self.depol_ptm(1)).is_cptp()) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, PTM(np.eye(4)).compose, PTM(np.eye(16))) self.assertRaises(QiskitError, PTM(np.eye(4)).compose, 2) def test_compose(self): """Test compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = PTM(self.ptmX) chan2 = PTM(self.ptmY) chan = chan1.compose(chan2) rho_targ = rho.evolve(PTM(self.ptmZ)) self.assertEqual(rho.evolve(chan), rho_targ) # 50% depolarizing channel chan1 = PTM(self.depol_ptm(0.5)) chan = chan1.compose(chan1) rho_targ = rho.evolve(PTM(self.depol_ptm(0.75))) self.assertEqual(rho.evolve(chan), rho_targ) # Compose random ptm1 = self.rand_matrix(4, 4, real=True) ptm2 = self.rand_matrix(4, 4, real=True) chan1 = PTM(ptm1, input_dims=2, output_dims=2) chan2 = PTM(ptm2, input_dims=2, output_dims=2) rho_targ = rho.evolve(chan1).evolve(chan2) chan = chan1.compose(chan2) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho.evolve(chan), rho_targ) chan = chan1 & chan2 self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho.evolve(chan), rho_targ) def test_dot(self): """Test dot method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = PTM(self.ptmX) chan2 = PTM(self.ptmY) rho_targ = rho.evolve(PTM(self.ptmZ)) self.assertEqual(rho.evolve(chan2.dot(chan1)), rho_targ) self.assertEqual(rho.evolve(chan2 @ chan1), rho_targ) # Compose random ptm1 = self.rand_matrix(4, 4, real=True) ptm2 = self.rand_matrix(4, 4, real=True) chan1 = PTM(ptm1, input_dims=2, output_dims=2) chan2 = PTM(ptm2, input_dims=2, output_dims=2) rho_targ = rho.evolve(chan1).evolve(chan2) self.assertEqual(rho.evolve(chan2.dot(chan1)), rho_targ) self.assertEqual(rho.evolve(chan2 @ chan1), rho_targ) def test_compose_front(self): """Test deprecated front compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = PTM(self.ptmX) chan2 = PTM(self.ptmY) chan = chan2.compose(chan1, front=True) rho_targ = rho.evolve(PTM(self.ptmZ)) self.assertEqual(rho.evolve(chan), rho_targ) # Compose random ptm1 = self.rand_matrix(4, 4, real=True) ptm2 = self.rand_matrix(4, 4, real=True) chan1 = PTM(ptm1, input_dims=2, output_dims=2) chan2 = PTM(ptm2, input_dims=2, output_dims=2) rho_targ = rho.evolve(chan1).evolve(chan2) chan = chan2.compose(chan1, front=True) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho.evolve(chan), rho_targ) def test_expand(self): """Test expand method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = PTM(self.ptmI) chan2 = PTM(self.ptmX) # X \otimes I chan = chan1.expand(chan2) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan2.expand(chan1) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing chan_dep = PTM(self.depol_ptm(1)) chan = chan_dep.expand(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_tensor(self): """Test tensor method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = PTM(self.ptmI) chan2 = PTM(self.ptmX) # X \otimes I chan = chan2.tensor(chan1) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan1.tensor(chan2) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing chan_dep = PTM(self.depol_ptm(1)) chan = chan_dep.tensor(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_power(self): """Test power method.""" # 10% depolarizing channel p_id = 0.9 depol = PTM(self.depol_ptm(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = depol.power(3) targ3 = PTM(self.depol_ptm(1 - p_id3)) self.assertEqual(chan3, targ3) def test_add(self): """Test add method.""" mat1 = 0.5 * self.ptmI mat2 = 0.5 * self.depol_ptm(1) chan1 = PTM(mat1) chan2 = PTM(mat2) targ = PTM(mat1 + mat2) self.assertEqual(chan1._add(chan2), targ) self.assertEqual(chan1 + chan2, targ) targ = PTM(mat1 - mat2) self.assertEqual(chan1 - chan2, targ) def test_add_qargs(self): """Test add method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = PTM(mat) op0 = PTM(mat0) op1 = PTM(mat1) op01 = op1.tensor(op0) eye = PTM(self.ptmI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op + op01([0, 1]) target = op + eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op + op01([1, 0]) target = op + eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op + op01([0, 2]) target = op + op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op + op01([2, 0]) target = op + op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_sub_qargs(self): """Test subtract method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = PTM(mat) op0 = PTM(mat0) op1 = PTM(mat1) op01 = op1.tensor(op0) eye = PTM(self.ptmI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op - op01([0, 1]) target = op - eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op - op01([1, 0]) target = op - eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op - op01([0, 2]) target = op - op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op - op01([2, 0]) target = op - op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_add_except(self): """Test add method raises exceptions.""" chan1 = PTM(self.ptmI) chan2 = PTM(np.eye(16)) self.assertRaises(QiskitError, chan1._add, chan2) self.assertRaises(QiskitError, chan1._add, 5) def test_multiply(self): """Test multiply method.""" chan = PTM(self.ptmI) val = 0.5 targ = PTM(val * self.ptmI) self.assertEqual(chan._multiply(val), targ) self.assertEqual(val * chan, targ) targ = PTM(self.ptmI * val) self.assertEqual(chan * val, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = PTM(self.ptmI) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" chan = PTM(self.ptmI) targ = PTM(-self.ptmI) self.assertEqual(-chan, targ) if __name__ == "__main__": unittest.main()
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 for Stinespring quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info import Stinespring from .channel_test_case import ChannelTestCase class TestStinespring(ChannelTestCase): """Tests for Stinespring channel representation.""" def test_init(self): """Test initialization""" # Initialize from unitary chan = Stinespring(self.UI) assert_allclose(chan.data, self.UI) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize from Stinespring chan = Stinespring(self.depol_stine(0.5)) assert_allclose(chan.data, self.depol_stine(0.5)) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize from Non-CPTP stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2) chan = Stinespring((stine_l, stine_r)) assert_allclose(chan.data, (stine_l, stine_r)) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize with redundant second op chan = Stinespring((stine_l, stine_l)) assert_allclose(chan.data, stine_l) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, Stinespring, stine_l, input_dims=4, output_dims=4) def test_circuit_init(self): """Test initialization from a circuit.""" circuit, target = self.simple_circuit_no_measure() op = Stinespring(circuit) target = Stinespring(target) self.assertEqual(op, target) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, Stinespring, circuit) def test_equal(self): """Test __eq__ method""" stine = tuple(self.rand_matrix(4, 2) for _ in range(2)) self.assertEqual(Stinespring(stine), Stinespring(stine)) def test_copy(self): """Test copy method""" mat = np.eye(4) with self.subTest("Deep copy"): orig = Stinespring(mat) cpy = orig.copy() cpy._data[0][0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = Stinespring(mat) clone = copy.copy(orig) clone._data[0][0, 0] = 0.0 self.assertTrue(clone == orig) def test_clone(self): """Test clone method""" mat = np.eye(4) orig = Stinespring(mat) clone = copy.copy(orig) clone._data[0][0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(Stinespring(self.depol_stine(0.5)).is_cptp()) self.assertTrue(Stinespring(self.UX).is_cptp()) # Non-CP stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2) self.assertFalse(Stinespring((stine_l, stine_r)).is_cptp()) self.assertFalse(Stinespring(self.UI + self.UX).is_cptp()) def test_conjugate(self): """Test conjugate method.""" stine_l, stine_r = self.rand_matrix(16, 2), self.rand_matrix(16, 2) # Single Stinespring list targ = Stinespring(stine_l.conj(), output_dims=4) chan1 = Stinespring(stine_l, output_dims=4) chan = chan1.conjugate() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (2, 4)) # Double Stinespring list targ = Stinespring((stine_l.conj(), stine_r.conj()), output_dims=4) chan1 = Stinespring((stine_l, stine_r), output_dims=4) chan = chan1.conjugate() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (2, 4)) def test_transpose(self): """Test transpose method.""" stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2) # Single square Stinespring list targ = Stinespring(stine_l.T, 4, 2) chan1 = Stinespring(stine_l, 2, 4) chan = chan1.transpose() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) # Double square Stinespring list targ = Stinespring((stine_l.T, stine_r.T), 4, 2) chan1 = Stinespring((stine_l, stine_r), 2, 4) chan = chan1.transpose() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) def test_adjoint(self): """Test adjoint method.""" stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2) # Single square Stinespring list targ = Stinespring(stine_l.T.conj(), 4, 2) chan1 = Stinespring(stine_l, 2, 4) chan = chan1.adjoint() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) # Double square Stinespring list targ = Stinespring((stine_l.T.conj(), stine_r.T.conj()), 4, 2) chan1 = Stinespring((stine_l, stine_r), 2, 4) chan = chan1.adjoint() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, Stinespring(np.eye(2)).compose, Stinespring(np.eye(4))) self.assertRaises(QiskitError, Stinespring(np.eye(2)).compose, 2) def test_compose(self): """Test compose method.""" # Random input test state rho_init = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Stinespring(self.UX) chan2 = Stinespring(self.UY) chan = chan1.compose(chan2) rho_targ = rho_init & Stinespring(self.UZ) self.assertEqual(rho_init.evolve(chan), rho_targ) # 50% depolarizing channel chan1 = Stinespring(self.depol_stine(0.5)) chan = chan1.compose(chan1) rho_targ = rho_init & Stinespring(self.depol_stine(0.75)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Compose different dimensions stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4) chan1 = Stinespring(stine1, input_dims=2, output_dims=4) chan2 = Stinespring(stine2, input_dims=4, output_dims=2) rho_targ = rho_init & chan1 & chan2 chan = chan1.compose(chan2) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan1 & chan2 self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_dot(self): """Test deprecated front compose method.""" # Random input test state rho_init = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Stinespring(self.UX) chan2 = Stinespring(self.UY) rho_targ = rho_init.evolve(Stinespring(self.UZ)) self.assertEqual(rho_init.evolve(chan1.dot(chan2)), rho_targ) self.assertEqual(rho_init.evolve(chan1 @ chan2), rho_targ) # 50% depolarizing channel chan1 = Stinespring(self.depol_stine(0.5)) rho_targ = rho_init & Stinespring(self.depol_stine(0.75)) self.assertEqual(rho_init.evolve(chan1.dot(chan1)), rho_targ) self.assertEqual(rho_init.evolve(chan1 @ chan1), rho_targ) # Compose different dimensions stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4) chan1 = Stinespring(stine1, input_dims=2, output_dims=4) chan2 = Stinespring(stine2, input_dims=4, output_dims=2) rho_targ = rho_init & chan1 & chan2 self.assertEqual(rho_init.evolve(chan2.dot(chan1)), rho_targ) self.assertEqual(rho_init.evolve(chan2 @ chan1), rho_targ) def test_compose_front(self): """Test deprecated front compose method.""" # Random input test state rho_init = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Stinespring(self.UX) chan2 = Stinespring(self.UY) chan = chan1.compose(chan2, front=True) rho_targ = rho_init & Stinespring(self.UZ) self.assertEqual(rho_init.evolve(chan), rho_targ) # 50% depolarizing channel chan1 = Stinespring(self.depol_stine(0.5)) chan = chan1.compose(chan1, front=True) rho_targ = rho_init & Stinespring(self.depol_stine(0.75)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Compose different dimensions stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4) chan1 = Stinespring(stine1, input_dims=2, output_dims=4) chan2 = Stinespring(stine2, input_dims=4, output_dims=2) rho_targ = rho_init & chan1 & chan2 chan = chan2.compose(chan1, front=True) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_expand(self): """Test expand method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Stinespring(self.UI) chan2 = Stinespring(self.UX) # X \otimes I chan = chan1.expand(chan2) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan2.expand(chan1) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing chan_dep = Stinespring(self.depol_stine(1)) chan = chan_dep.expand(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_tensor(self): """Test tensor method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Stinespring(self.UI) chan2 = Stinespring(self.UX) # X \otimes I chan = chan2.tensor(chan1) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan1.tensor(chan2) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing chan_dep = Stinespring(self.depol_stine(1)) chan = chan_dep.tensor(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_power(self): """Test power method.""" # 10% depolarizing channel rho_init = DensityMatrix(np.diag([1, 0])) p_id = 0.9 chan1 = Stinespring(self.depol_stine(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan = chan1.power(3) rho_targ = rho_init & chan1 & chan1 & chan1 self.assertEqual(rho_init & chan, rho_targ) rho_targ = rho_init & Stinespring(self.depol_stine(1 - p_id3)) self.assertEqual(rho_init & chan, rho_targ) def test_add(self): """Test add method.""" # Random input test state rho_init = DensityMatrix(self.rand_rho(2)) stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2) # Random Single-Stinespring maps chan1 = Stinespring(stine1, input_dims=2, output_dims=4) chan2 = Stinespring(stine2, input_dims=2, output_dims=4) rho_targ = (rho_init & chan1) + (rho_init & chan2) chan = chan1._add(chan2) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan1 + chan2 self.assertEqual(rho_init.evolve(chan), rho_targ) # Random Single-Stinespring maps chan = Stinespring((stine1, stine2)) rho_targ = 2 * (rho_init & chan) chan = chan._add(chan) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_subtract(self): """Test subtract method.""" # Random input test state rho_init = DensityMatrix(self.rand_rho(2)) stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2) # Random Single-Stinespring maps chan1 = Stinespring(stine1, input_dims=2, output_dims=4) chan2 = Stinespring(stine2, input_dims=2, output_dims=4) rho_targ = (rho_init & chan1) - (rho_init & chan2) chan = chan1 - chan2 self.assertEqual(rho_init.evolve(chan), rho_targ) # Random Single-Stinespring maps chan = Stinespring((stine1, stine2)) rho_targ = 0 * (rho_init & chan) chan = chan - chan self.assertEqual(rho_init.evolve(chan), rho_targ) def test_add_qargs(self): """Test add method with qargs.""" rho = DensityMatrix(self.rand_rho(8)) stine = self.rand_matrix(32, 8) stine0 = self.rand_matrix(8, 2) op = Stinespring(stine) op0 = Stinespring(stine0) eye = Stinespring(self.UI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(rho & value, rho & target) def test_sub_qargs(self): """Test sub method with qargs.""" rho = DensityMatrix(self.rand_rho(8)) stine = self.rand_matrix(32, 8) stine0 = self.rand_matrix(8, 2) op = Stinespring(stine) op0 = Stinespring(stine0) eye = Stinespring(self.UI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(rho & value, rho & target) def test_multiply(self): """Test multiply method.""" # Random initial state and Stinespring ops rho_init = DensityMatrix(self.rand_rho(2)) val = 0.5 stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2) # Single Stinespring set chan1 = Stinespring(stine1, input_dims=2, output_dims=4) rho_targ = val * (rho_init & chan1) chan = chan1._multiply(val) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = val * chan1 self.assertEqual(rho_init.evolve(chan), rho_targ) rho_targ = (rho_init & chan1) * val chan = chan1 * val self.assertEqual(rho_init.evolve(chan), rho_targ) # Double Stinespring set chan2 = Stinespring((stine1, stine2), input_dims=2, output_dims=4) rho_targ = val * (rho_init & chan2) chan = chan2._multiply(val) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = val * chan2 self.assertEqual(rho_init.evolve(chan), rho_targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = Stinespring(self.depol_stine(1)) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" rho_init = DensityMatrix(np.diag([1, 0])) rho_targ = DensityMatrix(np.diag([-0.5, -0.5])) chan = -Stinespring(self.depol_stine(1)) self.assertEqual(rho_init.evolve(chan), rho_targ) if __name__ == "__main__": unittest.main()
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 for SuperOp quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError, QuantumCircuit from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.operators import Operator from qiskit.quantum_info.operators.channel import SuperOp from .channel_test_case import ChannelTestCase class TestSuperOp(ChannelTestCase): """Tests for SuperOp channel representation.""" def test_init(self): """Test initialization""" chan = SuperOp(self.sopI) assert_allclose(chan.data, self.sopI) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) mat = np.zeros((4, 16)) chan = SuperOp(mat) assert_allclose(chan.data, mat) self.assertEqual(chan.dim, (4, 2)) self.assertIsNone(chan.num_qubits) chan = SuperOp(mat.T) assert_allclose(chan.data, mat.T) self.assertEqual(chan.dim, (2, 4)) self.assertIsNone(chan.num_qubits) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, SuperOp, mat, input_dims=[4], output_dims=[4]) def test_circuit_init(self): """Test initialization from a circuit.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) op = SuperOp(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = SuperOp(Operator(np.kron(y90, np.kron(self.UX, self.UH)))) self.assertEqual(target, op) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 0, 1) op = SuperOp(circuit) target = SuperOp(Operator(np.diag([1, 1, 1, np.exp(1j * lam)]))) self.assertEqual(target, op) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(0, 1) op = SuperOp(circuit) target = SuperOp( Operator(np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))) ) self.assertEqual(target, op) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, SuperOp, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(4, 4) self.assertEqual(SuperOp(mat), SuperOp(mat)) def test_copy(self): """Test copy method""" mat = np.eye(4) with self.subTest("Deep copy"): orig = SuperOp(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = SuperOp(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_clone(self): """Test clone method""" mat = np.eye(4) orig = SuperOp(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_evolve(self): """Test evolve method.""" input_rho = DensityMatrix([[0, 0], [0, 1]]) # Identity channel chan = SuperOp(self.sopI) target_rho = DensityMatrix([[0, 0], [0, 1]]) self.assertEqual(input_rho.evolve(chan), target_rho) # Hadamard channel mat = np.array([[1, 1], [1, -1]]) / np.sqrt(2) chan = SuperOp(np.kron(mat.conj(), mat)) target_rho = DensityMatrix(np.array([[1, -1], [-1, 1]]) / 2) self.assertEqual(input_rho.evolve(chan), target_rho) # Completely depolarizing channel chan = SuperOp(self.depol_sop(1)) target_rho = DensityMatrix(np.eye(2) / 2) self.assertEqual(input_rho.evolve(chan), target_rho) def test_evolve_subsystem(self): """Test subsystem evolve method.""" # Single-qubit random superoperators op_a = SuperOp(self.rand_matrix(4, 4)) op_b = SuperOp(self.rand_matrix(4, 4)) op_c = SuperOp(self.rand_matrix(4, 4)) id1 = SuperOp(np.eye(4)) id2 = SuperOp(np.eye(16)) rho = DensityMatrix(self.rand_rho(8)) # Test evolving single-qubit of 3-qubit system op = op_a # Evolve on qubit 0 full_op = id2.tensor(op_a) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[0]) self.assertEqual(rho_test, rho_targ) # Evolve on qubit 1 full_op = id1.tensor(op_a).tensor(id1) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[1]) self.assertEqual(rho_test, rho_targ) # Evolve on qubit 2 full_op = op_a.tensor(id2) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[2]) self.assertEqual(rho_test, rho_targ) # Test 2-qubit evolution op = op_b.tensor(op_a) # Evolve on qubits [0, 2] full_op = op_b.tensor(id1).tensor(op_a) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[0, 2]) self.assertEqual(rho_test, rho_targ) # Evolve on qubits [2, 0] full_op = op_a.tensor(id1).tensor(op_b) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[2, 0]) self.assertEqual(rho_test, rho_targ) # Test 3-qubit evolution op = op_c.tensor(op_b).tensor(op_a) # Evolve on qubits [0, 1, 2] full_op = op rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[0, 1, 2]) self.assertEqual(rho_test, rho_targ) # Evolve on qubits [2, 1, 0] full_op = op_a.tensor(op_b).tensor(op_c) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[2, 1, 0]) self.assertEqual(rho_test, rho_targ) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(SuperOp(self.depol_sop(0.25)).is_cptp()) # Non-CPTP should return false self.assertFalse(SuperOp(1.25 * self.sopI - 0.25 * self.depol_sop(1)).is_cptp()) def test_conjugate(self): """Test conjugate method.""" mat = self.rand_matrix(4, 4) chan = SuperOp(mat) targ = SuperOp(np.conjugate(mat)) self.assertEqual(chan.conjugate(), targ) def test_transpose(self): """Test transpose method.""" mat = self.rand_matrix(4, 4) chan = SuperOp(mat) targ = SuperOp(np.transpose(mat)) self.assertEqual(chan.transpose(), targ) def test_adjoint(self): """Test adjoint method.""" mat = self.rand_matrix(4, 4) chan = SuperOp(mat) targ = SuperOp(np.transpose(np.conj(mat))) self.assertEqual(chan.adjoint(), targ) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, SuperOp(np.eye(4)).compose, SuperOp(np.eye(16))) self.assertRaises(QiskitError, SuperOp(np.eye(4)).compose, 2) def test_compose(self): """Test compose method.""" # UnitaryChannel evolution chan1 = SuperOp(self.sopX) chan2 = SuperOp(self.sopY) chan = chan1.compose(chan2) targ = SuperOp(self.sopZ) self.assertEqual(chan, targ) # 50% depolarizing channel chan1 = SuperOp(self.depol_sop(0.5)) chan = chan1.compose(chan1) targ = SuperOp(self.depol_sop(0.75)) self.assertEqual(chan, targ) # Random superoperator mat1 = self.rand_matrix(4, 4) mat2 = self.rand_matrix(4, 4) chan1 = SuperOp(mat1) chan2 = SuperOp(mat2) targ = SuperOp(np.dot(mat2, mat1)) self.assertEqual(chan1.compose(chan2), targ) self.assertEqual(chan1 & chan2, targ) targ = SuperOp(np.dot(mat1, mat2)) self.assertEqual(chan2.compose(chan1), targ) self.assertEqual(chan2 & chan1, targ) # Compose different dimensions chan1 = SuperOp(self.rand_matrix(16, 4)) chan2 = SuperOp( self.rand_matrix(4, 16), ) chan = chan1.compose(chan2) self.assertEqual(chan.dim, (2, 2)) chan = chan2.compose(chan1) self.assertEqual(chan.dim, (4, 4)) def test_dot(self): """Test dot method.""" # UnitaryChannel evolution chan1 = SuperOp(self.sopX) chan2 = SuperOp(self.sopY) targ = SuperOp(self.sopZ) self.assertEqual(chan1.dot(chan2), targ) self.assertEqual(chan1 @ chan2, targ) # 50% depolarizing channel chan1 = SuperOp(self.depol_sop(0.5)) targ = SuperOp(self.depol_sop(0.75)) self.assertEqual(chan1.dot(chan1), targ) self.assertEqual(chan1 @ chan1, targ) # Random superoperator mat1 = self.rand_matrix(4, 4) mat2 = self.rand_matrix(4, 4) chan1 = SuperOp(mat1) chan2 = SuperOp(mat2) targ = SuperOp(np.dot(mat2, mat1)) self.assertEqual(chan2.dot(chan1), targ) targ = SuperOp(np.dot(mat1, mat2)) # Compose different dimensions chan1 = SuperOp(self.rand_matrix(16, 4)) chan2 = SuperOp(self.rand_matrix(4, 16)) chan = chan1.dot(chan2) self.assertEqual(chan.dim, (4, 4)) chan = chan1 @ chan2 self.assertEqual(chan.dim, (4, 4)) chan = chan2.dot(chan1) self.assertEqual(chan.dim, (2, 2)) chan = chan2 @ chan1 self.assertEqual(chan.dim, (2, 2)) def test_compose_front(self): """Test front compose method.""" # DEPRECATED # UnitaryChannel evolution chan1 = SuperOp(self.sopX) chan2 = SuperOp(self.sopY) chan = chan1.compose(chan2, front=True) targ = SuperOp(self.sopZ) self.assertEqual(chan, targ) # 50% depolarizing channel chan1 = SuperOp(self.depol_sop(0.5)) chan = chan1.compose(chan1, front=True) targ = SuperOp(self.depol_sop(0.75)) self.assertEqual(chan, targ) # Random superoperator mat1 = self.rand_matrix(4, 4) mat2 = self.rand_matrix(4, 4) chan1 = SuperOp(mat1) chan2 = SuperOp(mat2) targ = SuperOp(np.dot(mat2, mat1)) self.assertEqual(chan2.compose(chan1, front=True), targ) targ = SuperOp(np.dot(mat1, mat2)) self.assertEqual(chan1.compose(chan2, front=True), targ) # Compose different dimensions chan1 = SuperOp(self.rand_matrix(16, 4)) chan2 = SuperOp(self.rand_matrix(4, 16)) chan = chan1.compose(chan2, front=True) self.assertEqual(chan.dim, (4, 4)) chan = chan2.compose(chan1, front=True) self.assertEqual(chan.dim, (2, 2)) def test_compose_subsystem(self): """Test subsystem compose method.""" # 3-qubit superoperator mat = self.rand_matrix(64, 64) mat_a = self.rand_matrix(4, 4) mat_b = self.rand_matrix(4, 4) mat_c = self.rand_matrix(4, 4) iden = SuperOp(np.eye(4)) op = SuperOp(mat) op1 = SuperOp(mat_a) op2 = SuperOp(mat_b).tensor(SuperOp(mat_a)) op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) # op3 qargs=[0, 1, 2] full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op3, qargs=[0, 1, 2]), SuperOp(targ)) self.assertEqual(op & op3([0, 1, 2]), SuperOp(targ)) # op3 qargs=[2, 1, 0] full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c)) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op3, qargs=[2, 1, 0]), SuperOp(targ)) self.assertEqual(op & op3([2, 1, 0]), SuperOp(targ)) # op2 qargs=[0, 1] full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op2, qargs=[0, 1]), SuperOp(targ)) self.assertEqual(op & op2([0, 1]), SuperOp(targ)) # op2 qargs=[2, 0] full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b)) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op2, qargs=[2, 0]), SuperOp(targ)) self.assertEqual(op & op2([2, 0]), SuperOp(targ)) # op1 qargs=[0] full_op = iden.tensor(iden).tensor(SuperOp(mat_a)) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op1, qargs=[0]), SuperOp(targ)) self.assertEqual(op & op1([0]), SuperOp(targ)) # op1 qargs=[1] full_op = iden.tensor(SuperOp(mat_a)).tensor(iden) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op1, qargs=[1]), SuperOp(targ)) self.assertEqual(op & op1([1]), SuperOp(targ)) # op1 qargs=[2] full_op = SuperOp(mat_a).tensor(iden).tensor(iden) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op1, qargs=[2]), SuperOp(targ)) self.assertEqual(op & op1([2]), SuperOp(targ)) def test_dot_subsystem(self): """Test subsystem dot method.""" # 3-qubit operator mat = self.rand_matrix(64, 64) mat_a = self.rand_matrix(4, 4) mat_b = self.rand_matrix(4, 4) mat_c = self.rand_matrix(4, 4) iden = SuperOp(np.eye(4)) op = SuperOp(mat) op1 = SuperOp(mat_a) op2 = SuperOp(mat_b).tensor(SuperOp(mat_a)) op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) # op3 qargs=[0, 1, 2] full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op3, qargs=[0, 1, 2]), SuperOp(targ)) # op3 qargs=[2, 1, 0] full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c)) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op3, qargs=[2, 1, 0]), SuperOp(targ)) # op2 qargs=[0, 1] full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op2, qargs=[0, 1]), SuperOp(targ)) # op2 qargs=[2, 0] full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b)) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op2, qargs=[2, 0]), SuperOp(targ)) # op1 qargs=[0] full_op = iden.tensor(iden).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op1, qargs=[0]), SuperOp(targ)) # op1 qargs=[1] full_op = iden.tensor(SuperOp(mat_a)).tensor(iden) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op1, qargs=[1]), SuperOp(targ)) # op1 qargs=[2] full_op = SuperOp(mat_a).tensor(iden).tensor(iden) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op1, qargs=[2]), SuperOp(targ)) def test_compose_front_subsystem(self): """Test subsystem front compose method.""" # 3-qubit operator mat = self.rand_matrix(64, 64) mat_a = self.rand_matrix(4, 4) mat_b = self.rand_matrix(4, 4) mat_c = self.rand_matrix(4, 4) iden = SuperOp(np.eye(4)) op = SuperOp(mat) op1 = SuperOp(mat_a) op2 = SuperOp(mat_b).tensor(SuperOp(mat_a)) op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) # op3 qargs=[0, 1, 2] full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op3, qargs=[0, 1, 2], front=True), SuperOp(targ)) # op3 qargs=[2, 1, 0] full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c)) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op3, qargs=[2, 1, 0], front=True), SuperOp(targ)) # op2 qargs=[0, 1] full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op2, qargs=[0, 1], front=True), SuperOp(targ)) # op2 qargs=[2, 0] full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b)) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op2, qargs=[2, 0], front=True), SuperOp(targ)) # op1 qargs=[0] full_op = iden.tensor(iden).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op1, qargs=[0], front=True), SuperOp(targ)) # op1 qargs=[1] full_op = iden.tensor(SuperOp(mat_a)).tensor(iden) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op1, qargs=[1], front=True), SuperOp(targ)) # op1 qargs=[2] full_op = SuperOp(mat_a).tensor(iden).tensor(iden) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op1, qargs=[2], front=True), SuperOp(targ)) def test_expand(self): """Test expand method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = SuperOp(self.sopI) chan2 = SuperOp(self.sopX) # X \otimes I chan = chan1.expand(chan2) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan2.expand(chan1) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_tensor(self): """Test tensor method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = SuperOp(self.sopI) chan2 = SuperOp(self.sopX) # X \otimes I chan = chan2.tensor(chan1) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan2 ^ chan1 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan1.tensor(chan2) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan1 ^ chan2 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_power(self): """Test power method.""" # 10% depolarizing channel p_id = 0.9 depol = SuperOp(self.depol_sop(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = depol.power(3) targ3 = SuperOp(self.depol_sop(1 - p_id3)) self.assertEqual(chan3, targ3) def test_add(self): """Test add method.""" mat1 = 0.5 * self.sopI mat2 = 0.5 * self.depol_sop(1) chan1 = SuperOp(mat1) chan2 = SuperOp(mat2) targ = SuperOp(mat1 + mat2) self.assertEqual(chan1._add(chan2), targ) self.assertEqual(chan1 + chan2, targ) targ = SuperOp(mat1 - mat2) self.assertEqual(chan1 - chan2, targ) def test_add_qargs(self): """Test add method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = SuperOp(mat) op0 = SuperOp(mat0) op1 = SuperOp(mat1) op01 = op1.tensor(op0) eye = SuperOp(self.sopI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op + op01([0, 1]) target = op + eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op + op01([1, 0]) target = op + eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op + op01([0, 2]) target = op + op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op + op01([2, 0]) target = op + op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_sub_qargs(self): """Test subtract method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = SuperOp(mat) op0 = SuperOp(mat0) op1 = SuperOp(mat1) op01 = op1.tensor(op0) eye = SuperOp(self.sopI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op - op01([0, 1]) target = op - eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op - op01([1, 0]) target = op - eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op - op01([0, 2]) target = op - op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op - op01([2, 0]) target = op - op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_add_except(self): """Test add method raises exceptions.""" chan1 = SuperOp(self.sopI) chan2 = SuperOp(np.eye(16)) self.assertRaises(QiskitError, chan1._add, chan2) self.assertRaises(QiskitError, chan1._add, 5) def test_multiply(self): """Test multiply method.""" chan = SuperOp(self.sopI) val = 0.5 targ = SuperOp(val * self.sopI) self.assertEqual(chan._multiply(val), targ) self.assertEqual(val * chan, targ) targ = SuperOp(self.sopI * val) self.assertEqual(chan * val, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = SuperOp(self.sopI) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" chan = SuperOp(self.sopI) targ = SuperOp(-self.sopI) self.assertEqual(-chan, targ) if __name__ == "__main__": unittest.main()
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 for quantum channel representation transformations.""" import unittest import numpy as np from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.channel.choi import Choi from qiskit.quantum_info.operators.channel.superop import SuperOp from qiskit.quantum_info.operators.channel.kraus import Kraus from qiskit.quantum_info.operators.channel.stinespring import Stinespring from qiskit.quantum_info.operators.channel.ptm import PTM from qiskit.quantum_info.operators.channel.chi import Chi from .channel_test_case import ChannelTestCase class TestTransformations(ChannelTestCase): """Tests for Operator channel representation.""" unitary_mat = [ ChannelTestCase.UI, ChannelTestCase.UX, ChannelTestCase.UY, ChannelTestCase.UZ, ChannelTestCase.UH, ] unitary_choi = [ ChannelTestCase.choiI, ChannelTestCase.choiX, ChannelTestCase.choiY, ChannelTestCase.choiZ, ChannelTestCase.choiH, ] unitary_chi = [ ChannelTestCase.chiI, ChannelTestCase.chiX, ChannelTestCase.chiY, ChannelTestCase.chiZ, ChannelTestCase.chiH, ] unitary_sop = [ ChannelTestCase.sopI, ChannelTestCase.sopX, ChannelTestCase.sopY, ChannelTestCase.sopZ, ChannelTestCase.sopH, ] unitary_ptm = [ ChannelTestCase.ptmI, ChannelTestCase.ptmX, ChannelTestCase.ptmY, ChannelTestCase.ptmZ, ChannelTestCase.ptmH, ] def test_operator_to_operator(self): """Test Operator to Operator transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Operator(mat) chan2 = Operator(chan1) self.assertEqual(chan1, chan2) def test_operator_to_choi(self): """Test Operator to Choi transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Choi(choi) chan2 = Choi(Operator(mat)) self.assertEqual(chan1, chan2) def test_operator_to_superop(self): """Test Operator to SuperOp transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(Operator(mat)) self.assertEqual(chan1, chan2) def test_operator_to_kraus(self): """Test Operator to Kraus transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Kraus(mat) chan2 = Kraus(Operator(mat)) self.assertEqual(chan1, chan2) def test_operator_to_stinespring(self): """Test Operator to Stinespring transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Stinespring(mat) chan2 = Stinespring(Operator(chan1)) self.assertEqual(chan1, chan2) def test_operator_to_chi(self): """Test Operator to Chi transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Chi(chi) chan2 = Chi(Operator(mat)) self.assertEqual(chan1, chan2) def test_operator_to_ptm(self): """Test Operator to PTM transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(Operator(mat)) self.assertEqual(chan1, chan2) def test_choi_to_operator(self): """Test Choi to Operator transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Operator(mat) chan2 = Operator(Choi(choi)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) def test_choi_to_choi(self): """Test Choi to Choi transformation.""" # Test unitary channels for choi in self.unitary_choi: chan1 = Choi(choi) chan2 = Choi(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(chan1) self.assertEqual(chan1, chan2) def test_choi_to_superop(self): """Test Choi to SuperOp transformation.""" # Test unitary channels for choi, sop in zip(self.unitary_choi, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(Choi(choi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(Choi(self.depol_choi(p))) self.assertEqual(chan1, chan2) def test_choi_to_kraus(self): """Test Choi to Kraus transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Kraus(mat) chan2 = Kraus(Choi(choi)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Kraus(self.depol_kraus(p))) output = rho.evolve(Kraus(Choi(self.depol_choi(p)))) self.assertEqual(output, target) def test_choi_to_stinespring(self): """Test Choi to Stinespring transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Kraus(mat) chan2 = Kraus(Choi(choi)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(Choi(self.depol_choi(p)))) self.assertEqual(output, target) def test_choi_to_chi(self): """Test Choi to Chi transformation.""" # Test unitary channels for choi, chi in zip(self.unitary_choi, self.unitary_chi): chan1 = Chi(chi) chan2 = Chi(Choi(choi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(Choi(self.depol_choi(p))) self.assertEqual(chan1, chan2) def test_choi_to_ptm(self): """Test Choi to PTM transformation.""" # Test unitary channels for choi, ptm in zip(self.unitary_choi, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(Choi(choi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(Choi(self.depol_choi(p))) self.assertEqual(chan1, chan2) def test_superop_to_operator(self): """Test SuperOp to Operator transformation.""" for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = Operator(mat) chan2 = Operator(SuperOp(sop)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, SuperOp(self.depol_sop(0.5))) def test_superop_to_choi(self): """Test SuperOp to Choi transformation.""" # Test unitary channels for choi, sop in zip(self.unitary_choi, self.unitary_sop): chan1 = Choi(choi) chan2 = Choi(SuperOp(sop)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0, 0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(SuperOp(self.depol_sop(p))) self.assertEqual(chan1, chan2) def test_superop_to_superop(self): """Test SuperOp to SuperOp transformation.""" # Test unitary channels for sop in self.unitary_sop: chan1 = SuperOp(sop) chan2 = SuperOp(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0, 0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(chan1) self.assertEqual(chan1, chan2) def test_superop_to_kraus(self): """Test SuperOp to Kraus transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = Kraus(mat) chan2 = Kraus(SuperOp(sop)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Kraus(self.depol_kraus(p))) output = rho.evolve(Kraus(SuperOp(self.depol_sop(p)))) self.assertEqual(output, target) def test_superop_to_stinespring(self): """Test SuperOp to Stinespring transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = Stinespring(mat) chan2 = Stinespring(SuperOp(sop)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(SuperOp(self.depol_sop(p)))) self.assertEqual(output, target) def test_superop_to_chi(self): """Test SuperOp to Chi transformation.""" # Test unitary channels for sop, ptm in zip(self.unitary_sop, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(SuperOp(sop)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(SuperOp(self.depol_sop(p))) self.assertEqual(chan1, chan2) def test_superop_to_ptm(self): """Test SuperOp to PTM transformation.""" # Test unitary channels for sop, ptm in zip(self.unitary_sop, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(SuperOp(sop)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(SuperOp(self.depol_sop(p))) self.assertEqual(chan1, chan2) def test_kraus_to_operator(self): """Test Kraus to Operator transformation.""" for mat in self.unitary_mat: chan1 = Operator(mat) chan2 = Operator(Kraus(mat)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, Kraus(self.depol_kraus(0.5))) def test_kraus_to_choi(self): """Test Kraus to Choi transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Choi(choi) chan2 = Choi(Kraus(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(Kraus(self.depol_kraus(p))) self.assertEqual(chan1, chan2) def test_kraus_to_superop(self): """Test Kraus to SuperOp transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(Kraus(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(Kraus(self.depol_kraus(p))) self.assertEqual(chan1, chan2) def test_kraus_to_kraus(self): """Test Kraus to Kraus transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Kraus(mat) chan2 = Kraus(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Kraus(self.depol_kraus(p)) chan2 = Kraus(chan1) self.assertEqual(chan1, chan2) def test_kraus_to_stinespring(self): """Test Kraus to Stinespring transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Stinespring(mat) chan2 = Stinespring(Kraus(mat)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(Kraus(self.depol_kraus(p)))) self.assertEqual(output, target) def test_kraus_to_chi(self): """Test Kraus to Chi transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Chi(chi) chan2 = Chi(Kraus(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(Kraus(self.depol_kraus(p))) self.assertEqual(chan1, chan2) def test_kraus_to_ptm(self): """Test Kraus to PTM transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(Kraus(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(Kraus(self.depol_kraus(p))) self.assertEqual(chan1, chan2) def test_stinespring_to_operator(self): """Test Stinespring to Operator transformation.""" for mat in self.unitary_mat: chan1 = Operator(mat) chan2 = Operator(Stinespring(mat)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, Stinespring(self.depol_stine(0.5))) def test_stinespring_to_choi(self): """Test Stinespring to Choi transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Choi(choi) chan2 = Choi(Stinespring(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(Stinespring(self.depol_stine(p))) self.assertEqual(chan1, chan2) def test_stinespring_to_superop(self): """Test Stinespring to SuperOp transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(Kraus(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(Stinespring(self.depol_stine(p))) self.assertEqual(chan1, chan2) def test_stinespring_to_kraus(self): """Test Stinespring to Kraus transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Kraus(mat) chan2 = Kraus(Stinespring(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Kraus(self.depol_kraus(p)) chan2 = Kraus(Stinespring(self.depol_stine(p))) self.assertEqual(chan1, chan2) def test_stinespring_to_stinespring(self): """Test Stinespring to Stinespring transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Stinespring(mat) chan2 = Stinespring(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Stinespring(self.depol_stine(p)) chan2 = Stinespring(chan1) self.assertEqual(chan1, chan2) def test_stinespring_to_chi(self): """Test Stinespring to Chi transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Chi(chi) chan2 = Chi(Stinespring(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(Stinespring(self.depol_stine(p))) self.assertEqual(chan1, chan2) def test_stinespring_to_ptm(self): """Test Stinespring to PTM transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(Stinespring(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(Stinespring(self.depol_stine(p))) self.assertEqual(chan1, chan2) def test_chi_to_operator(self): """Test Chi to Operator transformation.""" for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Operator(mat) chan2 = Operator(Chi(chi)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, Chi(self.depol_chi(0.5))) def test_chi_to_choi(self): """Test Chi to Choi transformation.""" # Test unitary channels for chi, choi in zip(self.unitary_chi, self.unitary_choi): chan1 = Choi(choi) chan2 = Choi(Chi(chi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(Chi(self.depol_chi(p))) self.assertEqual(chan1, chan2) def test_chi_to_superop(self): """Test Chi to SuperOp transformation.""" # Test unitary channels for chi, sop in zip(self.unitary_chi, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(Chi(chi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(Chi(self.depol_chi(p))) self.assertEqual(chan1, chan2) def test_chi_to_kraus(self): """Test Chi to Kraus transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Kraus(mat) chan2 = Kraus(Chi(chi)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Kraus(self.depol_kraus(p))) output = rho.evolve(Kraus(Chi(self.depol_chi(p)))) self.assertEqual(output, target) def test_chi_to_stinespring(self): """Test Chi to Stinespring transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Kraus(mat) chan2 = Kraus(Chi(chi)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(Chi(self.depol_chi(p)))) self.assertEqual(output, target) def test_chi_to_chi(self): """Test Chi to Chi transformation.""" # Test unitary channels for chi in self.unitary_chi: chan1 = Chi(chi) chan2 = Chi(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(chan1) self.assertEqual(chan1, chan2) def test_chi_to_ptm(self): """Test Chi to PTM transformation.""" # Test unitary channels for chi, ptm in zip(self.unitary_chi, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(Chi(chi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(Chi(self.depol_chi(p))) self.assertEqual(chan1, chan2) def test_ptm_to_operator(self): """Test PTM to Operator transformation.""" for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = Operator(mat) chan2 = Operator(PTM(ptm)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, PTM(self.depol_ptm(0.5))) def test_ptm_to_choi(self): """Test PTM to Choi transformation.""" # Test unitary channels for ptm, choi in zip(self.unitary_ptm, self.unitary_choi): chan1 = Choi(choi) chan2 = Choi(PTM(ptm)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(PTM(self.depol_ptm(p))) self.assertEqual(chan1, chan2) def test_ptm_to_superop(self): """Test PTM to SuperOp transformation.""" # Test unitary channels for ptm, sop in zip(self.unitary_ptm, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(PTM(ptm)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(PTM(self.depol_ptm(p))) self.assertEqual(chan1, chan2) def test_ptm_to_kraus(self): """Test PTM to Kraus transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = Kraus(mat) chan2 = Kraus(PTM(ptm)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Kraus(self.depol_kraus(p))) output = rho.evolve(Kraus(PTM(self.depol_ptm(p)))) self.assertEqual(output, target) def test_ptm_to_stinespring(self): """Test PTM to Stinespring transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = Kraus(mat) chan2 = Kraus(PTM(ptm)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(PTM(self.depol_ptm(p)))) self.assertEqual(output, target) def test_ptm_to_chi(self): """Test PTM to Chi transformation.""" # Test unitary channels for chi, ptm in zip(self.unitary_chi, self.unitary_ptm): chan1 = Chi(chi) chan2 = Chi(PTM(ptm)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(PTM(self.depol_ptm(p))) self.assertEqual(chan1, chan2) def test_ptm_to_ptm(self): """Test PTM to PTM transformation.""" # Test unitary channels for ptm in self.unitary_ptm: chan1 = PTM(ptm) chan2 = PTM(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(chan1) self.assertEqual(chan1, chan2) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for qiskit/tools/parallel""" import os import time from unittest.mock import patch from qiskit.tools.parallel import get_platform_parallel_default, parallel_map from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.pulse import Schedule from qiskit.test import QiskitTestCase def _parfunc(x): """Function for testing parallel_map""" time.sleep(1) return x def _build_simple_circuit(_): qreg = QuantumRegister(2) creg = ClassicalRegister(2) qc = QuantumCircuit(qreg, creg) return qc def _build_simple_schedule(_): return Schedule() class TestGetPlatformParallelDefault(QiskitTestCase): """Tests get_parallel_default_for_platform.""" def test_windows_parallel_default(self): """Verifies the parallel default for Windows.""" with patch("sys.platform", "win32"): parallel_default = get_platform_parallel_default() self.assertEqual(parallel_default, False) def test_mac_os_unsupported_version_parallel_default(self): """Verifies the parallel default for macOS.""" with patch("sys.platform", "darwin"): with patch("sys.version_info", (3, 8, 0, "final", 0)): parallel_default = get_platform_parallel_default() self.assertEqual(parallel_default, False) def test_other_os_parallel_default(self): """Verifies the parallel default for Linux and other OSes.""" with patch("sys.platform", "linux"): parallel_default = get_platform_parallel_default() self.assertEqual(parallel_default, True) class TestParallel(QiskitTestCase): """A class for testing parallel_map functionality.""" def test_parallel_env_flag(self): """Verify parallel env flag is set""" self.assertEqual(os.getenv("QISKIT_IN_PARALLEL", None), "FALSE") def test_parallel(self): """Test parallel_map""" ans = parallel_map(_parfunc, list(range(10))) self.assertEqual(ans, list(range(10))) def test_parallel_circuit_names(self): """Verify unique circuit names in parallel""" out_circs = parallel_map(_build_simple_circuit, list(range(10))) names = [circ.name for circ in out_circs] self.assertEqual(len(names), len(set(names))) def test_parallel_schedule_names(self): """Verify unique schedule names in parallel""" out_schedules = parallel_map(_build_simple_schedule, list(range(10))) names = [schedule.name for schedule in out_schedules] self.assertEqual(len(names), len(set(names)))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for the wrapper functionality.""" import os import sys import unittest from qiskit.utils import optionals from qiskit.test import Path, QiskitTestCase, slow_test # Timeout (in seconds) for a single notebook. TIMEOUT = 1000 # Jupyter kernel to execute the notebook in. JUPYTER_KERNEL = "python3" @unittest.skipUnless(optionals.HAS_IBMQ, "requires IBMQ provider") @unittest.skipUnless(optionals.HAS_JUPYTER, "involves running Jupyter notebooks") class TestJupyter(QiskitTestCase): """Notebooks test case.""" def setUp(self): super().setUp() self.execution_path = os.path.join(Path.SDK.value, "..") self.notebook_dir = os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "notebooks", ) def _execute_notebook(self, filename): import nbformat from nbconvert.preprocessors import ExecutePreprocessor # Create the preprocessor. execute_preprocessor = ExecutePreprocessor(timeout=TIMEOUT, kernel_name=JUPYTER_KERNEL) # Read the notebook. with open(filename) as file_: notebook = nbformat.read(file_, as_version=4) top_str = """ import qiskit import qiskit.providers.ibmq import sys from unittest.mock import create_autospec, MagicMock from qiskit.providers.fake_provider import FakeProviderFactory from qiskit.providers import basicaer fake_prov = FakeProviderFactory() qiskit.IBMQ = fake_prov ibmq_mock = create_autospec(basicaer) ibmq_mock.IBMQJobApiError = MagicMock() sys.modules['qiskit.providers.ibmq'] = ibmq_mock sys.modules['qiskit.providers.ibmq.job'] = ibmq_mock sys.modules['qiskit.providers.ibmq.job.exceptions'] = ibmq_mock """ top = nbformat.notebooknode.NotebookNode( { "cell_type": "code", "execution_count": 0, "metadata": {}, "outputs": [], "source": top_str, } ) notebook.cells = [top] + notebook.cells # Run the notebook into the folder containing the `qiskit/` module. execute_preprocessor.preprocess(notebook, {"metadata": {"path": self.execution_path}}) @unittest.skipIf( sys.platform != "linux", "Fails with Python >=3.8 on osx and windows", ) def test_jupyter_jobs_pbars(self): """Test Jupyter progress bars and job status functionality""" self._execute_notebook(os.path.join(self.notebook_dir, "test_pbar_status.ipynb")) @unittest.skipIf(not optionals.HAS_MATPLOTLIB, "matplotlib not available.") @slow_test def test_backend_tools(self): """Test Jupyter backend tools.""" self._execute_notebook(os.path.join(self.notebook_dir, "test_backend_tools.ipynb")) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for the wrapper functionality.""" import sys import unittest from unittest.mock import patch from unittest.mock import MagicMock from io import StringIO import qiskit from qiskit import providers from qiskit.tools.monitor import backend_overview, backend_monitor from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeProviderFactory, FakeBackend, FakeVigo class TestBackendOverview(QiskitTestCase): """Tools test case.""" def _restore_ibmq(self): if not self.import_error: qiskit.IBMQ = self.ibmq_back else: del qiskit.IBMQ if self.prov_backup: providers.ibmq = self.prov_backup else: del providers.ibmq def _restore_ibmq_mod(self): if self.ibmq_module_backup is not None: sys.modules["qiskit.providers.ibmq"] = self.ibmq_module_backup else: sys.modules.pop("qiskit.providers.ibmq") def setUp(self): super().setUp() ibmq_mock = MagicMock() ibmq_mock.IBMQBackend = FakeBackend if "qiskit.providers.ibmq" in sys.modules: self.ibmq_module_backup = sys.modules["qiskit.providers.ibmq"] else: self.ibmq_module_backup = None sys.modules["qiskit.providers.ibmq"] = ibmq_mock self.addCleanup(self._restore_ibmq_mod) if hasattr(qiskit, "IBMQ"): self.import_error = False else: self.import_error = True qiskit.IBMQ = None self.ibmq_back = qiskit.IBMQ qiskit.IBMQ = FakeProviderFactory() self.addCleanup(self._restore_ibmq) if hasattr(providers, "ibmq"): self.prov_backup = providers.ibmq else: self.prov_backup = None providers.ibmq = MagicMock() @patch("qiskit.tools.monitor.overview.get_unique_backends", return_value=[FakeVigo()]) def test_backend_overview(self, _): """Test backend_overview""" with patch("sys.stdout", new=StringIO()) as fake_stdout: backend_overview() stdout = fake_stdout.getvalue() self.assertIn("Operational:", stdout) self.assertIn("Avg. T1:", stdout) self.assertIn("Num. Qubits:", stdout) @patch("qiskit.tools.monitor.overview.get_unique_backends", return_value=[FakeVigo()]) def test_backend_monitor(self, _): """Test backend_monitor""" for back in [FakeVigo()]: if not back.configuration().simulator: backend = back break with patch("sys.stdout", new=StringIO()) as fake_stdout: backend_monitor(backend) stdout = fake_stdout.getvalue() self.assertIn("Configuration", stdout) self.assertIn("Qubits [Name / Freq / T1 / T2 / ", stdout) for gate in backend.properties().gates: if gate.gate not in ["id"] and len(gate.qubits) == 1: self.assertIn(gate.gate.upper() + " err", stdout) self.assertIn("Readout err", stdout) self.assertIn("Multi-Qubit Gates [Name / Type / Gate Error]", stdout) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for the wrapper functionality.""" import io import unittest from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute from qiskit.tools.monitor import job_monitor from qiskit.test import QiskitTestCase class TestJobMonitor(QiskitTestCase): """Tools test case.""" def test_job_monitor(self): """Test job_monitor""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) qc = QuantumCircuit(qreg, creg) qc.h(qreg[0]) qc.cx(qreg[0], qreg[1]) qc.measure(qreg, creg) backend = BasicAer.get_backend("qasm_simulator") job_sim = execute([qc] * 10, backend) output = io.StringIO() job_monitor(job_sim, output=output) self.assertEqual(job_sim.status().name, "DONE") if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/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. """Test the MergeAdjacentBarriers pass""" import random import unittest from qiskit.transpiler.passes import MergeAdjacentBarriers from qiskit.converters import circuit_to_dag from qiskit import QuantumRegister, QuantumCircuit from qiskit.test import QiskitTestCase class TestMergeAdjacentBarriers(QiskitTestCase): """Test the MergeAdjacentBarriers pass""" def test_two_identical_barriers(self): """Merges two barriers that are identical into one β–‘ β–‘ β–‘ q_0: |0>─░──░─ -> q_0: |0>─░─ β–‘ β–‘ β–‘ """ qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_numerous_identical_barriers(self): """Merges 5 identical barriers in a row into one β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ q_0: |0>─░──░──░──░──░──░─ -> q_0: |0>─░─ β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ """ qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_of_different_sizes(self): """Test two barriers of different sizes are merged into one β–‘ β–‘ β–‘ q_0: |0>─░──░─ q_0: |0>─░─ β–‘ β–‘ -> β–‘ q_1: |0>────░─ q_1: |0>─░─ β–‘ β–‘ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_not_overlapping_barriers(self): """Test two barriers with no overlap are not merged (NB in these pictures they look like 1 barrier but they are actually 2 distinct barriers, this is just how the text drawer draws them) β–‘ β–‘ q_0: |0>─░─ q_0: |0>─░─ β–‘ -> β–‘ q_1: |0>─░─ q_1: |0>─░─ β–‘ β–‘ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.barrier(qr[1]) expected = QuantumCircuit(qr) expected.barrier(qr[0]) expected.barrier(qr[1]) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_obstacle_before(self): """Test with an obstacle before the larger barrier β–‘ β–‘ β–‘ q_0: |0>──░───░─ q_0: |0>──────░─ β”Œβ”€β”€β”€β” β–‘ -> β”Œβ”€β”€β”€β” β–‘ q_1: |0>─ H β”œβ”€β–‘β”€ q_1: |0>─ H β”œβ”€β–‘β”€ β””β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”˜ β–‘ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.h(qr[1]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.h(qr[1]) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_obstacle_after(self): """Test with an obstacle after the larger barrier β–‘ β–‘ β–‘ q_0: |0>─░───░── q_0: |0>─░────── β–‘ β”Œβ”€β”€β”€β” -> β–‘ β”Œβ”€β”€β”€β” q_1: |0>─░── H β”œ q_1: |0>─░── H β”œ β–‘ β””β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”˜ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.barrier(qr[0]) circuit.h(qr[1]) expected = QuantumCircuit(qr) expected.barrier(qr) expected.h(qr[1]) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle(self): """Test that barriers don't merge if there is an obstacle that is blocking β–‘ β”Œβ”€β”€β”€β” β–‘ β–‘ β”Œβ”€β”€β”€β” β–‘ q_0: |0>─░── H β”œβ”€β–‘β”€ -> q_0: |0>─░── H β”œβ”€β–‘β”€ β–‘ β””β”€β”€β”€β”˜ β–‘ β–‘ β””β”€β”€β”€β”˜ β–‘ """ qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.h(qr) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) expected.h(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle_long(self): """Test that barriers don't merge if there is an obstacle that is blocking β–‘ β”Œβ”€β”€β”€β” β–‘ β–‘ β”Œβ”€β”€β”€β” β–‘ q_0: |0>─░── H β”œβ”€β–‘β”€ q_0: |0>─░── H β”œβ”€β–‘β”€ β–‘ β””β”€β”€β”€β”˜ β–‘ -> β–‘ β””β”€β”€β”€β”˜ β–‘ q_1: |0>─────────░─ q_1: |0>─────────░─ β–‘ β–‘ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.h(qr[0]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr[0]) expected.h(qr[0]) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle_narrow(self): """Test that barriers don't merge if there is an obstacle that is blocking β–‘ β”Œβ”€β”€β”€β” β–‘ β–‘ β”Œβ”€β”€β”€β” β–‘ q_0: |0>─░── H β”œβ”€β–‘β”€ q_0: |0>─░── H β”œβ”€β–‘β”€ β–‘ β””β”€β”€β”€β”˜ β–‘ -> β–‘ β””β”€β”€β”€β”˜ β–‘ q_1: |0>─░───────░─ q_1: |0>─░───────░─ β–‘ β–‘ β–‘ β–‘ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.h(qr[0]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) expected.h(qr[0]) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle_twoQ(self): """Test that barriers don't merge if there is an obstacle that is blocking β–‘ β–‘ β–‘ β–‘ q_0: |0>─░───────░─ q_0: |0>─░───────░─ β–‘ β–‘ β–‘ β–‘ q_1: |0>─░───■───── -> q_1: |0>─░───■───── β–‘ β”Œβ”€β”΄β”€β” β–‘ β–‘ β”Œβ”€β”΄β”€β” β–‘ q_2: |0>──── X β”œβ”€β–‘β”€ q_2: |0>──── X β”œβ”€β–‘β”€ β””β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”˜ β–‘ """ qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.barrier(0, 1) circuit.cx(1, 2) circuit.barrier(0, 2) expected = QuantumCircuit(qr) expected.barrier(0, 1) expected.cx(1, 2) expected.barrier(0, 2) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_output_deterministic(self): """Test that the output barriers have a deterministic ordering (independent of PYTHONHASHSEED). This is important to guarantee that any subsequent topological iterations through the circuit are also deterministic; it's in general not possible for all transpiler passes to produce identical outputs across all valid topological orderings, especially if those passes have some stochastic element.""" order = list(range(20)) random.Random(2023_02_10).shuffle(order) circuit = QuantumCircuit(20) circuit.barrier([5, 2, 3]) circuit.barrier([7, 11, 14, 2, 4]) circuit.barrier(order) # All the barriers should get merged together. expected = QuantumCircuit(20) expected.barrier(range(20)) output = MergeAdjacentBarriers()(circuit) self.assertEqual(expected, output) # This assertion is that the ordering of the arguments in the barrier is fixed. self.assertEqual(list(output.data[0].qubits), list(output.qubits)) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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. """Test the BarrierBeforeFinalMeasurements pass""" import unittest from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements from qiskit.converters import circuit_to_dag from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.test import QiskitTestCase class TestBarrierBeforeFinalMeasurements(QiskitTestCase): """Tests the BarrierBeforeFinalMeasurements pass.""" def test_single_measure(self): """ A single measurement at the end | q:--[m]-- q:--|-[m]--- | -> | | c:---.--- c:-----.--- """ qr = QuantumRegister(1, 'q') cr = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) expected = QuantumCircuit(qr, cr) expected.barrier(qr) expected.measure(qr, cr) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_ignore_single_measure(self): """Ignore single measurement because it is not at the end q:--[m]-[H]- q:--[m]-[H]- | -> | c:---.------ c:---.------ """ qr = QuantumRegister(1, 'q') cr = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) circuit.h(qr[0]) expected = QuantumCircuit(qr, cr) expected.measure(qr, cr) expected.h(qr[0]) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_single_measure_mix(self): """Two measurements, but only one is at the end | q0:--[m]--[H]--[m]-- q0:--[m]--[H]--|-[m]--- | | -> | | | c:---.---------.--- c:---.-----------.--- """ qr = QuantumRegister(1, 'q') cr = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) circuit.h(qr) circuit.measure(qr, cr) expected = QuantumCircuit(qr, cr) expected.measure(qr, cr) expected.h(qr) expected.barrier(qr) expected.measure(qr, cr) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_two_qregs(self): """Two measurements in different qregs to different cregs | q0:--[H]--[m]------ q0:--[H]--|--[m]------ | | | q1:--------|--[m]-- -> q1:-------|---|--[m]-- | | | | | c0:--------.---|--- c0:----------.---|--- | | c1:------------.--- c0:--------------.--- """ qr0 = QuantumRegister(1, 'q0') qr1 = QuantumRegister(1, 'q1') cr0 = ClassicalRegister(1, 'c0') cr1 = ClassicalRegister(1, 'c1') circuit = QuantumCircuit(qr0, qr1, cr0, cr1) circuit.h(qr0) circuit.measure(qr0, cr0) circuit.measure(qr1, cr1) expected = QuantumCircuit(qr0, qr1, cr0, cr1) expected.h(qr0) expected.barrier(qr0, qr1) expected.measure(qr0, cr0) expected.measure(qr1, cr1) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_two_qregs_to_a_single_creg(self): """Two measurements in different qregs to the same creg | q0:--[H]--[m]------ q0:--[H]--|--[m]------ | | | q1:--------|--[m]-- -> q1:-------|---|--[m]-- | | | | | c0:--------.---|--- c0:-----------.---|--- ------------.--- ---------------.--- """ qr0 = QuantumRegister(1, 'q0') qr1 = QuantumRegister(1, 'q1') cr0 = ClassicalRegister(2, 'c0') circuit = QuantumCircuit(qr0, qr1, cr0) circuit.h(qr0) circuit.measure(qr0, cr0[0]) circuit.measure(qr1, cr0[1]) expected = QuantumCircuit(qr0, qr1, cr0) expected.h(qr0) expected.barrier(qr0, qr1) expected.measure(qr0, cr0[0]) expected.measure(qr1, cr0[1]) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_preserve_measure_for_conditional(self): """Test barrier is inserted after any measurements used for conditionals q0:--[H]--[m]------------ q0:--[H]--[m]--------------- | | q1:--------|--[ z]--[m]-- -> q1:--------|--[ z]--|--[m]-- | | | | | | c0:--------.--[=1]---|--- c0:--------.--[=1]------|--- | | c1:------------------.--- c1:---------------------.--- """ qr0 = QuantumRegister(1, 'q0') qr1 = QuantumRegister(1, 'q1') cr0 = ClassicalRegister(1, 'c0') cr1 = ClassicalRegister(1, 'c1') circuit = QuantumCircuit(qr0, qr1, cr0, cr1) circuit.h(qr0) circuit.measure(qr0, cr0) circuit.z(qr1).c_if(cr0, 1) circuit.measure(qr1, cr1) expected = QuantumCircuit(qr0, qr1, cr0, cr1) expected.h(qr0) expected.measure(qr0, cr0) expected.z(qr1).c_if(cr0, 1) expected.barrier(qr1) expected.measure(qr1, cr1) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) class TestBarrierBeforeMeasuremetsWhenABarrierIsAlreadyThere(QiskitTestCase): """Tests the BarrierBeforeFinalMeasurements pass when there is a barrier already""" def test_handle_redundancy(self): """The pass is idempotent | | q:--|-[m]-- q:--|-[m]--- | | -> | | c:-----.--- c:-----.--- """ qr = QuantumRegister(1, 'q') cr = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qr, cr) circuit.barrier(qr) circuit.measure(qr, cr) expected = QuantumCircuit(qr, cr) expected.barrier(qr) expected.measure(qr, cr) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_remove_barrier_in_different_qregs(self): """Two measurements in different qregs to the same creg q0:--|--[m]------ q0:---|--[m]------ | | | q1:--|---|--[m]-- -> q1:---|---|--[m]-- | | | | c0:------.---|--- c0:-------.---|--- ----------.--- -----------.--- """ qr0 = QuantumRegister(1, 'q0') qr1 = QuantumRegister(1, 'q1') cr0 = ClassicalRegister(2, 'c0') circuit = QuantumCircuit(qr0, qr1, cr0) circuit.barrier(qr0) circuit.barrier(qr1) circuit.measure(qr0, cr0[0]) circuit.measure(qr1, cr0[1]) expected = QuantumCircuit(qr0, qr1, cr0) expected.barrier(qr0, qr1) expected.measure(qr0, cr0[0]) expected.measure(qr1, cr0[1]) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_preserve_barriers_for_measurement_ordering(self): """If the circuit has a barrier to enforce a measurement order, preserve it in the output. q:---[m]--|------- q:---|--[m]--|------- ----|---|--[m]-- -> ---|---|---|--[m]-- | | | | c:----.-------|--- c:-------.-------|--- ------------.--- ---------------.--- """ qr = QuantumRegister(2, 'q') cr = ClassicalRegister(2, 'c') circuit = QuantumCircuit(qr, cr) circuit.measure(qr[0], cr[0]) circuit.barrier(qr) circuit.measure(qr[1], cr[1]) expected = QuantumCircuit(qr, cr) expected.barrier(qr) expected.measure(qr[0], cr[0]) expected.barrier(qr) expected.measure(qr[1], cr[1]) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_measures_followed_by_barriers_should_be_final(self): """If a measurement is followed only by a barrier, insert the barrier before it. q:---[H]--|--[m]--|------- q:---[H]--|--[m]-|------- ---[H]--|---|---|--[m]-- -> ---[H]--|---|--|--[m]-- | | | | c:------------.-------|--- c:------------.------|--- --------------------.--- -------------------.--- """ qr = QuantumRegister(2, 'q') cr = ClassicalRegister(2, 'c') circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.barrier(qr) circuit.measure(qr[0], cr[0]) circuit.barrier(qr) circuit.measure(qr[1], cr[1]) expected = QuantumCircuit(qr, cr) expected.h(qr) expected.barrier(qr) expected.measure(qr[0], cr[0]) expected.barrier(qr) expected.measure(qr[1], cr[1]) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_should_merge_with_smaller_duplicate_barrier(self): """If an equivalent barrier exists covering a subset of the qubits covered by the new barrier, it should be replaced. q:---|--[m]------------- q:---|--[m]------------- ---|---|---[m]-------- -> ---|---|---[m]-------- -------|----|---[m]--- ---|---|----|---[m]--- | | | | | | c:-------.----|----|---- c:-------.----|----|---- ------------.----|---- ------------.----|---- -----------------.---- -----------------.---- """ qr = QuantumRegister(3, 'q') cr = ClassicalRegister(3, 'c') circuit = QuantumCircuit(qr, cr) circuit.barrier(qr[0], qr[1]) circuit.measure(qr, cr) expected = QuantumCircuit(qr, cr) expected.barrier(qr) expected.measure(qr, cr) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_should_merge_with_larger_duplicate_barrier(self): """If a barrier exists and is stronger than the barrier to be inserted, preserve the existing barrier and do not insert a new barrier. q:---|--[m]--|------- q:---|--[m]-|------- ---|---|---|--[m]-- -> ---|---|--|--[m]-- ---|---|---|---|--- ---|---|--|---|--- | | | | c:-------.-------|--- c:-------.------|--- ---------------.--- --------------.--- ------------------- ------------------ """ qr = QuantumRegister(3, 'q') cr = ClassicalRegister(3, 'c') circuit = QuantumCircuit(qr, cr) circuit.barrier(qr) circuit.measure(qr[0], cr[0]) circuit.barrier(qr) circuit.measure(qr[1], cr[1]) expected = circuit pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barrier_doesnt_reorder_gates(self): """ A barrier should not allow the reordering of gates, as pointed out in #2102 q:--[u1(0)]-----------[m]--------- q:--[u1(0)]------------|--[m]--------- --[u1(1)]------------|-[m]------ -> --[u1(1)]------------|---|-[m]------ --[u1(2)]-|----------|--|-[m]---- --[u1(2)]-|----------|---|--|-[m]---- ----------|-[u1(03)]-|--|--|-[m]- ----------|-[u1(03)]-|---|--|--|-[m]- | | | | | | | | c:---------------------.--|--|--|- c:--------------------------.--|--|--|- ------------------------.--|--|- -----------------------------.--|--|- ---------------------------.--|- --------------------------------.--|- ------------------------------.- -----------------------------------.- """ qr = QuantumRegister(4) cr = ClassicalRegister(4) circuit = QuantumCircuit(qr, cr) circuit.u1(0, qr[0]) circuit.u1(1, qr[1]) circuit.u1(2, qr[2]) circuit.barrier(qr[2], qr[3]) circuit.u1(3, qr[3]) test_circuit = circuit.copy() test_circuit.measure(qr, cr) # expected circuit is the same, just with a barrier before the measurements expected = circuit.copy() expected.barrier(qr) expected.measure(qr, cr) pass_ = BarrierBeforeFinalMeasurements() result = pass_.run(circuit_to_dag(test_circuit)) self.assertEqual(result, circuit_to_dag(expected)) if __name__ == '__main__': unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the BasicSwap pass""" import unittest from qiskit.transpiler.passes import BasicSwap from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.layout import Layout from qiskit.transpiler import CouplingMap, Target from qiskit.circuit.library import CXGate from qiskit.converters import circuit_to_dag from qiskit import QuantumRegister, QuantumCircuit from qiskit.test import QiskitTestCase class TestBasicSwap(QiskitTestCase): """Tests the BasicSwap pass.""" def test_trivial_case(self): """No need to have any swap, the CX are distance 1 to each other q0:--(+)-[U]-(+)- | | q1:---.-------|-- | q2:-----------.-- CouplingMap map: [1]--[0]--[2] """ coupling = CouplingMap([[0, 1], [0, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.cx(qr[0], qr[2]) dag = circuit_to_dag(circuit) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_trivial_in_same_layer(self): """No need to have any swap, two CXs distance 1 to each other, in the same layer q0:--(+)-- | q1:---.--- q2:--(+)-- | q3:---.--- CouplingMap map: [0]--[1]--[2]--[3] """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[2], qr[3]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_a_single_swap(self): """Adding a swap q0:------- q1:--(+)-- | q2:---.--- CouplingMap map: [1]--[0]--[2] q0:--X---.--- | | q1:--X---|--- | q2:-----(+)-- """ coupling = CouplingMap([[0, 1], [0, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[1], qr[0]) expected.cx(qr[0], qr[2]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_a_single_swap_with_target(self): """Adding a swap q0:------- q1:--(+)-- | q2:---.--- CouplingMap map: [1]--[0]--[2] q0:--X---.--- | | q1:--X---|--- | q2:-----(+)-- """ target = Target() target.add_instruction(CXGate(), {(0, 1): None, (0, 2): None}) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[1], qr[0]) expected.cx(qr[0], qr[2]) pass_ = BasicSwap(target) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_a_single_swap_bigger_cm(self): """Swapper in a bigger coupling map q0:------- q1:---.--- | q2:--(+)-- CouplingMap map: [1]--[0]--[2]--[3] q0:--X---.--- | | q1:--X---|--- | q2:-----(+)-- """ coupling = CouplingMap([[0, 1], [0, 2], [2, 3]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[1], qr[0]) expected.cx(qr[0], qr[2]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_keep_layout(self): """After a swap, the following gates also change the wires. qr0:---.---[H]-- | qr1:---|-------- | qr2:--(+)------- CouplingMap map: [0]--[1]--[2] qr0:--X----------- | qr1:--X---.--[H]-- | qr2:-----(+)------ """ coupling = CouplingMap([[1, 0], [1, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[2]) circuit.h(qr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[0], qr[1]) expected.cx(qr[1], qr[2]) expected.h(qr[1]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap(self): """A far swap that affects coming CXs. qr0:--(+)---.-- | | qr1:---|----|-- | | qr2:---|----|-- | | qr3:---.---(+)- CouplingMap map: [0]--[1]--[2]--[3] qr0:--X-------------- | qr1:--X--X----------- | qr2:-----X--(+)---.-- | | qr3:---------.---(+)- """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[3]) circuit.cx(qr[3], qr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[0], qr[1]) expected.swap(qr[1], qr[2]) expected.cx(qr[2], qr[3]) expected.cx(qr[3], qr[2]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap_with_gate_the_front(self): """A far swap with a gate in the front. q0:------(+)-- | q1:-------|--- | q2:-------|--- | q3:--[H]--.--- CouplingMap map: [0]--[1]--[2]--[3] q0:-----------(+)-- | q1:---------X--.--- | q2:------X--X------ | q3:-[H]--X--------- """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.h(qr[3]) circuit.cx(qr[3], qr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.h(qr[3]) expected.swap(qr[3], qr[2]) expected.swap(qr[2], qr[1]) expected.cx(qr[1], qr[0]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap_with_gate_the_back(self): """A far swap with a gate in the back. q0:--(+)------ | q1:---|------- | q2:---|------- | q3:---.--[H]-- CouplingMap map: [0]--[1]--[2]--[3] q0:-------(+)------ | q1:-----X--.--[H]-- | q2:--X--X---------- | q3:--X------------- """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[3], qr[0]) circuit.h(qr[3]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[3], qr[2]) expected.swap(qr[2], qr[1]) expected.cx(qr[1], qr[0]) expected.h(qr[1]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap_with_gate_the_middle(self): """A far swap with a gate in the middle. q0:--(+)-------.-- | | q1:---|--------|-- | q2:---|--------|-- | | q3:---.--[H]--(+)- CouplingMap map: [0]--[1]--[2]--[3] q0:-------(+)-------.--- | | q1:-----X--.--[H]--(+)-- | q2:--X--X--------------- | q3:--X------------------ """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[3], qr[0]) circuit.h(qr[3]) circuit.cx(qr[0], qr[3]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[3], qr[2]) expected.swap(qr[2], qr[1]) expected.cx(qr[1], qr[0]) expected.h(qr[1]) expected.cx(qr[0], qr[1]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_fake_run(self): """A fake run, doesn't change dag q0:--(+)-------.-- | | q1:---|--------|-- | q2:---|--------|-- | | q3:---.--[H]--(+)- CouplingMap map: [0]--[1]--[2]--[3] q0:-------(+)-------.--- | | q1:-----X--.--[H]--(+)-- | q2:--X--X--------------- | q3:--X------------------ """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[3], qr[0]) circuit.h(qr[3]) circuit.cx(qr[0], qr[3]) fake_pm = PassManager([BasicSwap(coupling, fake_run=True)]) real_pm = PassManager([BasicSwap(coupling, fake_run=False)]) self.assertEqual(circuit, fake_pm.run(circuit)) self.assertNotEqual(circuit, real_pm.run(circuit)) self.assertIsInstance(fake_pm.property_set["final_layout"], Layout) self.assertEqual(fake_pm.property_set["final_layout"], real_pm.property_set["final_layout"]) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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. """Test the Check CNOT direction pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler.passes import CheckCXDirection from qiskit.transpiler import CouplingMap from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestCheckCNotDirection(QiskitTestCase): """ Tests the CheckCXDirection pass with CX gates""" def test_trivial_map(self): """ Trivial map in a circuit without entanglement qr0:---[H]--- qr1:---[H]--- qr2:---[H]--- CouplingMap map: None """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.h(qr) coupling = CouplingMap() dag = circuit_to_dag(circuit) pass_ = CheckCXDirection(coupling) pass_.run(dag) self.assertTrue(pass_.property_set['is_direction_mapped']) def test_true_direction(self): """ Mapped is easy to check qr0:---.--[H]--.-- | | qr1:--(+)------|-- | qr2:----------(+)- CouplingMap map: [1]<-[0]->[2] """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.cx(qr[0], qr[2]) coupling = CouplingMap([[0, 1], [0, 2]]) dag = circuit_to_dag(circuit) pass_ = CheckCXDirection(coupling) pass_.run(dag) self.assertTrue(pass_.property_set['is_direction_mapped']) def test_true_direction_in_same_layer(self): """ Two CXs distance_qubits 1 to each other, in the same layer qr0:--(+)-- | qr1:---.--- qr2:--(+)-- | qr3:---.--- CouplingMap map: [0]->[1]->[2]->[3] """ qr = QuantumRegister(4, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[3]) coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) dag = circuit_to_dag(circuit) pass_ = CheckCXDirection(coupling) pass_.run(dag) self.assertTrue(pass_.property_set['is_direction_mapped']) def test_wrongly_mapped(self): """ Needs [0]-[1] in a [0]--[2]--[1] qr0:--(+)-- | qr1:---.--- CouplingMap map: [0]->[2]->[1] """ qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) coupling = CouplingMap([[0, 2], [2, 1]]) dag = circuit_to_dag(circuit) pass_ = CheckCXDirection(coupling) pass_.run(dag) self.assertFalse(pass_.property_set['is_direction_mapped']) def test_true_direction_undirected(self): """ Mapped but with wrong direction qr0:--(+)-[H]--.-- | | qr1:---.-------|-- | qr2:----------(+)- CouplingMap map: [1]<-[0]->[2] """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.cx(qr[2], qr[0]) coupling = CouplingMap([[0, 1], [0, 2]]) dag = circuit_to_dag(circuit) pass_ = CheckCXDirection(coupling) pass_.run(dag) self.assertFalse(pass_.property_set['is_direction_mapped']) def test_false_direction_in_same_layer_undirected(self): """ Two CXs in the same layer, but one is wrongly directed qr0:--(+)-- | qr1:---.--- qr2:---.--- | qr3:--(+)-- CouplingMap map: [0]->[1]->[2]->[3] """ qr = QuantumRegister(4, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[3], qr[2]) coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) dag = circuit_to_dag(circuit) pass_ = CheckCXDirection(coupling) pass_.run(dag) self.assertFalse(pass_.property_set['is_direction_mapped']) class TestCheckCNotDirectionBarrier(QiskitTestCase): """ Tests the CheckCNotDirection pass with Swap gates""" def test_2q_barrier(self): """ A 2q barrier should be ignored qr0:--|-- | qr1:--|-- CouplingMap map: None """ qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.barrier(qr[0], qr[1]) coupling = CouplingMap() dag = circuit_to_dag(circuit) pass_ = CheckCXDirection(coupling) pass_.run(dag) self.assertTrue(pass_.property_set['is_direction_mapped']) if __name__ == '__main__': unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the Check Map pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.circuit.library import CXGate from qiskit.transpiler.passes import CheckMap from qiskit.transpiler import CouplingMap, Target from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestCheckMapCX(QiskitTestCase): """Tests the CheckMap pass with CX gates""" def test_trivial_nop_map(self): """Trivial map in a circuit without entanglement qr0:---[H]--- qr1:---[H]--- qr2:---[H]--- CouplingMap map: None """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.h(qr) coupling = CouplingMap() dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_trivial_nop_map_target(self): """Trivial map in a circuit without entanglement qr0:---[H]--- qr1:---[H]--- qr2:---[H]--- CouplingMap map: None """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.h(qr) target = Target() dag = circuit_to_dag(circuit) pass_ = CheckMap(target) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_true(self): """Mapped is easy to check qr0:--(+)-[H]-(+)- | | qr1:---.-------|-- | qr2:-----------.-- CouplingMap map: [1]--[0]--[2] """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.cx(qr[0], qr[2]) coupling = CouplingMap([[0, 1], [0, 2]]) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_false(self): """Needs [0]-[1] in a [0]--[2]--[1] qr0:--(+)-- | qr1:---.--- CouplingMap map: [0]--[2]--[1] """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) coupling = CouplingMap([[0, 2], [2, 1]]) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertFalse(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_false_target(self): """Needs [0]-[1] in a [0]--[2]--[1] qr0:--(+)-- | qr1:---.--- CouplingMap map: [0]--[2]--[1] """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) target = Target(num_qubits=2) target.add_instruction(CXGate(), {(0, 2): None, (2, 1): None}) dag = circuit_to_dag(circuit) pass_ = CheckMap(target) pass_.run(dag) self.assertFalse(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_cf_true(self): """Check control flow blocks are mapped.""" num_qubits = 3 coupling = CouplingMap.from_line(num_qubits) qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) true_body = QuantumCircuit(qr, cr) true_body.swap(0, 1) true_body.cx(2, 1) circuit.if_else((cr[0], 0), true_body, None, qr, cr) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_cf_false(self): """Check control flow blocks are not mapped.""" num_qubits = 3 coupling = CouplingMap.from_line(num_qubits) qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) true_body = QuantumCircuit(qr) true_body.cx(0, 2) circuit.if_else((cr[0], 0), true_body, None, qr, []) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertFalse(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_cf_layout_change_false(self): """Check control flow blocks with layout change are not mapped.""" num_qubits = 3 coupling = CouplingMap.from_line(num_qubits) qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) true_body = QuantumCircuit(qr, cr) true_body.cx(1, 2) circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], cr) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertFalse(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_cf_layout_change_true(self): """Check control flow blocks with layout change are mapped.""" num_qubits = 3 coupling = CouplingMap.from_line(num_qubits) qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) true_body = QuantumCircuit(qr) true_body.cx(0, 2) circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], []) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_cf_different_bits(self): """Check control flow blocks with layout change are mapped.""" num_qubits = 3 coupling = CouplingMap.from_line(num_qubits) qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) true_body = QuantumCircuit(3, 1) true_body.cx(0, 2) circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], [cr[0]]) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_disjoint_controlflow_bits(self): """test control flow on with different registers""" num_qubits = 4 coupling = CouplingMap.from_line(num_qubits) qr1 = QuantumRegister(4, "qr") qr2 = QuantumRegister(3, "qrif") cr = ClassicalRegister(3) circuit = QuantumCircuit(qr1, cr) true_body = QuantumCircuit(qr2, [cr[0]]) true_body.cx(0, 2) circuit.if_else((cr[0], 0), true_body, None, qr1[[1, 0, 2]], [cr[0]]) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_nested_controlflow_true(self): """Test nested controlflow with true evaluation.""" num_qubits = 4 coupling = CouplingMap.from_line(num_qubits) qr1 = QuantumRegister(4, "qr") qr2 = QuantumRegister(3, "qrif") cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(1) circuit = QuantumCircuit(qr1, cr1) true_body = QuantumCircuit(qr2, cr2) for_body = QuantumCircuit(3) for_body.cx(0, 2) true_body.for_loop(range(5), body=for_body, qubits=qr2, clbits=[]) circuit.if_else((cr1[0], 0), true_body, None, qr1[[1, 0, 2]], cr1) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_nested_controlflow_false(self): """Test nested controlflow with true evaluation.""" num_qubits = 4 coupling = CouplingMap.from_line(num_qubits) qr1 = QuantumRegister(4, "qr") qr2 = QuantumRegister(3, "qrif") cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(1) circuit = QuantumCircuit(qr1, cr1) true_body = QuantumCircuit(qr2, cr2) for_body = QuantumCircuit(3) for_body.cx(0, 2) true_body.for_loop(range(5), body=for_body, qubits=qr2, clbits=[]) circuit.if_else((cr1[0], 0), true_body, None, qr1[[0, 1, 2]], cr1) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertFalse(pass_.property_set["is_swap_mapped"]) def test_nested_conditional_unusual_bit_order(self): """Test that `CheckMap` succeeds when inner conditional blocks have clbits that are involved in their own (nested conditionals), and the binding order is not the same as the bit-definition order. See gh-10394.""" qr = QuantumRegister(2, "q") cr1 = ClassicalRegister(2, "c1") cr2 = ClassicalRegister(2, "c2") # Note that the bits here are not in the same order as in the outer circuit object, but they # are the same as the binding order in the `if_test`, so everything maps `{x: x}` and it # should all be fine. This kind of thing is a staple of the control-flow builders. inner_order = [cr2[0], cr1[0], cr2[1], cr1[1]] inner = QuantumCircuit(qr, inner_order, cr1, cr2) inner.cx(0, 1).c_if(cr2, 3) outer = QuantumCircuit(qr, cr1, cr2) outer.if_test((cr1, 3), inner, outer.qubits, inner_order) pass_ = CheckMap(CouplingMap.from_line(2)) pass_(outer) self.assertTrue(pass_.property_set["is_swap_mapped"]) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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. """Commutation analysis and transformation pass testing""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import PropertySet from qiskit.transpiler.passes import CommutationAnalysis from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestCommutationAnalysis(QiskitTestCase): """Test the Commutation pass.""" def setUp(self): self.pass_ = CommutationAnalysis() self.pset = self.pass_.property_set = PropertySet() def assertCommutationSet(self, result, expected): """ Compares the result of propertyset["commutation_set"] with a dictionary of the form {'q[0]': [ [node_id, ...], [node_id, ...] ]} """ result_to_compare = {} for qbit_str, sets in result.items(): if not isinstance(qbit_str, str): continue result_to_compare[qbit_str] = [] for commutation_set in sets: result_to_compare[qbit_str].append( sorted([node._node_id for node in commutation_set])) for qbit_str, sets in expected.items(): for commutation_set in sets: commutation_set.sort() self.assertDictEqual(result_to_compare, expected) def test_commutation_set_property_is_created(self): """Test property is created""" qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.h(qr) dag = circuit_to_dag(circuit) self.assertIsNone(self.pset['commutation_set']) self.pass_.run(dag) self.assertIsNotNone(self.pset['commutation_set']) def test_all_gates(self): """Test all gates on 1 and 2 qubits qr0:----[H]---[x]---[y]---[t]---[s]---[rz]---[u1]---[u2]---[u3]---.---.---.-- | | | qr1:-------------------------------------------------------------(+)-(Y)--.-- """ qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.x(qr[0]) circuit.y(qr[0]) circuit.t(qr[0]) circuit.s(qr[0]) circuit.rz(0.5, qr[0]) circuit.u1(0.5, qr[0]) circuit.u2(0.5, 0.6, qr[0]) circuit.u3(0.5, 0.6, 0.7, qr[0]) circuit.cx(qr[0], qr[1]) circuit.cy(qr[0], qr[1]) circuit.cz(qr[0], qr[1]) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [5], [6], [7], [8, 9, 10, 11], [12], [13], [14], [15], [16], [2]], 'qr[1]': [[3], [14], [15], [16], [4]]} self.assertCommutationSet(self.pset["commutation_set"], expected) def test_non_commutative_circuit(self): """A simple circuit where no gates commute qr0:---[H]--- qr1:---[H]--- qr2:---[H]--- """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.h(qr) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [7], [2]], 'qr[1]': [[3], [8], [4]], 'qr[2]': [[5], [9], [6]]} self.assertCommutationSet(self.pset["commutation_set"], expected) def test_non_commutative_circuit_2(self): """A simple circuit where no gates commute qr0:----.------------- | qr1:---(+)------.----- | qr2:---[H]-----(+)---- """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[2]) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [7], [2]], 'qr[1]': [[3], [7], [9], [4]], 'qr[2]': [[5], [8], [9], [6]]} self.assertCommutationSet(self.pset["commutation_set"], expected) def test_commutative_circuit(self): """A simple circuit where two CNOTs commute qr0:----.------------ | qr1:---(+)-----(+)--- | qr2:---[H]------.---- """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[2]) circuit.cx(qr[2], qr[1]) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [7], [2]], 'qr[1]': [[3], [7, 9], [4]], 'qr[2]': [[5], [8], [9], [6]]} self.assertCommutationSet(self.pset["commutation_set"], expected) def test_commutative_circuit_2(self): """A simple circuit where a CNOT and a Z gate commute, and a CNOT and a CNOT commute qr0:----.-----[Z]----- | qr1:---(+)----(+)---- | qr2:---[H]-----.---- """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.z(qr[0]) circuit.h(qr[2]) circuit.cx(qr[2], qr[1]) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [7, 8], [2]], 'qr[1]': [[3], [7, 10], [4]], 'qr[2]': [[5], [9], [10], [6]]} self.assertCommutationSet(self.pset["commutation_set"], expected) def test_commutative_circuit_3(self): """A simple circuit where multiple gates commute qr0:----.-----[Z]-----.----[z]----- | | qr1:---(+)----(+)----(+)----.------ | | qr2:---[H]-----.-----[x]---(+)----- """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[2]) circuit.z(qr[0]) circuit.cx(qr[2], qr[1]) circuit.cx(qr[0], qr[1]) circuit.x(qr[2]) circuit.z(qr[0]) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [7, 9, 11, 13], [2]], 'qr[1]': [[3], [7, 10, 11], [14], [4]], 'qr[2]': [[5], [8], [10], [12, 14], [6]]} self.assertCommutationSet(self.pset["commutation_set"], expected) def test_jordan_wigner_type_circuit(self): """A Jordan-Wigner type circuit where consecutive CNOTs commute qr0:----.-------------------------------------------------------------.---- | | qr1:---(+)----.-------------------------------------------------.----(+)--- | | qr2:---------(+)----.-------------------------------------.----(+)--------- | | qr3:---------------(+)----.-------------------------.----(+)--------------- | | qr4:---------------------(+)----.-------------.----(+)--------------------- | | qr5:---------------------------(+)----[z]----(+)--------------------------- """ qr = QuantumRegister(6, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[4], qr[5]) circuit.z(qr[5]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [13, 23], [2]], 'qr[1]': [[3], [13], [14, 22], [23], [4]], 'qr[2]': [[5], [14], [15, 21], [22], [6]], 'qr[3]': [[7], [15], [16, 20], [21], [8]], 'qr[4]': [[9], [16], [17, 19], [20], [10]], 'qr[5]': [[11], [17], [18], [19], [12]]} self.assertCommutationSet(self.pset["commutation_set"], expected) def test_all_commute_circuit(self): """Test circuit with that all commute""" qr = QuantumRegister(5, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[1]) circuit.cx(qr[4], qr[3]) circuit.cx(qr[2], qr[3]) circuit.z(qr[0]) circuit.z(qr[4]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[1]) circuit.cx(qr[4], qr[3]) circuit.cx(qr[2], qr[3]) dag = circuit_to_dag(circuit) self.pass_.run(dag) expected = {'qr[0]': [[1], [11, 15, 17], [2]], 'qr[1]': [[3], [11, 12, 17, 18], [4]], 'qr[2]': [[5], [12, 14, 18, 20], [6]], 'qr[3]': [[7], [13, 14, 19, 20], [8]], 'qr[4]': [[9], [13, 16, 19], [10]]} self.assertCommutationSet(self.pset["commutation_set"], expected) if __name__ == '__main__': unittest.main()
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. """Gate cancellation pass testing""" import unittest import numpy as np from qiskit.test import QiskitTestCase from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import U1Gate, RZGate, PhaseGate, CXGate, SXGate from qiskit.circuit.parameter import Parameter from qiskit.transpiler.target import Target from qiskit.transpiler import PassManager, PropertySet from qiskit.transpiler.passes import CommutationAnalysis, CommutativeCancellation, FixedPoint, Size from qiskit.quantum_info import Operator class TestCommutativeCancellation(QiskitTestCase): """Test the CommutativeCancellation pass.""" def setUp(self): super().setUp() self.com_pass_ = CommutationAnalysis() self.pass_ = CommutativeCancellation() self.pset = self.pass_.property_set = PropertySet() def test_all_gates(self): """Test all gates on 1 and 2 qubits q0:-[H]-[H]--[x]-[x]--[y]-[y]--[rz]-[rz]--[u1]-[u1]-[rx]-[rx]---.--.--.--.--.--.- | | | | | | q1:-------------------------------------------------------------X--X--Y--Y--.--.- = qr0:---[u1]--- qr1:---------- """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.x(qr[0]) circuit.x(qr[0]) circuit.y(qr[0]) circuit.y(qr[0]) circuit.rz(0.5, qr[0]) circuit.rz(0.5, qr[0]) circuit.append(U1Gate(0.5), [qr[0]]) # TODO this should work with Phase gates too circuit.append(U1Gate(0.5), [qr[0]]) circuit.rx(0.5, qr[0]) circuit.rx(0.5, qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cy(qr[0], qr[1]) circuit.cy(qr[0], qr[1]) circuit.cz(qr[0], qr[1]) circuit.cz(qr[0], qr[1]) passmanager = PassManager() passmanager.append(CommutativeCancellation()) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.append(RZGate(2.0), [qr[0]]) expected.rx(1.0, qr[0]) self.assertEqual(expected, new_circuit) def test_commutative_circuit1(self): """A simple circuit where three CNOTs commute, the first and the last cancel. qr0:----.---------------.-- qr0:------------ | | qr1:---(+)-----(+)-----(+)- = qr1:-------(+)-- | | qr2:---[H]------.---------- qr2:---[H]--.--- """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[2]) circuit.cx(qr[2], qr[1]) circuit.cx(qr[0], qr[1]) passmanager = PassManager() passmanager.append(CommutativeCancellation()) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.h(qr[2]) expected.cx(qr[2], qr[1]) self.assertEqual(expected, new_circuit) def test_consecutive_cnots(self): """A simple circuit equals identity qr0:----.- ----.-- qr0:------------ | | qr1:---(+)----(+)- = qr1:------------ """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) def test_consecutive_cnots2(self): """ Two CNOTs that equals identity, with rotation gates inserted. """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.rx(np.pi, qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.rx(np.pi, qr[0]) passmanager = PassManager() passmanager.append( [CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")], do_while=lambda property_set: not property_set["size_fixed_point"], ) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) def test_2_alternating_cnots(self): """A simple circuit where nothing should be cancelled. qr0:----.- ---(+)- qr0:----.----(+)- | | | | qr1:---(+)-----.-- = qr1:---(+)----.-- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.cx(qr[0], qr[1]) expected.cx(qr[1], qr[0]) self.assertEqual(expected, new_circuit) def test_control_bit_of_cnot(self): """A simple circuit where nothing should be cancelled. qr0:----.------[X]------.-- qr0:----.------[X]------.-- | | | | qr1:---(+)-------------(+)- = qr1:---(+)-------------(+)- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.x(qr[0]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.cx(qr[0], qr[1]) expected.x(qr[0]) expected.cx(qr[0], qr[1]) self.assertEqual(expected, new_circuit) def test_control_bit_of_cnot1(self): """A simple circuit where the two cnots shoule be cancelled. qr0:----.------[Z]------.-- qr0:---[Z]--- | | qr1:---(+)-------------(+)- = qr1:--------- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.z(qr[0]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.z(qr[0]) self.assertEqual(expected, new_circuit) def test_control_bit_of_cnot2(self): """A simple circuit where the two cnots shoule be cancelled. qr0:----.------[T]------.-- qr0:---[T]--- | | qr1:---(+)-------------(+)- = qr1:--------- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.t(qr[0]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.t(qr[0]) self.assertEqual(expected, new_circuit) def test_control_bit_of_cnot3(self): """A simple circuit where the two cnots shoule be cancelled. qr0:----.------[Rz]------.-- qr0:---[Rz]--- | | qr1:---(+)-------- -----(+)- = qr1:---------- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.rz(np.pi / 3, qr[0]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.rz(np.pi / 3, qr[0]) self.assertEqual(expected, new_circuit) def test_control_bit_of_cnot4(self): """A simple circuit where the two cnots shoule be cancelled. qr0:----.------[T]------.-- qr0:---[T]--- | | qr1:---(+)-------------(+)- = qr1:--------- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.t(qr[0]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.t(qr[0]) self.assertEqual(expected, new_circuit) def test_target_bit_of_cnot(self): """A simple circuit where nothing should be cancelled. qr0:----.---------------.-- qr0:----.---------------.-- | | | | qr1:---(+)-----[Z]-----(+)- = qr1:---(+)----[Z]------(+)- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.z(qr[1]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.cx(qr[0], qr[1]) expected.z(qr[1]) expected.cx(qr[0], qr[1]) self.assertEqual(expected, new_circuit) def test_target_bit_of_cnot1(self): """A simple circuit where nothing should be cancelled. qr0:----.---------------.-- qr0:----.---------------.-- | | | | qr1:---(+)-----[T]-----(+)- = qr1:---(+)----[T]------(+)- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.t(qr[1]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.cx(qr[0], qr[1]) expected.t(qr[1]) expected.cx(qr[0], qr[1]) self.assertEqual(expected, new_circuit) def test_target_bit_of_cnot2(self): """A simple circuit where nothing should be cancelled. qr0:----.---------------.-- qr0:----.---------------.-- | | | | qr1:---(+)-----[Rz]----(+)- = qr1:---(+)----[Rz]-----(+)- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.rz(np.pi / 3, qr[1]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.cx(qr[0], qr[1]) expected.rz(np.pi / 3, qr[1]) expected.cx(qr[0], qr[1]) self.assertEqual(expected, new_circuit) def test_commutative_circuit2(self): """ A simple circuit where three CNOTs commute, the first and the last cancel, also two X gates cancel and two Rz gates combine. qr0:----.---------------.-------- qr0:------------- | | qr1:---(+)---(+)--[X]--(+)--[X]-- = qr1:--------(+)-- | | qr2:---[Rz]---.---[Rz]-[T]--[S]-- qr2:--[U1]---.--- """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.rz(np.pi / 3, qr[2]) circuit.cx(qr[2], qr[1]) circuit.rz(np.pi / 3, qr[2]) circuit.t(qr[2]) circuit.s(qr[2]) circuit.x(qr[1]) circuit.cx(qr[0], qr[1]) circuit.x(qr[1]) passmanager = PassManager() passmanager.append(CommutativeCancellation()) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.append(RZGate(np.pi * 17 / 12), [qr[2]]) expected.cx(qr[2], qr[1]) expected.global_phase = (np.pi * 17 / 12 - (2 * np.pi / 3)) / 2 self.assertEqual(expected, new_circuit) def test_commutative_circuit3(self): """ A simple circuit where three CNOTs commute, the first and the last cancel, also two X gates cancel and two Rz gates combine. qr0:-------.------------------.------------- qr0:------------- | | qr1:------(+)------(+)--[X]--(+)-------[X]-- = qr1:--------(+)-- | | qr2:------[Rz]--.---.----.---[Rz]-[T]--[S]-- qr2:--[U1]---.--- | | qr3:-[Rz]--[X]-(+)------(+)--[X]-[Rz]------- qr3:--[Rz]------- """ qr = QuantumRegister(4, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.rz(np.pi / 3, qr[2]) circuit.rz(np.pi / 3, qr[3]) circuit.x(qr[3]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[2], qr[1]) circuit.cx(qr[2], qr[3]) circuit.rz(np.pi / 3, qr[2]) circuit.t(qr[2]) circuit.x(qr[3]) circuit.rz(np.pi / 3, qr[3]) circuit.s(qr[2]) circuit.x(qr[1]) circuit.cx(qr[0], qr[1]) circuit.x(qr[1]) passmanager = PassManager() passmanager.append( [CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")], do_while=lambda property_set: not property_set["size_fixed_point"], ) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.append(RZGate(np.pi * 17 / 12), [qr[2]]) expected.append(RZGate(np.pi * 2 / 3), [qr[3]]) expected.cx(qr[2], qr[1]) self.assertEqual( expected, new_circuit, msg=f"expected:\n{expected}\nnew_circuit:\n{new_circuit}" ) def test_cnot_cascade(self): """ A cascade of CNOTs that equals identity. """ qr = QuantumRegister(10, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[5], qr[6]) circuit.cx(qr[6], qr[7]) circuit.cx(qr[7], qr[8]) circuit.cx(qr[8], qr[9]) circuit.cx(qr[8], qr[9]) circuit.cx(qr[7], qr[8]) circuit.cx(qr[6], qr[7]) circuit.cx(qr[5], qr[6]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[0], qr[1]) passmanager = PassManager() # passmanager.append(CommutativeCancellation()) passmanager.append( [CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")], do_while=lambda property_set: not property_set["size_fixed_point"], ) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) def test_cnot_cascade1(self): """ A cascade of CNOTs that equals identity, with rotation gates inserted. """ qr = QuantumRegister(10, "qr") circuit = QuantumCircuit(qr) circuit.rx(np.pi, qr[0]) circuit.rx(np.pi, qr[1]) circuit.rx(np.pi, qr[2]) circuit.rx(np.pi, qr[3]) circuit.rx(np.pi, qr[4]) circuit.rx(np.pi, qr[5]) circuit.rx(np.pi, qr[6]) circuit.rx(np.pi, qr[7]) circuit.rx(np.pi, qr[8]) circuit.rx(np.pi, qr[9]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[5], qr[6]) circuit.cx(qr[6], qr[7]) circuit.cx(qr[7], qr[8]) circuit.cx(qr[8], qr[9]) circuit.cx(qr[8], qr[9]) circuit.cx(qr[7], qr[8]) circuit.cx(qr[6], qr[7]) circuit.cx(qr[5], qr[6]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[0], qr[1]) circuit.rx(np.pi, qr[0]) circuit.rx(np.pi, qr[1]) circuit.rx(np.pi, qr[2]) circuit.rx(np.pi, qr[3]) circuit.rx(np.pi, qr[4]) circuit.rx(np.pi, qr[5]) circuit.rx(np.pi, qr[6]) circuit.rx(np.pi, qr[7]) circuit.rx(np.pi, qr[8]) circuit.rx(np.pi, qr[9]) passmanager = PassManager() # passmanager.append(CommutativeCancellation()) passmanager.append( [CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")], do_while=lambda property_set: not property_set["size_fixed_point"], ) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) def test_conditional_gates_dont_commute(self): """Conditional gates do not commute and do not cancel""" # β”Œβ”€β”€β”€β”β”Œβ”€β” # q_0: ─ H β”œβ”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜β””β•₯β”˜ β”Œβ”€β” # q_1: ──■───╫────■────Mβ”œβ”€β”€β”€ # β”Œβ”€β”΄β”€β” β•‘ β”Œβ”€β”΄β”€β” β””β•₯β”˜β”Œβ”€β” # q_2: ─ X β”œβ”€β•«β”€β”€β”€ X β”œβ”€β”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”˜ β•‘ └─β•₯β”€β”˜ β•‘ β””β•₯β”˜ # β•‘ β”Œβ”€β”€β•¨β”€β”€β” β•‘ β•‘ # c: 2/══════╩═║ 0x0 β•žβ•β•©β•β•β•©β• # 0 β””β”€β”€β”€β”€β”€β”˜ 0 1 circuit = QuantumCircuit(3, 2) circuit.h(0) circuit.measure(0, 0) circuit.cx(1, 2) circuit.cx(1, 2).c_if(circuit.cregs[0], 0) circuit.measure([1, 2], [0, 1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) self.assertEqual(circuit, new_circuit) def test_basis_01(self): """Test basis priority change, phase gate""" circuit = QuantumCircuit(1) circuit.s(0) circuit.z(0) circuit.t(0) circuit.rz(np.pi, 0) passmanager = PassManager() passmanager.append(CommutativeCancellation(basis_gates=["cx", "p", "sx"])) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(1) expected.rz(11 * np.pi / 4, 0) expected.global_phase = 11 * np.pi / 4 / 2 - np.pi / 2 self.assertEqual(new_circuit, expected) def test_target_basis_01(self): """Test basis priority change, phase gate, with target.""" circuit = QuantumCircuit(1) circuit.s(0) circuit.z(0) circuit.t(0) circuit.rz(np.pi, 0) theta = Parameter("theta") target = Target(num_qubits=2) target.add_instruction(CXGate()) target.add_instruction(PhaseGate(theta)) target.add_instruction(SXGate()) passmanager = PassManager() passmanager.append(CommutativeCancellation(target=target)) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(1) expected.rz(11 * np.pi / 4, 0) expected.global_phase = 11 * np.pi / 4 / 2 - np.pi / 2 self.assertEqual(new_circuit, expected) def test_basis_02(self): """Test basis priority change, Rz gate""" circuit = QuantumCircuit(1) circuit.s(0) circuit.z(0) circuit.t(0) passmanager = PassManager() passmanager.append(CommutativeCancellation(basis_gates=["cx", "rz", "sx"])) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(1) expected.rz(7 * np.pi / 4, 0) expected.global_phase = 7 * np.pi / 4 / 2 self.assertEqual(new_circuit, expected) def test_basis_03(self): """Test no specified basis""" circuit = QuantumCircuit(1) circuit.s(0) circuit.z(0) circuit.t(0) passmanager = PassManager() passmanager.append(CommutativeCancellation()) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(1) expected.s(0) expected.z(0) expected.t(0) self.assertEqual(new_circuit, expected) def test_basis_global_phase_01(self): """Test no specified basis, rz""" circ = QuantumCircuit(1) circ.rz(np.pi / 2, 0) circ.p(np.pi / 2, 0) circ.p(np.pi / 2, 0) passmanager = PassManager() passmanager.append(CommutativeCancellation()) ccirc = passmanager.run(circ) self.assertEqual(Operator(circ), Operator(ccirc)) def test_basis_global_phase_02(self): """Test no specified basis, p""" circ = QuantumCircuit(1) circ.p(np.pi / 2, 0) circ.rz(np.pi / 2, 0) circ.p(np.pi / 2, 0) passmanager = PassManager() passmanager.append(CommutativeCancellation()) ccirc = passmanager.run(circ) self.assertEqual(Operator(circ), Operator(ccirc)) def test_basis_global_phase_03(self): """Test global phase preservation if cummulative z-rotation is 0""" circ = QuantumCircuit(1) circ.rz(np.pi / 2, 0) circ.p(np.pi / 2, 0) circ.z(0) passmanager = PassManager() passmanager.append(CommutativeCancellation()) ccirc = passmanager.run(circ) self.assertEqual(Operator(circ), Operator(ccirc)) def test_basic_classical_wires(self): """Test that transpile runs without internal errors when dealing with commutable operations with classical controls. Regression test for gh-8553.""" original = QuantumCircuit(2, 1) original.x(0).c_if(original.cregs[0], 0) original.x(1).c_if(original.cregs[0], 0) # This transpilation shouldn't change anything, but it should succeed. At one point it was # triggering an internal logic error and crashing. transpiled = PassManager([CommutativeCancellation()]).run(original) self.assertEqual(original, transpiled) def test_simple_if_else(self): """Test that the pass is not confused by if-else.""" base_test1 = QuantumCircuit(3, 3) base_test1.x(1) base_test1.cx(0, 1) base_test1.x(1) base_test2 = QuantumCircuit(3, 3) base_test2.rz(0.1, 1) base_test2.rz(0.1, 1) test = QuantumCircuit(3, 3) test.h(0) test.x(0) test.rx(0.2, 0) test.measure(0, 0) test.x(0) test.if_else( (test.clbits[0], True), base_test1.copy(), base_test2.copy(), test.qubits, test.clbits ) expected = QuantumCircuit(3, 3) expected.h(0) expected.rx(np.pi + 0.2, 0) expected.measure(0, 0) expected.x(0) expected_test1 = QuantumCircuit(3, 3) expected_test1.cx(0, 1) expected_test2 = QuantumCircuit(3, 3) expected_test2.rz(0.2, 1) expected.if_else( (expected.clbits[0], True), expected_test1.copy(), expected_test2.copy(), expected.qubits, expected.clbits, ) passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = passmanager.run(test) self.assertEqual(new_circuit, expected) def test_nested_control_flow(self): """Test that the pass does not add barrier into nested control flow.""" level2_test = QuantumCircuit(2, 1) level2_test.cz(0, 1) level2_test.cz(0, 1) level2_test.cz(0, 1) level2_test.measure(0, 0) level1_test = QuantumCircuit(2, 1) level1_test.for_loop((0,), None, level2_test.copy(), level1_test.qubits, level1_test.clbits) level1_test.h(0) level1_test.h(0) level1_test.measure(0, 0) test = QuantumCircuit(2, 1) test.while_loop((test.clbits[0], True), level1_test.copy(), test.qubits, test.clbits) test.measure(0, 0) level2_expected = QuantumCircuit(2, 1) level2_expected.cz(0, 1) level2_expected.measure(0, 0) level1_expected = QuantumCircuit(2, 1) level1_expected.for_loop( (0,), None, level2_expected.copy(), level1_expected.qubits, level1_expected.clbits ) level1_expected.measure(0, 0) expected = QuantumCircuit(2, 1) expected.while_loop( (expected.clbits[0], True), level1_expected.copy(), expected.qubits, expected.clbits ) expected.measure(0, 0) passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = passmanager.run(test) self.assertEqual(new_circuit, expected) def test_cancellation_not_crossing_block_boundary(self): """Test that the pass does cancel gates across control flow op block boundaries.""" test1 = QuantumCircuit(2, 2) test1.x(1) with test1.if_test((0, False)): test1.cx(0, 1) test1.x(1) passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = passmanager.run(test1) self.assertEqual(new_circuit, test1) def test_cancellation_not_crossing_between_blocks(self): """Test that the pass does cancel gates in different control flow ops.""" test2 = QuantumCircuit(2, 2) with test2.if_test((0, True)): test2.x(1) with test2.if_test((0, True)): test2.cx(0, 1) test2.x(1) passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = passmanager.run(test2) self.assertEqual(new_circuit, test2) if __name__ == "__main__": unittest.main()
https://github.com/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. """Depth pass testing""" import unittest from qiskit import QuantumCircuit, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler.passes import CountOps from qiskit.test import QiskitTestCase class TestCountOpsPass(QiskitTestCase): """Tests for CountOps analysis methods.""" def test_empty_dag(self): """Empty DAG has empty counts.""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = CountOps() _ = pass_.run(dag) self.assertDictEqual(pass_.property_set["count_ops"], {}) def test_just_qubits(self): """A dag with 8 operations (6 CXs and 2 Hs)""" # β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β” # q0_0: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€ X β”œβ”€ X β”œ # β”œβ”€β”€β”€β”€β”Œβ”€β”΄β”€β”β”Œβ”€β”΄β”€β”β”Œβ”€β”΄β”€β”β”Œβ”€β”΄β”€β”β””β”€β”¬β”€β”˜β””β”€β”¬β”€β”˜ # q0_1: ─ H β”œβ”€ X β”œβ”€ X β”œβ”€ X β”œβ”€ X β”œβ”€β”€β– β”€β”€β”€β”€β– β”€β”€ # β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[1], qr[0]) dag = circuit_to_dag(circuit) pass_ = CountOps() _ = pass_.run(dag) self.assertDictEqual(pass_.property_set["count_ops"], {"cx": 6, "h": 2}) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for pass cancelling 2 consecutive CNOTs on the same qubits.""" from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit import Clbit, Qubit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import CXCancellation from qiskit.test import QiskitTestCase class TestCXCancellation(QiskitTestCase): """Test the CXCancellation pass.""" def test_pass_cx_cancellation(self): """Test the cx cancellation pass. It should cancel consecutive cx pairs on same qubits. """ qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[1], qr[0]) pass_manager = PassManager() pass_manager.append(CXCancellation()) out_circuit = pass_manager.run(circuit) expected = QuantumCircuit(qr) expected.h(qr[0]) expected.h(qr[0]) self.assertEqual(out_circuit, expected) def test_pass_cx_cancellation_intermixed_ops(self): """Cancellation shouldn't be affected by the order of ops on different qubits.""" qr = QuantumRegister(4) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[3]) pass_manager = PassManager() pass_manager.append(CXCancellation()) out_circuit = pass_manager.run(circuit) expected = QuantumCircuit(qr) expected.h(qr[0]) expected.h(qr[1]) self.assertEqual(out_circuit, expected) def test_pass_cx_cancellation_chained_cx(self): """Include a test were not all operations can be cancelled.""" # β”Œβ”€β”€β”€β” # q0_0: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€ # β”œβ”€β”€β”€β”€β”Œβ”€β”΄β”€β” β”Œβ”€β”΄β”€β” # q0_1: ─ H β”œβ”€ X β”œβ”€β”€β– β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ # q0_2: ─────────── X β”œβ”€β”€β– β”€β”€β”€β”€β– β”€β”€ # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β”β”Œβ”€β”΄β”€β” # q0_3: ──────────────── X β”œβ”€ X β”œ # β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ qr = QuantumRegister(4) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[2], qr[3]) pass_manager = PassManager() pass_manager.append(CXCancellation()) out_circuit = pass_manager.run(circuit) # β”Œβ”€β”€β”€β” # q0_0: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€ # β”œβ”€β”€β”€β”€β”Œβ”€β”΄β”€β” β”Œβ”€β”΄β”€β” # q0_1: ─ H β”œβ”€ X β”œβ”€β”€β– β”€β”€β”€ X β”œ # β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ # q0_2: ─────────── X β”œβ”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ # q0_3: ──────────────────── expected = QuantumCircuit(qr) expected.h(qr[0]) expected.h(qr[1]) expected.cx(qr[0], qr[1]) expected.cx(qr[1], qr[2]) expected.cx(qr[0], qr[1]) self.assertEqual(out_circuit, expected) def test_swapped_cx(self): """Test that CX isn't cancelled if there are intermediary ops.""" qr = QuantumRegister(4) circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) circuit.swap(qr[1], qr[2]) circuit.cx(qr[1], qr[0]) pass_manager = PassManager() pass_manager.append(CXCancellation()) out_circuit = pass_manager.run(circuit) self.assertEqual(out_circuit, circuit) def test_inverted_cx(self): """Test that CX order dependence is respected.""" qr = QuantumRegister(4) circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[1]) pass_manager = PassManager() pass_manager.append(CXCancellation()) out_circuit = pass_manager.run(circuit) self.assertEqual(out_circuit, circuit) def test_if_else(self): """Test that the pass recurses in a simple if-else.""" pass_ = CXCancellation() inner_test = QuantumCircuit(4, 1) inner_test.cx(0, 1) inner_test.cx(0, 1) inner_test.cx(2, 3) inner_expected = QuantumCircuit(4, 1) inner_expected.cx(2, 3) test = QuantumCircuit(4, 1) test.h(0) test.measure(0, 0) test.if_else((0, True), inner_test.copy(), inner_test.copy(), range(4), [0]) expected = QuantumCircuit(4, 1) expected.h(0) expected.measure(0, 0) expected.if_else((0, True), inner_expected, inner_expected, range(4), [0]) self.assertEqual(pass_(test), expected) def test_nested_control_flow(self): """Test that collection recurses into nested control flow.""" pass_ = CXCancellation() qubits = [Qubit() for _ in [None] * 4] clbit = Clbit() inner_test = QuantumCircuit(qubits, [clbit]) inner_test.cx(0, 1) inner_test.cx(0, 1) inner_test.cx(2, 3) inner_expected = QuantumCircuit(qubits, [clbit]) inner_expected.cx(2, 3) true_body = QuantumCircuit(qubits, [clbit]) true_body.while_loop((clbit, True), inner_test.copy(), [0, 1, 2, 3], [0]) test = QuantumCircuit(qubits, [clbit]) test.for_loop(range(2), None, inner_test.copy(), [0, 1, 2, 3], [0]) test.if_else((clbit, True), true_body, None, [0, 1, 2, 3], [0]) expected_if_body = QuantumCircuit(qubits, [clbit]) expected_if_body.while_loop((clbit, True), inner_expected, [0, 1, 2, 3], [0]) expected = QuantumCircuit(qubits, [clbit]) expected.for_loop(range(2), None, inner_expected, [0, 1, 2, 3], [0]) expected.if_else((clbit, True), expected_if_body, None, [0, 1, 2, 3], [0]) self.assertEqual(pass_(test), expected)
https://github.com/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. """DAGFixedPoint pass testing""" import unittest from qiskit.transpiler.passes import DAGFixedPoint from qiskit import QuantumRegister, QuantumCircuit from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestFixedPointPass(QiskitTestCase): """Tests for PropertySet methods.""" def test_empty_dag_true(self): """Test the dag fixed point of an empty dag.""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = DAGFixedPoint() pass_.run(dag) self.assertFalse(pass_.property_set["dag_fixed_point"]) pass_.run(dag) self.assertTrue(pass_.property_set["dag_fixed_point"]) def test_nonempty_dag_false(self): """Test the dag false fixed point of a non-empty dag.""" qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) pass_ = DAGFixedPoint() pass_.run(dag) self.assertFalse(pass_.property_set["dag_fixed_point"]) dag.remove_all_ops_named("h") pass_.run(dag) self.assertFalse(pass_.property_set["dag_fixed_point"]) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the decompose pass""" from numpy import pi from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.transpiler.passes import Decompose from qiskit.converters import circuit_to_dag from qiskit.circuit.library import HGate, CCXGate, U2Gate from qiskit.quantum_info.operators import Operator from qiskit.test import QiskitTestCase class TestDecompose(QiskitTestCase): """Tests the decompose pass.""" def setUp(self): super().setUp() # example complex circuit # β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” # q2_0: ─0 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€ H β”œβ”€0 β”œ # β”‚ β”‚ β”‚ β””β”€β”€β”€β”˜β”‚ circuit-57 β”‚ # q2_1: ─1 gate1 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€1 β”œ # β”‚ β”‚β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ # q2_2: ─2 β”œβ”€0 β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”‚ β”‚ β”‚ # q2_3: ───────────1 gate2 β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”‚ β”‚β”Œβ”€β”΄β”€β” # q2_4: ───────────2 β”œβ”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”˜ circ1 = QuantumCircuit(3) circ1.h(0) circ1.t(1) circ1.x(2) my_gate = circ1.to_gate(label="gate1") circ2 = QuantumCircuit(3) circ2.h(0) circ2.cx(0, 1) circ2.x(2) my_gate2 = circ2.to_gate(label="gate2") circ3 = QuantumCircuit(2) circ3.x(0) q_bits = QuantumRegister(5) qc = QuantumCircuit(q_bits) qc.append(my_gate, q_bits[:3]) qc.append(my_gate2, q_bits[2:]) qc.mct(q_bits[:4], q_bits[4]) qc.h(0) qc.append(circ3, [0, 1]) self.complex_circuit = qc def test_basic(self): """Test decompose a single H into u2.""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) dag = circuit_to_dag(circuit) pass_ = Decompose(HGate) after_dag = pass_.run(dag) op_nodes = after_dag.op_nodes() self.assertEqual(len(op_nodes), 1) self.assertEqual(op_nodes[0].name, "u2") def test_decompose_none(self): """Test decompose a single H into u2.""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) dag = circuit_to_dag(circuit) pass_ = Decompose() after_dag = pass_.run(dag) op_nodes = after_dag.op_nodes() self.assertEqual(len(op_nodes), 1) self.assertEqual(op_nodes[0].name, "u2") def test_decompose_only_h(self): """Test to decompose a single H, without the rest""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) pass_ = Decompose(HGate) after_dag = pass_.run(dag) op_nodes = after_dag.op_nodes() self.assertEqual(len(op_nodes), 2) for node in op_nodes: self.assertIn(node.name, ["cx", "u2"]) def test_decompose_toffoli(self): """Test decompose CCX.""" qr1 = QuantumRegister(2, "qr1") qr2 = QuantumRegister(1, "qr2") circuit = QuantumCircuit(qr1, qr2) circuit.ccx(qr1[0], qr1[1], qr2[0]) dag = circuit_to_dag(circuit) pass_ = Decompose(CCXGate) after_dag = pass_.run(dag) op_nodes = after_dag.op_nodes() self.assertEqual(len(op_nodes), 15) for node in op_nodes: self.assertIn(node.name, ["h", "t", "tdg", "cx"]) def test_decompose_conditional(self): """Test decompose a 1-qubit gates with a conditional.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr).c_if(cr, 1) circuit.x(qr).c_if(cr, 1) dag = circuit_to_dag(circuit) pass_ = Decompose(HGate) after_dag = pass_.run(dag) ref_circuit = QuantumCircuit(qr, cr) ref_circuit.append(U2Gate(0, pi), [qr[0]]).c_if(cr, 1) ref_circuit.x(qr).c_if(cr, 1) ref_dag = circuit_to_dag(ref_circuit) self.assertEqual(after_dag, ref_dag) def test_decompose_oversized_instruction(self): """Test decompose on a single-op gate that doesn't use all qubits.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/3440 qc1 = QuantumCircuit(2) qc1.x(0) gate = qc1.to_gate() qc2 = QuantumCircuit(2) qc2.append(gate, [0, 1]) output = qc2.decompose() self.assertEqual(qc1, output) def test_decomposition_preserves_qregs_order(self): """Test decomposing a gate preserves it's definition registers order""" qr = QuantumRegister(2, "qr1") qc1 = QuantumCircuit(qr) qc1.cx(1, 0) gate = qc1.to_gate() qr2 = QuantumRegister(2, "qr2") qc2 = QuantumCircuit(qr2) qc2.append(gate, qr2) expected = QuantumCircuit(qr2) expected.cx(1, 0) self.assertEqual(qc2.decompose(), expected) def test_decompose_global_phase_1q(self): """Test decomposition of circuit with global phase""" qc1 = QuantumCircuit(1) qc1.rz(0.1, 0) qc1.ry(0.5, 0) qc1.global_phase += pi / 4 qcd = qc1.decompose() self.assertEqual(Operator(qc1), Operator(qcd)) def test_decompose_global_phase_2q(self): """Test decomposition of circuit with global phase""" qc1 = QuantumCircuit(2, global_phase=pi / 4) qc1.rz(0.1, 0) qc1.rxx(0.2, 0, 1) qcd = qc1.decompose() self.assertEqual(Operator(qc1), Operator(qcd)) def test_decompose_global_phase_1q_composite(self): """Test decomposition of circuit with global phase in a composite gate.""" circ = QuantumCircuit(1, global_phase=pi / 2) circ.x(0) circ.h(0) v = circ.to_gate() qc1 = QuantumCircuit(1) qc1.append(v, [0]) qcd = qc1.decompose() self.assertEqual(Operator(qc1), Operator(qcd)) def test_decompose_only_h_gate(self): """Test decomposition parameters so that only a certain gate is decomposed.""" circ = QuantumCircuit(2, 1) circ.h(0) circ.cz(0, 1) decom_circ = circ.decompose(["h"]) dag = circuit_to_dag(decom_circ) self.assertEqual(len(dag.op_nodes()), 2) self.assertEqual(dag.op_nodes()[0].name, "u2") self.assertEqual(dag.op_nodes()[1].name, "cz") def test_decompose_only_given_label(self): """Test decomposition parameters so that only a given label is decomposed.""" decom_circ = self.complex_circuit.decompose(["gate2"]) dag = circuit_to_dag(decom_circ) self.assertEqual(len(dag.op_nodes()), 7) self.assertEqual(dag.op_nodes()[0].op.label, "gate1") self.assertEqual(dag.op_nodes()[1].name, "h") self.assertEqual(dag.op_nodes()[2].name, "cx") self.assertEqual(dag.op_nodes()[3].name, "x") self.assertEqual(dag.op_nodes()[4].name, "mcx") self.assertEqual(dag.op_nodes()[5].name, "h") self.assertRegex(dag.op_nodes()[6].name, "circuit-") def test_decompose_only_given_name(self): """Test decomposition parameters so that only given name is decomposed.""" decom_circ = self.complex_circuit.decompose(["mcx"]) dag = circuit_to_dag(decom_circ) self.assertEqual(len(dag.op_nodes()), 13) self.assertEqual(dag.op_nodes()[0].op.label, "gate1") self.assertEqual(dag.op_nodes()[1].op.label, "gate2") self.assertEqual(dag.op_nodes()[2].name, "h") self.assertEqual(dag.op_nodes()[3].name, "cu1") self.assertEqual(dag.op_nodes()[4].name, "rcccx") self.assertEqual(dag.op_nodes()[5].name, "h") self.assertEqual(dag.op_nodes()[6].name, "h") self.assertEqual(dag.op_nodes()[7].name, "cu1") self.assertEqual(dag.op_nodes()[8].name, "rcccx_dg") self.assertEqual(dag.op_nodes()[9].name, "h") self.assertEqual(dag.op_nodes()[10].name, "c3sx") self.assertEqual(dag.op_nodes()[11].name, "h") self.assertRegex(dag.op_nodes()[12].name, "circuit-") def test_decompose_mixture_of_names_and_labels(self): """Test decomposition parameters so that mixture of names and labels is decomposed""" decom_circ = self.complex_circuit.decompose(["mcx", "gate2"]) dag = circuit_to_dag(decom_circ) self.assertEqual(len(dag.op_nodes()), 15) self.assertEqual(dag.op_nodes()[0].op.label, "gate1") self.assertEqual(dag.op_nodes()[1].name, "h") self.assertEqual(dag.op_nodes()[2].name, "cx") self.assertEqual(dag.op_nodes()[3].name, "x") self.assertEqual(dag.op_nodes()[4].name, "h") self.assertEqual(dag.op_nodes()[5].name, "cu1") self.assertEqual(dag.op_nodes()[6].name, "rcccx") self.assertEqual(dag.op_nodes()[7].name, "h") self.assertEqual(dag.op_nodes()[8].name, "h") self.assertEqual(dag.op_nodes()[9].name, "cu1") self.assertEqual(dag.op_nodes()[10].name, "rcccx_dg") self.assertEqual(dag.op_nodes()[11].name, "h") self.assertEqual(dag.op_nodes()[12].name, "c3sx") self.assertEqual(dag.op_nodes()[13].name, "h") self.assertRegex(dag.op_nodes()[14].name, "circuit-") def test_decompose_name_wildcards(self): """Test decomposition parameters so that name wildcards is decomposed""" decom_circ = self.complex_circuit.decompose(["circuit-*"]) dag = circuit_to_dag(decom_circ) self.assertEqual(len(dag.op_nodes()), 9) self.assertEqual(dag.op_nodes()[0].name, "h") self.assertEqual(dag.op_nodes()[1].name, "t") self.assertEqual(dag.op_nodes()[2].name, "x") self.assertEqual(dag.op_nodes()[3].name, "h") self.assertRegex(dag.op_nodes()[4].name, "cx") self.assertEqual(dag.op_nodes()[5].name, "x") self.assertEqual(dag.op_nodes()[6].name, "mcx") self.assertEqual(dag.op_nodes()[7].name, "h") self.assertEqual(dag.op_nodes()[8].name, "x") def test_decompose_label_wildcards(self): """Test decomposition parameters so that label wildcards is decomposed""" decom_circ = self.complex_circuit.decompose(["gate*"]) dag = circuit_to_dag(decom_circ) self.assertEqual(len(dag.op_nodes()), 9) self.assertEqual(dag.op_nodes()[0].name, "h") self.assertEqual(dag.op_nodes()[1].name, "t") self.assertEqual(dag.op_nodes()[2].name, "x") self.assertEqual(dag.op_nodes()[3].name, "h") self.assertEqual(dag.op_nodes()[4].name, "cx") self.assertEqual(dag.op_nodes()[5].name, "x") self.assertEqual(dag.op_nodes()[6].name, "mcx") self.assertEqual(dag.op_nodes()[7].name, "h") self.assertRegex(dag.op_nodes()[8].name, "circuit-") def test_decompose_empty_gate(self): """Test a gate where the definition is an empty circuit is decomposed.""" empty = QuantumCircuit(1) circuit = QuantumCircuit(1) circuit.append(empty.to_gate(), [0]) decomposed = circuit.decompose() self.assertEqual(len(decomposed.data), 0) def test_decompose_reps(self): """Test decompose reps function is decomposed correctly""" decom_circ = self.complex_circuit.decompose(reps=2) decomposed = self.complex_circuit.decompose().decompose() self.assertEqual(decom_circ, decomposed) def test_decompose_single_qubit_clbit(self): """Test the decomposition of a block with a single qubit and clbit works. Regression test of Qiskit/qiskit-terra#8591. """ block = QuantumCircuit(1, 1) block.h(0) circuit = QuantumCircuit(1, 1) circuit.append(block, [0], [0]) decomposed = circuit.decompose() self.assertEqual(decomposed, block)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the DenseLayout pass""" import unittest import numpy as np from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.circuit import Parameter, Qubit from qiskit.circuit.library import CXGate, UGate, ECRGate, RZGate from qiskit.transpiler import CouplingMap, Target, InstructionProperties, TranspilerError from qiskit.transpiler.passes import DenseLayout from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeTokyo from qiskit.transpiler.passes.layout.dense_layout import _build_error_matrix class TestDenseLayout(QiskitTestCase): """Tests the DenseLayout pass""" def setUp(self): super().setUp() self.cmap20 = FakeTokyo().configuration().coupling_map self.target_19 = Target() rng = np.random.default_rng(12345) instruction_props = { edge: InstructionProperties( duration=rng.uniform(1e-7, 1e-6), error=rng.uniform(1e-4, 1e-3) ) for edge in CouplingMap.from_heavy_hex(3).get_edges() } self.target_19.add_instruction(CXGate(), instruction_props) def test_5q_circuit_20q_coupling(self): """Test finds dense 5q corner in 20q coupling map.""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[3], qr[1]) circuit.cx(qr[0], qr[2]) dag = circuit_to_dag(circuit) pass_ = DenseLayout(CouplingMap(self.cmap20)) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 11) self.assertEqual(layout[qr[1]], 10) self.assertEqual(layout[qr[2]], 6) self.assertEqual(layout[qr[3]], 5) self.assertEqual(layout[qr[4]], 0) def test_6q_circuit_20q_coupling(self): """Test finds dense 5q corner in 20q coupling map.""" qr0 = QuantumRegister(3, "q0") qr1 = QuantumRegister(3, "q1") circuit = QuantumCircuit(qr0, qr1) circuit.cx(qr0[0], qr1[2]) circuit.cx(qr1[1], qr0[2]) dag = circuit_to_dag(circuit) pass_ = DenseLayout(CouplingMap(self.cmap20)) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr0[0]], 11) self.assertEqual(layout[qr0[1]], 10) self.assertEqual(layout[qr0[2]], 6) self.assertEqual(layout[qr1[0]], 5) self.assertEqual(layout[qr1[1]], 1) self.assertEqual(layout[qr1[2]], 0) def test_5q_circuit_19q_target_with_noise(self): """Test layout works finds a dense 5q subgraph in a 19q heavy hex target.""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[3], qr[1]) circuit.cx(qr[0], qr[2]) dag = circuit_to_dag(circuit) pass_ = DenseLayout(target=self.target_19) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 9) self.assertEqual(layout[qr[1]], 3) self.assertEqual(layout[qr[2]], 11) self.assertEqual(layout[qr[3]], 15) self.assertEqual(layout[qr[4]], 4) def test_5q_circuit_19q_target_without_noise(self): """Test layout works finds a dense 5q subgraph in a 19q heavy hex target with no noise.""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[3], qr[1]) circuit.cx(qr[0], qr[2]) dag = circuit_to_dag(circuit) instruction_props = {edge: None for edge in CouplingMap.from_heavy_hex(3).get_edges()} noiseless_target = Target() noiseless_target.add_instruction(CXGate(), instruction_props) pass_ = DenseLayout(target=noiseless_target) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 1) self.assertEqual(layout[qr[1]], 13) self.assertEqual(layout[qr[2]], 0) self.assertEqual(layout[qr[3]], 9) self.assertEqual(layout[qr[4]], 3) def test_ideal_target_no_coupling(self): """Test pass fails as expected if a target without edge constraints exists.""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[3], qr[1]) circuit.cx(qr[0], qr[2]) dag = circuit_to_dag(circuit) target = Target(num_qubits=19) target.add_instruction(CXGate()) layout_pass = DenseLayout(target=target) with self.assertRaises(TranspilerError): layout_pass.run(dag) def test_target_too_small_for_circuit(self): """Test error is raised when target is too small for circuit.""" target = Target() target.add_instruction( CXGate(), {edge: None for edge in CouplingMap.from_line(3).get_edges()} ) dag = circuit_to_dag(QuantumCircuit(5)) layout_pass = DenseLayout(target=target) with self.assertRaises(TranspilerError): layout_pass.run(dag) def test_19q_target_with_noise_error_matrix(self): """Test the error matrix construction works for a just cx target.""" expected_error_mat = np.zeros((19, 19)) for qargs, props in self.target_19["cx"].items(): error = props.error expected_error_mat[qargs[0]][qargs[1]] = error error_mat = _build_error_matrix( self.target_19.num_qubits, {i: i for i in range(self.target_19.num_qubits)}, target=self.target_19, )[0] np.testing.assert_array_equal(expected_error_mat, error_mat) def test_multiple_gate_error_matrix(self): """Test error matrix ona small target with multiple gets on each qubit generates""" target = Target(num_qubits=3) phi = Parameter("phi") lam = Parameter("lam") theta = Parameter("theta") target.add_instruction( RZGate(phi), {(i,): InstructionProperties(duration=0, error=0) for i in range(3)} ) target.add_instruction( UGate(theta, phi, lam), {(i,): InstructionProperties(duration=1e-7, error=1e-2) for i in range(3)}, ) cx_props = { (0, 1): InstructionProperties(error=1e-3), (0, 2): InstructionProperties(error=1e-3), (1, 0): InstructionProperties(error=1e-3), (1, 2): InstructionProperties(error=1e-3), (2, 0): InstructionProperties(error=1e-3), (2, 1): InstructionProperties(error=1e-3), } target.add_instruction(CXGate(), cx_props) ecr_props = { (0, 1): InstructionProperties(error=2e-2), (1, 2): InstructionProperties(error=2e-2), (2, 0): InstructionProperties(error=2e-2), } target.add_instruction(ECRGate(), ecr_props) expected_error_matrix = np.array( [ [1e-2, 2e-2, 1e-3], [1e-3, 1e-2, 2e-2], [2e-2, 1e-3, 1e-2], ] ) error_mat = _build_error_matrix( target.num_qubits, {i: i for i in range(target.num_qubits)}, target=target )[0] np.testing.assert_array_equal(expected_error_matrix, error_mat) def test_5q_circuit_20q_with_if_else(self): """Test layout works finds a dense 5q subgraph in a 19q heavy hex target.""" qr = QuantumRegister(5, "q") cr = ClassicalRegister(5) circuit = QuantumCircuit(qr, cr) true_body = QuantumCircuit(qr, cr) false_body = QuantumCircuit(qr, cr) true_body.cx(qr[0], qr[3]) true_body.cx(qr[3], qr[4]) false_body.cx(qr[3], qr[1]) false_body.cx(qr[0], qr[2]) circuit.if_else((cr, 0), true_body, false_body, qr, cr) circuit.cx(0, 4) dag = circuit_to_dag(circuit) pass_ = DenseLayout(CouplingMap(self.cmap20)) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 11) self.assertEqual(layout[qr[1]], 10) self.assertEqual(layout[qr[2]], 6) self.assertEqual(layout[qr[3]], 5) self.assertEqual(layout[qr[4]], 0) def test_loose_bit_circuit(self): """Test dense layout works with loose bits outside a register.""" bits = [Qubit() for _ in range(5)] circuit = QuantumCircuit() circuit.add_bits(bits) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) dag = circuit_to_dag(circuit) pass_ = DenseLayout(CouplingMap(self.cmap20)) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[bits[0]], 11) self.assertEqual(layout[bits[1]], 10) self.assertEqual(layout[bits[2]], 6) self.assertEqual(layout[bits[3]], 5) self.assertEqual(layout[bits[4]], 0) if __name__ == "__main__": unittest.main()
https://github.com/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. """Depth pass testing""" import unittest from qiskit import QuantumCircuit, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler.passes import Depth from qiskit.test import QiskitTestCase class TestDepthPass(QiskitTestCase): """Tests for Depth analysis methods.""" def test_empty_dag(self): """Empty DAG has 0 depth""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = Depth() _ = pass_.run(dag) self.assertEqual(pass_.property_set["depth"], 0) def test_just_qubits(self): """A dag with 8 operations and no classic bits""" # β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β” # q0_0: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€ X β”œβ”€ X β”œ # β”œβ”€β”€β”€β”€β”Œβ”€β”΄β”€β”β”Œβ”€β”΄β”€β”β”Œβ”€β”΄β”€β”β”Œβ”€β”΄β”€β”β””β”€β”¬β”€β”˜β””β”€β”¬β”€β”˜ # q0_1: ─ H β”œβ”€ X β”œβ”€ X β”œβ”€ X β”œβ”€ X β”œβ”€β”€β– β”€β”€β”€β”€β– β”€β”€ # β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜ qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[1], qr[0]) dag = circuit_to_dag(circuit) pass_ = Depth() _ = pass_.run(dag) self.assertEqual(pass_.property_set["depth"], 7) def test_depth_one(self): """A dag with operations in parallel and depth 1""" qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) dag = circuit_to_dag(circuit) pass_ = Depth() _ = pass_.run(dag) self.assertEqual(pass_.property_set["depth"], 1) def test_depth_control_flow(self): """A DAG with control flow still gives an estimate.""" qc = QuantumCircuit(5, 1) qc.h(0) qc.measure(0, 0) with qc.if_test((qc.clbits[0], True)) as else_: qc.x(1) qc.cx(2, 3) with else_: qc.x(1) with qc.for_loop(range(3)): qc.z(2) with qc.for_loop((4, 0, 1)): qc.z(2) with qc.while_loop((qc.clbits[0], True)): qc.h(0) qc.measure(0, 0) pass_ = Depth(recurse=True) pass_(qc) self.assertEqual(pass_.property_set["depth"], 16) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- 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. """Test the CX Direction pass""" import unittest from math import pi from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit.transpiler import TranspilerError from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes import CXDirection from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestCXDirection(QiskitTestCase): """ Tests the CXDirection pass.""" def test_no_cnots(self): """ Trivial map in a circuit without entanglement qr0:---[H]--- qr1:---[H]--- qr2:---[H]--- CouplingMap map: None """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.h(qr) coupling = CouplingMap() dag = circuit_to_dag(circuit) pass_ = CXDirection(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_direction_error(self): """ The mapping cannot be fixed by direction mapper qr0:--------- qr1:---(+)--- | qr2:----.---- CouplingMap map: [2] <- [0] -> [1] """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) coupling = CouplingMap([[0, 1], [0, 2]]) dag = circuit_to_dag(circuit) pass_ = CXDirection(coupling) with self.assertRaises(TranspilerError): pass_.run(dag) def test_direction_correct(self): """ The CX is in the right direction qr0:---(+)--- | qr1:----.---- CouplingMap map: [0] -> [1] """ qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) pass_ = CXDirection(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_direction_flip(self): """ Flip a CX qr0:----.---- | qr1:---(+)--- CouplingMap map: [0] -> [1] qr0:-[H]-(+)-[H]-- | qr1:-[H]--.--[H]-- """ qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.u2(0, pi, qr[0]) expected.u2(0, pi, qr[1]) expected.cx(qr[0], qr[1]) expected.u2(0, pi, qr[0]) expected.u2(0, pi, qr[1]) pass_ = CXDirection(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_flip_with_measure(self): """ qr0: -(+)-[m]- | | qr1: --.---|-- | cr0: ------.-- CouplingMap map: [0] -> [1] qr0: -[H]--.--[H]-[m]- | | qr1: -[H]-(+)-[H]--|-- | cr0: --------------.-- """ qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(1, 'cr') circuit = QuantumCircuit(qr, cr) circuit.cx(qr[1], qr[0]) circuit.measure(qr[0], cr[0]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.u2(0, pi, qr[0]) expected.u2(0, pi, qr[1]) expected.cx(qr[0], qr[1]) expected.u2(0, pi, qr[0]) expected.u2(0, pi, qr[1]) expected.measure(qr[0], cr[0]) pass_ = CXDirection(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) if __name__ == '__main__': unittest.main()
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. """Test the EnlargeWithAncilla pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import Layout from qiskit.transpiler.passes import EnlargeWithAncilla from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestEnlargeWithAncilla(QiskitTestCase): """Tests the EnlargeWithAncilla pass.""" def setUp(self): super().setUp() self.qr3 = QuantumRegister(3, "qr") circuit = QuantumCircuit(self.qr3) circuit.h(self.qr3) self.dag = circuit_to_dag(circuit) def test_no_extension(self): """There are no virtual qubits to extend.""" layout = Layout({self.qr3[0]: 0, self.qr3[1]: 1, self.qr3[2]: 2}) pass_ = EnlargeWithAncilla() pass_.property_set["layout"] = layout after = pass_.run(self.dag) qregs = list(after.qregs.values()) self.assertEqual(1, len(qregs)) self.assertEqual(self.qr3, qregs[0]) def test_with_extension(self): """There are 2 virtual qubit to extend.""" ancilla = QuantumRegister(2, "ancilla") layout = Layout( {0: self.qr3[0], 1: ancilla[0], 2: self.qr3[1], 3: ancilla[1], 4: self.qr3[2]} ) layout.add_register(ancilla) pass_ = EnlargeWithAncilla() pass_.property_set["layout"] = layout after = pass_.run(self.dag) qregs = list(after.qregs.values()) self.assertEqual(2, len(qregs)) self.assertEqual(self.qr3, qregs[0]) self.assertEqual(ancilla, qregs[1]) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the LookaheadSwap pass""" import unittest from numpy import pi from qiskit.dagcircuit import DAGCircuit from qiskit.transpiler.passes import LookaheadSwap from qiskit.transpiler import CouplingMap, Target from qiskit.converters import circuit_to_dag from qiskit.circuit.library import CXGate from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeMelbourne class TestLookaheadSwap(QiskitTestCase): """Tests the LookaheadSwap pass.""" def test_lookahead_swap_doesnt_modify_mapped_circuit(self): """Test that lookahead swap is idempotent. It should not modify a circuit which is already compatible with the coupling map, and can be applied repeatedly without modifying the circuit. """ qr = QuantumRegister(3, name="q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[2]) circuit.cx(qr[0], qr[1]) original_dag = circuit_to_dag(circuit) # Create coupling map which contains all two-qubit gates in the circuit. coupling_map = CouplingMap([[0, 1], [0, 2]]) mapped_dag = LookaheadSwap(coupling_map).run(original_dag) self.assertEqual(original_dag, mapped_dag) remapped_dag = LookaheadSwap(coupling_map).run(mapped_dag) self.assertEqual(mapped_dag, remapped_dag) def test_lookahead_swap_should_add_a_single_swap(self): """Test that LookaheadSwap will insert a SWAP to match layout. For a single cx gate which is not available in the current layout, test that the mapper inserts a single swap to enable the gate. """ qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[2]) dag_circuit = circuit_to_dag(circuit) coupling_map = CouplingMap([[0, 1], [1, 2]]) mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit) self.assertEqual( mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1 ) def test_lookahead_swap_finds_minimal_swap_solution(self): """Of many valid SWAPs, test that LookaheadSwap finds the cheapest path. For a two CNOT circuit: cx q[0],q[2]; cx q[0],q[1] on the initial layout: qN -> qN (At least) two solutions exist: - SWAP q[0],[1], cx q[0],q[2], cx q[0],q[1] - SWAP q[1],[2], cx q[0],q[2], SWAP q[1],q[2], cx q[0],q[1] Verify that we find the first solution, as it requires fewer SWAPs. """ qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[2]) circuit.cx(qr[0], qr[1]) dag_circuit = circuit_to_dag(circuit) coupling_map = CouplingMap([[0, 1], [1, 2]]) mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit) self.assertEqual( mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1 ) def test_lookahead_swap_maps_measurements(self): """Verify measurement nodes are updated to map correct cregs to re-mapped qregs. Create a circuit with measures on q0 and q2, following a swap between q0 and q2. Since that swap is not in the coupling, one of the two will be required to move. Verify that the mapped measure corresponds to one of the two possible layouts following the swap. """ qr = QuantumRegister(3, "q") cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[2]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[2], cr[1]) dag_circuit = circuit_to_dag(circuit) coupling_map = CouplingMap([[0, 1], [1, 2]]) mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit) mapped_measure_qargs = {op.qargs[0] for op in mapped_dag.named_nodes("measure")} self.assertIn(mapped_measure_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}]) def test_lookahead_swap_maps_measurements_with_target(self): """Verify measurement nodes are updated to map correct cregs to re-mapped qregs. Create a circuit with measures on q0 and q2, following a swap between q0 and q2. Since that swap is not in the coupling, one of the two will be required to move. Verify that the mapped measure corresponds to one of the two possible layouts following the swap. """ qr = QuantumRegister(3, "q") cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[2]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[2], cr[1]) dag_circuit = circuit_to_dag(circuit) target = Target() target.add_instruction(CXGate(), {(0, 1): None, (1, 2): None}) mapped_dag = LookaheadSwap(target).run(dag_circuit) mapped_measure_qargs = {op.qargs[0] for op in mapped_dag.named_nodes("measure")} self.assertIn(mapped_measure_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}]) def test_lookahead_swap_maps_barriers(self): """Verify barrier nodes are updated to re-mapped qregs. Create a circuit with a barrier on q0 and q2, following a swap between q0 and q2. Since that swap is not in the coupling, one of the two will be required to move. Verify that the mapped barrier corresponds to one of the two possible layouts following the swap. """ qr = QuantumRegister(3, "q") cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[2]) circuit.barrier(qr[0], qr[2]) dag_circuit = circuit_to_dag(circuit) coupling_map = CouplingMap([[0, 1], [1, 2]]) mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit) mapped_barrier_qargs = [set(op.qargs) for op in mapped_dag.named_nodes("barrier")][0] self.assertIn(mapped_barrier_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}]) def test_lookahead_swap_higher_depth_width_is_better(self): """Test that lookahead swap finds better circuit with increasing search space. Increasing the tree width and depth is expected to yield a better (or same) quality circuit, in the form of fewer SWAPs. """ # q_0: ──■───────────────────■───────────────────────────────────────────────» # β”Œβ”€β”΄β”€β” β”‚ β”Œβ”€β”€β”€β” Β» # q_1: ─ X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€Β» # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β”‚ β””β”€β”¬β”€β”˜β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” Β» # q_2: ────── X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β– β”€β”€Β» # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β”Œβ”€β”΄β”€β” β”‚ β””β”€β”¬β”€β”˜ β”Œβ”€β”€β”€β”β””β”€β”¬β”€β”˜ β”‚ Β» # q_3: ─────────── X β”œβ”€β”€β– β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β– β”€β”€β”€ X β”œβ”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€Β» # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ β”Œβ”€β”€β”€β” β”‚ β”‚ β”‚ β””β”€β”¬β”€β”˜ β”‚ β”‚ Β» # q_4: ──────────────── X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”Όβ”€β”€β”€β”€β– β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€Β» # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β””β”€β”¬β”€β”˜ β”‚ β”‚ β”‚ β”‚ β”‚ Β» # q_5: ───────────────────── X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β– β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€Β» # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β”‚ β”‚ β”‚ β”‚ β”‚ Β» # q_6: ────────────────────────── X β”œβ”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”Όβ”€β”€Β» # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β”‚ β”Œβ”€β”΄β”€β” β”Œβ”€β”΄β”€β”Β» # q_7: ─────────────────────────────── X β”œβ”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œΒ» # β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜Β» # Β«q_0: ──■─────── # Β« β”‚ # Β«q_1: ──┼─────── # Β« β”‚ # Β«q_2: ──┼─────── # Β« β”‚ # Β«q_3: ──┼─────── # Β« β”‚ # Β«q_4: ──┼─────── # Β« β”‚ # Β«q_5: ──┼────■── # Β« β”Œβ”€β”΄β”€β” β”‚ # Β«q_6: ─ X β”œβ”€β”€β”Όβ”€β”€ # Β« β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” # Β«q_7: ────── X β”œ # Β« β””β”€β”€β”€β”˜ qr = QuantumRegister(8, name="q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[5], qr[6]) circuit.cx(qr[6], qr[7]) circuit.cx(qr[0], qr[3]) circuit.cx(qr[6], qr[4]) circuit.cx(qr[7], qr[1]) circuit.cx(qr[4], qr[2]) circuit.cx(qr[3], qr[7]) circuit.cx(qr[5], qr[3]) circuit.cx(qr[6], qr[2]) circuit.cx(qr[2], qr[7]) circuit.cx(qr[0], qr[6]) circuit.cx(qr[5], qr[7]) original_dag = circuit_to_dag(circuit) # Create a ring of 8 connected qubits coupling_map = CouplingMap.from_grid(num_rows=2, num_columns=4) mapped_dag_1 = LookaheadSwap(coupling_map, search_depth=3, search_width=3).run(original_dag) mapped_dag_2 = LookaheadSwap(coupling_map, search_depth=5, search_width=5).run(original_dag) num_swaps_1 = mapped_dag_1.count_ops().get("swap", 0) num_swaps_2 = mapped_dag_2.count_ops().get("swap", 0) self.assertLessEqual(num_swaps_2, num_swaps_1) def test_lookahead_swap_hang_in_min_case(self): """Verify LookaheadSwap does not stall in minimal case.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2171 qr = QuantumRegister(14, "q") qc = QuantumCircuit(qr) qc.cx(qr[0], qr[13]) qc.cx(qr[1], qr[13]) qc.cx(qr[1], qr[0]) qc.cx(qr[13], qr[1]) dag = circuit_to_dag(qc) cmap = CouplingMap(FakeMelbourne().configuration().coupling_map) out = LookaheadSwap(cmap, search_depth=4, search_width=4).run(dag) self.assertIsInstance(out, DAGCircuit) def test_lookahead_swap_hang_full_case(self): """Verify LookaheadSwap does not stall in reported case.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2171 qr = QuantumRegister(14, "q") qc = QuantumCircuit(qr) qc.cx(qr[0], qr[13]) qc.cx(qr[1], qr[13]) qc.cx(qr[1], qr[0]) qc.cx(qr[13], qr[1]) qc.cx(qr[6], qr[7]) qc.cx(qr[8], qr[7]) qc.cx(qr[8], qr[6]) qc.cx(qr[7], qr[8]) qc.cx(qr[0], qr[13]) qc.cx(qr[1], qr[0]) qc.cx(qr[13], qr[1]) qc.cx(qr[0], qr[1]) dag = circuit_to_dag(qc) cmap = CouplingMap(FakeMelbourne().configuration().coupling_map) out = LookaheadSwap(cmap, search_depth=4, search_width=4).run(dag) self.assertIsInstance(out, DAGCircuit) def test_global_phase_preservation(self): """Test that LookaheadSwap preserves global phase""" qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.global_phase = pi / 3 circuit.cx(qr[0], qr[2]) dag_circuit = circuit_to_dag(circuit) coupling_map = CouplingMap([[0, 1], [1, 2]]) mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit) self.assertEqual(mapped_dag.global_phase, circuit.global_phase) self.assertEqual( mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1 ) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Meta tests for mappers. The test checks the output of the swapper to a ground truth DAG (one for each test/swapper) saved in as a QASM (in `test/python/qasm/`). If they need to be regenerated, the DAG candidate is compiled and run in a simulator and the count is checked before being saved. This happens with (in the root directory): > python -m test.python.transpiler.test_mappers regenerate To make a new swapper pass throw all the common tests, create a new class inside the file `path/to/test_mappers.py` that: * the class name should start with `Tests...`. * inheriting from ``SwapperCommonTestCases, QiskitTestCase`` * overwrite the required attribute ``pass_class`` For example:: class TestsSomeSwap(SwapperCommonTestCases, QiskitTestCase): pass_class = SomeSwap # The pass class additional_args = {'seed_transpiler': 42} # In case SomeSwap.__init__ requires # additional arguments To **add a test for all the swappers**, add a new method ``test_foo``to the ``SwapperCommonTestCases`` class: * defining the following required ``self`` attributes: ``self.count``, ``self.shots``, ``self.delta``. They are required for the regeneration of the ground truth. * use the ``self.assertResult`` assertion for comparing for regeneration of the ground truth. * explicitly set a unique ``name`` of the ``QuantumCircuit``, as it it used for the name of the QASM file of the ground truth. For example:: def test_a_common_test(self): self.count = {'000': 512, '110': 512} # The expected count for this circuit self.shots = 1024 # Shots to run in the backend. self.delta = 5 # This is delta for the AlmostEqual during # the count check coupling_map = [[0, 1], [0, 2]] # The coupling map for this specific test qr = QuantumRegister(3, 'q') # cr = ClassicalRegister(3, 'c') # Set the circuit to test circuit = QuantumCircuit(qr, cr, # and don't forget to put a name name='some_name') # (it will be used to save the QASM circuit.h(qr[1]) # circuit.cx(qr[1], qr[2]) # circuit.measure(qr, cr) # result = transpile(circuit, self.create_backend(), coupling_map=coupling_map, pass_manager=self.create_passmanager(coupling_map)) self.assertResult(result, circuit) ``` """ # pylint: disable=attribute-defined-outside-init import unittest import os import sys from qiskit import execute from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, BasicAer from qiskit.transpiler import PassManager from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap, SabreSwap from qiskit.transpiler.passes import SetLayout from qiskit.transpiler import CouplingMap, Layout from qiskit.test import QiskitTestCase class CommonUtilitiesMixin: """Utilities for meta testing. Subclasses should redefine the ``pass_class`` argument, with a Swap Mapper class. Note: This class assumes that the subclass is also inheriting from ``QiskitTestCase``, and it uses ``QiskitTestCase`` methods directly. """ regenerate_expected = False seed_simulator = 42 seed_transpiler = 42 additional_args = {} pass_class = None def create_passmanager(self, coupling_map, initial_layout=None): """Returns a PassManager using self.pass_class(coupling_map, initial_layout)""" passmanager = PassManager() if initial_layout: passmanager.append(SetLayout(Layout(initial_layout))) # pylint: disable=not-callable passmanager.append(self.pass_class(CouplingMap(coupling_map), **self.additional_args)) return passmanager def create_backend(self): """Returns a Backend.""" return BasicAer.get_backend("qasm_simulator") def generate_ground_truth(self, transpiled_result, filename): """Generates the expected result into a file. Checks if transpiled_result matches self.counts by running in a backend (self.create_backend()). That's saved in a QASM in filename. Args: transpiled_result (DAGCircuit): The DAGCircuit to execute. filename (string): Where the QASM is saved. """ sim_backend = self.create_backend() job = execute( transpiled_result, sim_backend, seed_simulator=self.seed_simulator, seed_transpiler=self.seed_transpiler, shots=self.shots, ) self.assertDictAlmostEqual(self.counts, job.result().get_counts(), delta=self.delta) transpiled_result.qasm(formatted=False, filename=filename) def assertResult(self, result, circuit): """Fetches the QASM in circuit.name file and compares it with result.""" qasm_name = f"{type(self).__name__}_{circuit.name}.qasm" qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") filename = os.path.join(qasm_dir, qasm_name) if self.regenerate_expected: # Run result in backend to test that is valid. self.generate_ground_truth(result, filename) expected = QuantumCircuit.from_qasm_file(filename) self.assertEqual(result, expected) class SwapperCommonTestCases(CommonUtilitiesMixin): """Tests that are run in several mappers. The tests here will be run in several mappers. When adding a test, please ensure that the test: * defines ``self.count``, ``self.shots``, ``self.delta``. * uses the ``self.assertResult`` assertion for comparing for regeneration of the ground truth. * explicitly sets a unique ``name`` of the ``QuantumCircuit``. See also ``CommonUtilitiesMixin`` and the module docstring. """ def test_a_cx_to_map(self): """A single CX needs to be remapped. q0:----------m----- | q1:-[H]-(+)--|-m--- | | | q2:------.---|-|-m- | | | c0:----------.-|-|- c1:------------.-|- c2:--------------.- CouplingMap map: [1]<-[0]->[2] expected count: '000': 50% '110': 50% """ self.counts = {"000": 512, "110": 512} self.shots = 1024 self.delta = 5 coupling_map = [[0, 1], [0, 2]] qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr, name="a_cx_to_map") circuit.h(qr[1]) circuit.cx(qr[1], qr[2]) circuit.measure(qr, cr) result = self.create_passmanager(coupling_map).run(circuit) self.assertResult(result, circuit) def test_initial_layout(self): """Using a non-trivial initial_layout. q3:----------------m-- q0:----------m-----|-- | | q1:-[H]-(+)--|-m---|-- | | | | q2:------.---|-|-m-|-- | | | | c0:----------.-|-|-|-- c1:------------.-|-|-- c2:--------------.-|-- c3:----------------.-- CouplingMap map: [1]<-[0]->[2]->[3] expected count: '000': 50% '110': 50% """ self.counts = {"0000": 512, "0110": 512} self.shots = 1024 self.delta = 5 coupling_map = [[0, 1], [0, 2], [2, 3]] qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circuit = QuantumCircuit(qr, cr, name="initial_layout") circuit.h(qr[1]) circuit.cx(qr[1], qr[2]) circuit.measure(qr, cr) layout = {qr[3]: 0, qr[0]: 1, qr[1]: 2, qr[2]: 3} result = self.create_passmanager(coupling_map, layout).run(circuit) self.assertResult(result, circuit) def test_handle_measurement(self): """Handle measurement correctly. q0:--.-----(+)-m------- | | | q1:-(+)-(+)-|--|-m----- | | | | q2:------|--|--|-|-m--- | | | | | q3:-[H]--.--.--|-|-|-m- | | | | c0:------------.-|-|-|- c1:--------------.-|-|- c2:----------------.-|- c3:------------------.- CouplingMap map: [0]->[1]->[2]->[3] expected count: '0000': 50% '1011': 50% """ self.counts = {"1011": 512, "0000": 512} self.shots = 1024 self.delta = 5 coupling_map = [[0, 1], [1, 2], [2, 3]] qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circuit = QuantumCircuit(qr, cr, name="handle_measurement") circuit.h(qr[3]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[3], qr[1]) circuit.cx(qr[3], qr[0]) circuit.measure(qr, cr) result = self.create_passmanager(coupling_map).run(circuit) self.assertResult(result, circuit) class TestsBasicSwap(SwapperCommonTestCases, QiskitTestCase): """Test SwapperCommonTestCases using BasicSwap.""" pass_class = BasicSwap class TestsLookaheadSwap(SwapperCommonTestCases, QiskitTestCase): """Test SwapperCommonTestCases using LookaheadSwap.""" pass_class = LookaheadSwap class TestsStochasticSwap(SwapperCommonTestCases, QiskitTestCase): """Test SwapperCommonTestCases using StochasticSwap.""" pass_class = StochasticSwap additional_args = {"seed": 0} class TestsSabreSwap(SwapperCommonTestCases, QiskitTestCase): """Test SwapperCommonTestCases using SabreSwap.""" pass_class = SabreSwap additional_args = {"seed": 1242} if __name__ == "__main__": if len(sys.argv) >= 2 and sys.argv[1] == "regenerate": CommonUtilitiesMixin.regenerate_expected = True del sys.argv[1] unittest.main()