repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# -*- 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. """ The Variational Quantum Eigensolver algorithm. See https://arxiv.org/abs/1304.3061 """ import logging import functools import numpy as np from qiskit import ClassicalRegister, QuantumCircuit from qiskit.aqua.algorithms.adaptive.vq_algorithm import VQAlgorithm from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class from qiskit.aqua.utils.backend_utils import is_aer_statevector_backend from qiskit.aqua.utils import find_regs_by_name logger = logging.getLogger(__name__) class VQE(VQAlgorithm): """ The Variational Quantum Eigensolver algorithm. See https://arxiv.org/abs/1304.3061 """ CONFIGURATION = { 'name': 'VQE', 'description': 'VQE Algorithm', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'vqe_schema', 'type': 'object', 'properties': { 'operator_mode': { 'type': 'string', 'default': 'matrix', 'oneOf': [ {'enum': ['matrix', 'paulis', 'grouped_paulis']} ] }, 'initial_point': { 'type': ['array', 'null'], "items": { "type": "number" }, 'default': None }, 'max_evals_grouped': { 'type': 'integer', 'default': 1 } }, 'additionalProperties': False }, 'problems': ['energy', 'ising'], 'depends': [ {'pluggable_type': 'optimizer', 'default': { 'name': 'L_BFGS_B' } }, {'pluggable_type': 'variational_form', 'default': { 'name': 'RYRZ' } }, ], } def __init__(self, operator, var_form, optimizer, operator_mode='matrix', initial_point=None, max_evals_grouped=1, aux_operators=None, callback=None): """Constructor. Args: operator (Operator): Qubit operator operator_mode (str): operator mode, used for eval of operator var_form (VariationalForm): parametrized variational form. optimizer (Optimizer): the classical optimization algorithm. initial_point (numpy.ndarray): optimizer initial point. max_evals_grouped (int): max number of evaluations performed simultaneously aux_operators (list of Operator): Auxiliary operators to be evaluated at each eigenvalue callback (Callable): a callback that can access the intermediate data during the optimization. Internally, four arguments are provided as follows the index of evaluation, parameters of variational form, evaluated mean, evaluated standard devation. """ self.validate(locals()) super().__init__(var_form=var_form, optimizer=optimizer, cost_fn=self._energy_evaluation, initial_point=initial_point) self._optimizer.set_max_evals_grouped(max_evals_grouped) self._callback = callback if initial_point is None: self._initial_point = var_form.preferred_init_points self._operator = operator self._operator_mode = operator_mode self._eval_count = 0 if aux_operators is None: self._aux_operators = [] else: self._aux_operators = [aux_operators] if not isinstance(aux_operators, list) else aux_operators logger.info(self.print_settings()) @classmethod def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance. Args: params (dict): parameters dictionary algo_input (EnergyInput): EnergyInput instance Returns: VQE: vqe object """ if algo_input is None: raise AquaError("EnergyInput instance is required.") operator = algo_input.qubit_op vqe_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) operator_mode = vqe_params.get('operator_mode') initial_point = vqe_params.get('initial_point') max_evals_grouped = vqe_params.get('max_evals_grouped') # Set up variational form, we need to add computed num qubits # Pass all parameters so that Variational Form can create its dependents var_form_params = params.get(Pluggable.SECTION_KEY_VAR_FORM) var_form_params['num_qubits'] = operator.num_qubits var_form = get_pluggable_class(PluggableType.VARIATIONAL_FORM, var_form_params['name']).init_params(params) # Set up optimizer opt_params = params.get(Pluggable.SECTION_KEY_OPTIMIZER) optimizer = get_pluggable_class(PluggableType.OPTIMIZER, opt_params['name']).init_params(params) return cls(operator, var_form, optimizer, operator_mode=operator_mode, initial_point=initial_point, max_evals_grouped=max_evals_grouped, aux_operators=algo_input.aux_ops) @property def setting(self): """Prepare the setting of VQE as a string.""" ret = "Algorithm: {}\n".format(self._configuration['name']) params = "" for key, value in self.__dict__.items(): if key != "_configuration" and key[0] == "_": if "initial_point" in key and value is None: params += "-- {}: {}\n".format(key[1:], "Random seed") else: params += "-- {}: {}\n".format(key[1:], value) ret += "{}".format(params) return ret def print_settings(self): """ Preparing the setting of VQE into a string. Returns: str: the formatted setting of VQE """ ret = "\n" ret += "==================== Setting of {} ============================\n".format(self.configuration['name']) ret += "{}".format(self.setting) ret += "===============================================================\n" ret += "{}".format(self._var_form.setting) ret += "===============================================================\n" ret += "{}".format(self._optimizer.setting) ret += "===============================================================\n" return ret def construct_circuit(self, parameter, backend=None, use_simulator_operator_mode=False): """Generate the circuits. Args: parameters (numpy.ndarray): parameters for variational form. backend (qiskit.BaseBackend): backend object. use_simulator_operator_mode (bool): is backend from AerProvider, if True and mode is paulis, single circuit is generated. Returns: [QuantumCircuit]: the generated circuits with Hamiltonian. """ input_circuit = self._var_form.construct_circuit(parameter) if backend is None: warning_msg = "Circuits used in VQE depends on the backend type, " from qiskit import BasicAer if self._operator_mode == 'matrix': temp_backend_name = 'statevector_simulator' else: temp_backend_name = 'qasm_simulator' backend = BasicAer.get_backend(temp_backend_name) warning_msg += "since operator_mode is '{}', '{}' backend is used.".format( self._operator_mode, temp_backend_name) logger.warning(warning_msg) circuit = self._operator.construct_evaluation_circuit(self._operator_mode, input_circuit, backend, use_simulator_operator_mode) return circuit def _eval_aux_ops(self, threshold=1e-12, params=None): if params is None: params = self.optimal_params wavefn_circuit = self._var_form.construct_circuit(params) circuits = [] values = [] params = [] for operator in self._aux_operators: if not operator.is_empty(): temp_circuit = QuantumCircuit() + wavefn_circuit circuit = operator.construct_evaluation_circuit(self._operator_mode, temp_circuit, self._quantum_instance.backend, self._use_simulator_operator_mode) params.append(operator.aer_paulis) else: circuit = None circuits.append(circuit) if len(circuits) > 0: to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, [c for c in circuits if c is not None]) if self._use_simulator_operator_mode: extra_args = {'expectation': { 'params': params, 'num_qubits': self._operator.num_qubits} } else: extra_args = {} result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args) for operator, circuit in zip(self._aux_operators, circuits): if circuit is None: mean, std = 0.0, 0.0 else: mean, std = operator.evaluate_with_result(self._operator_mode, circuit, self._quantum_instance.backend, result, self._use_simulator_operator_mode) mean = mean.real if abs(mean.real) > threshold else 0.0 std = std.real if abs(std.real) > threshold else 0.0 values.append((mean, std)) if len(values) > 0: aux_op_vals = np.empty([1, len(self._aux_operators), 2]) aux_op_vals[0, :] = np.asarray(values) self._ret['aux_ops'] = aux_op_vals def _run(self): """ Run the algorithm to compute the minimum eigenvalue. Returns: Dictionary of results """ if not self._quantum_instance.is_statevector and self._operator_mode == 'matrix': logger.warning('Qasm simulation does not work on {} mode, changing ' 'the operator_mode to "paulis"'.format(self._operator_mode)) self._operator_mode = 'paulis' self._use_simulator_operator_mode = \ is_aer_statevector_backend(self._quantum_instance.backend) \ and self._operator_mode != 'matrix' self._quantum_instance.circuit_summary = True self._eval_count = 0 self._ret = self.find_minimum(initial_point=self.initial_point, var_form=self.var_form, cost_fn=self._energy_evaluation, optimizer=self.optimizer) if self._ret['num_optimizer_evals'] is not None and self._eval_count >= self._ret['num_optimizer_evals']: self._eval_count = self._ret['num_optimizer_evals'] self._eval_time = self._ret['eval_time'] logger.info('Optimization complete in {} seconds.\nFound opt_params {} in {} evals'.format( self._eval_time, self._ret['opt_params'], self._eval_count)) self._ret['eval_count'] = self._eval_count self._ret['energy'] = self.get_optimal_cost() self._ret['eigvals'] = np.asarray([self.get_optimal_cost()]) self._ret['eigvecs'] = np.asarray([self.get_optimal_vector()]) self._eval_aux_ops() return self._ret # This is the objective function to be passed to the optimizer that is uses for evaluation def _energy_evaluation(self, parameters): """ Evaluate energy at given parameters for the variational form. Args: parameters (numpy.ndarray): parameters for variational form. Returns: float or list of float: energy of the hamiltonian of each parameter. """ num_parameter_sets = len(parameters) // self._var_form.num_parameters circuits = [] parameter_sets = np.split(parameters, num_parameter_sets) mean_energy = [] std_energy = [] for idx in range(len(parameter_sets)): parameter = parameter_sets[idx] circuit = self.construct_circuit(parameter, self._quantum_instance.backend, self._use_simulator_operator_mode) circuits.append(circuit) to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, circuits) if self._use_simulator_operator_mode: extra_args = {'expectation': { 'params': [self._operator.aer_paulis], 'num_qubits': self._operator.num_qubits} } else: extra_args = {} result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args) for idx in range(len(parameter_sets)): mean, std = self._operator.evaluate_with_result( self._operator_mode, circuits[idx], self._quantum_instance.backend, result, self._use_simulator_operator_mode) mean_energy.append(np.real(mean)) std_energy.append(np.real(std)) self._eval_count += 1 if self._callback is not None: self._callback(self._eval_count, parameter_sets[idx], np.real(mean), np.real(std)) logger.info('Energy evaluation {} returned {}'.format(self._eval_count, np.real(mean))) return mean_energy if len(mean_energy) > 1 else mean_energy[0] def get_optimal_cost(self): if 'opt_params' not in self._ret: raise AquaError("Cannot return optimal cost before running the algorithm to find optimal params.") return self._ret['min_val'] def get_optimal_circuit(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal circuit before running the algorithm to find optimal params.") return self._var_form.construct_circuit(self._ret['opt_params']) def get_optimal_vector(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal vector before running the algorithm to find optimal params.") qc = self.get_optimal_circuit() if self._quantum_instance.is_statevector: ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_statevector(qc, decimals=16) else: c = ClassicalRegister(qc.width(), name='c') q = find_regs_by_name(qc, 'q') qc.add_register(c) qc.barrier(q) qc.measure(q, c) ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_counts(qc) return self._ret['min_vector'] @property def optimal_params(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal params before running the algorithm.") return self._ret['opt_params']
https://github.com/BankNatchapol/Quantum-Classical-Logic-Gate
BankNatchapol
import sys import numpy as np from matplotlib import pyplot as plt from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, visualization from random import randint def to_binary(N,n_bit): Nbin = np.zeros(n_bit, dtype=bool) for i in range(1,n_bit+1): bit_state = (N % (2**i) != 0) if bit_state: N -= 2**(i-1) Nbin[n_bit-i] = bit_state return Nbin def modular_multiplication(qc,a,N): """ applies the unitary operator that implements modular multiplication function x -> a*x(modN) Only works for the particular case x -> 7*x(mod15)! """ for i in range(0,3): qc.x(i) qc.cx(2,1) qc.cx(1,2) qc.cx(2,1) qc.cx(1,0) qc.cx(0,1) qc.cx(1,0) qc.cx(3,0) qc.cx(0,1) qc.cx(1,0) def quantum_period(a, N, n_bit): # Quantum part print(" Searching the period for N =", N, "and a =", a) qr = QuantumRegister(n_bit) cr = ClassicalRegister(n_bit) qc = QuantumCircuit(qr,cr) simulator = Aer.get_backend('qasm_simulator') s0 = randint(1, N-1) # Chooses random int sbin = to_binary(s0,n_bit) # Turns to binary print("\n Starting at \n s =", s0, "=", "{0:b}".format(s0), "(bin)") # Quantum register is initialized with s (in binary) for i in range(0,n_bit): if sbin[n_bit-i-1]: qc.x(i) s = s0 r=-1 # makes while loop run at least 2 times # Applies modular multiplication transformation until we come back to initial number s while s != s0 or r <= 0: r+=1 # sets up circuit structure qc.measure(qr, cr) modular_multiplication(qc,a,N) qc.draw('mpl') # runs circuit and processes data job = execute(qc,simulator, shots=10) result_counts = job.result().get_counts(qc) result_histogram_key = list(result_counts)[0] # https://qiskit.org/documentation/stubs/qiskit.result.Result.get_counts.html#qiskit.result.Result.get_counts s = int(result_histogram_key, 2) print(" ", result_counts) plt.show() print("\n Found period r =", r) return r if __name__ == '__main__': a = 7 N = 15 n_bit=5 r = quantum_period(a, N, n_bit)
https://github.com/bagmk/qiskit-quantum-state-classifier
bagmk
https://github.com/bagmk/qiskit-quantum-state-classifier
bagmk
import numpy as np import copy from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer, execute, transpile, assemble from qiskit.tools.visualization import * from qiskit.ignis.mitigation.measurement import (complete_meas_cal, tensored_meas_cal, CompleteMeasFitter, TensoredMeasFitter) import json from scipy.signal import savgol_filter import time from qiskit.tools.monitor import job_monitor from o_utils import ora # classifier utilities from o_plot import opl # utilities for result plot from c_utils import new_cut # circuit building utilities def json_dic_loader(dic_name): f = open(data_directory+dic_name+'.json') return json.load(f) # common code for calling the classifier for ideal device and for real devices def add_single_dic(target_data_list): start_time = time.time() print("started",time.strftime('%d/%m/%Y %H:%M:%S'),mitig_name, "mitigation",mit_str,o_metric,model_name) # added for D,S,M choice. Mainstream : mixed set of 20 states first = 0 last = nb_states if unique_char == "D": last = int(nb_states/2) elif unique_char == "S": first = int(nb_states/2) # get the classifier error curve in function of the number of shot and the "safe shot number" error_curve, safe_rate, ernb = ora.provide_error_curve(PD_model=model_dic[model_name][first:last,:], PD_test=PD_test[first:last,:], trials=trials, window=window, epsilon=epsilon, max_shots=max_shots, pol=pol, verbosality=verbosality) tail = savgol_filter(ernb, window, pol, axis=0) len_curve = len(error_curve) safe_shot_nb = len_curve - int((window-1)/2) # OK print('safe_shot_nb',safe_shot_nb, 'safe_rate',safe_rate, "nb trials:",trials) err_rates = tail[int((window-1)/2),:]/trials err_rate_max = np.max(err_rates) err_rate_min = np.min(err_rates) r=4 print("savgol interpolated error rate mean:", np.round(np.mean(err_rates),r), "min:", np.round(err_rate_min,r), "max:", np.round(err_rate_max,r), "for", [ien for ien, jen in enumerate(err_rates) if jen == err_rate_max]) end_time = time.time() #save the data in a list of dictionaries : single_dic={"project":mitig_name, "id_gates":id_gates, "mitigation":mit_str, "model":model_name, "metric":o_metric, "device":project_device, "curve_length":len_curve, "shots": safe_shot_nb, "shots_rate": safe_rate, "error_curve":error_curve, "trials":trials,"window":window, "epsilon":epsilon,"SG_pol": pol, "computation_time":end_time-start_time, "time_completed":time.strftime('%d/%m/%Y %H:%M:%S'), "trials":trials, "QV": QV_dic[project_device], "fidelity": fidelity_dic[project_device], "error_nb":ernb} target_data_list.append(single_dic) print("completed",time.strftime('%d/%m/%Y %H:%M:%S'),mitig_name, "mitigation",mit_str,o_metric,model_name,"\n") simulator = Aer.get_backend('qasm_simulator') #specify the layout of the devices used_qubits = 5 qubit_list = [0,1,2,3,4] #short_version = False #program_name="QAD" # 1st pilot project GHZ Psi+ / W Phi+ program_name="AL2" # 2d pilot project W Psi+ / Wbar Phi+ Flag_char = "DS" # this for a mix of two types of separable states if len(Flag_char) >= 2: unique_char = "M" else: unique_char = Flag_char # These dictionaries for the devices used in the study if program_name == "QAD": fidelity_dic = {'ibmq_athens': 0.925110, 'ibmq_valencia': 0.809101, 'ibmq_ourense': 0.802380, "ibmqx2": 0.627392, 'ibmq_santiago': 0.919399, 'ibmq_vigo': 0.908840, 'ideal_device': 1.0} data_directory = "data_files/" elif program_name == "AL2": fidelity_dic = {'ibmq_athens': 0.910145, 'ibmq_valencia': 0.794262, 'ibmq_ourense': 0.818974, "ibmqx2": 0.359528, 'ibmq_santiago': 0.900024, 'ibmq_vigo': 0.841831, 'ideal_device': 1.0} data_directory = "data2_files/" QV_dic = {'ibmq_athens': 32.0, 'ibmq_valencia': 16.0, 'ibmq_ourense': 8.0, "ibmqx2": 8.0, 'ibmq_santiago': 32.0, 'ibmq_vigo': 16.0, 'ideal_device': np.inf} dev_dic = {'ibmq_santiago': "San",'ibmq_athens': "Ath", 'ibmq_valencia': "Val", 'ibmq_vigo': 'Vig','ibmq_ourense': "Our", "ibmqx2": 'Yor', 'ideal_device': "Ide"} # specify the device: here first the ideal noise-free device project_device = 'ideal_device' device_name = dev_dic[project_device] # specify the nb of id gates between state creation and measurements # zero for the ideal device id_gates = 0 str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) # tail of the file names for RAM storage mitig_name = program_name + "_" + device_name project_name = mitig_name + "_" + unique_char + zfilled print(mitig_name) print(project_name) # establish the result label list # meas_calibs will be used for mitigation in the real device section qr = QuantumRegister(used_qubits) meas_calibs, label_list = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal') nb_labels=len(label_list) print(nb_labels,label_list) len(meas_calibs) # permutation list # here it is simple to write down the list, # but a version using itertools will be wellcome for >5 qubits projects if used_qubits == 5: q_perm = [[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [0, 1, 4, 2, 3], [0, 2, 3, 1, 4], [0, 2, 4, 1, 3], [0, 3, 4, 1, 2], [1, 2, 3, 0, 4], [1, 2, 4, 0, 3], [1, 3, 4, 0, 2], [2, 3, 4, 0, 1]] else: print("work in progress - meanwhile please provide the list of permutations") # define the two subsets of 10 separable states if program_name == "QAD": state_1a = ["W","Phi+"] state_1b = ["GHZ","Psi+"] elif program_name == "ALT" or "AL2": state_1a = ["W","Psi+"] state_1b = ["Wbar","Phi+"] l_states = state_1a+state_1b l_states # version 20 circuits for demonstration # (in the version run on real devices: two batches of 10 circuits, "shallow" and "deep") # these circuits limited to state creation are ready to be saved # for ultimately building circuits adapted to noisy simulator and real devices # as option, these circuits will include a row of id gates between creation and measurements circ_ori = [] for i_s in range(0,len(l_states),2): for perm in q_perm: mycircuit = QuantumCircuit(used_qubits, used_qubits) mycircuit = new_cut.circuit_builder(mycircuit, perm, l_states[i_s],l_states[i_s+1]) circ_ori.append(mycircuit) # add measurement section to the circuit set newly created: nb_states = len(circ_ori) circ_ideal = copy.deepcopy(circ_ori) for i_state in range(nb_states): new_cut.add_barrier_and_measure(circ_ideal[i_state],qubit_list) ideal_dic = {} # execute on noise free simulator s_sim = 12000 job_simul = execute(circ_ideal, backend=simulator, shots=s_sim) tot_results_simul = job_simul.result() # establish a dictionary of count results on noise free simulator: # (this step is only useful if ram storage is performed) void_counts = dict(zip(label_list, np.zeros(2**used_qubits))) tot_results_sim_dic = {} for i_state in range(nb_states): counts_simul = copy.deepcopy(void_counts) counts_simul.update(tot_results_simul.get_counts(i_state)) ideal_dic[str(i_state)]=counts_simul i_state_test = 10 print(device_name, "circuit #",i_state_test) circ_ideal[i_state_test].draw(output='mpl') print(device_name, "circuit #",i_state_test) plot_histogram(ideal_dic[str(i_state_test)], legend=['noise free simulation'], color = "b", figsize=(10.,5.)) i_state_test = 10 print(device_name, "circuit #",i_state_test) circ_ideal[i_state_test].draw(output='mpl') print(device_name, "circuit #",i_state_test) plot_histogram(ideal_dic[str(i_state_test)], legend=['noise free simulation'], color = "b", figsize=(10.,5.)) # try loading the dictionary of results if its creation was skipped if len(ideal_dic) == 0: ideal_dic = json_dic_loader("ideal_dic_"+project_name) nb_states = len(ideal_dic) nb_labels = len(list(ideal_dic.values())[0]) s_sim = sum(list(ideal_dic.values())[0].values()) PD_ideal = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): PD_ideal[i_state, :] = list(ideal_dic[str(i_state)].values()) # now a little trick to get the ideal values from the simulator approximated values with np.errstate(divide='ignore'): # ignore the divide by zero warning PD_ideal = 1/np.round(s_sim/(PD_ideal)) # have a look at the matrix head and tail: print("first and last state probability distributions:") print(np.round(np.vstack((PD_ideal[0:1,:],PD_ideal[-1:,:])),4)) # here will be appended the data we want for the curve plot ideal_data_list=[] # you may want to skip this cell as it will require a long time # because of the high number of trials required by the Monte Carlo simulation for each nb o shots value # the following values are defined in the study summary (readme file): trials=100 # to be set to 10000 if not demo window=5 # shorter window than for the real device counts epsilon = .001 min_shots = 5 max_shots = 100 pol=2 subset = None # variable not used here verbosality = 5 # printing step for intermediate results when increasing the experiment shot number PD_test = PD_ideal mitigation_dic = {"Na": None} o_metrics_desired = ['jensenshannon', 'sqeuclidean'] model_dic = {"ideal_sim": PD_ideal} for mit_str, mitigation in mitigation_dic.items(): if mitigation != None: # thus only for counts on real device PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) for o_metric in o_metrics_desired: for model_name in model_dic.keys(): add_single_dic(ideal_data_list) # get the stored results of the Monte Carlo simulation in case you skipped the previous step if len(ideal_data_list) == 0: ideal_data_list = json_dic_loader("ideal_device_data_list_"+project_name) # have a look at the mean error rate curves and error rate at save shot number n_s # NB the r_hat_mean curves and legend reported r_hat_max errors the unsmoothed values opl.plot_curves(ideal_data_list,np.array([0,1]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$" , ["model"], ["device","metric"], right_xlimit = 20, bottom_ylimit = -0.001, top_ylimit = 0.05) from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() project_device = 'ibmq_valencia'# you may choice here a different backend device_name = dev_dic[project_device] mitig_name = program_name + "_" + device_name print(mitig_name) #determine here the backend device = provider.get_backend(project_device) # the backend names are listed here above properties = device.properties() coupling_map = device.configuration().coupling_map # retrieve the corresponding measurement mitigation filter obtained at experimental time # use a fake job because use of the from_dict method simulator = Aer.get_backend('qasm_simulator') fake_job_cal = execute(meas_calibs, backend=simulator, shots=1) fake_cal_results = fake_job_cal.result() cal_results_dic = json_dic_loader("cal_results_dic_"+mitig_name) if 'date' in cal_results_dic.keys(): str(cal_results_dic['date']) cal_results = fake_cal_results.from_dict(cal_results_dic) meas_fitter = CompleteMeasFitter(cal_results, label_list, qubit_list=qubit_list, circlabel='mcal') meas_filter = meas_fitter.filter # have a look at the average measurement fidefily of this device: print("Average Measurement Fidelity was: %f" % meas_fitter.readout_fidelity(), "for",project_device) id_gates = 0 str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) project_name = mitig_name + "_" + unique_char + zfilled print(project_name) # transpile verbose = True summary_dic = {} seed_transpiler_list = list(range(nb_states)) real_circs = [] start_time = time.strftime('%d/%m/%Y %H:%M:%S') print("Start at DMY: ",start_time) for i_state in list(range(nb_states)): # prepare circuit to be transpiled circuit = copy.deepcopy(circ_ori[i_state]) if id_gates > 0: circuit.barrier() for id_gates_index in range(id_gates): for index, value in enumerate(qubit_list): circuit.id(value) new_cut.add_barrier_and_measure(circuit, qubit_list) summary = [] depth_list = [] Q_state_opt_new = transpile(circuit, backend=device, coupling_map = coupling_map, seed_transpiler=seed_transpiler_list[i_state], optimization_level=2, initial_layout=qubit_list) summary_dic[i_state] = {"depth": Q_state_opt_new.depth(), 'circuit':Q_state_opt_new} real_circs.append(Q_state_opt_new) if verbose: print("circuit %2i" % i_state,"length",summary_dic[i_state]["depth"], "DMY: ",time.strftime('%d/%m/%Y %H:%M:%S')) end_time = time.strftime('%d/%m/%Y %H:%M:%S') print("Completed at DMY: ",end_time) i_state_test = 10 print(project_device, "circuit #",i_state_test, "circuit length:",real_circs[i_state_test].depth()) #summary_dic[i_state_test]['depth']) # you may want to skip this if large nb of id gates before measurement real_circs[i_state_test].draw(output='mpl') #check a circuit on noise-free simulator job_simul = execute(real_circs[i_state_test], backend=simulator, shots=s_sim) print(project_device, "circuit #",i_state_test, "on noise free simulator") plot_histogram(job_simul.result().get_counts(), legend=['noise free simulation'], color = "b", figsize=(10.,5.)) #changing keys of dictionary for merging: def key_change(ini_dict, i_subset): ini_list = [] len_ini = len(ini_dict) for i in range(len_ini): ini_list.append(str(i+i_subset*len_ini)) return dict(zip(ini_list, list(ini_dict.values()))) if program_name == "QAD": #retrieve the data corresponding to the 1st project lfc = list(Flag_char) circ_ideal =[] empirical_dic = {} for i_subset, subset in enumerate(lfc): qasm_circs_dic = json_dic_loader('qasm_circs_dic_QAD_'+device_name+'_'+ subset + zfilled) j=0 # j included for project with several transpilation sessions for each device - not used here qasm_circs = qasm_circs_dic[str(j)] nb_circs = len(qasm_circs) for i_circs in range(nb_circs): circ_ideal.append(QuantumCircuit().from_qasm_str(qasm_circs[i_circs])) empirical_dic = {**empirical_dic, **key_change(json_dic_loader("experimental"+"_"+mitig_name +"_"\ +subset+zfilled), i_subset)} test_dic = copy.deepcopy(empirical_dic) #nb_states = len(circ_ideal) if program_name == "AL2": empirical_dic = json_dic_loader('experimental_'+project_name) test_dic = json_dic_loader('test_'+project_name) def rectify_counts(tot_res, test_cqi,mitigation,m_filter) : void_counts = dict(zip(label_list, np.zeros(2**used_qubits))) try: counts_results_real_test = tot_res[str(test_cqi)] except KeyError as error: counts_results_real_test = tot_res[test_cqi] raw_counts_test = copy.deepcopy(void_counts) raw_counts_test.update(counts_results_real_test) if mitigation: mitigated_results_test = meas_filter.apply(raw_counts_test, method = 'least_squares') returned_counts = copy.deepcopy(void_counts) returned_counts.update(mitigated_results_test) else: returned_counts = copy.deepcopy(raw_counts_test) return returned_counts def get_clean_matrix(dic, mitigation,m_filter): clean_matrix = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): rectified_counts = rectify_counts(dic,i_state, mitigation,m_filter) # get a rectified counts dictionary clean_matrix[i_state, :] = list(rectified_counts.values()) clean_matrix = clean_matrix/clean_matrix.sum(axis=1, keepdims=True) return clean_matrix # We need to create a first matrix version. It will then vary for each considered set of distribution mitigation = False PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) print("first and last state probability distributions:") print(np.round(np.vstack((PD_exper[0:1,:],PD_exper[-1:,:])),3)) if program_name == "QAD": PD_test = copy.deepcopy(PD_exper) elif program_name == "AL2": mitigation = False PD_test = get_clean_matrix(test_dic, mitigation=mitigation, m_filter=meas_filter) print("first and last state probability distributions:") print(np.round(np.vstack((PD_test[0:1,:],PD_test[-1:,:])),3)) # here will be appended the data we want for the final plot of this notebook empirical_data_list=[] # you may want to skip this cell as it will require a long time # because of the high number of trials required by the Monte Carlo simulation for each nb o shots value # the following values are defined in the study summary notebook: trials=100 # should be 1000 if not demo window=11 epsilon = .001 max_shots = 500 pol=2 verbosality = 10 # printing step for intermediate results when increasing the experiment shot number # In this section you can easily make your choice of combinations: # mitigation or not, metric, model mitigation_dic = {"no":False, "yes" : True} #mitigation_dic = {"no":False} #mitigation_dic = {"yes" : True} o_metrics_desired = ['jensenshannon', 'sqeuclidean'] #o_metrics_desired = ['jensenshannon'] #o_metrics_desired = ['sqeuclidean'] model_dic = {"empirical": PD_exper, "ideal_sim": PD_ideal} #model_dic = {"empirical": PD_exper} #model_dic = {"ideal_sim": PD_ideal} # Obtain a sequence of results in form of a list of dictionaries for mit_str, mitigation in mitigation_dic.items(): # here we toggle PD_exper as we toggled mitigation status PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) PD_test = get_clean_matrix(test_dic, mitigation=mitigation, m_filter=meas_filter) for o_metric in o_metrics_desired: print(project_name, model_dic.keys(), o_metric) for model_name in model_dic.keys(): add_single_dic(empirical_data_list) # get the stored results of the Monte Carlo simulation in case you skipped the previous step if len(empirical_data_list) == 0: empirical_data_list = json_dic_loader('Nemp_data_list_'+project_name) # have a look at the mean error rate curves and error rate at save shot number n_s # NB the r_hat_mean curves and legend reported r_hat_max errors are the unsmoothed values opl.plot_curves(ideal_data_list + empirical_data_list, np.array(range(2+len(empirical_data_list))), "$\epsilon=0.001$" , ["device"], ["model","metric","mitigation","id_gates"], right_xlimit = 80, bottom_ylimit = -0.02, top_ylimit = 1) import winsound duration = 2000 # milliseconds freq = 800 # Hz winsound.Beep(freq, duration) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/bagmk/qiskit-quantum-state-classifier
bagmk
import numpy as np import copy from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer, execute, transpile, assemble from qiskit.tools.visualization import * from qiskit.ignis.mitigation.measurement import (complete_meas_cal, tensored_meas_cal, CompleteMeasFitter, TensoredMeasFitter) import json from scipy.signal import savgol_filter import time from o_utils import ora # classifier utilities from o_plot import opl # utilities for result plot from c_utils import cut # circuit building utilities data_directory = "data_files/" def json_dic_loader(dic_name): f = open(data_directory+dic_name+'.json') return json.load(f) simulator = Aer.get_backend('qasm_simulator') #specify the layout of the devices used_qubits = 5 qubit_list = [0,1,2,3,4] program_name="QAD" # in hommage of the Qiskit advocates Flag_char = "DS" # this for a mix of GHZ Psi+ and W Phi+ separable states if len(Flag_char) >= 2: unique_char = "M" else: unique_char = Flag_char # These dictionaries for the devices used in the study fidelity_dic = {'ibmq_athens': 0.925110, 'ibmq_valencia': 0.809101, 'ibmq_ourense': 0.802380, "ibmqx2": 0.627392, 'ibmq_santiago': 0.919399, 'ibmq_vigo': 0.908840, 'ideal_device': 1.0} QV_dic = {'ibmq_athens': 32.0, 'ibmq_valencia': 16.0, 'ibmq_ourense': 8.0, "ibmqx2": 8.0, 'ibmq_santiago': 32.0, 'ibmq_vigo': 16.0, 'ideal_device': np.inf} dev_dic = {'ibmq_santiago': "San",'ibmq_athens': "Ath", 'ibmq_valencia': "Val", 'ibmq_vigo': 'Vig','ibmq_ourense': "Our", "ibmqx2": 'Yor', 'ideal_device': "Ide"} # specify the device: here first the ideal noise-free device project_device = 'ideal_device' device_name = dev_dic[project_device] # specify the nb of id gates between state creation and measurements # zero for the ideal device of course id_gates = 0 str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) # tail of the file names for RAM storage mitig_name = program_name + "_" + device_name project_name = mitig_name + "_" + unique_char + zfilled print(mitig_name) print(project_name) # establish the result label list # meas_calibs will be used for mitigation in the real device section qr = QuantumRegister(used_qubits) # meas_calibs, label_list = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal') nb_labels=len(label_list) print(nb_labels,label_list) len(meas_calibs) # permutation list # here it is simple to write down the list, # but a version using itertools will be wellcome for >5 qubits projects q_perm = [[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [0, 1, 4, 2, 3], [0, 2, 3, 1, 4], [0, 2, 4, 1, 3], [0, 3, 4, 1, 2], [1, 2, 3, 0, 4], [1, 2, 4, 0, 3], [1, 3, 4, 0, 2], [2, 3, 4, 0, 1]] # version 20 circuits for demonstration # (in the version run on real devices: two batches of 10 circuits, "shallow" and "deep") # these circuits limited to state creation are ready to be saved # for ultimately building circuits adapted to noisy simulator and real devices # as option, these circuits will include a row of id gates between creation and measurements circ_ori = [] for state_1 in ("W", "GHZ"): if state_1 == "GHZ": state_2 = "Psi+" if state_1 == "W": state_2 = "Phi+" for perm in q_perm: mycircuit = QuantumCircuit(used_qubits, used_qubits) mycircuit = cut.circuit_builder(mycircuit, perm, state_1,state_2) circ_ori.append(mycircuit) # add measurement section to the circuit set newly created: nb_states = len(circ_ori) circ_ideal = copy.deepcopy(circ_ori) for i_state in range(nb_states): cut.add_barrier_and_measure(circ_ideal[i_state],qubit_list) # execute on noise free simulator s_sim = 12000 job_simul = execute(circ_ideal, backend=simulator, shots=s_sim) tot_results_simul = job_simul.result() # establish a dictionary of count results on noise free simulator: # (this step is only useful if ram storage is performed) void_counts = dict(zip(label_list, np.zeros(2**used_qubits, dtype=int))) tot_results_sim_dic = {} ideal_dic = {} for i_state in range(nb_states): counts_simul = copy.deepcopy(void_counts) counts_simul.update(tot_results_simul.get_counts(i_state)) ideal_dic[str(i_state)]=counts_simul i_state_test = 5 print(device_name, "circuit #",i_state_test) circ_ideal[i_state_test].draw(output='mpl') print(device_name, "circuit #",i_state_test) plot_histogram(ideal_dic[str(i_state_test)], legend=['noise free simulation'], color = "b", figsize=(10.,5.)) i_state_test = 19 print(device_name, "circuit #",i_state_test) circ_ideal[i_state_test].draw(output='mpl') print(device_name, "circuit #",i_state_test) plot_histogram(ideal_dic[str(i_state_test)], legend=['noise free simulation'], color = "b", figsize=(10.,5.)) PD_ideal = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): PD_ideal[i_state, :] = list(ideal_dic[str(i_state)].values()) # now a little trick to get the ideal values from the simulator approximated values with np.errstate(divide='ignore'): # ignore the divide by zero warning PD_ideal = 1/np.round(s_sim/(PD_ideal)) # have a look at the matrix head and tail: print("first and last state probability distributions:") print(np.round(np.vstack((PD_ideal[0:1,:],PD_ideal[-1:,:])),4)) # common code for the different options def add_single_dic(target_data_list): start_time = time.time() print("started",time.strftime('%d/%m/%Y %H:%M:%S'),mitig_name, "mitigation",mit_str,o_metric,model_name) # added for D,S,M choice. Mainstream : mixed set of 20 states first = 0 last = nb_states if unique_char == "D": last = int(nb_states/2) elif unique_char == "S": first = int(nb_states/2) # get the classifier error curve in function of the number of shot and the "safe shot number" error_curve, safe_rate, ernb = ora.provide_error_curve(PD_model=model_dic[model_name][first:last,:], PD_test=PD_test[first:last,:], trials=trials, window=window, epsilon=epsilon, max_shots=max_shots, pol=pol, verbosality=verbosality) tail = savgol_filter(ernb, window, pol, axis=0) len_curve = len(error_curve) safe_shot_nb = len_curve - int((window-1)/2) # OK print('safe_shot_nb',safe_shot_nb, 'safe_rate',safe_rate, "nb trials:",trials) err_rates = tail[int((window-1)/2),:]/trials err_rate_max = np.max(err_rates) err_rate_min = np.min(err_rates) r=4 print("savgol interpolated error rate mean:", np.round(np.mean(err_rates),r), "min:", np.round(err_rate_min,r), "max:", np.round(err_rate_max,r), "for", [ien for ien, jen in enumerate(err_rates) if jen == err_rate_max]) end_time = time.time() #save the data in a list of dictionaries : single_dic={"project":mitig_name, "id_gates":id_gates, "mitigation":mit_str, "model":model_name, "metric":o_metric, "device":project_device, "curve_length":len_curve, "shots": safe_shot_nb, "shots_rate": safe_rate, "error_curve":error_curve, "trials":trials,"window":window, "epsilon":epsilon,"SG_pol": pol, "computation_time":end_time-start_time, "time_completed":time.strftime('%d/%m/%Y %H:%M:%S'), "trials":trials, "QV": QV_dic[project_device], "fidelity": fidelity_dic[project_device], "error_nb":ernb} target_data_list.append(single_dic) print("completed",time.strftime('%d/%m/%Y %H:%M:%S'),mitig_name, "mitigation",mit_str,o_metric,model_name,"\n") # here will be appended the data we want for the curve plot ideal_data_list=[] # you may want to skip this cell as it will require a long time # because of the high number of trials required by the Monte Carlo simulation for each nb o shots value # the following values are defined in the study summary (readme file): trials=10000 window=5 # shorter window than for the real device counts epsilon = .001 min_shots = 5 max_shots = 100 pol=2 subset = None # variable not used here verbosality = 5 # printing step for intermediate results when increasing the experiment shot number PD_test = PD_ideal mitigation_dic = {"Na": None} o_metrics_desired = ['jensenshannon', 'sqeuclidean'] model_dic = {"ideal_sim": PD_ideal} for mit_str, mitigation in mitigation_dic.items(): if mitigation != None: # thus only for counts on real device PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) for o_metric in o_metrics_desired: for model_name in model_dic.keys(): add_single_dic(ideal_data_list) # get the stored results of the Monte Carlo simulation in case you skipped the previous step if len(ideal_data_list) == 0: ideal_data_list = json_dic_loader("ideal_device_data_list_"+project_name) # have a look at the mean error rate curves and error rate at save shot number n_s # NB the r_hat_mean curves and legend reported r_hat_max errors the unsmoothed values opl.plot_curves(ideal_data_list,np.array([0,1]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$" , ["model"], ["device","metric"], right_xlimit = 15, bottom_ylimit = -0.01, top_ylimit = 0.3) from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') print(provider.backends()) project_device = 'ibmq_vigo'# you may choice here a different backend device_name = dev_dic[project_device] id_gates = 0 str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) mitig_name = program_name + "_" + device_name project_name = mitig_name + "_" + unique_char + zfilled print(mitig_name) print(project_name) # determine here the backend device = provider.get_backend(project_device) # the backend names are listed here above properties = device.properties() coupling_map = device.configuration().coupling_map # transpile verbose = True summary_dic = {} seed_transpiler_list = list(range(nb_states)) start_time = time.strftime('%d/%m/%Y %H:%M:%S') print("Start at DMY: ",start_time) for i_state in list(range(nb_states)): # prepare circuit to be transpiled circuit = copy.deepcopy(circ_ori[i_state]) if id_gates > 0: circuit.barrier() for id_gates_index in range(id_gates): for index, value in enumerate(qubit_list): circuit.id(value) cut.add_barrier_and_measure(circuit, qubit_list) summary = [] depth_list = [] Q_state_opt_new = transpile(circuit, backend=device, coupling_map = coupling_map, seed_transpiler=seed_transpiler_list[i_state], optimization_level=2, initial_layout=qubit_list) summary_dic[i_state] = {"depth": Q_state_opt_new.depth(), 'circuit':Q_state_opt_new} if verbose: print("circuit %2i" % i_state,"length",summary_dic[i_state]["depth"], "DMY: ",time.strftime('%d/%m/%Y %H:%M:%S')) end_time = time.strftime('%d/%m/%Y %H:%M:%S') print("Completed at DMY: ",end_time) i_state_test = 0 print(project_device, "circuit #",i_state_test, "circuit length:", summary_dic[i_state_test]['depth']) # you may want to skip this if large nb of id gates before measurement summary_dic[i_state_test]['circuit'].draw(output='mpl') job_simul = execute(summary_dic[i_state_test]['circuit'], backend=simulator, shots=s_sim) print(project_device, "circuit #",i_state_test, "on noise free simulator") plot_histogram(job_simul.result().get_counts(), legend=['noise free simulation'], color = "b", figsize=(10.,5.)) data_directory = "data_files/" def json_dic_loader(dic_name): f = open(data_directory+dic_name+'.json') return json.load(f) # changing keys of dictionary for merging: def key_change(ini_dict, i_subset): ini_list = [] len_ini = len(ini_dict) for i in range(len_ini): ini_list.append(str(i+i_subset*len_ini)) return dict(zip(ini_list, list(ini_dict.values()))) # retrieve the data corresponding to this project lfc = list(Flag_char) circ_ideal =[] empirical_dic = {} for i_subset, subset in enumerate(lfc): qasm_circs_dic = json_dic_loader('qasm_circs_dic_QAD_'+device_name+'_'+ subset + zfilled) j=0 # j included for project with several transpilation sessions for each device - not used here qasm_circs = qasm_circs_dic[str(j)] nb_circs = len(qasm_circs) for i_circs in range(nb_circs): circ_ideal.append(QuantumCircuit().from_qasm_str(qasm_circs[i_circs])) empirical_dic = {**empirical_dic, **key_change(json_dic_loader("experimental"+"_"+mitig_name +"_"\ +subset+zfilled), i_subset)} nb_states = len(circ_ideal) # retrieve the corresponding measurement mitigation filter obtained at experimental time # use a fake job because the caL_results were stored as dictionary simulator = Aer.get_backend('qasm_simulator') fake_job_cal = execute(meas_calibs, backend=simulator, shots=1) fake_cal_results = fake_job_cal.result() cal_results_dic = json_dic_loader("cal_results_dic_"+mitig_name) cal_results = fake_cal_results.from_dict(cal_results_dic) meas_fitter = CompleteMeasFitter(cal_results, label_list, qubit_list=qubit_list, circlabel='mcal') meas_filter = meas_fitter.filter # have a look at the average measurement fidefily of this device: print("Average Measurement Fidelity was: %f" % meas_fitter.readout_fidelity(), "for",project_device) def rectify_counts(tot_res, test_cqi,mitigation,m_filter) : # IMPORTANT MODIFICATION try: counts_results_real_test = tot_res[str(test_cqi)] except KeyError as error: counts_results_real_test = tot_res[test_cqi] raw_counts_test = copy.deepcopy(void_counts) raw_counts_test.update(counts_results_real_test) if mitigation: mitigated_results_test = meas_filter.apply(raw_counts_test, method = 'least_squares') returned_counts = copy.deepcopy(void_counts) returned_counts.update(mitigated_results_test) else: returned_counts = copy.deepcopy(raw_counts_test) return returned_counts def get_clean_matrix(dic, mitigation,m_filter): clean_matrix = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): rectified_counts = rectify_counts(dic,i_state, mitigation,m_filter) # get a rectified counts dictionary clean_matrix[i_state, :] = list(rectified_counts.values()) clean_matrix = clean_matrix/clean_matrix.sum(axis=1, keepdims=True) return clean_matrix # We need to create a first matrix version. It will then vary for each considered set of distribution mitigation = True PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) print("first and last state probability distributions:") print(np.round(np.vstack((PD_exper[0:1,:],PD_exper[-1:,:])),4)) # here will be appended the data we want for the final plot of this notebook empirical_data_list=[] # you may want to skip this cell as it will require a long time # because of the high number of trials required by the Monte Carlo simulation for each nb o shots value # the following values are defined in the study summary notebook: trials=1000 window=11 epsilon = .001 max_shots = 500 pol=2 verbosality = 10 # printing step for intermediate results when increasing the experiment shot number mitigation_dic = {"no": False,"yes" : True} o_metrics_desired = ['jensenshannon', 'sqeuclidean'] model_dic = {"empirical": PD_exper, "ideal_sim": PD_ideal} for mit_str, mitigation in mitigation_dic.items(): # here we toggle PD_exper as we toggled mitigation status PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) PD_test = PD_exper for o_metric in o_metrics_desired: print(project_name, model_dic.keys(), o_metric) for model_name in model_dic.keys(): add_single_dic(empirical_data_list) # get the stored results of the Monte Carlo simulation in case you skipped the previous step if len(empirical_data_list) == 0: empirical_data_list = json_dic_loader('nemp_data_list_'+project_name) 'nemp_data_list_'+project_name # have a look at the mean error rate curves and error rate at save shot number n_s # NB the r_hat_mean curves and legend reported r_hat_max errors are the unsmoothed values opl.plot_curves(ideal_data_list + empirical_data_list, np.array(range(2+len(empirical_data_list))), "$\epsilon=0.001$" , ["device"], ["model","metric","mitigation","id_gates"], right_xlimit = 30, bottom_ylimit = -0.02, top_ylimit = 0.3) import winsound duration = 2000 # milliseconds freq = 800 # Hz winsound.Beep(freq, duration) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/bagmk/qiskit-quantum-state-classifier
bagmk
import numpy as np import pandas as pd import json as json from scipy import stats from statsmodels.formula.api import ols import matplotlib.pyplot as plt from scipy.signal import savgol_filter from o_plot import opl # a small local package dedicated to this project # Prepare the data # loading the data file_name = 'TE4AL2_data_new.json' f = open(file_name) All_data = json.load(f) print(len(All_data)) # Calculate shot number 'm_shots' for mean error rate 'm_shot_rates' <= epsilon_t len_data = len(All_data) epsilon_t = 0.0005 window = 11 for i in range(len_data): curve = np.array(All_data[i]['error_curve']) # filter the curve only for real devices: if All_data[i]['device']!="ideal_device": curve = savgol_filter(curve,window,2) # find the safe shot number: len_c = len(curve) n_a = np.argmin(np.flip(curve)<=epsilon_t)+1 if n_a == 1: n_a = np.nan m_r = np.nan else: m_r = curve[len_c-n_a+1] All_data[i]['min_r_shots'] = len_c-n_a All_data[i]['min_r'] = m_r # find mean error rate at n_s for i in range(len_data): i_shot = All_data[i]["shots"] if not np.isnan(i_shot): j = int(i_shot)-1 All_data[i]['mns_rate'] = All_data[i]['error_curve'][j] else: All_data[i]['mns_rate'] = np.nan #defining the pandas data frame for statistics df_All= pd.DataFrame(All_data,columns=['shot_rates','shots', 'device', 'fidelity', 'mitigation','model','id_gates', 'QV', 'metric','error_curve', 'mns_rate','min_r_shots','min_r']) # any shot number >= 488 indicates that the curve calculation # was ended after reaching n = 500, hence this data correction: df_All.loc[df_All.shots>=488,"shots"]=np.nan # add the variable neperian log of safe shot number: df_All['log_shots'] = np.log(df_All['shots']) df_All['log_min_r_shots'] = np.log(df_All['min_r_shots']) print("max mean error rate at n_s over all experiments =", round(max(df_All.mns_rate[:-2]),6), "vs epsilon_a =", epsilon_t) df_All.mns_rate[:-2].plot.hist(alpha=0.5, legend = True) df_All.min_r[:-2].plot.hist(alpha=0.5, legend = True) stat_model = ols("log_shots ~ metric + mitigation + model + fidelity + QV + id_gates", df_All.query("device != 'ideal_device' ")).fit() print(stat_model.summary()) stat_model = ols("log_min_r_shots ~ metric + mitigation + model + fidelity + QV + id_gates", df_All.query("device != 'ideal_device' ")).fit() print(stat_model.summary()) # this for Jensen-Shannon metric s_metric = 'jensenshannon' sm = np.array([96]) SAD=0 # ! will be unselected by running the next cell # mainstream option for metric: squared euclidean distance # skip this cell if you don't want this option s_metric = 'sqeuclidean' sm = np.array([97]) SAD=2 # this for no mitigation mit = 'no' MIT=-4 # ! will be unselected by running the next cell # mainstream option: this for measurement mitigation # skip this cell if you don't want this option mit = 'yes' MIT=0 # select data according to the options df_mod = df_All[df_All.mitigation == mit][df_All.metric == s_metric] print("mitigation:",mit," metric:",s_metric ) df_mod.groupby('device')[['shots','min_r_shots']].describe(percentiles=[0.5]) ADD=0+SAD+MIT opl.plot_curves(All_data, np.append(sm,ADD+np.array([4,5,12,13,20,21,28,29,36,37,44,45])), "No noise simulator vs empirical model - $\epsilon=0.001$ - no delay", ["metric","mitigation"], ["device","model"], right_xlimit = 60) for depvar in ['log_shots', 'log_min_r_shots']: print("mitigation:",mit," metric:",s_metric, "variable:", depvar) df_dep = df_mod.query("id_gates == 0.0").groupby(['model'])[depvar] print(df_dep.describe(percentiles=[0.5]),"\n") # no error rate curve obtained for ibmqx2 with the ideal model, hence this exclusion: df_emp=df_mod.query("model == 'empirical' & device != 'ibmqx2' & id_gates == 0.0 ") df_ide=df_mod.query("model == 'ideal_sim' & device != 'ibmqx2' & id_gates == 0.0") #.reindex_like(df_emp,'nearest') # back to numpy arrays from pandas: print("paired data") print(np.asarray(df_emp[depvar])) print(np.asarray(df_ide[depvar]),"\n") print(stats.ttest_rel(np.asarray(df_emp[depvar]),np.asarray(df_ide[depvar]))) print(stats.wilcoxon(np.asarray(df_emp[depvar]),np.asarray(df_ide[depvar])),"\n") ADD=48+SAD+MIT opl.plot_curves(All_data, np.append(sm,ADD+np.array([4,5,12,13,20,21,28,29,36,37,44,45])), "No noise simulator vs empirical model - $\epsilon=0.001$ - with delay", ["metric","mitigation"], ["device","model"], right_xlimit = 70) for depvar in ['log_shots', 'log_min_r_shots']: print("mitigation:",mit," metric:",s_metric, "variable:", depvar) df_dep = df_mod.query("id_gates == 256.0").groupby(['model'])[depvar] print(df_dep.describe(percentiles=[0.5]),"\n") # no error rate curve obtained for ibmqx2 with the ideal model, hence this exclusion: df_emp=df_mod.query("model == 'empirical' & device != 'ibmqx2' & id_gates == 256.0 ") df_ide=df_mod.query("model == 'ideal_sim' & device != 'ibmqx2' & id_gates == 256.0") #.reindex_like(df_emp,'nearest') # back to numpy arrays from pandas: print("paired data") print(np.asarray(df_emp[depvar])) print(np.asarray(df_ide[depvar]),"\n") print(stats.ttest_rel(np.asarray(df_emp[depvar]),np.asarray(df_ide[depvar]))) print(stats.wilcoxon(np.asarray(df_emp[depvar]),np.asarray(df_ide[depvar])),"\n") for depvar in ['log_shots', 'log_min_r_shots']: print("mitigation:",mit," metric:",s_metric, "variable:", depvar) df_dep = df_mod.groupby(['model'])[depvar] print(df_dep.describe(percentiles=[0.5]),"\n") # no error rate curve obtained for ibmqx2 with the ideal model, hence this exclusion: df_emp=df_mod.query("model == 'empirical' & device != 'ibmqx2' ") df_ide=df_mod.query("model == 'ideal_sim' & device != 'ibmqx2' ") #.reindex_like(df_emp,'nearest') # back to numpy arrays from pandas: print("paired data") print(np.asarray(df_emp[depvar])) print(np.asarray(df_ide[depvar]),"\n") print(stats.ttest_rel(np.asarray(df_emp[depvar]),np.asarray(df_ide[depvar]))) print(stats.wilcoxon(np.asarray(df_emp[depvar]),np.asarray(df_ide[depvar])),"\n") print("mitigation:",mit," metric:",s_metric ) stat_model = ols("log_shots ~ model + fidelity + model*fidelity", df_mod).fit() print(stat_model.summary()) print("mitigation:",mit," metric:",s_metric ) stat_model = ols("log_min_r_shots ~ model + fidelity + model*fidelity", df_mod).fit() print(stat_model.summary()) # restore mainstream option: mitigation mit = 'yes' MIT=0 ADD=0+SAD+MIT opl.plot_curves(All_data, np.append(sm,ADD+np.array([4,12,20,28,36,44])), "Empirical model - $\epsilon=0.001$ - no delay", ["metric","mitigation"], ["device","model"], right_xlimit = 210, top_ylimit = 0.5) # rem: in this figure, the ideal device calculated value is shown # but not included in the regression model df_short = df_All.query("model == 'empirical' & id_gates == 0.0 " ) df_short = df_short[df_short.metric == s_metric] # exclude ibmqx2 when no mitigation (no data) if mit == "no": df_short = df_short[df_short.device != 'ibmqx2'] # here for adding the "ideal device" observation" df_ideal= df_All.query("device == 'ideal_device' ") df_ideal = df_ideal[df_ideal.metric == s_metric] df_short = df_short[df_short['mitigation']==mit] tit_head = "$\ln \; n_s$ for $\epsilon$ = 0.001 vs " tit_tail = "(only the real devices data are used in the regression model)" opl.plot_scatter(df_ideal.append(df_short),"fidelity", tit_head + "quantum readout error fidelity\n" +tit_tail, ydata='log_shots', left_xlimit = 0.1*np.floor(min(df_short.fidelity*10)), right_xlimit = 1.01, bottom_ylimit = np.floor(min(df_ideal.log_shots)), top_ylimit = 1+np.ceil(max(df_short.log_shots))) print("mitigation:",mit," metric:",s_metric ) stat_model = ols("log_shots ~ fidelity", df_mod.query("id_gates == 0.0 & model == 'empirical'")).fit() print(stat_model.summary()) # check: show that python linregress (see figure) and OLS stat_model (table) agree print("r calculated in the OLS model:", round(np.sqrt(stat_model.rsquared),3)) print("to be compared to the value of r reportted in the figure legend") # calculate the expected value of n_s for a theoretical fidelity equal to 1.0 # to be compared to the oracle derived value for an ideal device: n_s = 16 id_fidelity = 1.0 alpha, beta = stat_model.params n_ideal = np.exp(alpha+beta*id_fidelity) print("extrapolated value of n_s at fidelity = 1.0:", n_ideal) print("to be compared to the oracle derived value for an ideal device: n_s = 16")
https://github.com/bagmk/qiskit-quantum-state-classifier
bagmk
import numpy as np import pandas as pd import json as json from scipy import stats from statsmodels.formula.api import ols from o_plot import opl # a small local package dedicated to this project import sys print(sys.executable) # loading the data file_name = 'QAD_data_new.json' f = open(file_name) All_data = json.load(f) #defining the pandas data frame for statistics df_All= pd.DataFrame(All_data,columns=['shots', 'device', 'fidelity', 'mitigation','model','id_gates', 'QV', 'metric']) # any shot number >= 488 indicates that the curve calculation was ended after reaching n = 500: df_All.loc[df_All.shots>=488,"shots"]=np.nan # add the variable neperian log of safe shot number: df_All['log_shots'] = np.log(df_All['shots']) stat_model = ols("log_shots ~ metric + mitigation + model + fidelity + QV + id_gates + device", df_All.query("device != 'ideal_device' ")).fit() print(stat_model.summary()) # this for Jensen-Shannon metric s_metric = 'jensenshannon' sm = np.array([96]) SAD=0 # ! will be unselected by running the next cell # main option for metric: squared euclidean distance # skip this cell if you don't want this option s_metric = 'sqeuclidean' sm = np.array([97]) SAD=2 # this for measurement mitigation mit = 'yes' MIT=0 # ! will be unselected by running the next cell # main option: no mitigation # skip this cell if you don't want this option mit = 'no' MIT=-4 # select data according to the options df_mod = df_All[df_All.mitigation == mit][df_All.metric == s_metric] print("mitigation:",mit," metric:",s_metric ) df_mod.groupby('device')[['shots','log_shots']].describe(percentiles=[0.5]) ADD=0+SAD+MIT opl.plot_curves(All_data, np.append(sm,ADD+np.array([4,5,12,13,20,21,28,29,36,37,44,45])), "No noise simulator vs empirical model - $\epsilon=0.001$ - no delay", ["metric","mitigation"], ["device","model"], right_xlimit = 70) print("mitigation:",mit," metric:",s_metric ) stat_model = ols("log_shots ~ model + fidelity ", df_mod.query("id_gates == 0.0 ")).fit() print(stat_model.summary()) ADD=48+SAD+MIT opl.plot_curves(All_data, np.append(sm,ADD+np.array([4,5,12,13,20,21,28,29,36,37,44,45])), "No noise simulator vs empirical model - $\epsilon=0.001$ - with delay", ["metric","mitigation"], ["device","model"], right_xlimit = 70) print("mitigation:",mit," metric:",s_metric ) stat_model = ols("log_shots ~ model + fidelity", df_mod.query("id_gates == 256.0")).fit() print(stat_model.summary()) print("mitigation:",mit," metric:",s_metric ) stat_model = ols("log_shots ~ model + fidelity + id_gates", df_mod).fit() print(stat_model.summary()) # rem: in this figure, the ideal device calculated value is shown # but not included in the regression model df_short = df_All.query("model == 'empirical' & id_gates == 0.0") df_short = df_short[df_short.metric == s_metric] # here for adding the "ideal device" observation (11 shots for fidelity = 1.0) df_ideal= df_All.query("device == 'ideal_device' ") df_ideal = df_ideal[df_ideal.metric == s_metric] df_short = df_short[df_short['mitigation']==mit] tit_head = "$\ln \; n_s$ for $\epsilon$ = 0.001 vs " tit_tail = "mitigation:"+mit+ " metric:"+s_metric+" model: empirical, no delay" opl.plot_scatter(df_ideal.append(df_short),"fidelity", tit_head + "quantum readout error fidelity\n" +tit_tail, left_xlimit = 0.6, right_xlimit = 1.01, bottom_ylimit = 2, top_ylimit = 6) print("mitigation:",mit," metric:",s_metric ) stat_model = ols("log_shots ~ fidelity", df_mod.query("id_gates == 0.0 & model == 'empirical'")).fit() print(stat_model.summary()) # check if python linregress (figure) and OLS stat_model (table) agree round(np.sqrt(stat_model.rsquared),3) # calculate the expected value of n_s for a theoretical fidelity equal to 1.0 # to be compared to the oracle derived value for an ideal device: n_s = 11 alpha, beta = stat_model.params n_ideal = np.exp(alpha+beta) n_ideal ADD=0+SAD+MIT opl.plot_curves(All_data, np.append(sm,ADD+np.array([4,12,20,28,36,44])), "Empirical model - $\epsilon=0.001$ - no delay", ["metric","mitigation"], ["device","model"], right_xlimit = 45, top_ylimit = 0.5) opl.plot_scatter(df_short, "QV", tit_head + "quantum volume\n" + tit_tail, left_xlimit = 0, right_xlimit = 33, bottom_ylimit = 2, top_ylimit = 6) print("mitigation:",mit," metric:",s_metric ) stat_model = ols("log_shots ~ QV", df_mod.query("id_gates == 0.0 & model == 'empirical'")).fit() print(stat_model.summary()) # # check if python linregress (figure) and OLS stat_model (table) agree round(np.sqrt(stat_model.rsquared),3)
https://github.com/bagmk/qiskit-quantum-state-classifier
bagmk
import numpy as np import json as json from o_plot import opl # a small local package dedicated to this project import sys print(sys.executable) # loading the data file_name = 'TAL2_data_new.json' f = open(file_name) All_data = json.load(f) # this for Jensen-Shannon metric s_metric = 'jensenshannon' sm = np.array([96]) SAD=0 # ! will be unselected by running the next cell # main option for metric: squared euclidean distance # skip this cell if you don't want this option s_metric = 'sqeuclidean' sm = np.array([97]) SAD=2 # this for no mitigation mit = 'no' MIT=-4 # ! will be unselected by running the next cell # mainstream option: this for measurement mitigation # skip this cell if you don't want this option mit = 'yes' MIT=0 ADD=-3 opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - no delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=1 opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - no delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=45 opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - with delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=49 opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - with delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=-4 opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - no delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=0 opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - no delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=44 opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - with delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=48 opl.plot_curves(All_data,ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared eucliden distance - $\epsilon=0.001$ - with delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=1+SAD opl.plot_curves(All_data, np.append(sm,ADD+np.array([0,4,8,12,16,20,24,28,32,36,40,44])), "Effect of mitigation - $\epsilon=0.001$ - no delay", ["model","metric"], ["device","mitigation"], right_xlimit = 90) ADD=49+SAD opl.plot_curves(All_data, np.append(sm,ADD+np.array([0,4,8,12,16,20,24,28,32,36,40,44])), "Effect of mitigation - $\epsilon=0.001$ - with delay", ["model","metric"], ["device","mitigation"], right_xlimit = 90) ADD=0+SAD opl.plot_curves(All_data,np.append(sm,ADD+np.array([0,4,8,12,16,20,24,28,32,36,40,44])), "Effect of mitigation - $\epsilon=0.001$ - no delay", ["model","metric"], ["device","mitigation"], right_xlimit = 90) ADD=48+SAD opl.plot_curves(All_data,np.append(sm,ADD+np.array([0,4,8,12,16,20,24,28,32,36,40,44])), "Effect of mitigation - $\epsilon=0.001$ - with delay", ["model","metric"], ["device","mitigation"], right_xlimit =90) ADD=-3+SAD opl.plot_curves(All_data,np.append(sm,ADD+np.array([4,52,12,60,20,68,28,76,36,84,44,92])), "Effect of Delay - $\epsilon=0.001$", ["model","metric","mitigation"], ["device","model","id_gates"], right_xlimit = 90) ADD=1+SAD opl.plot_curves(All_data,np.append(sm,ADD+np.array([4,52,12,60,20,68,28,76,36,84,44,92])), "Effect of Delay - $\epsilon=0.001$", ["model","metric","mitigation"], ["device","model","id_gates"], right_xlimit = 90) ADD=-4+SAD opl.plot_curves(All_data,np.append(sm,ADD+np.array([4,52,12,60,20,68,28,76,36,84,44,92])), "Effect of Delay - $\epsilon=0.001$", ["model","metric","mitigation"], ["device","model","id_gates"], right_xlimit = 90) ADD=0+SAD opl.plot_curves(All_data,np.append(sm,ADD+np.array([4,52,12,60,20,68,28,76,36,84,44,92])), "Effect of Delay - $\epsilon=0.001$", ["model","metric","mitigation"], ["device","model","id_gates"], right_xlimit = 90)
https://github.com/bagmk/qiskit-quantum-state-classifier
bagmk
import numpy as np import json as json from o_plot import opl # a small local package dedicated to this project import sys print(sys.executable) # loading the data file_name = 'QAD_data_new.json' f = open(file_name) All_data = json.load(f) # this for Jensen-Shannon metric s_metric = 'jensenshannon' sm = np.array([96]) SAD=0 # ! will be unselected by running the next cell # main option for metric: squared euclidean distance # skip this cell if you don't want this option s_metric = 'sqeuclidean' sm = np.array([97]) SAD=2 # this for measurement mitigation mit = 'yes' MIT=0 # ! will be unselected by running the next cell # main option: no mitigation # skip this cell if you don't want this option mit = 'no' MIT=-4 ADD=-3 opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - no delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=1 opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - no delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=45 opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - with delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=49 opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - with delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=-4 opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - no delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=0 opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - no delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=44 opl.plot_curves(All_data, ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$ - with delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=48 opl.plot_curves(All_data,ADD+np.array([96-ADD,97-ADD,4,6,12,14,20,22,28,30,36,38,44,46]), "Jensen-Shannon vs squared eucliden distance - $\epsilon=0.001$ - with delay", ["model","mitigation"], ["device","metric"], right_xlimit = 90) ADD=1+SAD opl.plot_curves(All_data, np.append(sm,ADD+np.array([0,4,8,12,16,20,24,28,32,36,40,44])), "Effect of mitigation - $\epsilon=0.001$ - no delay", ["model","metric"], ["device","mitigation"], right_xlimit = 90) ADD=49+SAD opl.plot_curves(All_data, np.append(sm,ADD+np.array([0,4,8,12,16,20,24,28,32,36,40,44])), "Effect of mitigation - $\epsilon=0.001$ - with delay", ["model","metric"], ["device","mitigation"], right_xlimit = 90) ADD=0+SAD opl.plot_curves(All_data,np.append(sm,ADD+np.array([0,4,8,12,16,20,24,28,32,36,40,44])), "Effect of mitigation - $\epsilon=0.001$ - no delay", ["model","metric"], ["device","mitigation"], right_xlimit = 90) ADD=48+SAD opl.plot_curves(All_data,np.append(sm,ADD+np.array([0,4,8,12,16,20,24,28,32,36,40,44])), "Effect of mitigation - $\epsilon=0.001$ - with delay", ["model","metric"], ["device","mitigation"], right_xlimit =90) ADD=-3+SAD opl.plot_curves(All_data,np.append(sm,ADD+np.array([4,52,12,60,20,68,28,76,36,84,44,92])), "Effect of Delay - $\epsilon=0.001$", ["model","metric","mitigation"], ["device","model","id_gates"], right_xlimit = 90) ADD=1+SAD opl.plot_curves(All_data,np.append(sm,ADD+np.array([4,52,12,60,20,68,28,76,36,84,44,92])), "Effect of Delay - $\epsilon=0.001$", ["model","metric","mitigation"], ["device","model","id_gates"], right_xlimit = 90) ADD=-4+SAD opl.plot_curves(All_data,np.append(sm,ADD+np.array([4,52,12,60,20,68,28,76,36,84,44,92])), "Effect of Delay - $\epsilon=0.001$", ["model","metric","mitigation"], ["device","model","id_gates"], right_xlimit = 90) ADD=0+SAD opl.plot_curves(All_data,np.append(sm,ADD+np.array([4,52,12,60,20,68,28,76,36,84,44,92])), "Effect of Delay - $\epsilon=0.001$", ["model","metric","mitigation"], ["device","model","id_gates"], right_xlimit = 90)
https://github.com/bagmk/qiskit-quantum-state-classifier
bagmk
import numpy as np import copy from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer, execute, transpile, assemble from qiskit.tools.visualization import * from qiskit.ignis.mitigation.measurement import (complete_meas_cal, tensored_meas_cal, CompleteMeasFitter, TensoredMeasFitter) import json import time from qiskit.tools.monitor import job_monitor from c_utils import new_cut # circuit building utilities data_directory = "data2_files/" # this directory for 2d pilot project data def json_dic_loader(dic_name): f = open(data_directory+dic_name+'.json') return json.load(f) def json_dic_dumper(dic, dic_name): with open(data_directory+dic_name+'.json', 'w') as f: json.dump(dic,f) simulator = Aer.get_backend('qasm_simulator') #specify the layout of the devices used_qubits = 5 qubit_list = [0,1,2,3,4] program_name="AL2" # This for a mix of W/Psi+ and W_bar/Phi+ separable states (2d pilot project) Flag_char = "DS" # use the joint set if len(Flag_char) >= 2: unique_char = "M" # for "mixed" else: unique_char = Flag_char # These dictionaries for the devices used in the study QV_dic = {'ibmq_athens': 32.0, 'ibmq_valencia': 16.0, 'ibmq_ourense': 8.0, "ibmqx2": 8.0, 'ibmq_santiago': 32.0, 'ibmq_vigo': 16.0, 'ideal_device': np.inf} dev_dic = {'ibmq_santiago': "San",'ibmq_athens': "Ath", 'ibmq_valencia': "Val", 'ibmq_vigo': 'Vig','ibmq_ourense': "Our", "ibmqx2": 'Yor', 'ideal_device': "Ide"} # specify the device: here first the ideal noise-free device project_device = 'ideal_device' device_name = dev_dic[project_device] # specify the nb of id gates between state creation and measurements # zero for the ideal device of course id_gates = 0 str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) # tail of the file names for RAM storage mitig_name = program_name + "_" + device_name project_name = mitig_name + "_" + unique_char + zfilled print(mitig_name) print(project_name) # establish the result label list # meas_calibs will be used for mitigation in the real device section qr = QuantumRegister(used_qubits) # meas_calibs, label_list = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal') nb_labels=len(label_list) print(nb_labels,label_list) len(meas_calibs) # permutation list # here it is simple to write down the list, # but a version using itertools will be wellcome for >5 qubits projects q_perm = [[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [0, 1, 4, 2, 3], [0, 2, 3, 1, 4], [0, 2, 4, 1, 3], [0, 3, 4, 1, 2], [1, 2, 3, 0, 4], [1, 2, 4, 0, 3], [1, 3, 4, 0, 2], [2, 3, 4, 0, 1]] # define the two subsets of 10 separable states if program_name == "QAD": state_1a = ["W","Phi+"] state_1b = ["GHZ","Psi+"] elif program_name == "ALT" or "AL2": state_1a = ["W","Psi+"] state_1b = ["Wbar","Phi+"] l_states = state_1a+state_1b l_states # version 20 circuits for demonstration # (in the version run on real devices: two batches of 10 circuits) # these circuits limited to state creation are ready to be saved # for ultimately building circuits adapted to noisy simulator and real devices # as option, these circuits will include a row of id gates between creation and measurements circ_ori = [] for i_s in range(0,len(l_states),2): for perm in q_perm: mycircuit = QuantumCircuit(used_qubits, used_qubits) mycircuit = new_cut.circuit_builder(mycircuit, perm, l_states[i_s],l_states[i_s+1]) circ_ori.append(mycircuit) # add measurement section to the circuit set newly created: nb_states = len(circ_ori) circ_ideal = copy.deepcopy(circ_ori) for i_state in range(nb_states): new_cut.add_barrier_and_measure(circ_ideal[i_state],qubit_list) # execute on noise free simulator s_sim = 12000 job_simul = execute(circ_ideal, backend=simulator, shots=s_sim) tot_results_simul = job_simul.result() # establish a dictionary of count results on noise free simulator: # (this step is only useful if ram storage is performed) void_counts = dict(zip(label_list, np.full(2**used_qubits,0.0))) #, dtype=int))) tot_results_sim_dic = {} ideal_dic = {} for i_state in range(nb_states): counts_simul = copy.deepcopy(void_counts) counts_simul.update(tot_results_simul.get_counts(i_state)) ideal_dic[str(i_state)]=counts_simul i_state_test = 0 print(device_name, "circuit #",i_state_test) circ_ideal[i_state_test].draw(output='mpl') print(device_name, "circuit #",i_state_test) plot_histogram(ideal_dic[str(i_state_test)], legend=['noise free simulation'], color = "b", figsize=(10.,5.)) i_state_test = 10 print(device_name, "circuit #",i_state_test) circ_ideal[i_state_test].draw(output='mpl') print(device_name, "circuit #",i_state_test) plot_histogram(ideal_dic[str(i_state_test)], legend=['noise free simulation'], color = "b", figsize=(10.,5.)) PD_ideal = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): PD_ideal[i_state, :] = list(ideal_dic[str(i_state)].values()) # now a little trick to get the ideal values from the simulator approximated values with np.errstate(divide='ignore'): # ignore the divide by zero warning PD_ideal = 1/np.round(s_sim/(PD_ideal)) # have a look at the matrix head and tail: print("first and last state probability distributions:") print(np.round(np.vstack((PD_ideal[0:1,:],PD_ideal[-1:,:])),4)) from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') print(provider.backends()) project_device = 'ibmq_valencia'# you may choice here a different backend device_name = dev_dic[project_device] mitig_name = program_name + "_" + device_name print(mitig_name) # determine here the backend device = provider.get_backend(project_device) # the backend names are listed here above properties = device.properties() coupling_map = device.configuration().coupling_map id_gates = 0 # choice of 0 or 256 at this time str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) project_name = mitig_name + "_" + unique_char + zfilled print(project_name) circuit_dic = json_dic_loader("circuit_"+ project_name) real_circs = [] for i_state in list(range(nb_states)): real_circs.append(QuantumCircuit().from_qasm_str(circuit_dic[str(i_state)])) i_state_test = 10 print(project_device, "circuit #",i_state_test, "circuit depth:",real_circs[i_state_test].depth()) print('gates = ',real_circs[i_state_test].count_ops()) # you may want to skip this if large nb of id gates before measurement real_circs[i_state_test].draw(output='mpl') job_simul = execute(real_circs[i_state_test], backend=simulator, shots=s_sim) print(project_device, "circuit #",i_state_test, "on noise free simulator") simul_results = job_simul.result().get_counts() plot_histogram(simul_results, legend=['noise free simulation'], color = "b", figsize=(10.,5.)) # retrieve the corresponding measurement mitigation filter obtained at experimental time # use a fake job because the calibration results were stored as dictionary simulator = Aer.get_backend('qasm_simulator') fake_job_cal = execute(meas_calibs, backend=simulator, shots=1) fake_cal_results = fake_job_cal.result() cal_results_dic = json_dic_loader("cal_results_dic_"+mitig_name) if 'date' in cal_results_dic.keys(): str(cal_results_dic['date']) cal_results = fake_cal_results.from_dict(cal_results_dic) meas_fitter = CompleteMeasFitter(cal_results, label_list, qubit_list=qubit_list, circlabel='mcal') meas_filter = meas_fitter.filter # have a look at the average measurement fidefily of this device: print("Average Measurement Fidelity was: %f" % meas_fitter.readout_fidelity(), "for",project_device) empirical_dic = json_dic_loader('experimental_'+project_name) test_dic = json_dic_loader('test_'+project_name) def rectify_counts(tot_res, test_cqi,mitigation,m_filter) : # IMPORTANT MODIFICATION try: counts_results_real_test = tot_res[str(test_cqi)] except KeyError as error: counts_results_real_test = tot_res[test_cqi] raw_counts_test = copy.deepcopy(void_counts) raw_counts_test.update(counts_results_real_test) if mitigation: mitigated_results_test = meas_filter.apply(raw_counts_test, method = 'least_squares') returned_counts = copy.deepcopy(void_counts) returned_counts.update(mitigated_results_test) else: returned_counts = copy.deepcopy(raw_counts_test) return returned_counts def get_clean_matrix(dic, mitigation,m_filter): clean_matrix = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): rectified_counts = rectify_counts(dic,i_state, mitigation,m_filter) # get a rectified counts dictionary clean_matrix[i_state, :] = list(rectified_counts.values()) clean_matrix = clean_matrix/clean_matrix.sum(axis=1, keepdims=True) return clean_matrix def obtain_pooled_PDM(mitigation): PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) PD_test = get_clean_matrix(test_dic, mitigation=mitigation, m_filter=meas_filter) return PD_exper + PD_test PD_tot = obtain_pooled_PDM(False) PD_totm = obtain_pooled_PDM(True) i_state_test = 19 # choose here the circuit print(project_device, "circuit #",i_state_test, "circuit depth:",real_circs[i_state_test].depth()) print('gates = ',real_circs[i_state_test].count_ops()) ideal_results = dict(zip(label_list,PD_ideal[i_state_test])) real_results = dict(zip(label_list,PD_tot[i_state_test])) mit_results = dict(zip(label_list,PD_totm[i_state_test])) plot_histogram([ideal_results, real_results, mit_results], legend=['ideal device','real results on\n '+ project_device, 'after measurement\n errror mitigation'], color =["b","r","g"], bar_labels=False, figsize=(10.,5.)) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/bagmk/qiskit-quantum-state-classifier
bagmk
import numpy as np import copy from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer, execute, transpile, assemble from qiskit.tools.visualization import * from qiskit.ignis.mitigation.measurement import (complete_meas_cal, tensored_meas_cal, CompleteMeasFitter, TensoredMeasFitter) import json from scipy.signal import savgol_filter import time from qiskit.tools.monitor import job_monitor from o_utils import ora # classifier utilities from o_plot import opl # utilities for result plot from c_utils import new_cut # circuit building utilities def json_dic_loader(dic_name): f = open(data_directory+dic_name+'.json') return json.load(f) # common code for calling the classifier for ideal device and for real devices def add_single_dic(target_data_list): start_time = time.time() print("started",time.strftime('%d/%m/%Y %H:%M:%S'),mitig_name, "mitigation",mit_str,o_metric,model_name) # added for D,S,M choice. Mainstream : mixed set of 20 states first = 0 last = nb_states if unique_char == "D": last = int(nb_states/2) elif unique_char == "S": first = int(nb_states/2) # get the classifier error curve in function of the number of shot and the "safe shot number" error_curve, safe_rate, ernb = ora.provide_error_curve(PD_model=model_dic[model_name][first:last,:], PD_test=PD_test[first:last,:], trials=trials, window=window, epsilon=epsilon, max_shots=max_shots, pol=pol, verbosality=verbosality) tail = savgol_filter(ernb, window, pol, axis=0) len_curve = len(error_curve) safe_shot_nb = len_curve - int((window-1)/2) # OK print('safe_shot_nb',safe_shot_nb, 'safe_rate',safe_rate, "nb trials:",trials) err_rates = tail[int((window-1)/2),:]/trials err_rate_max = np.max(err_rates) err_rate_min = np.min(err_rates) r=4 print("savgol interpolated error rate mean:", np.round(np.mean(err_rates),r), "min:", np.round(err_rate_min,r), "max:", np.round(err_rate_max,r), "for", [ien for ien, jen in enumerate(err_rates) if jen == err_rate_max]) end_time = time.time() #save the data in a list of dictionaries : single_dic={"project":mitig_name, "id_gates":id_gates, "mitigation":mit_str, "model":model_name, "metric":o_metric, "device":project_device, "curve_length":len_curve, "shots": safe_shot_nb, "shots_rate": safe_rate, "error_curve":error_curve, "trials":trials,"window":window, "epsilon":epsilon,"SG_pol": pol, "computation_time":end_time-start_time, "time_completed":time.strftime('%d/%m/%Y %H:%M:%S'), "trials":trials, "QV": QV_dic[project_device], "fidelity": fidelity_dic[project_device], "error_nb":ernb} target_data_list.append(single_dic) print("completed",time.strftime('%d/%m/%Y %H:%M:%S'),mitig_name, "mitigation",mit_str,o_metric,model_name,"\n") simulator = Aer.get_backend('qasm_simulator') #specify the layout of the devices used_qubits = 5 qubit_list = [0,1,2,3,4] short_version = True #program_name="QAD" # 1st pilot project GHZ Psi+ / W Phi+ program_name="AL2" # 2d pilot project W Psi+ / Wbar Phi+ Flag_char = "DS" # this for a mix of two types of separable states if len(Flag_char) >= 2: unique_char = "M" else: unique_char = Flag_char # These dictionaries for the devices used in the study if program_name == "QAD": fidelity_dic = {'ibmq_athens': 0.925110, 'ibmq_valencia': 0.809101, 'ibmq_ourense': 0.802380, "ibmqx2": 0.627392, 'ibmq_santiago': 0.919399, 'ibmq_vigo': 0.908840, 'ideal_device': 1.0} data_directory = "data_files/" elif program_name == "AL2": fidelity_dic = {'ibmq_athens': 0.910145, 'ibmq_valencia': 0.794262, 'ibmq_ourense': 0.818974, "ibmqx2": 0.359528, 'ibmq_santiago': 0.900024, 'ibmq_vigo': 0.841831, 'ideal_device': 1.0} data_directory = "data2_files/" QV_dic = {'ibmq_athens': 32.0, 'ibmq_valencia': 16.0, 'ibmq_ourense': 8.0, "ibmqx2": 8.0, 'ibmq_santiago': 32.0, 'ibmq_vigo': 16.0, 'ideal_device': np.inf} dev_dic = {'ibmq_santiago': "San",'ibmq_athens': "Ath", 'ibmq_valencia': "Val", 'ibmq_vigo': 'Vig','ibmq_ourense': "Our", "ibmqx2": 'Yor', 'ideal_device': "Ide"} # specify the device: here first the ideal noise-free device project_device = 'ideal_device' device_name = dev_dic[project_device] # specify the nb of id gates between state creation and measurements # zero for the ideal device id_gates = 0 str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) # tail of the file names for RAM storage mitig_name = program_name + "_" + device_name project_name = mitig_name + "_" + unique_char + zfilled print(mitig_name) print(project_name) # establish the result label list # meas_calibs will be used for mitigation in the real device section qr = QuantumRegister(used_qubits) meas_calibs, label_list = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal') nb_labels=len(label_list) print(nb_labels,label_list) len(meas_calibs) # permutation list # here it is simple to write down the list, # but a version using itertools will be wellcome for >5 qubits projects if used_qubits == 5: q_perm = [[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [0, 1, 4, 2, 3], [0, 2, 3, 1, 4], [0, 2, 4, 1, 3], [0, 3, 4, 1, 2], [1, 2, 3, 0, 4], [1, 2, 4, 0, 3], [1, 3, 4, 0, 2], [2, 3, 4, 0, 1]] else: print("work in progress - meanwhile please provide the list of permutations") # try loading the dictionary of results if its creation was skipped if short_version == True: ideal_dic = json_dic_loader("ideal_dic_"+project_name) nb_states = len(ideal_dic) nb_labels = len(list(ideal_dic.values())[0]) s_sim = sum(list(ideal_dic.values())[0].values()) PD_ideal = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): PD_ideal[i_state, :] = list(ideal_dic[str(i_state)].values()) # now a little trick to get the ideal values from the simulator approximated values with np.errstate(divide='ignore'): # ignore the divide by zero warning PD_ideal = 1/np.round(s_sim/(PD_ideal)) # have a look at the matrix head and tail: print("first and last state probability distributions:") print(np.round(np.vstack((PD_ideal[0:1,:],PD_ideal[-1:,:])),4)) # here will be appended the data we want for the curve plot ideal_data_list=[] # you may want to skip this cell as it will require a long time # because of the high number of trials required by the Monte Carlo simulation for each nb o shots value # the following values are defined in the study summary (readme file): trials=100 # should be 10000 if not demo window=5 # shorter window than for the real device counts epsilon = .001 min_shots = 5 max_shots = 100 pol=2 subset = None # variable not used here verbosality = 5 # printing step for intermediate results when increasing the experiment shot number PD_test = PD_ideal mitigation_dic = {"Na": None} o_metrics_desired = ['jensenshannon', 'sqeuclidean'] model_dic = {"ideal_sim": PD_ideal} for mit_str, mitigation in mitigation_dic.items(): if mitigation != None: # thus only for counts on real device PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) for o_metric in o_metrics_desired: for model_name in model_dic.keys(): add_single_dic(ideal_data_list) # get the stored results of the Monte Carlo simulation in case you skipped the previous step if len(ideal_data_list) == 0: ideal_data_list = json_dic_loader("ideal_device_data_list_"+project_name) # have a look at the mean error rate curves and error rate at save shot number n_s # NB the r_hat_mean curves and legend reported r_hat_max errors the unsmoothed values opl.plot_curves(ideal_data_list,np.array([0,1]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$" , ["model"], ["device","metric"], right_xlimit = 20, bottom_ylimit = -0.001, top_ylimit = 0.05) from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() project_device = 'ibmq_valencia'# you may choice here a different backend device_name = dev_dic[project_device] mitig_name = program_name + "_" + device_name print(mitig_name) #determine here the backend device = provider.get_backend(project_device) # the backend names are listed here above properties = device.properties() coupling_map = device.configuration().coupling_map # retrieve the corresponding measurement mitigation filter obtained at experimental time # use a fake job because the calibration results were stored as dictionary simulator = Aer.get_backend('qasm_simulator') fake_job_cal = execute(meas_calibs, backend=simulator, shots=1) fake_cal_results = fake_job_cal.result() cal_results_dic = json_dic_loader("cal_results_dic_"+mitig_name) if 'date' in cal_results_dic.keys(): str(cal_results_dic['date']) cal_results = fake_cal_results.from_dict(cal_results_dic) meas_fitter = CompleteMeasFitter(cal_results, label_list, qubit_list=qubit_list, circlabel='mcal') meas_filter = meas_fitter.filter # have a look at the average measurement fidefily of this device: print("Average Measurement Fidelity was: %f" % meas_fitter.readout_fidelity(), "for",project_device) id_gates = 0 str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) project_name = mitig_name + "_" + unique_char + zfilled print(project_name) #changing keys of dictionary for merging: def key_change(ini_dict, i_subset): ini_list = [] len_ini = len(ini_dict) for i in range(len_ini): ini_list.append(str(i+i_subset*len_ini)) return dict(zip(ini_list, list(ini_dict.values()))) if program_name == "QAD": #retrieve the data corresponding to the 1st project lfc = list(Flag_char) circ_ideal =[] empirical_dic = {} for i_subset, subset in enumerate(lfc): qasm_circs_dic = json_dic_loader('qasm_circs_dic_QAD_'+device_name+'_'+ subset + zfilled) j=0 # j included for project with several transpilation sessions for each device - not used here qasm_circs = qasm_circs_dic[str(j)] nb_circs = len(qasm_circs) for i_circs in range(nb_circs): circ_ideal.append(QuantumCircuit().from_qasm_str(qasm_circs[i_circs])) empirical_dic = {**empirical_dic, **key_change(json_dic_loader("experimental"+"_"+mitig_name +"_"\ +subset+zfilled), i_subset)} test_dic = copy.deepcopy(empirical_dic) #nb_states = len(circ_ideal) project_name if program_name == "AL2": empirical_dic = json_dic_loader('experimental_'+project_name) test_dic = json_dic_loader('test_'+project_name) def rectify_counts(tot_res, test_cqi,mitigation,m_filter) : void_counts = dict(zip(label_list, np.zeros(2**used_qubits))) try: counts_results_real_test = tot_res[str(test_cqi)] except KeyError as error: counts_results_real_test = tot_res[test_cqi] raw_counts_test = copy.deepcopy(void_counts) raw_counts_test.update(counts_results_real_test) if mitigation: mitigated_results_test = meas_filter.apply(raw_counts_test, method = 'least_squares') returned_counts = copy.deepcopy(void_counts) returned_counts.update(mitigated_results_test) else: returned_counts = copy.deepcopy(raw_counts_test) return returned_counts def get_clean_matrix(dic, mitigation,m_filter): clean_matrix = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): rectified_counts = rectify_counts(dic,i_state, mitigation,m_filter) # get a rectified counts dictionary clean_matrix[i_state, :] = list(rectified_counts.values()) clean_matrix = clean_matrix/clean_matrix.sum(axis=1, keepdims=True) return clean_matrix # We need to create a first matrix version. It will then vary for each considered set of distribution mitigation = False PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) print("first and last state probability distributions:") print(np.round(np.vstack((PD_exper[0:1,:],PD_exper[-1:,:])),3)) if program_name == "QAD": PD_test = copy.deepcopy(PD_exper) elif program_name == "AL2": mitigation = False PD_test = get_clean_matrix(test_dic, mitigation=mitigation, m_filter=meas_filter) print("first and last state probability distributions:") print(np.round(np.vstack((PD_test[0:1,:],PD_test[-1:,:])),3)) # here will be appended the data we want for the final plot of this notebook empirical_data_list=[] # you may want to skip this cell as it will require a long time # because of the high number of trials required by the Monte Carlo simulation for each nb o shots value # the following values are defined in the study summary notebook: trials=100 window=11 epsilon = .001 max_shots = 500 pol=2 verbosality = 10 # printing step for intermediate results when increasing the experiment shot number # In this section you can easily make your choice of combinations # mitigation or not, metric and model mitigation_dic = {"no":False, "yes" : True} #mitigation_dic = {"no":False} #mitigation_dic = {"yes" : True} o_metrics_desired = ['jensenshannon', 'sqeuclidean'] #o_metrics_desired = ['jensenshannon'] #o_metrics_desired = ['sqeuclidean'] model_dic = {"empirical": PD_exper, "ideal_sim": PD_ideal} #model_dic = {"empirical": PD_exper} #model_dic = {"ideal_sim": PD_ideal} # Obtain a sequence of results in form of a list of dictionaries for mit_str, mitigation in mitigation_dic.items(): # here we toggle PD_exper as we toggled mitigation status PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) PD_test = get_clean_matrix(test_dic, mitigation=mitigation, m_filter=meas_filter) for o_metric in o_metrics_desired: print(project_name, model_dic.keys(), o_metric) for model_name in model_dic.keys(): add_single_dic(empirical_data_list) # get the stored results of the Monte Carlo simulation in case you skipped the previous step if len(empirical_data_list) == 0: empirical_data_list = json_dic_loader('nemp_data_list_'+project_name) # have a look at the mean error rate curves and error rate at save shot number n_s # NB the r_hat_mean curves and legend reported r_hat_max errors are the unsmoothed values opl.plot_curves(ideal_data_list + empirical_data_list, np.array(range(2+len(empirical_data_list))), "$\epsilon=0.001$" , ["device"], ["model","metric","mitigation","id_gates"], right_xlimit = 80, bottom_ylimit = -0.02, top_ylimit = 1) import winsound duration = 2000 # milliseconds freq = 800 # Hz winsound.Beep(freq, duration) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/bagmk/qiskit-quantum-state-classifier
bagmk
#!/usr/bin/env python # coding: utf-8 # In[ ]: import numpy as np import time import copy from qiskit import transpile def circuit_builder(Circuit, q_list, state_1, state_2): if state_1 == "GHZ": Circuit.h(q_list[0]) Circuit.cx(q_list[0],q_list[1]) Circuit.cx(q_list[1],q_list[2]) elif state_1[0] == "W": Circuit.x(q_list[2]) Circuit.ry(-0.955316618124509, q_list[1]) Circuit.cz(q_list[2],q_list[1]) Circuit.ry(0.955316618124509, q_list[1]) Circuit.ry(-np.pi/4, q_list[0]) Circuit.cz(q_list[1],q_list[0]) Circuit.ry(np.pi/4, q_list[0]) Circuit.cx(q_list[0],q_list[1]) Circuit.cx(q_list[0],q_list[2]) Circuit.cx(q_list[1],q_list[2]) if state_1[1:] == "bar": Circuit.x(q_list[0]) Circuit.x(q_list[1]) Circuit.x(q_list[2]) # common for Phi+ and Phi+ states: Circuit.h(q_list[3]) Circuit.cx(q_list[3],q_list[4]) if state_2 == "Psi+": Circuit.x(q_list[4]) return Circuit def add_barrier_and_measure(Circuit, q_list): Circuit.barrier() Circuit.measure(q_list,q_list) return Circuit def prepare_circuits(qubit_list,cqi_list, circ_ori, nb_trials, level, seed_trans, device, coupling_map, nb_id_gates=0, verbose=False): #version with a limit of trials start_time = time.strftime('%d/%m/%Y %H:%M:%S') print("Start at DMY: ",start_time) summary_dic = {} for cqi in cqi_list: circuit = copy.deepcopy(circ_ori[cqi]) if nb_id_gates > 0: circuit.barrier() for id_nb_id_gates in range(nb_id_gates): for index, value in enumerate(qubit_list): circuit.id(value) add_barrier_and_measure(circuit, qubit_list) summary = [] depth_list = [] count_run = 0 max_count_run = nb_trials * 3 break_flag = False for j in range(nb_trials): if seed_trans != None: seed_transpiler=seed_trans[j*len(cqi_list)+1] else: seed_transpiler = None new_depth = 0 while not break_flag and (new_depth == 0 or depth_list.count(new_depth) != 0): Q_state_opt_new = transpile(circuit, backend=device, coupling_map = coupling_map, seed_transpiler=seed_transpiler, optimization_level=level, initial_layout=qubit_list) new_depth = Q_state_opt_new.depth() if count_run == 0: to_insert = {"depth": new_depth, 'circuit':Q_state_opt_new} count_run += 1 if count_run == max_count_run: break_flag = True if not break_flag: depth_list.append(new_depth) summary.append({"depth": new_depth, 'circuit':Q_state_opt_new}) if break_flag: len_list = len(depth_list) for i_trial in range(nb_trials - len_list): summary.insert(0, to_insert) break time_exp = time.strftime('%d/%m/%Y %H:%M:%S') if verbose: print("%2i" % cqi,"DMY: ",time_exp) summary_dic[cqi] = summary end_time = time.strftime('%d/%m/%Y %H:%M:%S') print("Completed at DMY: ",end_time) return summary_dic
https://github.com/LohitPotnuru/DeutschJozsaAlgorithm_Qiskit
LohitPotnuru
from qiskit import * from random import randint from qiskit_textbook.problems import dj_problem_oracle #number of bits in function qiskit_ex= bool(input("Enter a value if you want to test a random qiskit 4-bit oracle")) if qiskit_ex==False: n=int(input("Enter the number of bits in the function: ")) if (input("Is the function constant? "))=='True': constant=True else: constant=False print(constant) else: n=4 #create circuit and initialize states circuit=QuantumCircuit(n+1,n) circuit.x(n) circuit.h(range(n+1)) circuit.barrier() circuit.draw() #generate a constant function try: if constant==True: oracle=QuantumCircuit(n+1) num=randint(0,2) if num==0: oracle.i(n) if num==1: oracle.x(n) #test oracle for 2 qubit if constant==False: oracle=QuantumCircuit(n+1) b =randint(1,2**n) b_str = format(b, '0'+str(n)+'b') for i in range(len(b_str)): if b_str[i]=='1': oracle.x(int(i)) oracle.cx(range(0,n),n) for i in range(len(b_str)): if b_str[i]=='1': oracle.x(int(i)) circuit+=oracle circuit.barrier() except: oracle=QuantumCircuit(n+1) gate = dj_problem_oracle(2) oracle.append(oracle, range(n+1)) circuit+=oracle circuit.barrier() circuit.draw() #reverse initial H gates and add measurements circuit.h(range(n)) circuit.measure(range(n),range(n)) circuit.draw() #use Aer's qasm_simulater to execute backend = BasicAer.get_backend('qasm_simulator') #execute+ get results result = execute(circuit, backend, shots = 1000).result() #get counts of results counts = result.get_counts() print(counts) constant='' for i in range(n): constant+="0" if max(counts)==constant: print("the function is constant") else: print("the function is balanced")
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ 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/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. 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/swe-train/qiskit__qiskit
swe-train
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/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ 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/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """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/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ This module contains the definition of a base class for quantum fourier transforms. """ from abc import abstractmethod from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua import Pluggable, AquaError class QFT(Pluggable): """Base class for QFT. This method should initialize the module and its configuration, and use an exception if a component of the module is available. Args: configuration (dict): configuration dictionary """ @abstractmethod def __init__(self, *args, **kwargs): super().__init__() @classmethod def init_params(cls, params): qft_params = params.get(Pluggable.SECTION_KEY_QFT) kwargs = {k: v for k, v in qft_params.items() if k != 'name'} return cls(**kwargs) @abstractmethod def _build_matrix(self): raise NotImplementedError @abstractmethod def _build_circuit(self, qubits=None, circuit=None, do_swaps=True): raise NotImplementedError def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True): """Construct the circuit. Args: mode (str): 'matrix' or 'circuit' qubits (QuantumRegister or qubits): register or qubits to build the circuit on. circuit (QuantumCircuit): circuit for construction. do_swaps (bool): include the swaps. Returns: The matrix or circuit depending on the specified mode. """ if mode == 'circuit': return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps) elif mode == 'matrix': return self._build_matrix() else: raise AquaError('Unrecognized mode: {}.'.format(mode))
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Ripple adder example based on Cuccaro et al., quant-ph/0410184. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### backend = BasicAer.get_backend("qasm_simulator") coupling_map = [ [0, 1], [0, 8], [1, 2], [1, 9], [2, 3], [2, 10], [3, 4], [3, 11], [4, 5], [4, 12], [5, 6], [5, 13], [6, 7], [6, 14], [7, 15], [8, 9], [9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], ] ############################################################### # Make a quantum program for the n-bit ripple adder. ############################################################### n = 2 a = QuantumRegister(n, "a") b = QuantumRegister(n, "b") cin = QuantumRegister(1, "cin") cout = QuantumRegister(1, "cout") ans = ClassicalRegister(n + 1, "ans") qc = QuantumCircuit(a, b, cin, cout, ans, name="rippleadd") def majority(p, a, b, c): """Majority gate.""" p.cx(c, b) p.cx(c, a) p.ccx(a, b, c) def unmajority(p, a, b, c): """Unmajority gate.""" p.ccx(a, b, c) p.cx(c, a) p.cx(a, b) # Build a temporary subcircuit that adds a to b, # storing the result in b adder_subcircuit = QuantumCircuit(cin, a, b, cout) majority(adder_subcircuit, cin[0], b[0], a[0]) for j in range(n - 1): majority(adder_subcircuit, a[j], b[j + 1], a[j + 1]) adder_subcircuit.cx(a[n - 1], cout[0]) for j in reversed(range(n - 1)): unmajority(adder_subcircuit, a[j], b[j + 1], a[j + 1]) unmajority(adder_subcircuit, cin[0], b[0], a[0]) # Set the inputs to the adder qc.x(a[0]) # Set input a = 0...0001 qc.x(b) # Set input b = 1...1111 # Apply the adder qc &= adder_subcircuit # Measure the output register in the computational basis for j in range(n): qc.measure(b[j], ans[j]) qc.measure(cout[0], ans[n]) ############################################################### # execute the program. ############################################################### # First version: not mapped job = execute(qc, backend=backend, coupling_map=None, shots=1024) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph job = execute(qc, backend=backend, coupling_map=coupling_map, shots=1024) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """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/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ 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/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ 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/swe-train/qiskit__qiskit
swe-train
# -*- 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/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Assemble function for converting a list of circuits into a qobj.""" import hashlib from collections import defaultdict from typing import Any, Dict, List, Tuple, Union from qiskit import qobj, pulse from qiskit.assembler.run_config import RunConfig from qiskit.exceptions import QiskitError from qiskit.pulse import instructions, transforms, library, schedule, channels from qiskit.qobj import utils as qobj_utils, converters from qiskit.qobj.converters.pulse_instruction import ParametricPulseShapes def assemble_schedules( schedules: List[ Union[ schedule.ScheduleBlock, schedule.ScheduleComponent, Tuple[int, schedule.ScheduleComponent], ] ], qobj_id: int, qobj_header: qobj.QobjHeader, run_config: RunConfig, ) -> qobj.PulseQobj: """Assembles a list of schedules into a qobj that can be run on the backend. Args: schedules: Schedules to assemble. qobj_id: Identifier for the generated qobj. qobj_header: Header to pass to the results. run_config: Configuration of the runtime environment. Returns: The Qobj to be run on the backends. Raises: QiskitError: when frequency settings are not supplied. Examples: .. code-block:: python from qiskit import pulse from qiskit.assembler import assemble_schedules from qiskit.assembler.run_config import RunConfig # Construct a Qobj header for the output Qobj header = {"backend_name": "FakeOpenPulse2Q", "backend_version": "0.0.0"} # Build a configuration object for the output Qobj config = RunConfig(shots=1024, memory=False, meas_level=1, meas_return='avg', memory_slot_size=100, parametric_pulses=[], init_qubits=True, qubit_lo_freq=[4900000000.0, 5000000000.0], meas_lo_freq=[6500000000.0, 6600000000.0], schedule_los=[]) # Build a Pulse schedule to assemble into a Qobj 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") # Assemble a Qobj from the schedule. pulseQobj = assemble_schedules(schedules=[schedule], qobj_id="custom-id", qobj_header=header, run_config=config) """ if not hasattr(run_config, "qubit_lo_freq"): raise QiskitError("qubit_lo_freq must be supplied.") if not hasattr(run_config, "meas_lo_freq"): raise QiskitError("meas_lo_freq must be supplied.") lo_converter = converters.LoConfigConverter( qobj.PulseQobjExperimentConfig, **run_config.to_dict() ) experiments, experiment_config = _assemble_experiments(schedules, lo_converter, run_config) qobj_config = _assemble_config(lo_converter, experiment_config, run_config) return qobj.PulseQobj( experiments=experiments, qobj_id=qobj_id, header=qobj_header, config=qobj_config ) def _assemble_experiments( schedules: List[Union[schedule.ScheduleComponent, Tuple[int, schedule.ScheduleComponent]]], lo_converter: converters.LoConfigConverter, run_config: RunConfig, ) -> Tuple[List[qobj.PulseQobjExperiment], Dict[str, Any]]: """Assembles a list of schedules into PulseQobjExperiments, and returns related metadata that will be assembled into the Qobj configuration. Args: schedules: Schedules to assemble. lo_converter: The configured frequency converter and validator. run_config: Configuration of the runtime environment. Returns: The list of assembled experiments, and the dictionary of related experiment config. Raises: QiskitError: when frequency settings are not compatible with the experiments. """ freq_configs = [lo_converter(lo_dict) for lo_dict in getattr(run_config, "schedule_los", [])] if len(schedules) > 1 and len(freq_configs) not in [0, 1, len(schedules)]: raise QiskitError( "Invalid 'schedule_los' setting specified. If specified, it should be " "either have a single entry to apply the same LOs for each schedule or " "have length equal to the number of schedules." ) instruction_converter = getattr( run_config, "instruction_converter", converters.InstructionToQobjConverter ) instruction_converter = instruction_converter(qobj.PulseQobjInstruction, **run_config.to_dict()) formatted_schedules = [transforms.target_qobj_transform(sched) for sched in schedules] compressed_schedules = transforms.compress_pulses(formatted_schedules) user_pulselib = {} experiments = [] for idx, sched in enumerate(compressed_schedules): qobj_instructions, max_memory_slot = _assemble_instructions( sched, instruction_converter, run_config, user_pulselib ) metadata = sched.metadata if metadata is None: metadata = {} # TODO: add other experimental header items (see circuit assembler) qobj_experiment_header = qobj.QobjExperimentHeader( memory_slots=max_memory_slot + 1, # Memory slots are 0 indexed name=sched.name or "Experiment-%d" % idx, metadata=metadata, ) experiment = qobj.PulseQobjExperiment( header=qobj_experiment_header, instructions=qobj_instructions ) if freq_configs: # This handles the cases where one frequency setting applies to all experiments and # where each experiment has a different frequency freq_idx = idx if len(freq_configs) != 1 else 0 experiment.config = freq_configs[freq_idx] experiments.append(experiment) # Frequency sweep if freq_configs and len(experiments) == 1: experiment = experiments[0] experiments = [] for freq_config in freq_configs: experiments.append( qobj.PulseQobjExperiment( header=experiment.header, instructions=experiment.instructions, config=freq_config, ) ) # Top level Qobj configuration experiment_config = { "pulse_library": [ qobj.PulseLibraryItem(name=name, samples=samples) for name, samples in user_pulselib.items() ], "memory_slots": max(exp.header.memory_slots for exp in experiments), } return experiments, experiment_config def _assemble_instructions( sched: Union[pulse.Schedule, pulse.ScheduleBlock], instruction_converter: converters.InstructionToQobjConverter, run_config: RunConfig, user_pulselib: Dict[str, List[complex]], ) -> Tuple[List[qobj.PulseQobjInstruction], int]: """Assembles the instructions in a schedule into a list of PulseQobjInstructions and returns related metadata that will be assembled into the Qobj configuration. Lookup table for pulses defined in all experiments are registered in ``user_pulselib``. This object should be mutable python dictionary so that items are properly updated after each instruction assemble. The dictionary is not returned to avoid redundancy. Args: sched: Schedule to assemble. instruction_converter: A converter instance which can convert PulseInstructions to PulseQobjInstructions. run_config: Configuration of the runtime environment. user_pulselib: User pulse library from previous schedule. Returns: A list of converted instructions, the user pulse library dictionary (from pulse name to pulse samples), and the maximum number of readout memory slots used by this Schedule. """ sched = transforms.target_qobj_transform(sched) max_memory_slot = 0 qobj_instructions = [] acquire_instruction_map = defaultdict(list) for time, instruction in sched.instructions: if isinstance(instruction, instructions.Play): if isinstance(instruction.pulse, (library.ParametricPulse, library.SymbolicPulse)): is_backend_supported = True try: pulse_shape = ParametricPulseShapes.from_instance(instruction.pulse).name if pulse_shape not in run_config.parametric_pulses: is_backend_supported = False except ValueError: # Custom pulse class, or bare SymbolicPulse object. is_backend_supported = False if not is_backend_supported: instruction = instructions.Play( instruction.pulse.get_waveform(), instruction.channel, name=instruction.name ) if isinstance(instruction.pulse, library.Waveform): name = hashlib.sha256(instruction.pulse.samples).hexdigest() instruction = instructions.Play( library.Waveform(name=name, samples=instruction.pulse.samples), channel=instruction.channel, name=name, ) user_pulselib[name] = instruction.pulse.samples # ignore explicit delay instrs on acq channels as they are invalid on IBMQ backends; # timing of other instrs will still be shifted appropriately if isinstance(instruction, instructions.Delay) and isinstance( instruction.channel, channels.AcquireChannel ): continue if isinstance(instruction, instructions.Acquire): if instruction.mem_slot: max_memory_slot = max(max_memory_slot, instruction.mem_slot.index) # Acquires have a single AcquireChannel per inst, but we have to bundle them # together into the Qobj as one instruction with many channels acquire_instruction_map[(time, instruction.duration)].append(instruction) continue qobj_instructions.append(instruction_converter(time, instruction)) if acquire_instruction_map: if hasattr(run_config, "meas_map"): _validate_meas_map(acquire_instruction_map, run_config.meas_map) for (time, _), instruction_bundle in acquire_instruction_map.items(): qobj_instructions.append( instruction_converter(time, instruction_bundle), ) return qobj_instructions, max_memory_slot def _validate_meas_map( instruction_map: Dict[Tuple[int, instructions.Acquire], List[instructions.Acquire]], meas_map: List[List[int]], ) -> None: """Validate all qubits tied in ``meas_map`` are to be acquired. Args: instruction_map: A dictionary grouping Acquire instructions according to their start time and duration. meas_map: List of groups of qubits that must be acquired together. Raises: QiskitError: If the instructions do not satisfy the measurement map. """ sorted_inst_map = sorted(instruction_map.items(), key=lambda item: item[0]) meas_map_sets = [set(m) for m in meas_map] # error if there is time overlap between qubits in the same meas_map for idx, inst in enumerate(sorted_inst_map[:-1]): inst_end_time = inst[0][0] + inst[0][1] next_inst = sorted_inst_map[idx + 1] next_inst_time = next_inst[0][0] if next_inst_time < inst_end_time: inst_qubits = {inst.channel.index for inst in inst[1]} next_inst_qubits = {inst.channel.index for inst in next_inst[1]} for meas_set in meas_map_sets: common_instr_qubits = inst_qubits.intersection(meas_set) common_next = next_inst_qubits.intersection(meas_set) if common_instr_qubits and common_next: raise QiskitError( "Qubits {} and {} are in the same measurement grouping: {}. " "They must either be acquired at the same time, or disjointly" ". Instead, they were acquired at times: {}-{} and " "{}-{}".format( common_instr_qubits, common_next, meas_map, inst[0][0], inst_end_time, next_inst_time, next_inst_time + next_inst[0][1], ) ) def _assemble_config( lo_converter: converters.LoConfigConverter, experiment_config: Dict[str, Any], run_config: RunConfig, ) -> qobj.PulseQobjConfig: """Assembles the QobjConfiguration from experimental config and runtime config. Args: lo_converter: The configured frequency converter and validator. experiment_config: Schedules to assemble. run_config: Configuration of the runtime environment. Returns: The assembled PulseQobjConfig. """ qobj_config = run_config.to_dict() qobj_config.update(experiment_config) # Run config not needed in qobj config qobj_config.pop("meas_map", None) qobj_config.pop("qubit_lo_range", None) qobj_config.pop("meas_lo_range", None) # convert enums to serialized values meas_return = qobj_config.get("meas_return", "avg") if isinstance(meas_return, qobj_utils.MeasReturnType): qobj_config["meas_return"] = meas_return.value meas_level = qobj_config.get("meas_level", 2) if isinstance(meas_level, qobj_utils.MeasLevel): qobj_config["meas_level"] = meas_level.value # convert LO frequencies to GHz qobj_config["qubit_lo_freq"] = [freq / 1e9 for freq in qobj_config["qubit_lo_freq"]] qobj_config["meas_lo_freq"] = [freq / 1e9 for freq in qobj_config["meas_lo_freq"]] # override defaults if single entry for ``schedule_los`` schedule_los = qobj_config.pop("schedule_los", []) if len(schedule_los) == 1: lo_dict = schedule_los[0] q_los = lo_converter.get_qubit_los(lo_dict) # Hz -> GHz if q_los: qobj_config["qubit_lo_freq"] = [freq / 1e9 for freq in q_los] m_los = lo_converter.get_meas_los(lo_dict) if m_los: qobj_config["meas_lo_freq"] = [freq / 1e9 for freq in m_los] return qobj.PulseQobjConfig(**qobj_config)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Disassemble function for a qobj into a list of circuits and its config""" from typing import Any, Dict, List, NewType, Tuple, Union import collections import math from qiskit import pulse from qiskit.circuit.classicalregister import ClassicalRegister from qiskit.circuit.instruction import Instruction from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister from qiskit.qobj import PulseQobjInstruction from qiskit.qobj.converters import QobjToInstructionConverter # A ``CircuitModule`` is a representation of a circuit execution on the backend. # It is currently a list of quantum circuits to execute, a run Qobj dictionary # and a header dictionary. CircuitModule = NewType( "CircuitModule", Tuple[List[QuantumCircuit], Dict[str, Any], Dict[str, Any]] ) # A ``PulseModule`` is a representation of a pulse execution on the backend. # It is currently a list of pulse schedules to execute, a run Qobj dictionary # and a header dictionary. PulseModule = NewType("PulseModule", Tuple[List[pulse.Schedule], Dict[str, Any], Dict[str, Any]]) def disassemble(qobj) -> Union[CircuitModule, PulseModule]: """Disassemble a qobj and return the circuits or pulse schedules, run_config, and user header. .. note:: ``disassemble(assemble(qc))`` is not guaranteed to produce an exactly equal circuit to the input, due to limitations in the :obj:`.QasmQobj` format that need to be maintained for backend system compatibility. This is most likely to be the case when using newer features of :obj:`.QuantumCircuit`. In most cases, the output should be equivalent, if not quite equal. Args: qobj (Qobj): The input qobj object to disassemble Returns: Union[CircuitModule, PulseModule]: The disassembled program which consists of: * programs: A list of quantum circuits or pulse schedules * run_config: The dict of the run config * user_qobj_header: The dict of any user headers in the qobj Examples: .. code-block:: python from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.compiler.assembler import assemble from qiskit.assembler.disassemble import disassemble # Create a circuit to assemble into a qobj q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) # Assemble the circuit into a Qobj qobj = assemble(qc, shots=2000, memory=True) # Disassemble the qobj back into a circuit circuits, run_config_out, headers = disassemble(qobj) """ if qobj.type == "PULSE": return _disassemble_pulse_schedule(qobj) else: return _disassemble_circuit(qobj) def _disassemble_circuit(qobj) -> CircuitModule: run_config = qobj.config.to_dict() # convert lo freq back to Hz qubit_lo_freq = run_config.get("qubit_lo_freq", []) if qubit_lo_freq: run_config["qubit_lo_freq"] = [freq * 1e9 for freq in qubit_lo_freq] meas_lo_freq = run_config.get("meas_lo_freq", []) if meas_lo_freq: run_config["meas_lo_freq"] = [freq * 1e9 for freq in meas_lo_freq] user_qobj_header = qobj.header.to_dict() return CircuitModule((_experiments_to_circuits(qobj), run_config, user_qobj_header)) def _qobj_to_circuit_cals(qobj, pulse_lib): """Return circuit calibrations dictionary from qobj/exp config calibrations.""" qobj_cals = qobj.config.calibrations.to_dict()["gates"] converter = QobjToInstructionConverter(pulse_lib) qc_cals = {} for gate in qobj_cals: config = (tuple(gate["qubits"]), tuple(gate["params"])) cal = { config: pulse.Schedule( name="{} {} {}".format(gate["name"], str(gate["params"]), str(gate["qubits"])) ) } for instruction in gate["instructions"]: qobj_instruction = PulseQobjInstruction.from_dict(instruction) schedule = converter(qobj_instruction) cal[config] = cal[config].insert(schedule.ch_start_time(), schedule) if gate["name"] in qc_cals: qc_cals[gate["name"]].update(cal) else: qc_cals[gate["name"]] = cal return qc_cals def _experiments_to_circuits(qobj): """Return a list of QuantumCircuit object(s) from a qobj. Args: qobj (Qobj): The Qobj object to convert to QuantumCircuits Returns: list: A list of QuantumCircuit objects from the qobj """ if not qobj.experiments: return None circuits = [] for exp in qobj.experiments: quantum_registers = [QuantumRegister(i[1], name=i[0]) for i in exp.header.qreg_sizes] classical_registers = [ClassicalRegister(i[1], name=i[0]) for i in exp.header.creg_sizes] circuit = QuantumCircuit(*quantum_registers, *classical_registers, name=exp.header.name) qreg_dict = collections.OrderedDict() creg_dict = collections.OrderedDict() for reg in quantum_registers: qreg_dict[reg.name] = reg for reg in classical_registers: creg_dict[reg.name] = reg conditional = {} for i in exp.instructions: name = i.name qubits = [] params = getattr(i, "params", []) try: for qubit in i.qubits: qubit_label = exp.header.qubit_labels[qubit] qubits.append(qreg_dict[qubit_label[0]][qubit_label[1]]) except Exception: # pylint: disable=broad-except pass clbits = [] try: for clbit in i.memory: clbit_label = exp.header.clbit_labels[clbit] clbits.append(creg_dict[clbit_label[0]][clbit_label[1]]) except Exception: # pylint: disable=broad-except pass if hasattr(circuit, name): instr_method = getattr(circuit, name) if i.name in ["snapshot"]: _inst = instr_method( i.label, snapshot_type=i.snapshot_type, qubits=qubits, params=params ) elif i.name == "initialize": _inst = instr_method(params, qubits) elif i.name == "isometry": _inst = instr_method(*params, qubits, clbits) elif i.name in ["mcx", "mcu1", "mcp"]: _inst = instr_method(*params, qubits[:-1], qubits[-1], *clbits) else: _inst = instr_method(*params, *qubits, *clbits) elif name == "bfunc": conditional["value"] = int(i.val, 16) full_bit_size = sum(creg_dict[x].size for x in creg_dict) mask_map = {} raw_map = {} raw = [] for creg in creg_dict: size = creg_dict[creg].size reg_raw = [1] * size if not raw: raw = reg_raw else: for pos, val in enumerate(raw): if val == 1: raw[pos] = 0 raw = reg_raw + raw mask = [0] * (full_bit_size - len(raw)) + raw raw_map[creg] = mask mask_map[int("".join(str(x) for x in mask), 2)] = creg if bin(int(i.mask, 16)).count("1") == 1: # The condition is on a single bit. This might be a single-bit condition, or it # might be a register of length one. The case that it's a single-bit condition # in a register of length one is ambiguous, and we choose to return a condition # on the register. This may not match the input circuit exactly, but is at # least equivalent. cbit = int(math.log2(int(i.mask, 16))) for reg in creg_dict.values(): size = reg.size if cbit >= size: cbit -= size else: conditional["register"] = reg if reg.size == 1 else reg[cbit] break mask_str = bin(int(i.mask, 16))[2:].zfill(full_bit_size) mask = [int(item) for item in list(mask_str)] else: creg = mask_map[int(i.mask, 16)] conditional["register"] = creg_dict[creg] mask = raw_map[creg] val = int(i.val, 16) for j in reversed(mask): if j == 0: val = val >> 1 else: conditional["value"] = val break else: _inst = temp_opaque_instruction = Instruction( name=name, num_qubits=len(qubits), num_clbits=len(clbits), params=params ) circuit.append(temp_opaque_instruction, qubits, clbits) if conditional and name != "bfunc": _inst.c_if(conditional["register"], conditional["value"]) conditional = {} pulse_lib = qobj.config.pulse_library if hasattr(qobj.config, "pulse_library") else [] # The dict update method did not work here; could investigate in the future if hasattr(qobj.config, "calibrations"): circuit.calibrations = dict( **circuit.calibrations, **_qobj_to_circuit_cals(qobj, pulse_lib) ) if hasattr(exp.config, "calibrations"): circuit.calibrations = dict( **circuit.calibrations, **_qobj_to_circuit_cals(exp, pulse_lib) ) circuits.append(circuit) return circuits def _disassemble_pulse_schedule(qobj) -> PulseModule: run_config = qobj.config.to_dict() run_config.pop("pulse_library") qubit_lo_freq = run_config.get("qubit_lo_freq") if qubit_lo_freq: run_config["qubit_lo_freq"] = [freq * 1e9 for freq in qubit_lo_freq] meas_lo_freq = run_config.get("meas_lo_freq") if meas_lo_freq: run_config["meas_lo_freq"] = [freq * 1e9 for freq in meas_lo_freq] user_qobj_header = qobj.header.to_dict() # extract schedule lo settings schedule_los = [] for program in qobj.experiments: program_los = {} if hasattr(program, "config"): if hasattr(program.config, "qubit_lo_freq"): for i, lo in enumerate(program.config.qubit_lo_freq): program_los[pulse.DriveChannel(i)] = lo * 1e9 if hasattr(program.config, "meas_lo_freq"): for i, lo in enumerate(program.config.meas_lo_freq): program_los[pulse.MeasureChannel(i)] = lo * 1e9 schedule_los.append(program_los) if any(schedule_los): run_config["schedule_los"] = schedule_los return PulseModule((_experiments_to_schedules(qobj), run_config, user_qobj_header)) def _experiments_to_schedules(qobj) -> List[pulse.Schedule]: """Return a list of :class:`qiskit.pulse.Schedule` object(s) from a qobj. Args: qobj (Qobj): The Qobj object to convert to pulse schedules. Returns: A list of :class:`qiskit.pulse.Schedule` objects from the qobj Raises: pulse.PulseError: If a parameterized instruction is supplied. """ converter = QobjToInstructionConverter(qobj.config.pulse_library) schedules = [] for program in qobj.experiments: insts = [] for inst in program.instructions: insts.append(converter(inst)) schedule = pulse.Schedule(*insts) schedules.append(schedule) return schedules
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Code from commutative_analysis pass that checks commutation relations between DAG nodes.""" from functools import lru_cache from typing import List, Union import numpy as np from qiskit import QiskitError from qiskit.circuit import Qubit from qiskit.circuit.operation import Operation from qiskit.circuit.controlflow import CONTROL_FLOW_OP_NAMES from qiskit.quantum_info.operators import Operator _skipped_op_names = {"measure", "reset", "delay", "initialize"} _no_cache_op_names = {"annotated"} @lru_cache(maxsize=None) def _identity_op(num_qubits): """Cached identity matrix""" return Operator( np.eye(2**num_qubits), input_dims=(2,) * num_qubits, output_dims=(2,) * num_qubits ) class CommutationChecker: """This code is essentially copy-pasted from commutative_analysis.py. This code cleverly hashes commutativity and non-commutativity results between DAG nodes and seems quite efficient for large Clifford circuits. They may be other possible efficiency improvements: using rule-based commutativity analysis, evicting from the cache less useful entries, etc. """ def __init__(self, standard_gate_commutations: dict = None, cache_max_entries: int = 10**6): super().__init__() if standard_gate_commutations is None: self._standard_commutations = {} else: self._standard_commutations = standard_gate_commutations self._cache_max_entries = cache_max_entries # self._cached_commutation has the same structure as standard_gate_commutations, i.e. a # dict[pair of gate names][relative placement][tuple of gate parameters] := True/False self._cached_commutations = {} self._current_cache_entries = 0 self._cache_miss = 0 self._cache_hit = 0 def commute( self, op1: Operation, qargs1: List, cargs1: List, op2: Operation, qargs2: List, cargs2: List, max_num_qubits: int = 3, ) -> bool: """ Checks if two Operations commute. The return value of `True` means that the operations truly commute, and the return value of `False` means that either the operations do not commute or that the commutation check was skipped (for example, when the operations have conditions or have too many qubits). Args: op1: first operation. qargs1: first operation's qubits. cargs1: first operation's clbits. op2: second operation. qargs2: second operation's qubits. cargs2: second operation's clbits. max_num_qubits: the maximum number of qubits to consider, the check may be skipped if the number of qubits for either operation exceeds this amount. Returns: bool: whether two operations commute. """ structural_commutation = _commutation_precheck( op1, qargs1, cargs1, op2, qargs2, cargs2, max_num_qubits ) if structural_commutation is not None: return structural_commutation first_op_tuple, second_op_tuple = _order_operations( op1, qargs1, cargs1, op2, qargs2, cargs2 ) first_op, first_qargs, _ = first_op_tuple second_op, second_qargs, _ = second_op_tuple skip_cache = first_op.name in _no_cache_op_names or second_op.name in _no_cache_op_names if skip_cache: return _commute_matmul(first_op, first_qargs, second_op, second_qargs) commutation_lookup = self.check_commutation_entries( first_op, first_qargs, second_op, second_qargs ) if commutation_lookup is not None: return commutation_lookup # Compute commutation via matrix multiplication is_commuting = _commute_matmul(first_op, first_qargs, second_op, second_qargs) # Store result in this session's commutation_library # TODO implement LRU cache or similar # Rebuild cache if current cache exceeded max size if self._current_cache_entries >= self._cache_max_entries: self.clear_cached_commutations() first_params = getattr(first_op, "params", []) second_params = getattr(second_op, "params", []) if len(first_params) > 0 or len(second_params) > 0: self._cached_commutations.setdefault((first_op.name, second_op.name), {}).setdefault( _get_relative_placement(first_qargs, second_qargs), {} )[ (_hashable_parameters(first_params), _hashable_parameters(second_params)) ] = is_commuting else: self._cached_commutations.setdefault((first_op.name, second_op.name), {})[ _get_relative_placement(first_qargs, second_qargs) ] = is_commuting self._current_cache_entries += 1 return is_commuting def num_cached_entries(self): """Returns number of cached entries""" return self._current_cache_entries def clear_cached_commutations(self): """Clears the dictionary holding cached commutations""" self._current_cache_entries = 0 self._cache_miss = 0 self._cache_hit = 0 self._cached_commutations = {} def check_commutation_entries( self, first_op: Operation, first_qargs: List, second_op: Operation, second_qargs: List, ) -> Union[bool, None]: """Returns stored commutation relation if any Args: first_op: first operation. first_qargs: first operation's qubits. second_op: second operation. second_qargs: second operation's qubits. Return: bool: True if the gates commute and false if it is not the case. """ # We don't precompute commutations for parameterized gates, yet commutation = _query_commutation( first_op, first_qargs, second_op, second_qargs, self._standard_commutations, ) if commutation is not None: return commutation commutation = _query_commutation( first_op, first_qargs, second_op, second_qargs, self._cached_commutations, ) if commutation is None: self._cache_miss += 1 else: self._cache_hit += 1 return commutation def _hashable_parameters(params): """Convert the parameters of a gate into a hashable format for lookup in a dictionary. This aims to be fast in common cases, and is not intended to work outside of the lifetime of a single commutation pass; it does not handle mutable state correctly if the state is actually changed.""" try: hash(params) return params except TypeError: pass if isinstance(params, (list, tuple)): return tuple(_hashable_parameters(x) for x in params) if isinstance(params, np.ndarray): # Using the bytes of the matrix as key is runtime efficient but requires more space: 128 bits # times the number of parameters instead of a single 64 bit id. However, by using the bytes as # an id, we can reuse the cached commutations between different passes. return (np.ndarray, params.tobytes()) # Catch anything else with a slow conversion. return ("fallback", str(params)) def is_commutation_supported(op): """ Filter operations whose commutation is not supported due to bugs in transpiler passes invoking commutation analysis. Args: op (Operation): operation to be checked for commutation relation Return: True if determining the commutation of op is currently supported """ # Bug in CommutativeCancellation, e.g. see gh-8553 if getattr(op, "condition", False): return False # Commutation of ControlFlow gates also not supported yet. This may be pending a control flow graph. if op.name in CONTROL_FLOW_OP_NAMES: return False return True def is_commutation_skipped(op, qargs, max_num_qubits): """ Filter operations whose commutation will not be determined. Args: op (Operation): operation to be checked for commutation relation qargs (List): operation qubits max_num_qubits (int): the maximum number of qubits to consider, the check may be skipped if the number of qubits for either operation exceeds this amount. Return: True if determining the commutation of op is currently not supported """ if ( len(qargs) > max_num_qubits or getattr(op, "_directive", False) or op.name in _skipped_op_names ): return True if getattr(op, "is_parameterized", False) and op.is_parameterized(): return True # we can proceed if op has defined: to_operator, to_matrix and __array__, or if its definition can be # recursively resolved by operations that have a matrix. We check this by constructing an Operator. if (hasattr(op, "to_matrix") and hasattr(op, "__array__")) or hasattr(op, "to_operator"): return False return False def _commutation_precheck( op1: Operation, qargs1: List, cargs1: List, op2: Operation, qargs2: List, cargs2: List, max_num_qubits, ): if not is_commutation_supported(op1) or not is_commutation_supported(op2): return False if set(qargs1).isdisjoint(qargs2) and set(cargs1).isdisjoint(cargs2): return True if is_commutation_skipped(op1, qargs1, max_num_qubits) or is_commutation_skipped( op2, qargs2, max_num_qubits ): return False return None def _get_relative_placement(first_qargs: List[Qubit], second_qargs: List[Qubit]) -> tuple: """Determines the relative qubit placement of two gates. Note: this is NOT symmetric. Args: first_qargs (DAGOpNode): first gate second_qargs (DAGOpNode): second gate Return: A tuple that describes the relative qubit placement: E.g. _get_relative_placement(CX(0, 1), CX(1, 2)) would return (None, 0) as there is no overlap on the first qubit of the first gate but there is an overlap on the second qubit of the first gate, i.e. qubit 0 of the second gate. Likewise, _get_relative_placement(CX(1, 2), CX(0, 1)) would return (1, None) """ qubits_g2 = {q_g1: i_g1 for i_g1, q_g1 in enumerate(second_qargs)} return tuple(qubits_g2.get(q_g0, None) for q_g0 in first_qargs) @lru_cache(maxsize=10**3) def _persistent_id(op_name: str) -> int: """Returns an integer id of a string that is persistent over different python executions (note that hash() can not be used, i.e. its value can change over two python executions) Args: op_name (str): The string whose integer id should be determined. Return: The integer id of the input string. """ return int.from_bytes(bytes(op_name, encoding="utf-8"), byteorder="big", signed=True) def _order_operations( op1: Operation, qargs1: List, cargs1: List, op2: Operation, qargs2: List, cargs2: List ): """Orders two operations in a canonical way that is persistent over @different python versions and executions Args: op1: first operation. qargs1: first operation's qubits. cargs1: first operation's clbits. op2: second operation. qargs2: second operation's qubits. cargs2: second operation's clbits. Return: The input operations in a persistent, canonical order. """ op1_tuple = (op1, qargs1, cargs1) op2_tuple = (op2, qargs2, cargs2) least_qubits_op, most_qubits_op = ( (op1_tuple, op2_tuple) if op1.num_qubits < op2.num_qubits else (op2_tuple, op1_tuple) ) # prefer operation with the least number of qubits as first key as this results in shorter keys if op1.num_qubits != op2.num_qubits: return least_qubits_op, most_qubits_op else: return ( (op1_tuple, op2_tuple) if _persistent_id(op1.name) < _persistent_id(op2.name) else (op2_tuple, op1_tuple) ) def _query_commutation( first_op: Operation, first_qargs: List, second_op: Operation, second_qargs: List, _commutation_lib: dict, ) -> Union[bool, None]: """Queries and returns the commutation of a pair of operations from a provided commutation library Args: first_op: first operation. first_qargs: first operation's qubits. first_cargs: first operation's clbits. second_op: second operation. second_qargs: second operation's qubits. second_cargs: second operation's clbits. _commutation_lib (dict): dictionary of commutation relations Return: True if first_op and second_op commute, False if they do not commute and None if the commutation is not in the library """ commutation = _commutation_lib.get((first_op.name, second_op.name), None) # Return here if the commutation is constant over all relative placements of the operations if commutation is None or isinstance(commutation, bool): return commutation # If we arrive here, there is an entry in the commutation library but it depends on the # placement of the operations and also possibly on operation parameters if isinstance(commutation, dict): commutation_after_placement = commutation.get( _get_relative_placement(first_qargs, second_qargs), None ) # if we have another dict in commutation_after_placement, commutation depends on params if isinstance(commutation_after_placement, dict): # Param commutation entry exists and must be a dict first_params = getattr(first_op, "params", []) second_params = getattr(second_op, "params", []) return commutation_after_placement.get( (_hashable_parameters(first_params), _hashable_parameters(second_params)), None, ) else: # queried commutation is True, False or None return commutation_after_placement else: raise ValueError("Expected commutation to be None, bool or a dict") def _commute_matmul( first_ops: Operation, first_qargs: List, second_op: Operation, second_qargs: List ): qarg = {q: i for i, q in enumerate(first_qargs)} num_qubits = len(qarg) for q in second_qargs: if q not in qarg: qarg[q] = num_qubits num_qubits += 1 first_qarg = tuple(qarg[q] for q in first_qargs) second_qarg = tuple(qarg[q] for q in second_qargs) # try to generate an Operator out of op, if this succeeds we can determine commutativity, otherwise # return false try: operator_1 = Operator( first_ops, input_dims=(2,) * len(first_qarg), output_dims=(2,) * len(first_qarg) ) operator_2 = Operator( second_op, input_dims=(2,) * len(second_qarg), output_dims=(2,) * len(second_qarg) ) except QiskitError: return False if first_qarg == second_qarg: # Use full composition if possible to get the fastest matmul paths. op12 = operator_1.compose(operator_2) op21 = operator_2.compose(operator_1) else: # Expand operator_1 to be large enough to contain operator_2 as well; this relies on qargs1 # being the lowest possible indices so the identity can be tensored before it. extra_qarg2 = num_qubits - len(first_qarg) if extra_qarg2: id_op = _identity_op(extra_qarg2) operator_1 = id_op.tensor(operator_1) op12 = operator_1.compose(operator_2, qargs=second_qarg, front=False) op21 = operator_1.compose(operator_2, qargs=second_qarg, front=True) ret = op12 == op21 return ret
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Controlled unitary gate.""" from __future__ import annotations import copy from typing import Optional, Union from qiskit.circuit.exceptions import CircuitError # pylint: disable=cyclic-import from .quantumcircuit import QuantumCircuit from .gate import Gate from .quantumregister import QuantumRegister from ._utils import _ctrl_state_to_int class ControlledGate(Gate): """Controlled unitary gate.""" def __init__( self, name: str, num_qubits: int, params: list, label: Optional[str] = None, num_ctrl_qubits: Optional[int] = 1, definition: Optional["QuantumCircuit"] = None, ctrl_state: Optional[Union[int, str]] = None, base_gate: Optional[Gate] = None, ): """Create a new ControlledGate. In the new gate the first ``num_ctrl_qubits`` of the gate are the controls. Args: name: The name of the gate. num_qubits: The number of qubits the gate acts on. params: A list of parameters for the gate. label: An optional label for the gate. num_ctrl_qubits: Number of control qubits. definition: A list of gate rules for implementing this gate. The elements of the list are tuples of (:meth:`~qiskit.circuit.Gate`, [qubit_list], [clbit_list]). ctrl_state: The control state in decimal or as a bitstring (e.g. '111'). If specified as a bitstring the length must equal num_ctrl_qubits, MSB on left. If None, use 2**num_ctrl_qubits-1. base_gate: Gate object to be controlled. Raises: CircuitError: If ``num_ctrl_qubits`` >= ``num_qubits``. CircuitError: ctrl_state < 0 or ctrl_state > 2**num_ctrl_qubits. Examples: Create a controlled standard gate and apply it to a circuit. .. plot:: :include-source: from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qr = QuantumRegister(3) qc = QuantumCircuit(qr) c3h_gate = HGate().control(2) qc.append(c3h_gate, qr) qc.draw('mpl') Create a controlled custom gate and apply it to a circuit. .. plot:: :include-source: from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qc1 = QuantumCircuit(2) qc1.x(0) qc1.h(1) custom = qc1.to_gate().control(2) qc2 = QuantumCircuit(4) qc2.append(custom, [0, 3, 1, 2]) qc2.draw('mpl') """ self.base_gate = None if base_gate is None else base_gate.copy() super().__init__(name, num_qubits, params, label=label) self._num_ctrl_qubits = 1 self.num_ctrl_qubits = num_ctrl_qubits self.definition = copy.deepcopy(definition) self._ctrl_state = None self.ctrl_state = ctrl_state self._name = name @property def definition(self) -> QuantumCircuit: """Return definition in terms of other basic gates. If the gate has open controls, as determined from `self.ctrl_state`, the returned definition is conjugated with X without changing the internal `_definition`. """ if self._open_ctrl: closed_gate = self.copy() closed_gate.ctrl_state = None bit_ctrl_state = bin(self.ctrl_state)[2:].zfill(self.num_ctrl_qubits) qreg = QuantumRegister(self.num_qubits, "q") qc_open_ctrl = QuantumCircuit(qreg) for qind, val in enumerate(bit_ctrl_state[::-1]): if val == "0": qc_open_ctrl.x(qind) qc_open_ctrl.append(closed_gate, qargs=qreg[:]) for qind, val in enumerate(bit_ctrl_state[::-1]): if val == "0": qc_open_ctrl.x(qind) return qc_open_ctrl else: return super().definition @definition.setter def definition(self, excited_def: "QuantumCircuit"): """Set controlled gate definition with closed controls. Args: excited_def: The circuit with all closed controls. """ self._definition = excited_def @property def name(self) -> str: """Get name of gate. If the gate has open controls the gate name will become: <original_name_o<ctrl_state> where <original_name> is the gate name for the default case of closed control qubits and <ctrl_state> is the integer value of the control state for the gate. """ if self._open_ctrl: return f"{self._name}_o{self.ctrl_state}" else: return self._name @name.setter def name(self, name_str): """Set the name of the gate. Note the reported name may differ from the set name if the gate has open controls. """ self._name = name_str @property def num_ctrl_qubits(self): """Get number of control qubits. Returns: int: The number of control qubits for the gate. """ return self._num_ctrl_qubits @num_ctrl_qubits.setter def num_ctrl_qubits(self, num_ctrl_qubits): """Set the number of control qubits. Args: num_ctrl_qubits (int): The number of control qubits. Raises: CircuitError: ``num_ctrl_qubits`` is not an integer in ``[1, num_qubits]``. """ if num_ctrl_qubits != int(num_ctrl_qubits): raise CircuitError("The number of control qubits must be an integer.") num_ctrl_qubits = int(num_ctrl_qubits) # This is a range rather than an equality limit because some controlled gates represent a # controlled version of the base gate whose definition also uses auxiliary qubits. upper_limit = self.num_qubits - getattr(self.base_gate, "num_qubits", 0) if num_ctrl_qubits < 1 or num_ctrl_qubits > upper_limit: limit = "num_qubits" if self.base_gate is None else "num_qubits - base_gate.num_qubits" raise CircuitError(f"The number of control qubits must be in `[1, {limit}]`.") self._num_ctrl_qubits = num_ctrl_qubits @property def ctrl_state(self) -> int: """Return the control state of the gate as a decimal integer.""" return self._ctrl_state @ctrl_state.setter def ctrl_state(self, ctrl_state: Union[int, str, None]): """Set the control state of this gate. Args: ctrl_state: The control state of the gate. Raises: CircuitError: ctrl_state is invalid. """ self._ctrl_state = _ctrl_state_to_int(ctrl_state, self.num_ctrl_qubits) @property def params(self): """Get parameters from base_gate. Returns: list: List of gate parameters. Raises: CircuitError: Controlled gate does not define a base gate """ if self.base_gate: return self.base_gate.params else: raise CircuitError("Controlled gate does not define base gate for extracting params") @params.setter def params(self, parameters): """Set base gate parameters. Args: parameters (list): The list of parameters to set. Raises: CircuitError: If controlled gate does not define a base gate. """ if self.base_gate: self.base_gate.params = parameters else: raise CircuitError("Controlled gate does not define base gate for extracting params") def __deepcopy__(self, _memo=None): cpy = copy.copy(self) cpy.base_gate = self.base_gate.copy() if self._definition: cpy._definition = copy.deepcopy(self._definition, _memo) return cpy @property def _open_ctrl(self) -> bool: """Return whether gate has any open controls""" return self.ctrl_state < 2**self.num_ctrl_qubits - 1 def __eq__(self, other) -> bool: return ( isinstance(other, ControlledGate) and self.num_ctrl_qubits == other.num_ctrl_qubits and self.ctrl_state == other.ctrl_state and self.base_gate == other.base_gate and self.num_qubits == other.num_qubits and self.num_clbits == other.num_clbits and self.definition == other.definition ) def inverse(self) -> "ControlledGate": """Invert this gate by calling inverse on the base gate.""" return self.base_gate.inverse().control(self.num_ctrl_qubits, ctrl_state=self.ctrl_state)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Quantum Operation Mixin.""" from abc import ABC, abstractmethod class Operation(ABC): """Quantum Operation Interface Class. For objects that can be added to a :class:`~qiskit.circuit.QuantumCircuit`. These objects include :class:`~qiskit.circuit.Gate`, :class:`~qiskit.circuit.Reset`, :class:`~qiskit.circuit.Barrier`, :class:`~qiskit.circuit.Measure`, and operators such as :class:`~qiskit.quantum_info.Clifford`. The main purpose is to add an :class:`~qiskit.circuit.Operation` to a :class:`~qiskit.circuit.QuantumCircuit` without synthesizing it before the transpilation. Example: Add a Clifford and a Toffoli gate to a QuantumCircuit. .. plot:: :include-source: from qiskit import QuantumCircuit from qiskit.quantum_info import Clifford, random_clifford qc = QuantumCircuit(3) cliff = random_clifford(2) qc.append(cliff, [0, 1]) qc.ccx(0, 1, 2) qc.draw('mpl') """ __slots__ = () @property @abstractmethod def name(self): """Unique string identifier for operation type.""" raise NotImplementedError @property @abstractmethod def num_qubits(self): """Number of qubits.""" raise NotImplementedError @property @abstractmethod def num_clbits(self): """Number of classical bits.""" raise NotImplementedError
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=bad-docstring-quotes,invalid-name """Quantum circuit object.""" from __future__ import annotations import collections.abc import copy import itertools import multiprocessing as mp import string import re import warnings import typing from collections import OrderedDict, defaultdict, namedtuple from typing import ( Union, Optional, Tuple, Type, TypeVar, Sequence, Callable, Mapping, Iterable, Any, DefaultDict, Literal, overload, ) import numpy as np from qiskit.exceptions import QiskitError from qiskit.utils.multiprocessing import is_main_process from qiskit.circuit.instruction import Instruction from qiskit.circuit.gate import Gate from qiskit.circuit.parameter import Parameter from qiskit.circuit.exceptions import CircuitError from qiskit.utils import optionals as _optionals from . import _classical_resource_map from ._utils import sort_parameters from .classical import expr from .parameterexpression import ParameterExpression, ParameterValueType from .quantumregister import QuantumRegister, Qubit, AncillaRegister, AncillaQubit from .classicalregister import ClassicalRegister, Clbit from .parametertable import ParameterReferences, ParameterTable, ParameterView from .parametervector import ParameterVector from .instructionset import InstructionSet from .operation import Operation from .register import Register from .bit import Bit from .quantumcircuitdata import QuantumCircuitData, CircuitInstruction from .delay import Delay from .measure import Measure from .reset import Reset from .tools import pi_check if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import from qiskit.transpiler.layout import TranspileLayout # pylint: disable=cyclic-import BitLocations = namedtuple("BitLocations", ("index", "registers")) # The following types are not marked private to avoid leaking this "private/public" abstraction out # into the documentation. They are not imported by circuit.__init__, nor are they meant to be. # Arbitrary type variables for marking up generics. S = TypeVar("S") T = TypeVar("T") # Types that can be coerced to a valid Qubit specifier in a circuit. QubitSpecifier = Union[ Qubit, QuantumRegister, int, slice, Sequence[Union[Qubit, int]], ] # Types that can be coerced to a valid Clbit specifier in a circuit. ClbitSpecifier = Union[ Clbit, ClassicalRegister, int, slice, Sequence[Union[Clbit, int]], ] # Generic type which is either :obj:`~Qubit` or :obj:`~Clbit`, used to specify types of functions # which operate on either type of bit, but not both at the same time. BitType = TypeVar("BitType", Qubit, Clbit) # Regex pattern to match valid OpenQASM identifiers VALID_QASM2_IDENTIFIER = re.compile("[a-z][a-zA-Z_0-9]*") QASM2_RESERVED = { "OPENQASM", "qreg", "creg", "include", "gate", "opaque", "U", "CX", "measure", "reset", "if", "barrier", } class QuantumCircuit: """Create a new circuit. A circuit is a list of instructions bound to some registers. Args: regs (list(:class:`~.Register`) or list(``int``) or list(list(:class:`~.Bit`))): The registers to be included in the circuit. * If a list of :class:`~.Register` objects, represents the :class:`.QuantumRegister` and/or :class:`.ClassicalRegister` objects to include in the circuit. For example: * ``QuantumCircuit(QuantumRegister(4))`` * ``QuantumCircuit(QuantumRegister(4), ClassicalRegister(3))`` * ``QuantumCircuit(QuantumRegister(4, 'qr0'), QuantumRegister(2, 'qr1'))`` * If a list of ``int``, the amount of qubits and/or classical bits to include in the circuit. It can either be a single int for just the number of quantum bits, or 2 ints for the number of quantum bits and classical bits, respectively. For example: * ``QuantumCircuit(4) # A QuantumCircuit with 4 qubits`` * ``QuantumCircuit(4, 3) # A QuantumCircuit with 4 qubits and 3 classical bits`` * If a list of python lists containing :class:`.Bit` objects, a collection of :class:`.Bit` s to be added to the circuit. name (str): the name of the quantum circuit. If not set, an automatically generated string will be assigned. global_phase (float or ParameterExpression): The global phase of the circuit in radians. metadata (dict): Arbitrary key value metadata to associate with the circuit. This gets stored as free-form data in a dict in the :attr:`~qiskit.circuit.QuantumCircuit.metadata` attribute. It will not be directly used in the circuit. Raises: CircuitError: if the circuit name, if given, is not valid. Examples: Construct a simple Bell state circuit. .. plot:: :include-source: from qiskit import QuantumCircuit qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) qc.draw('mpl') Construct a 5-qubit GHZ circuit. .. code-block:: from qiskit import QuantumCircuit qc = QuantumCircuit(5) qc.h(0) qc.cx(0, range(1, 5)) qc.measure_all() Construct a 4-qubit Bernstein-Vazirani circuit using registers. .. plot:: :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl') """ instances = 0 prefix = "circuit" # Class variable OPENQASM header header = "OPENQASM 2.0;" extension_lib = 'include "qelib1.inc";' def __init__( self, *regs: Register | int | Sequence[Bit], name: str | None = None, global_phase: ParameterValueType = 0, metadata: dict | None = None, ): if any(not isinstance(reg, (list, QuantumRegister, ClassicalRegister)) for reg in regs): # check if inputs are integers, but also allow e.g. 2.0 try: valid_reg_size = all(reg == int(reg) for reg in regs) except (ValueError, TypeError): valid_reg_size = False if not valid_reg_size: raise CircuitError( "Circuit args must be Registers or integers. (%s '%s' was " "provided)" % ([type(reg).__name__ for reg in regs], regs) ) regs = tuple(int(reg) for reg in regs) # cast to int self._base_name = None if name is None: self._base_name = self.cls_prefix() self._name_update() elif not isinstance(name, str): raise CircuitError( "The circuit name should be a string (or None to auto-generate a name)." ) else: self._base_name = name self.name = name self._increment_instances() # Data contains a list of instructions and their contexts, # in the order they were applied. self._data: list[CircuitInstruction] = [] self._op_start_times = None # A stack to hold the instruction sets that are being built up during for-, if- and # while-block construction. These are stored as a stripped down sequence of instructions, # and sets of qubits and clbits, rather than a full QuantumCircuit instance because the # builder interfaces need to wait until they are completed before they can fill in things # like `break` and `continue`. This is because these instructions need to "operate" on the # full width of bits, but the builder interface won't know what bits are used until the end. self._control_flow_scopes: list[ "qiskit.circuit.controlflow.builder.ControlFlowBuilderBlock" ] = [] self.qregs: list[QuantumRegister] = [] self.cregs: list[ClassicalRegister] = [] self._qubits: list[Qubit] = [] self._clbits: list[Clbit] = [] # Dict mapping Qubit or Clbit instances to tuple comprised of 0) the # corresponding index in circuit.{qubits,clbits} and 1) a list of # Register-int pairs for each Register containing the Bit and its index # within that register. self._qubit_indices: dict[Qubit, BitLocations] = {} self._clbit_indices: dict[Clbit, BitLocations] = {} self._ancillas: list[AncillaQubit] = [] self._calibrations: DefaultDict[str, dict[tuple, Any]] = defaultdict(dict) self.add_register(*regs) # Parameter table tracks instructions with variable parameters. self._parameter_table = ParameterTable() # Cache to avoid re-sorting parameters self._parameters = None self._layout = None self._global_phase: ParameterValueType = 0 self.global_phase = global_phase self.duration = None self.unit = "dt" self.metadata = {} if metadata is None else metadata @staticmethod def from_instructions( instructions: Iterable[ CircuitInstruction | tuple[qiskit.circuit.Instruction] | tuple[qiskit.circuit.Instruction, Iterable[Qubit]] | tuple[qiskit.circuit.Instruction, Iterable[Qubit], Iterable[Clbit]] ], *, qubits: Iterable[Qubit] = (), clbits: Iterable[Clbit] = (), name: str | None = None, global_phase: ParameterValueType = 0, metadata: dict | None = None, ) -> "QuantumCircuit": """Construct a circuit from an iterable of CircuitInstructions. Args: instructions: The instructions to add to the circuit. qubits: Any qubits to add to the circuit. This argument can be used, for example, to enforce a particular ordering of qubits. clbits: Any classical bits to add to the circuit. This argument can be used, for example, to enforce a particular ordering of classical bits. name: The name of the circuit. global_phase: The global phase of the circuit in radians. metadata: Arbitrary key value metadata to associate with the circuit. Returns: The quantum circuit. """ circuit = QuantumCircuit(name=name, global_phase=global_phase, metadata=metadata) added_qubits = set() added_clbits = set() if qubits: qubits = list(qubits) circuit.add_bits(qubits) added_qubits.update(qubits) if clbits: clbits = list(clbits) circuit.add_bits(clbits) added_clbits.update(clbits) for instruction in instructions: if not isinstance(instruction, CircuitInstruction): instruction = CircuitInstruction(*instruction) qubits = [qubit for qubit in instruction.qubits if qubit not in added_qubits] clbits = [clbit for clbit in instruction.clbits if clbit not in added_clbits] circuit.add_bits(qubits) circuit.add_bits(clbits) added_qubits.update(qubits) added_clbits.update(clbits) circuit._append(instruction) return circuit @property def layout(self) -> Optional[TranspileLayout]: r"""Return any associated layout information about the circuit This attribute contains an optional :class:`~.TranspileLayout` object. This is typically set on the output from :func:`~.transpile` or :meth:`.PassManager.run` to retain information about the permutations caused on the input circuit by transpilation. There are two types of permutations caused by the :func:`~.transpile` function, an initial layout which permutes the qubits based on the selected physical qubits on the :class:`~.Target`, and a final layout which is an output permutation caused by :class:`~.SwapGate`\s inserted during routing. """ return self._layout @property def data(self) -> QuantumCircuitData: """Return the circuit data (instructions and context). Returns: QuantumCircuitData: a list-like object containing the :class:`.CircuitInstruction`\\ s for each instruction. """ return QuantumCircuitData(self) @data.setter def data(self, data_input: Iterable): """Sets the circuit data from a list of instructions and context. Args: data_input (Iterable): A sequence of instructions with their execution contexts. The elements must either be instances of :class:`.CircuitInstruction` (preferred), or a 3-tuple of ``(instruction, qargs, cargs)`` (legacy). In the legacy format, ``instruction`` must be an :class:`~.circuit.Instruction`, while ``qargs`` and ``cargs`` must be iterables of :class:`.Qubit` or :class:`.Clbit` specifiers (similar to the allowed forms in calls to :meth:`append`). """ # If data_input is QuantumCircuitData(self), clearing self._data # below will also empty data_input, so make a shallow copy first. data_input = list(data_input) self._data = [] self._parameter_table = ParameterTable() if not data_input: return if isinstance(data_input[0], CircuitInstruction): for instruction in data_input: self.append(instruction) else: for instruction, qargs, cargs in data_input: self.append(instruction, qargs, cargs) @property def op_start_times(self) -> list[int]: """Return a list of operation start times. This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit. Returns: List of integers representing instruction start times. The index corresponds to the index of instruction in :attr:`QuantumCircuit.data`. Raises: AttributeError: When circuit is not scheduled. """ if self._op_start_times is None: raise AttributeError( "This circuit is not scheduled. " "To schedule it run the circuit through one of the transpiler scheduling passes." ) return self._op_start_times @property def calibrations(self) -> dict: """Return calibration dictionary. The custom pulse definition of a given gate is of the form ``{'gate_name': {(qubits, params): schedule}}`` """ return dict(self._calibrations) @calibrations.setter def calibrations(self, calibrations: dict): """Set the circuit calibration data from a dictionary of calibration definition. Args: calibrations (dict): A dictionary of input in the format ``{'gate_name': {(qubits, gate_params): schedule}}`` """ self._calibrations = defaultdict(dict, calibrations) def has_calibration_for(self, instruction: CircuitInstruction | tuple): """Return True if the circuit has a calibration defined for the instruction context. In this case, the operation does not need to be translated to the device basis. """ if isinstance(instruction, CircuitInstruction): operation = instruction.operation qubits = instruction.qubits else: operation, qubits, _ = instruction if not self.calibrations or operation.name not in self.calibrations: return False qubits = tuple(self.qubits.index(qubit) for qubit in qubits) params = [] for p in operation.params: if isinstance(p, ParameterExpression) and not p.parameters: params.append(float(p)) else: params.append(p) params = tuple(params) return (qubits, params) in self.calibrations[operation.name] @property def metadata(self) -> dict: """The user provided metadata associated with the circuit. The metadata for the circuit is a user provided ``dict`` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit. """ return self._metadata @metadata.setter def metadata(self, metadata: dict | None): """Update the circuit metadata""" if metadata is None: metadata = {} warnings.warn( "Setting metadata to None was deprecated in Terra 0.24.0 and this ability will be " "removed in a future release. Instead, set metadata to an empty dictionary.", DeprecationWarning, stacklevel=2, ) elif not isinstance(metadata, dict): raise TypeError("Only a dictionary is accepted for circuit metadata") self._metadata = metadata def __str__(self) -> str: return str(self.draw(output="text")) def __eq__(self, other) -> bool: if not isinstance(other, QuantumCircuit): return False # TODO: remove the DAG from this function from qiskit.converters import circuit_to_dag return circuit_to_dag(self, copy_operations=False) == circuit_to_dag( other, copy_operations=False ) @classmethod def _increment_instances(cls): cls.instances += 1 @classmethod def cls_instances(cls) -> int: """Return the current number of instances of this class, useful for auto naming.""" return cls.instances @classmethod def cls_prefix(cls) -> str: """Return the prefix to use for auto naming.""" return cls.prefix def _name_update(self) -> None: """update name of instance using instance number""" if not is_main_process(): pid_name = f"-{mp.current_process().pid}" else: pid_name = "" self.name = f"{self._base_name}-{self.cls_instances()}{pid_name}" def has_register(self, register: Register) -> bool: """ Test if this circuit has the register r. Args: register (Register): a quantum or classical register. Returns: bool: True if the register is contained in this circuit. """ has_reg = False if isinstance(register, QuantumRegister) and register in self.qregs: has_reg = True elif isinstance(register, ClassicalRegister) and register in self.cregs: has_reg = True return has_reg def reverse_ops(self) -> "QuantumCircuit": """Reverse the circuit by reversing the order of instructions. This is done by recursively reversing all instructions. It does not invert (adjoint) any gate. Returns: QuantumCircuit: the reversed circuit. Examples: input: .. parsed-literal:: ┌───┐ q_0: ┤ H ├─────■────── └───┘┌────┴─────┐ q_1: ─────┤ RX(1.57) ├ └──────────┘ output: .. parsed-literal:: ┌───┐ q_0: ─────■──────┤ H ├ ┌────┴─────┐└───┘ q_1: ┤ RX(1.57) ├───── └──────────┘ """ reverse_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + "_reverse" ) for instruction in reversed(self.data): reverse_circ._append(instruction.replace(operation=instruction.operation.reverse_ops())) reverse_circ.duration = self.duration reverse_circ.unit = self.unit return reverse_circ def reverse_bits(self) -> "QuantumCircuit": """Return a circuit with the opposite order of wires. The circuit is "vertically" flipped. If a circuit is defined over multiple registers, the resulting circuit will have the same registers but with their order flipped. This method is useful for converting a circuit written in little-endian convention to the big-endian equivalent, and vice versa. Returns: QuantumCircuit: the circuit with reversed bit order. Examples: input: .. parsed-literal:: ┌───┐ a_0: ┤ H ├──■───────────────── └───┘┌─┴─┐ a_1: ─────┤ X ├──■──────────── └───┘┌─┴─┐ a_2: ──────────┤ X ├──■─────── └───┘┌─┴─┐ b_0: ───────────────┤ X ├──■── └───┘┌─┴─┐ b_1: ────────────────────┤ X ├ └───┘ output: .. parsed-literal:: ┌───┐ b_0: ────────────────────┤ X ├ ┌───┐└─┬─┘ b_1: ───────────────┤ X ├──■── ┌───┐└─┬─┘ a_0: ──────────┤ X ├──■─────── ┌───┐└─┬─┘ a_1: ─────┤ X ├──■──────────── ┌───┐└─┬─┘ a_2: ┤ H ├──■───────────────── └───┘ """ circ = QuantumCircuit( list(reversed(self.qubits)), list(reversed(self.clbits)), name=self.name, global_phase=self.global_phase, ) new_qubit_map = circ.qubits[::-1] new_clbit_map = circ.clbits[::-1] for reg in reversed(self.qregs): bits = [new_qubit_map[self.find_bit(qubit).index] for qubit in reversed(reg)] circ.add_register(QuantumRegister(bits=bits, name=reg.name)) for reg in reversed(self.cregs): bits = [new_clbit_map[self.find_bit(clbit).index] for clbit in reversed(reg)] circ.add_register(ClassicalRegister(bits=bits, name=reg.name)) for instruction in self.data: qubits = [new_qubit_map[self.find_bit(qubit).index] for qubit in instruction.qubits] clbits = [new_clbit_map[self.find_bit(clbit).index] for clbit in instruction.clbits] circ._append(instruction.replace(qubits=qubits, clbits=clbits)) return circ def inverse(self) -> "QuantumCircuit": """Invert (take adjoint of) this circuit. This is done by recursively inverting all gates. Returns: QuantumCircuit: the inverted circuit Raises: CircuitError: if the circuit cannot be inverted. Examples: input: .. parsed-literal:: ┌───┐ q_0: ┤ H ├─────■────── └───┘┌────┴─────┐ q_1: ─────┤ RX(1.57) ├ └──────────┘ output: .. parsed-literal:: ┌───┐ q_0: ──────■──────┤ H ├ ┌─────┴─────┐└───┘ q_1: ┤ RX(-1.57) ├───── └───────────┘ """ inverse_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + "_dg", global_phase=-self.global_phase, ) for instruction in reversed(self._data): inverse_circ._append(instruction.replace(operation=instruction.operation.inverse())) return inverse_circ def repeat(self, reps: int) -> "QuantumCircuit": """Repeat this circuit ``reps`` times. Args: reps (int): How often this circuit should be repeated. Returns: QuantumCircuit: A circuit containing ``reps`` repetitions of this circuit. """ repeated_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + f"**{reps}" ) # benefit of appending instructions: decomposing shows the subparts, i.e. the power # is actually `reps` times this circuit, and it is currently much faster than `compose`. if reps > 0: try: # try to append as gate if possible to not disallow to_gate inst: Instruction = self.to_gate() except QiskitError: inst = self.to_instruction() for _ in range(reps): repeated_circ._append(inst, self.qubits, self.clbits) return repeated_circ def power(self, power: float, matrix_power: bool = False) -> "QuantumCircuit": """Raise this circuit to the power of ``power``. If ``power`` is a positive integer and ``matrix_power`` is ``False``, this implementation defaults to calling ``repeat``. Otherwise, if the circuit is unitary, the matrix is computed to calculate the matrix power. Args: power (float): The power to raise this circuit to. matrix_power (bool): If True, the circuit is converted to a matrix and then the matrix power is computed. If False, and ``power`` is a positive integer, the implementation defaults to ``repeat``. Raises: CircuitError: If the circuit needs to be converted to a gate but it is not unitary. Returns: QuantumCircuit: A circuit implementing this circuit raised to the power of ``power``. """ if power >= 0 and isinstance(power, (int, np.integer)) and not matrix_power: return self.repeat(power) # attempt conversion to gate if self.num_parameters > 0: raise CircuitError( "Cannot raise a parameterized circuit to a non-positive power " "or matrix-power, please bind the free parameters: " "{}".format(self.parameters) ) try: gate = self.to_gate() except QiskitError as ex: raise CircuitError( "The circuit contains non-unitary operations and cannot be " "controlled. Note that no qiskit.circuit.Instruction objects may " "be in the circuit for this operation." ) from ex power_circuit = QuantumCircuit(self.qubits, self.clbits, *self.qregs, *self.cregs) power_circuit.append(gate.power(power), list(range(gate.num_qubits))) return power_circuit def control( self, num_ctrl_qubits: int = 1, label: str | None = None, ctrl_state: str | int | None = None, ) -> "QuantumCircuit": """Control this circuit on ``num_ctrl_qubits`` qubits. Args: num_ctrl_qubits (int): The number of control qubits. label (str): An optional label to give the controlled operation for visualization. ctrl_state (str or int): The control state in decimal or as a bitstring (e.g. '111'). If None, use ``2**num_ctrl_qubits - 1``. Returns: QuantumCircuit: The controlled version of this circuit. Raises: CircuitError: If the circuit contains a non-unitary operation and cannot be controlled. """ try: gate = self.to_gate() except QiskitError as ex: raise CircuitError( "The circuit contains non-unitary operations and cannot be " "controlled. Note that no qiskit.circuit.Instruction objects may " "be in the circuit for this operation." ) from ex controlled_gate = gate.control(num_ctrl_qubits, label, ctrl_state) control_qreg = QuantumRegister(num_ctrl_qubits) controlled_circ = QuantumCircuit( control_qreg, self.qubits, *self.qregs, name=f"c_{self.name}" ) controlled_circ.append(controlled_gate, controlled_circ.qubits) return controlled_circ def compose( self, other: Union["QuantumCircuit", Instruction], qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, clbits: ClbitSpecifier | Sequence[ClbitSpecifier] | None = None, front: bool = False, inplace: bool = False, wrap: bool = False, ) -> Optional["QuantumCircuit"]: """Compose circuit with ``other`` circuit or instruction, optionally permuting wires. ``other`` can be narrower or of equal width to ``self``. Args: other (qiskit.circuit.Instruction or QuantumCircuit): (sub)circuit or instruction to compose onto self. If not a :obj:`.QuantumCircuit`, this can be anything that :obj:`.append` will accept. qubits (list[Qubit|int]): qubits of self to compose onto. clbits (list[Clbit|int]): clbits of self to compose onto. front (bool): If True, front composition will be performed. This is not possible within control-flow builder context managers. inplace (bool): If True, modify the object. Otherwise return composed circuit. wrap (bool): If True, wraps the other circuit into a gate (or instruction, depending on whether it contains only unitary instructions) before composing it onto self. Returns: QuantumCircuit: the composed circuit (returns None if inplace==True). Raises: CircuitError: if no correct wire mapping can be made between the two circuits, such as if ``other`` is wider than ``self``. CircuitError: if trying to emit a new circuit while ``self`` has a partially built control-flow context active, such as the context-manager forms of :meth:`if_test`, :meth:`for_loop` and :meth:`while_loop`. CircuitError: if trying to compose to the front of a circuit when a control-flow builder block is active; there is no clear meaning to this action. Examples: .. code-block:: python >>> lhs.compose(rhs, qubits=[3, 2], inplace=True) .. parsed-literal:: ┌───┐ ┌─────┐ ┌───┐ lqr_1_0: ───┤ H ├─── rqr_0: ──■──┤ Tdg ├ lqr_1_0: ───┤ H ├─────────────── ├───┤ ┌─┴─┐└─────┘ ├───┤ lqr_1_1: ───┤ X ├─── rqr_1: ┤ X ├─────── lqr_1_1: ───┤ X ├─────────────── ┌──┴───┴──┐ └───┘ ┌──┴───┴──┐┌───┐ lqr_1_2: ┤ U1(0.1) ├ + = lqr_1_2: ┤ U1(0.1) ├┤ X ├─────── └─────────┘ └─────────┘└─┬─┘┌─────┐ lqr_2_0: ─────■───── lqr_2_0: ─────■───────■──┤ Tdg ├ ┌─┴─┐ ┌─┴─┐ └─────┘ lqr_2_1: ───┤ X ├─── lqr_2_1: ───┤ X ├─────────────── └───┘ └───┘ lcr_0: 0 ═══════════ lcr_0: 0 ═══════════════════════ lcr_1: 0 ═══════════ lcr_1: 0 ═══════════════════════ """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.switch_case import SwitchCaseOp if inplace and front and self._control_flow_scopes: # If we're composing onto ourselves while in a stateful control-flow builder context, # there's no clear meaning to composition to the "front" of the circuit. raise CircuitError( "Cannot compose to the front of a circuit while a control-flow context is active." ) if not inplace and self._control_flow_scopes: # If we're inside a stateful control-flow builder scope, even if we successfully cloned # the partial builder scope (not simple), the scope wouldn't be controlled by an active # `with` statement, so the output circuit would be permanently broken. raise CircuitError( "Cannot emit a new composed circuit while a control-flow context is active." ) dest = self if inplace else self.copy() # As a special case, allow composing some clbits onto no clbits - normally the destination # has to be strictly larger. This allows composing final measurements onto unitary circuits. if isinstance(other, QuantumCircuit): if not self.clbits and other.clbits: dest.add_bits(other.clbits) for reg in other.cregs: dest.add_register(reg) if wrap and isinstance(other, QuantumCircuit): other = ( other.to_gate() if all(isinstance(ins.operation, Gate) for ins in other.data) else other.to_instruction() ) if not isinstance(other, QuantumCircuit): if qubits is None: qubits = self.qubits[: other.num_qubits] if clbits is None: clbits = self.clbits[: other.num_clbits] if front: # Need to keep a reference to the data for use after we've emptied it. old_data = list(dest.data) dest.clear() dest.append(other, qubits, clbits) for instruction in old_data: dest._append(instruction) else: dest.append(other, qargs=qubits, cargs=clbits) if inplace: return None return dest if other.num_qubits > dest.num_qubits or other.num_clbits > dest.num_clbits: raise CircuitError( "Trying to compose with another QuantumCircuit which has more 'in' edges." ) # number of qubits and clbits must match number in circuit or None edge_map: dict[Qubit | Clbit, Qubit | Clbit] = {} if qubits is None: edge_map.update(zip(other.qubits, dest.qubits)) else: mapped_qubits = dest.qbit_argument_conversion(qubits) if len(mapped_qubits) != len(other.qubits): raise CircuitError( f"Number of items in qubits parameter ({len(mapped_qubits)}) does not" f" match number of qubits in the circuit ({len(other.qubits)})." ) edge_map.update(zip(other.qubits, mapped_qubits)) if clbits is None: edge_map.update(zip(other.clbits, dest.clbits)) else: mapped_clbits = dest.cbit_argument_conversion(clbits) if len(mapped_clbits) != len(other.clbits): raise CircuitError( f"Number of items in clbits parameter ({len(mapped_clbits)}) does not" f" match number of clbits in the circuit ({len(other.clbits)})." ) edge_map.update(zip(other.clbits, dest.cbit_argument_conversion(clbits))) variable_mapper = _classical_resource_map.VariableMapper( dest.cregs, edge_map, dest.add_register ) mapped_instrs: list[CircuitInstruction] = [] for instr in other.data: n_qargs: list[Qubit] = [edge_map[qarg] for qarg in instr.qubits] n_cargs: list[Clbit] = [edge_map[carg] for carg in instr.clbits] n_op = instr.operation.copy() if (condition := getattr(n_op, "condition", None)) is not None: n_op.condition = variable_mapper.map_condition(condition) if isinstance(n_op, SwitchCaseOp): n_op.target = variable_mapper.map_target(n_op.target) mapped_instrs.append(CircuitInstruction(n_op, n_qargs, n_cargs)) if front: # adjust new instrs before original ones and update all parameters mapped_instrs += dest.data dest.clear() append = dest._control_flow_scopes[-1].append if dest._control_flow_scopes else dest._append for instr in mapped_instrs: append(instr) for gate, cals in other.calibrations.items(): dest._calibrations[gate].update(cals) dest.global_phase += other.global_phase if inplace: return None return dest def tensor(self, other: "QuantumCircuit", inplace: bool = False) -> Optional["QuantumCircuit"]: """Tensor ``self`` with ``other``. Remember that in the little-endian convention the leftmost operation will be at the bottom of the circuit. See also `the docs <qiskit.org/documentation/tutorials/circuits/3_summary_of_quantum_operations.html>`__ for more information. .. parsed-literal:: ┌────────┐ ┌─────┐ ┌─────┐ q_0: ┤ bottom ├ ⊗ q_0: ┤ top ├ = q_0: ─┤ top ├── └────────┘ └─────┘ ┌┴─────┴─┐ q_1: ┤ bottom ├ └────────┘ Args: other (QuantumCircuit): The other circuit to tensor this circuit with. inplace (bool): If True, modify the object. Otherwise return composed circuit. Examples: .. plot:: :include-source: from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl') Returns: QuantumCircuit: The tensored circuit (returns None if inplace==True). """ num_qubits = self.num_qubits + other.num_qubits num_clbits = self.num_clbits + other.num_clbits # If a user defined both circuits with via register sizes and not with named registers # (e.g. QuantumCircuit(2, 2)) then we have a naming collision, as the registers are by # default called "q" resp. "c". To still allow tensoring we define new registers of the # correct sizes. if ( len(self.qregs) == len(other.qregs) == 1 and self.qregs[0].name == other.qregs[0].name == "q" ): # check if classical registers are in the circuit if num_clbits > 0: dest = QuantumCircuit(num_qubits, num_clbits) else: dest = QuantumCircuit(num_qubits) # handle case if ``measure_all`` was called on both circuits, in which case the # registers are both named "meas" elif ( len(self.cregs) == len(other.cregs) == 1 and self.cregs[0].name == other.cregs[0].name == "meas" ): cr = ClassicalRegister(self.num_clbits + other.num_clbits, "meas") dest = QuantumCircuit(*other.qregs, *self.qregs, cr) # Now we don't have to handle any more cases arising from special implicit naming else: dest = QuantumCircuit( other.qubits, self.qubits, other.clbits, self.clbits, *other.qregs, *self.qregs, *other.cregs, *self.cregs, ) # compose self onto the output, and then other dest.compose(other, range(other.num_qubits), range(other.num_clbits), inplace=True) dest.compose( self, range(other.num_qubits, num_qubits), range(other.num_clbits, num_clbits), inplace=True, ) # Replace information from tensored circuit into self when inplace = True if inplace: self.__dict__.update(dest.__dict__) return None return dest @property def qubits(self) -> list[Qubit]: """ Returns a list of quantum bits in the order that the registers were added. """ return self._qubits @property def clbits(self) -> list[Clbit]: """ Returns a list of classical bits in the order that the registers were added. """ return self._clbits @property def ancillas(self) -> list[AncillaQubit]: """ Returns a list of ancilla bits in the order that the registers were added. """ return self._ancillas def __and__(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """Overload & to implement self.compose.""" return self.compose(rhs) def __iand__(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """Overload &= to implement self.compose in place.""" self.compose(rhs, inplace=True) return self def __xor__(self, top: "QuantumCircuit") -> "QuantumCircuit": """Overload ^ to implement self.tensor.""" return self.tensor(top) def __ixor__(self, top: "QuantumCircuit") -> "QuantumCircuit": """Overload ^= to implement self.tensor in place.""" self.tensor(top, inplace=True) return self def __len__(self) -> int: """Return number of operations in circuit.""" return len(self._data) @typing.overload def __getitem__(self, item: int) -> CircuitInstruction: ... @typing.overload def __getitem__(self, item: slice) -> list[CircuitInstruction]: ... def __getitem__(self, item): """Return indexed operation.""" return self._data[item] @staticmethod def cast(value: S, type_: Callable[..., T]) -> Union[S, T]: """Best effort to cast value to type. Otherwise, returns the value.""" try: return type_(value) except (ValueError, TypeError): return value def qbit_argument_conversion(self, qubit_representation: QubitSpecifier) -> list[Qubit]: """ Converts several qubit representations (such as indexes, range, etc.) into a list of qubits. Args: qubit_representation (Object): representation to expand Returns: List(Qubit): the resolved instances of the qubits. """ return _bit_argument_conversion( qubit_representation, self.qubits, self._qubit_indices, Qubit ) def cbit_argument_conversion(self, clbit_representation: ClbitSpecifier) -> list[Clbit]: """ Converts several classical bit representations (such as indexes, range, etc.) into a list of classical bits. Args: clbit_representation (Object): representation to expand Returns: List(tuple): Where each tuple is a classical bit. """ return _bit_argument_conversion( clbit_representation, self.clbits, self._clbit_indices, Clbit ) def _resolve_classical_resource(self, specifier): """Resolve a single classical resource specifier into a concrete resource, raising an error if the specifier is invalid. This is slightly different to :meth:`.cbit_argument_conversion`, because it should not unwrap :obj:`.ClassicalRegister` instances into lists, and in general it should not allow iterables or broadcasting. It is expected to be used as a callback for things like :meth:`.InstructionSet.c_if` to check the validity of their arguments. Args: specifier (Union[Clbit, ClassicalRegister, int]): a specifier of a classical resource present in this circuit. An ``int`` will be resolved into a :obj:`.Clbit` using the same conventions as measurement operations on this circuit use. Returns: Union[Clbit, ClassicalRegister]: the resolved resource. Raises: CircuitError: if the resource is not present in this circuit, or if the integer index passed is out-of-bounds. """ if isinstance(specifier, Clbit): if specifier not in self._clbit_indices: raise CircuitError(f"Clbit {specifier} is not present in this circuit.") return specifier if isinstance(specifier, ClassicalRegister): # This is linear complexity for something that should be constant, but QuantumCircuit # does not currently keep a hashmap of registers, and requires non-trivial changes to # how it exposes its registers publically before such a map can be safely stored so it # doesn't miss updates. (Jake, 2021-11-10). if specifier not in self.cregs: raise CircuitError(f"Register {specifier} is not present in this circuit.") return specifier if isinstance(specifier, int): try: return self._clbits[specifier] except IndexError: raise CircuitError(f"Classical bit index {specifier} is out-of-range.") from None raise CircuitError(f"Unknown classical resource specifier: '{specifier}'.") def _validate_expr(self, node: expr.Expr) -> expr.Expr: for var in expr.iter_vars(node): if isinstance(var.var, Clbit): if var.var not in self._clbit_indices: raise CircuitError(f"Clbit {var.var} is not present in this circuit.") elif isinstance(var.var, ClassicalRegister): if var.var not in self.cregs: raise CircuitError(f"Register {var.var} is not present in this circuit.") return node def append( self, instruction: Operation | CircuitInstruction, qargs: Sequence[QubitSpecifier] | None = None, cargs: Sequence[ClbitSpecifier] | None = None, ) -> InstructionSet: """Append one or more instructions to the end of the circuit, modifying the circuit in place. The ``qargs`` and ``cargs`` will be expanded and broadcast according to the rules of the given :class:`~.circuit.Instruction`, and any non-:class:`.Bit` specifiers (such as integer indices) will be resolved into the relevant instances. If a :class:`.CircuitInstruction` is given, it will be unwrapped, verified in the context of this circuit, and a new object will be appended to the circuit. In this case, you may not pass ``qargs`` or ``cargs`` separately. Args: instruction: :class:`~.circuit.Instruction` instance to append, or a :class:`.CircuitInstruction` with all its context. qargs: specifiers of the :class:`.Qubit`\\ s to attach instruction to. cargs: specifiers of the :class:`.Clbit`\\ s to attach instruction to. Returns: qiskit.circuit.InstructionSet: a handle to the :class:`.CircuitInstruction`\\ s that were actually added to the circuit. Raises: CircuitError: if the operation passed is not an instance of :class:`~.circuit.Instruction` . """ if isinstance(instruction, CircuitInstruction): operation = instruction.operation qargs = instruction.qubits cargs = instruction.clbits else: operation = instruction # Convert input to instruction if not isinstance(operation, Operation): if hasattr(operation, "to_instruction"): operation = operation.to_instruction() if not isinstance(operation, Operation): raise CircuitError("operation.to_instruction() is not an Operation.") else: if issubclass(operation, Operation): raise CircuitError( "Object is a subclass of Operation, please add () to " "pass an instance of this object." ) raise CircuitError( "Object to append must be an Operation or have a to_instruction() method." ) # Make copy of parameterized gate instances if hasattr(operation, "params"): is_parameter = any(isinstance(param, Parameter) for param in operation.params) if is_parameter: operation = copy.deepcopy(operation) expanded_qargs = [self.qbit_argument_conversion(qarg) for qarg in qargs or []] expanded_cargs = [self.cbit_argument_conversion(carg) for carg in cargs or []] if self._control_flow_scopes: appender = self._control_flow_scopes[-1].append requester = self._control_flow_scopes[-1].request_classical_resource else: appender = self._append requester = self._resolve_classical_resource instructions = InstructionSet(resource_requester=requester) if isinstance(operation, Instruction): for qarg, carg in operation.broadcast_arguments(expanded_qargs, expanded_cargs): self._check_dups(qarg) instruction = CircuitInstruction(operation, qarg, carg) appender(instruction) instructions.add(instruction) else: # For Operations that are non-Instructions, we use the Instruction's default method for qarg, carg in Instruction.broadcast_arguments( operation, expanded_qargs, expanded_cargs ): self._check_dups(qarg) instruction = CircuitInstruction(operation, qarg, carg) appender(instruction) instructions.add(instruction) return instructions # Preferred new style. @typing.overload def _append( self, instruction: CircuitInstruction, _qargs: None = None, _cargs: None = None ) -> CircuitInstruction: ... # To-be-deprecated old style. @typing.overload def _append( self, operation: Operation, qargs: Sequence[Qubit], cargs: Sequence[Clbit], ) -> Operation: ... def _append( self, instruction: CircuitInstruction | Instruction, qargs: Sequence[Qubit] | None = None, cargs: Sequence[Clbit] | None = None, ): """Append an instruction to the end of the circuit, modifying the circuit in place. .. warning:: This is an internal fast-path function, and it is the responsibility of the caller to ensure that all the arguments are valid; there is no error checking here. In particular, all the qubits and clbits must already exist in the circuit and there can be no duplicates in the list. .. note:: This function may be used by callers other than :obj:`.QuantumCircuit` when the caller is sure that all error-checking, broadcasting and scoping has already been performed, and the only reference to the circuit the instructions are being appended to is within that same function. In particular, it is not safe to call :meth:`QuantumCircuit._append` on a circuit that is received by a function argument. This is because :meth:`.QuantumCircuit._append` will not recognise the scoping constructs of the control-flow builder interface. Args: instruction: Operation instance to append qargs: Qubits to attach the instruction to. cargs: Clbits to attach the instruction to. Returns: Operation: a handle to the instruction that was just added :meta public: """ old_style = not isinstance(instruction, CircuitInstruction) if old_style: instruction = CircuitInstruction(instruction, qargs, cargs) self._data.append(instruction) if isinstance(instruction.operation, Instruction): self._update_parameter_table(instruction) # mark as normal circuit if a new instruction is added self.duration = None self.unit = "dt" return instruction.operation if old_style else instruction def _update_parameter_table(self, instruction: CircuitInstruction): for param_index, param in enumerate(instruction.operation.params): if isinstance(param, (ParameterExpression, QuantumCircuit)): # Scoped constructs like the control-flow ops use QuantumCircuit as a parameter. atomic_parameters = set(param.parameters) else: atomic_parameters = set() for parameter in atomic_parameters: if parameter in self._parameter_table: self._parameter_table[parameter].add((instruction.operation, param_index)) else: if parameter.name in self._parameter_table.get_names(): raise CircuitError(f"Name conflict on adding parameter: {parameter.name}") self._parameter_table[parameter] = ParameterReferences( ((instruction.operation, param_index),) ) # clear cache if new parameter is added self._parameters = None def add_register(self, *regs: Register | int | Sequence[Bit]) -> None: """Add registers.""" if not regs: return if any(isinstance(reg, int) for reg in regs): # QuantumCircuit defined without registers if len(regs) == 1 and isinstance(regs[0], int): # QuantumCircuit with anonymous quantum wires e.g. QuantumCircuit(2) if regs[0] == 0: regs = () else: regs = (QuantumRegister(regs[0], "q"),) elif len(regs) == 2 and all(isinstance(reg, int) for reg in regs): # QuantumCircuit with anonymous wires e.g. QuantumCircuit(2, 3) if regs[0] == 0: qregs: tuple[QuantumRegister, ...] = () else: qregs = (QuantumRegister(regs[0], "q"),) if regs[1] == 0: cregs: tuple[ClassicalRegister, ...] = () else: cregs = (ClassicalRegister(regs[1], "c"),) regs = qregs + cregs else: raise CircuitError( "QuantumCircuit parameters can be Registers or Integers." " If Integers, up to 2 arguments. QuantumCircuit was called" " with %s." % (regs,) ) for register in regs: if isinstance(register, Register) and any( register.name == reg.name for reg in self.qregs + self.cregs ): raise CircuitError('register name "%s" already exists' % register.name) if isinstance(register, AncillaRegister): for bit in register: if bit not in self._qubit_indices: self._ancillas.append(bit) if isinstance(register, QuantumRegister): self.qregs.append(register) for idx, bit in enumerate(register): if bit in self._qubit_indices: self._qubit_indices[bit].registers.append((register, idx)) else: self._qubits.append(bit) self._qubit_indices[bit] = BitLocations( len(self._qubits) - 1, [(register, idx)] ) elif isinstance(register, ClassicalRegister): self.cregs.append(register) for idx, bit in enumerate(register): if bit in self._clbit_indices: self._clbit_indices[bit].registers.append((register, idx)) else: self._clbits.append(bit) self._clbit_indices[bit] = BitLocations( len(self._clbits) - 1, [(register, idx)] ) elif isinstance(register, list): self.add_bits(register) else: raise CircuitError("expected a register") def add_bits(self, bits: Iterable[Bit]) -> None: """Add Bits to the circuit.""" duplicate_bits = set(self._qubit_indices).union(self._clbit_indices).intersection(bits) if duplicate_bits: raise CircuitError(f"Attempted to add bits found already in circuit: {duplicate_bits}") for bit in bits: if isinstance(bit, AncillaQubit): self._ancillas.append(bit) if isinstance(bit, Qubit): self._qubits.append(bit) self._qubit_indices[bit] = BitLocations(len(self._qubits) - 1, []) elif isinstance(bit, Clbit): self._clbits.append(bit) self._clbit_indices[bit] = BitLocations(len(self._clbits) - 1, []) else: raise CircuitError( "Expected an instance of Qubit, Clbit, or " "AncillaQubit, but was passed {}".format(bit) ) def find_bit(self, bit: Bit) -> BitLocations: """Find locations in the circuit which can be used to reference a given :obj:`~Bit`. Args: bit (Bit): The bit to locate. Returns: namedtuple(int, List[Tuple(Register, int)]): A 2-tuple. The first element (``index``) contains the index at which the ``Bit`` can be found (in either :obj:`~QuantumCircuit.qubits`, :obj:`~QuantumCircuit.clbits`, depending on its type). The second element (``registers``) is a list of ``(register, index)`` pairs with an entry for each :obj:`~Register` in the circuit which contains the :obj:`~Bit` (and the index in the :obj:`~Register` at which it can be found). Notes: The circuit index of an :obj:`~AncillaQubit` will be its index in :obj:`~QuantumCircuit.qubits`, not :obj:`~QuantumCircuit.ancillas`. Raises: CircuitError: If the supplied :obj:`~Bit` was of an unknown type. CircuitError: If the supplied :obj:`~Bit` could not be found on the circuit. """ try: if isinstance(bit, Qubit): return self._qubit_indices[bit] elif isinstance(bit, Clbit): return self._clbit_indices[bit] else: raise CircuitError(f"Could not locate bit of unknown type: {type(bit)}") except KeyError as err: raise CircuitError( f"Could not locate provided bit: {bit}. Has it been added to the QuantumCircuit?" ) from err def _check_dups(self, qubits: Sequence[Qubit]) -> None: """Raise exception if list of qubits contains duplicates.""" squbits = set(qubits) if len(squbits) != len(qubits): raise CircuitError("duplicate qubit arguments") def to_instruction( self, parameter_map: dict[Parameter, ParameterValueType] | None = None, label: str | None = None, ) -> Instruction: """Create an Instruction out of this circuit. Args: parameter_map(dict): For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the instruction. If None, existing circuit parameters will also parameterize the instruction. label (str): Optional gate label. Returns: qiskit.circuit.Instruction: a composite instruction encapsulating this circuit (can be decomposed back) """ from qiskit.converters.circuit_to_instruction import circuit_to_instruction return circuit_to_instruction(self, parameter_map, label=label) def to_gate( self, parameter_map: dict[Parameter, ParameterValueType] | None = None, label: str | None = None, ) -> Gate: """Create a Gate out of this circuit. Args: parameter_map(dict): For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the gate. If None, existing circuit parameters will also parameterize the gate. label (str): Optional gate label. Returns: Gate: a composite gate encapsulating this circuit (can be decomposed back) """ from qiskit.converters.circuit_to_gate import circuit_to_gate return circuit_to_gate(self, parameter_map, label=label) def decompose( self, gates_to_decompose: Type[Gate] | Sequence[Type[Gate]] | Sequence[str] | str | None = None, reps: int = 1, ) -> "QuantumCircuit": """Call a decomposition pass on this circuit, to decompose one level (shallow decompose). Args: gates_to_decompose (type or str or list(type, str)): Optional subset of gates to decompose. Can be a gate type, such as ``HGate``, or a gate name, such as 'h', or a gate label, such as 'My H Gate', or a list of any combination of these. If a gate name is entered, it will decompose all gates with that name, whether the gates have labels or not. Defaults to all gates in circuit. reps (int): Optional number of times the circuit should be decomposed. For instance, ``reps=2`` equals calling ``circuit.decompose().decompose()``. can decompose specific gates specific time Returns: QuantumCircuit: a circuit one level decomposed """ # pylint: disable=cyclic-import from qiskit.transpiler.passes.basis.decompose import Decompose from qiskit.transpiler.passes.synthesis import HighLevelSynthesis from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_circuit import dag_to_circuit dag = circuit_to_dag(self) dag = HighLevelSynthesis().run(dag) pass_ = Decompose(gates_to_decompose) for _ in range(reps): dag = pass_.run(dag) return dag_to_circuit(dag) def qasm( self, formatted: bool = False, filename: str | None = None, encoding: str | None = None, ) -> str | None: """Return OpenQASM string. Args: formatted (bool): Return formatted Qasm string. filename (str): Save Qasm to file with name 'filename'. encoding (str): Optionally specify the encoding to use for the output file if ``filename`` is specified. By default this is set to the system's default encoding (ie whatever ``locale.getpreferredencoding()`` returns) and can be set to any valid codec or alias from stdlib's `codec module <https://docs.python.org/3/library/codecs.html#standard-encodings>`__ Returns: str: If formatted=False. Raises: MissingOptionalLibraryError: If pygments is not installed and ``formatted`` is ``True``. QASM2ExportError: If circuit has free parameters. QASM2ExportError: If an operation that has no OpenQASM 2 representation is encountered. """ from qiskit.qasm2 import QASM2ExportError # pylint: disable=cyclic-import if self.num_parameters > 0: raise QASM2ExportError( "Cannot represent circuits with unbound parameters in OpenQASM 2." ) existing_gate_names = { "barrier", "measure", "reset", "u3", "u2", "u1", "cx", "id", "u0", "u", "p", "x", "y", "z", "h", "s", "sdg", "t", "tdg", "rx", "ry", "rz", "sx", "sxdg", "cz", "cy", "swap", "ch", "ccx", "cswap", "crx", "cry", "crz", "cu1", "cp", "cu3", "csx", "cu", "rxx", "rzz", "rccx", "rc3x", "c3x", "c3sx", # This is the Qiskit gate name, but the qelib1.inc name is 'c3sqrtx'. "c4x", } # Mapping of instruction name to a pair of the source for a definition, and an OQ2 string # that includes the `gate` or `opaque` statement that defines the gate. gates_to_define: OrderedDict[str, tuple[Instruction, str]] = OrderedDict() regless_qubits = [bit for bit in self.qubits if not self.find_bit(bit).registers] regless_clbits = [bit for bit in self.clbits if not self.find_bit(bit).registers] dummy_registers: list[QuantumRegister | ClassicalRegister] = [] if regless_qubits: dummy_registers.append(QuantumRegister(name="qregless", bits=regless_qubits)) if regless_clbits: dummy_registers.append(ClassicalRegister(name="cregless", bits=regless_clbits)) register_escaped_names: dict[str, QuantumRegister | ClassicalRegister] = {} for regs in (self.qregs, self.cregs, dummy_registers): for reg in regs: register_escaped_names[ _make_unique(_qasm_escape_name(reg.name, "reg_"), register_escaped_names) ] = reg bit_labels: dict[Qubit | Clbit, str] = { bit: "%s[%d]" % (name, idx) for name, register in register_escaped_names.items() for (idx, bit) in enumerate(register) } register_definitions_qasm = "".join( f"{'qreg' if isinstance(reg, QuantumRegister) else 'creg'} {name}[{reg.size}];\n" for name, reg in register_escaped_names.items() ) instruction_calls = [] for instruction in self._data: operation = instruction.operation if operation.name == "measure": qubit = instruction.qubits[0] clbit = instruction.clbits[0] instruction_qasm = f"measure {bit_labels[qubit]} -> {bit_labels[clbit]};" elif operation.name == "reset": instruction_qasm = f"reset {bit_labels[instruction.qubits[0]]};" elif operation.name == "barrier": if not instruction.qubits: # Barriers with no operands are invalid in (strict) OQ2, and the statement # would have no meaning anyway. continue qargs = ",".join(bit_labels[q] for q in instruction.qubits) instruction_qasm = "barrier;" if not qargs else f"barrier {qargs};" else: instruction_qasm = _qasm2_custom_operation_statement( instruction, existing_gate_names, gates_to_define, bit_labels ) instruction_calls.append(instruction_qasm) instructions_qasm = "".join(f"{call}\n" for call in instruction_calls) gate_definitions_qasm = "".join(f"{qasm}\n" for _, qasm in gates_to_define.values()) out = "".join( ( self.header, "\n", self.extension_lib, "\n", gate_definitions_qasm, register_definitions_qasm, instructions_qasm, ) ) if filename: with open(filename, "w+", encoding=encoding) as file: file.write(out) if formatted: _optionals.HAS_PYGMENTS.require_now("formatted OpenQASM 2 output") import pygments from pygments.formatters import ( # pylint: disable=no-name-in-module Terminal256Formatter, ) from qiskit.qasm.pygments import OpenQASMLexer from qiskit.qasm.pygments import QasmTerminalStyle code = pygments.highlight( out, OpenQASMLexer(), Terminal256Formatter(style=QasmTerminalStyle) ) print(code) return None return out def draw( self, output: str | None = None, scale: float | None = None, filename: str | None = None, style: dict | str | None = None, interactive: bool = False, plot_barriers: bool = True, reverse_bits: bool = None, justify: str | None = None, vertical_compression: str | None = "medium", idle_wires: bool = True, with_layout: bool = True, fold: int | None = None, # The type of ax is matplotlib.axes.Axes, but this is not a fixed dependency, so cannot be # safely forward-referenced. ax: Any | None = None, initial_state: bool = False, cregbundle: bool = None, wire_order: list = None, ): """Draw the quantum circuit. Use the output parameter to choose the drawing format: **text**: ASCII art TextDrawing that can be printed in the console. **mpl**: images with color rendered purely in Python using matplotlib. **latex**: high-quality images compiled via latex. **latex_source**: raw uncompiled latex output. .. warning:: Support for :class:`~.expr.Expr` nodes in conditions and :attr:`.SwitchCaseOp.target` fields is preliminary and incomplete. The ``text`` and ``mpl`` drawers will make a best-effort attempt to show data dependencies, but the LaTeX-based drawers will skip these completely. Args: output (str): select the output method to use for drawing the circuit. Valid choices are ``text``, ``mpl``, ``latex``, ``latex_source``. By default the `text` drawer is used unless the user config file (usually ``~/.qiskit/settings.conf``) has an alternative backend set as the default. For example, ``circuit_drawer = latex``. If the output kwarg is set, that backend will always be used over the default in the user config file. scale (float): scale of image to draw (shrink if < 1.0). Only used by the `mpl`, `latex` and `latex_source` outputs. Defaults to 1.0. filename (str): file path to save image to. Defaults to None. style (dict or str): dictionary of style or file name of style json file. This option is only used by the `mpl` or `latex` output type. If `style` is a str, it is used as the path to a json file which contains a style dict. The file will be opened, parsed, and then any style elements in the dict will replace the default values in the input dict. A file to be loaded must end in ``.json``, but the name entered here can omit ``.json``. For example, ``style='iqx.json'`` or ``style='iqx'``. If `style` is a dict and the ``'name'`` key is set, that name will be used to load a json file, followed by loading the other items in the style dict. For example, ``style={'name': 'iqx'}``. If `style` is not a str and `name` is not a key in the style dict, then the default value from the user config file (usually ``~/.qiskit/settings.conf``) will be used, for example, ``circuit_mpl_style = iqx``. If none of these are set, the `default` style will be used. The search path for style json files can be specified in the user config, for example, ``circuit_mpl_style_path = /home/user/styles:/home/user``. See: :class:`~qiskit.visualization.qcstyle.DefaultStyle` for more information on the contents. interactive (bool): when set to 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. Defaults to False. reverse_bits (bool): when set to True, reverse the bit order inside registers for the output visualization. Defaults to False unless the user config file (usually ``~/.qiskit/settings.conf``) has an alternative value set. For example, ``circuit_reverse_bits = True``. 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. vertical_compression (string): ``high``, ``medium`` or ``low``. It merges the lines generated by the `text` output so the drawing will take less vertical room. Default is ``medium``. Only used by the `text` output, will be silently ignored otherwise. idle_wires (bool): include idle wires (wires with no circuit elements) in output visualization. Default is True. with_layout (bool): include layout information, with labels on the physical layout. Default is True. fold (int): sets pagination. It can be disabled using -1. In `text`, sets the length of the lines. This is 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 running in jupyter, the default line length is set to 80 characters. In `mpl`, it is the number of (visual) layers before folding. Default is 25. ax (matplotlib.axes.Axes): Only used by the `mpl` backend. An optional Axes object to be used for the visualization output. If none is specified, a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. initial_state (bool): Optional. Adds ``|0>`` in the beginning of the wire. Default is False. cregbundle (bool): Optional. If set True, bundle classical registers. Default is True, except for when ``output`` is set to ``"text"``. wire_order (list): Optional. A list of integers used to reorder the display of the bits. The list must have an entry for every bit with the bits in the range 0 to (``num_qubits`` + ``num_clbits``). Returns: :class:`.TextDrawing` or :class:`matplotlib.figure` or :class:`PIL.Image` or :class:`str`: * `TextDrawing` (output='text') A drawing that can be printed as ascii art. * `matplotlib.figure.Figure` (output='mpl') A matplotlib figure object for the circuit diagram. * `PIL.Image` (output='latex') An in-memory representation of the image of the circuit diagram. * `str` (output='latex_source') The LaTeX source code for visualizing the circuit diagram. Raises: VisualizationError: when an invalid output method is selected ImportError: when the output methods requires non-installed libraries. Example: .. plot:: :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'}) """ # pylint: disable=cyclic-import from qiskit.visualization import circuit_drawer return circuit_drawer( self, scale=scale, filename=filename, style=style, output=output, interactive=interactive, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify, vertical_compression=vertical_compression, idle_wires=idle_wires, with_layout=with_layout, fold=fold, ax=ax, initial_state=initial_state, cregbundle=cregbundle, wire_order=wire_order, ) def size( self, filter_function: Callable[..., int] = lambda x: not getattr( x.operation, "_directive", False ), ) -> int: """Returns total number of instructions in circuit. Args: filter_function (callable): a function to filter out some instructions. Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)). By default filters out "directives", such as barrier or snapshot. Returns: int: Total number of gate operations. """ return sum(map(filter_function, self._data)) def depth( self, filter_function: Callable[..., int] = lambda x: not getattr( x.operation, "_directive", False ), ) -> int: """Return circuit depth (i.e., length of critical path). Args: filter_function (callable): A function to filter instructions. Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)). Instructions for which the function returns False are ignored in the computation of the circuit depth. By default filters out "directives", such as barrier or snapshot. Returns: int: Depth of circuit. Notes: The circuit depth and the DAG depth need not be the same. """ # Assign each bit in the circuit a unique integer # to index into op_stack. bit_indices: dict[Qubit | Clbit, int] = { bit: idx for idx, bit in enumerate(self.qubits + self.clbits) } # If no bits, return 0 if not bit_indices: return 0 # A list that holds the height of each qubit # and classical bit. op_stack = [0] * len(bit_indices) # Here we are playing a modified version of # Tetris where we stack gates, but multi-qubit # gates, or measurements have a block for each # qubit or cbit that are connected by a virtual # line so that they all stacked at the same depth. # Conditional gates act on all cbits in the register # they are conditioned on. # The max stack height is the circuit depth. for instruction in self._data: levels = [] reg_ints = [] for ind, reg in enumerate(instruction.qubits + instruction.clbits): # Add to the stacks of the qubits and # cbits used in the gate. reg_ints.append(bit_indices[reg]) if filter_function(instruction): levels.append(op_stack[reg_ints[ind]] + 1) else: levels.append(op_stack[reg_ints[ind]]) # Assuming here that there is no conditional # snapshots or barriers ever. if getattr(instruction.operation, "condition", None): # Controls operate over all bits of a classical register # or over a single bit if isinstance(instruction.operation.condition[0], Clbit): condition_bits = [instruction.operation.condition[0]] else: condition_bits = instruction.operation.condition[0] for cbit in condition_bits: idx = bit_indices[cbit] if idx not in reg_ints: reg_ints.append(idx) levels.append(op_stack[idx] + 1) max_level = max(levels) for ind in reg_ints: op_stack[ind] = max_level return max(op_stack) def width(self) -> int: """Return number of qubits plus clbits in circuit. Returns: int: Width of circuit. """ return len(self.qubits) + len(self.clbits) @property def num_qubits(self) -> int: """Return number of qubits.""" return len(self.qubits) @property def num_ancillas(self) -> int: """Return the number of ancilla qubits.""" return len(self.ancillas) @property def num_clbits(self) -> int: """Return number of classical bits.""" return len(self.clbits) # The stringified return type is because OrderedDict can't be subscripted before Python 3.9, and # typing.OrderedDict wasn't added until 3.7.2. It can be turned into a proper type once 3.6 # support is dropped. def count_ops(self) -> "OrderedDict[Instruction, int]": """Count each operation kind in the circuit. Returns: OrderedDict: a breakdown of how many operations of each kind, sorted by amount. """ count_ops: dict[Instruction, int] = {} for instruction in self._data: count_ops[instruction.operation.name] = count_ops.get(instruction.operation.name, 0) + 1 return OrderedDict(sorted(count_ops.items(), key=lambda kv: kv[1], reverse=True)) def num_nonlocal_gates(self) -> int: """Return number of non-local gates (i.e. involving 2+ qubits). Conditional nonlocal gates are also included. """ multi_qubit_gates = 0 for instruction in self._data: if instruction.operation.num_qubits > 1 and not getattr( instruction.operation, "_directive", False ): multi_qubit_gates += 1 return multi_qubit_gates def get_instructions(self, name: str) -> list[CircuitInstruction]: """Get instructions matching name. Args: name (str): The name of instruction to. Returns: list(tuple): list of (instruction, qargs, cargs). """ return [match for match in self._data if match.operation.name == name] def num_connected_components(self, unitary_only: bool = False) -> int: """How many non-entangled subcircuits can the circuit be factored to. Args: unitary_only (bool): Compute only unitary part of graph. Returns: int: Number of connected components in circuit. """ # Convert registers to ints (as done in depth). bits = self.qubits if unitary_only else (self.qubits + self.clbits) bit_indices: dict[Qubit | Clbit, int] = {bit: idx for idx, bit in enumerate(bits)} # Start with each qubit or cbit being its own subgraph. sub_graphs = [[bit] for bit in range(len(bit_indices))] num_sub_graphs = len(sub_graphs) # Here we are traversing the gates and looking to see # which of the sub_graphs the gate joins together. for instruction in self._data: if unitary_only: args = instruction.qubits num_qargs = len(args) else: args = instruction.qubits + instruction.clbits num_qargs = len(args) + ( 1 if getattr(instruction.operation, "condition", None) else 0 ) if num_qargs >= 2 and not getattr(instruction.operation, "_directive", False): graphs_touched = [] num_touched = 0 # Controls necessarily join all the cbits in the # register that they use. if not unitary_only: for bit in instruction.operation.condition_bits: idx = bit_indices[bit] for k in range(num_sub_graphs): if idx in sub_graphs[k]: graphs_touched.append(k) break for item in args: reg_int = bit_indices[item] for k in range(num_sub_graphs): if reg_int in sub_graphs[k]: if k not in graphs_touched: graphs_touched.append(k) break graphs_touched = list(set(graphs_touched)) num_touched = len(graphs_touched) # If the gate touches more than one subgraph # join those graphs together and return # reduced number of subgraphs if num_touched > 1: connections = [] for idx in graphs_touched: connections.extend(sub_graphs[idx]) _sub_graphs = [] for idx in range(num_sub_graphs): if idx not in graphs_touched: _sub_graphs.append(sub_graphs[idx]) _sub_graphs.append(connections) sub_graphs = _sub_graphs num_sub_graphs -= num_touched - 1 # Cannot go lower than one so break if num_sub_graphs == 1: break return num_sub_graphs def num_unitary_factors(self) -> int: """Computes the number of tensor factors in the unitary (quantum) part of the circuit only. """ return self.num_connected_components(unitary_only=True) def num_tensor_factors(self) -> int: """Computes the number of tensor factors in the unitary (quantum) part of the circuit only. Notes: This is here for backwards compatibility, and will be removed in a future release of Qiskit. You should call `num_unitary_factors` instead. """ return self.num_unitary_factors() def copy(self, name: str | None = None) -> "QuantumCircuit": """Copy the circuit. Args: name (str): name to be given to the copied circuit. If None, then the name stays the same. Returns: QuantumCircuit: a deepcopy of the current circuit, with the specified name """ cpy = self.copy_empty_like(name) operation_copies = { id(instruction.operation): instruction.operation.copy() for instruction in self._data } cpy._parameter_table = ParameterTable( { param: ParameterReferences( (operation_copies[id(operation)], param_index) for operation, param_index in self._parameter_table[param] ) for param in self._parameter_table } ) cpy._data = [ instruction.replace(operation=operation_copies[id(instruction.operation)]) for instruction in self._data ] return cpy def copy_empty_like(self, name: str | None = None) -> "QuantumCircuit": """Return a copy of self with the same structure but empty. That structure includes: * name, calibrations and other metadata * global phase * all the qubits and clbits, including the registers Args: name (str): Name for the copied circuit. If None, then the name stays the same. Returns: QuantumCircuit: An empty copy of self. """ if not (name is None or isinstance(name, str)): raise TypeError( f"invalid name for a circuit: '{name}'. The name must be a string or 'None'." ) cpy = copy.copy(self) # copy registers correctly, in copy.copy they are only copied via reference cpy.qregs = self.qregs.copy() cpy.cregs = self.cregs.copy() cpy._qubits = self._qubits.copy() cpy._ancillas = self._ancillas.copy() cpy._clbits = self._clbits.copy() cpy._qubit_indices = self._qubit_indices.copy() cpy._clbit_indices = self._clbit_indices.copy() cpy._parameter_table = ParameterTable() cpy._data = [] cpy._calibrations = copy.deepcopy(self._calibrations) cpy._metadata = copy.deepcopy(self._metadata) if name: cpy.name = name return cpy def clear(self) -> None: """Clear all instructions in self. Clearing the circuits will keep the metadata and calibrations. """ self._data.clear() self._parameter_table.clear() def _create_creg(self, length: int, name: str) -> ClassicalRegister: """Creates a creg, checking if ClassicalRegister with same name exists""" if name in [creg.name for creg in self.cregs]: save_prefix = ClassicalRegister.prefix ClassicalRegister.prefix = name new_creg = ClassicalRegister(length) ClassicalRegister.prefix = save_prefix else: new_creg = ClassicalRegister(length, name) return new_creg def _create_qreg(self, length: int, name: str) -> QuantumRegister: """Creates a qreg, checking if QuantumRegister with same name exists""" if name in [qreg.name for qreg in self.qregs]: save_prefix = QuantumRegister.prefix QuantumRegister.prefix = name new_qreg = QuantumRegister(length) QuantumRegister.prefix = save_prefix else: new_qreg = QuantumRegister(length, name) return new_qreg def reset(self, qubit: QubitSpecifier) -> InstructionSet: """Reset the quantum bit(s) to their default state. Args: qubit: qubit(s) to reset. Returns: qiskit.circuit.InstructionSet: handle to the added instruction. """ return self.append(Reset(), [qubit], []) def measure(self, qubit: QubitSpecifier, cbit: ClbitSpecifier) -> InstructionSet: r"""Measure a quantum bit (``qubit``) in the Z basis into a classical bit (``cbit``). When a quantum state is measured, a qubit is projected in the computational (Pauli Z) basis to either :math:`\lvert 0 \rangle` or :math:`\lvert 1 \rangle`. The classical bit ``cbit`` indicates the result of that projection as a ``0`` or a ``1`` respectively. This operation is non-reversible. Args: qubit: qubit(s) to measure. cbit: classical bit(s) to place the measurement result(s) in. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. Raises: CircuitError: if arguments have bad format. Examples: In this example, a qubit is measured and the result of that measurement is stored in the classical bit (usually expressed in diagrams as a double line): .. code-block:: from qiskit import QuantumCircuit circuit = QuantumCircuit(1, 1) circuit.h(0) circuit.measure(0, 0) circuit.draw() .. parsed-literal:: ┌───┐┌─┐ q: ┤ H ├┤M├ └───┘└╥┘ c: 1/══════╩═ 0 It is possible to call ``measure`` with lists of ``qubits`` and ``cbits`` as a shortcut for one-to-one measurement. These two forms produce identical results: .. code-block:: circuit = QuantumCircuit(2, 2) circuit.measure([0,1], [0,1]) .. code-block:: circuit = QuantumCircuit(2, 2) circuit.measure(0, 0) circuit.measure(1, 1) Instead of lists, you can use :class:`~qiskit.circuit.QuantumRegister` and :class:`~qiskit.circuit.ClassicalRegister` under the same logic. .. code-block:: from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qreg = QuantumRegister(2, "qreg") creg = ClassicalRegister(2, "creg") circuit = QuantumCircuit(qreg, creg) circuit.measure(qreg, creg) This is equivalent to: .. code-block:: circuit = QuantumCircuit(qreg, creg) circuit.measure(qreg[0], creg[0]) circuit.measure(qreg[1], creg[1]) """ return self.append(Measure(), [qubit], [cbit]) def measure_active(self, inplace: bool = True) -> Optional["QuantumCircuit"]: """Adds measurement to all non-idle qubits. Creates a new ClassicalRegister with a size equal to the number of non-idle qubits being measured. Returns a new circuit with measurements if `inplace=False`. Args: inplace (bool): All measurements inplace or return new circuit. Returns: QuantumCircuit: Returns circuit with measurements when `inplace = False`. """ from qiskit.converters.circuit_to_dag import circuit_to_dag if inplace: circ = self else: circ = self.copy() dag = circuit_to_dag(circ) qubits_to_measure = [qubit for qubit in circ.qubits if qubit not in dag.idle_wires()] new_creg = circ._create_creg(len(qubits_to_measure), "measure") circ.add_register(new_creg) circ.barrier() circ.measure(qubits_to_measure, new_creg) if not inplace: return circ else: return None def measure_all( self, inplace: bool = True, add_bits: bool = True ) -> Optional["QuantumCircuit"]: """Adds measurement to all qubits. By default, adds new classical bits in a :obj:`.ClassicalRegister` to store these measurements. If ``add_bits=False``, the results of the measurements will instead be stored in the already existing classical bits, with qubit ``n`` being measured into classical bit ``n``. Returns a new circuit with measurements if ``inplace=False``. Args: inplace (bool): All measurements inplace or return new circuit. add_bits (bool): Whether to add new bits to store the results. Returns: QuantumCircuit: Returns circuit with measurements when ``inplace=False``. Raises: CircuitError: if ``add_bits=False`` but there are not enough classical bits. """ if inplace: circ = self else: circ = self.copy() if add_bits: new_creg = circ._create_creg(len(circ.qubits), "meas") circ.add_register(new_creg) circ.barrier() circ.measure(circ.qubits, new_creg) else: if len(circ.clbits) < len(circ.qubits): raise CircuitError( "The number of classical bits must be equal or greater than " "the number of qubits." ) circ.barrier() circ.measure(circ.qubits, circ.clbits[0 : len(circ.qubits)]) if not inplace: return circ else: return None def remove_final_measurements(self, inplace: bool = True) -> Optional["QuantumCircuit"]: """Removes final measurements and barriers on all qubits if they are present. Deletes the classical registers that were used to store the values from these measurements that become idle as a result of this operation, and deletes classical bits that are referenced only by removed registers, or that aren't referenced at all but have become idle as a result of this operation. Measurements and barriers are considered final if they are followed by no other operations (aside from other measurements or barriers.) Args: inplace (bool): All measurements removed inplace or return new circuit. Returns: QuantumCircuit: Returns the resulting circuit when ``inplace=False``, else None. """ # pylint: disable=cyclic-import from qiskit.transpiler.passes import RemoveFinalMeasurements from qiskit.converters import circuit_to_dag if inplace: circ = self else: circ = self.copy() dag = circuit_to_dag(circ) remove_final_meas = RemoveFinalMeasurements() new_dag = remove_final_meas.run(dag) kept_cregs = set(new_dag.cregs.values()) kept_clbits = set(new_dag.clbits) # Filter only cregs/clbits still in new DAG, preserving original circuit order cregs_to_add = [creg for creg in circ.cregs if creg in kept_cregs] clbits_to_add = [clbit for clbit in circ._clbits if clbit in kept_clbits] # Clear cregs and clbits circ.cregs = [] circ._clbits = [] circ._clbit_indices = {} # We must add the clbits first to preserve the original circuit # order. This way, add_register never adds clbits and just # creates registers that point to them. circ.add_bits(clbits_to_add) for creg in cregs_to_add: circ.add_register(creg) # Clear instruction info circ.data.clear() circ._parameter_table.clear() # Set circ instructions to match the new DAG for node in new_dag.topological_op_nodes(): # Get arguments for classical condition (if any) inst = node.op.copy() circ.append(inst, node.qargs, node.cargs) if not inplace: return circ else: return None @staticmethod def from_qasm_file(path: str) -> "QuantumCircuit": """Take in a QASM file and generate a QuantumCircuit object. Args: path (str): Path to the file for a QASM program Return: QuantumCircuit: The QuantumCircuit object for the input QASM See also: :func:`.qasm2.load`: the complete interface to the OpenQASM 2 importer. """ # pylint: disable=cyclic-import from qiskit import qasm2 return qasm2.load( path, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) @staticmethod def from_qasm_str(qasm_str: str) -> "QuantumCircuit": """Take in a QASM string and generate a QuantumCircuit object. Args: qasm_str (str): A QASM program string Return: QuantumCircuit: The QuantumCircuit object for the input QASM See also: :func:`.qasm2.loads`: the complete interface to the OpenQASM 2 importer. """ # pylint: disable=cyclic-import from qiskit import qasm2 return qasm2.loads( qasm_str, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) @property def global_phase(self) -> ParameterValueType: """Return the global phase of the circuit in radians.""" return self._global_phase @global_phase.setter def global_phase(self, angle: ParameterValueType): """Set the phase of the circuit. Args: angle (float, ParameterExpression): radians """ if isinstance(angle, ParameterExpression) and angle.parameters: self._global_phase = angle else: # Set the phase to the [0, 2π) interval angle = float(angle) if not angle: self._global_phase = 0 else: self._global_phase = angle % (2 * np.pi) @property def parameters(self) -> ParameterView: """The parameters defined in the circuit. This attribute returns the :class:`.Parameter` objects in the circuit sorted alphabetically. Note that parameters instantiated with a :class:`.ParameterVector` are still sorted numerically. Examples: The snippet below shows that insertion order of parameters does not matter. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter >>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant") >>> circuit = QuantumCircuit(1) >>> circuit.rx(b, 0) >>> circuit.rz(elephant, 0) >>> circuit.ry(a, 0) >>> circuit.parameters # sorted alphabetically! ParameterView([Parameter(a), Parameter(b), Parameter(elephant)]) Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal "10" comes before "2" in strict alphabetical sorting. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter >>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")] >>> circuit = QuantumCircuit(1) >>> circuit.u(*angles, 0) >>> circuit.draw() ┌─────────────────────────────┐ q: ┤ U(angle_1,angle_2,angle_10) ├ └─────────────────────────────┘ >>> circuit.parameters ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)]) To respect numerical sorting, a :class:`.ParameterVector` can be used. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector >>> x = ParameterVector("x", 12) >>> circuit = QuantumCircuit(1) >>> for x_i in x: ... circuit.rx(x_i, 0) >>> circuit.parameters ParameterView([ ParameterVectorElement(x[0]), ParameterVectorElement(x[1]), ParameterVectorElement(x[2]), ParameterVectorElement(x[3]), ..., ParameterVectorElement(x[11]) ]) Returns: The sorted :class:`.Parameter` objects in the circuit. """ # parameters from gates if self._parameters is None: self._parameters = sort_parameters(self._unsorted_parameters()) # return as parameter view, which implements the set and list interface return ParameterView(self._parameters) @property def num_parameters(self) -> int: """The number of parameter objects in the circuit.""" return len(self._unsorted_parameters()) def _unsorted_parameters(self) -> set[Parameter]: """Efficiently get all parameters in the circuit, without any sorting overhead.""" parameters = set(self._parameter_table) if isinstance(self.global_phase, ParameterExpression): parameters.update(self.global_phase.parameters) return parameters @overload def assign_parameters( self, parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]], inplace: Literal[False] = ..., *, flat_input: bool = ..., strict: bool = ..., ) -> "QuantumCircuit": ... @overload def assign_parameters( self, parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]], inplace: Literal[True] = ..., *, flat_input: bool = ..., strict: bool = ..., ) -> None: ... def assign_parameters( # pylint: disable=missing-raises-doc self, parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]], inplace: bool = False, *, flat_input: bool = False, strict: bool = True, ) -> Optional["QuantumCircuit"]: """Assign parameters to new parameters or values. If ``parameters`` is passed as a dictionary, the keys must be :class:`.Parameter` instances in the current circuit. The values of the dictionary can either be numeric values or new parameter objects. If ``parameters`` is passed as a list or array, the elements are assigned to the current parameters in the order of :attr:`parameters` which is sorted alphabetically (while respecting the ordering in :class:`.ParameterVector` objects). The values can be assigned to the current circuit object or to a copy of it. Args: parameters: Either a dictionary or iterable specifying the new parameter values. inplace: If False, a copy of the circuit with the bound parameters is returned. If True the circuit instance itself is modified. flat_input: If ``True`` and ``parameters`` is a mapping type, it is assumed to be exactly a mapping of ``{parameter: value}``. By default (``False``), the mapping may also contain :class:`.ParameterVector` keys that point to a corresponding sequence of values, and these will be unrolled during the mapping. strict: If ``False``, any parameters given in the mapping that are not used in the circuit will be ignored. If ``True`` (the default), an error will be raised indicating a logic error. Raises: CircuitError: If parameters is a dict and contains parameters not present in the circuit. ValueError: If parameters is a list/array and the length mismatches the number of free parameters in the circuit. Returns: A copy of the circuit with bound parameters if ``inplace`` is False, otherwise None. Examples: Create a parameterized circuit and assign the parameters in-place. .. plot:: :include-source: from qiskit.circuit import QuantumCircuit, Parameter circuit = QuantumCircuit(2) params = [Parameter('A'), Parameter('B'), Parameter('C')] circuit.ry(params[0], 0) circuit.crx(params[1], 0, 1) circuit.draw('mpl') circuit.assign_parameters({params[0]: params[2]}, inplace=True) circuit.draw('mpl') Bind the values out-of-place by list and get a copy of the original circuit. .. plot:: :include-source: from qiskit.circuit import QuantumCircuit, ParameterVector circuit = QuantumCircuit(2) params = ParameterVector('P', 2) circuit.ry(params[0], 0) circuit.crx(params[1], 0, 1) bound_circuit = circuit.assign_parameters([1, 2]) bound_circuit.draw('mpl') circuit.draw('mpl') """ if inplace: target = self else: target = self.copy() target._increment_instances() target._name_update() # Normalise the inputs into simple abstract interfaces, so we've dispatched the "iteration" # logic in one place at the start of the function. This lets us do things like calculate # and cache expensive properties for (e.g.) the sequence format only if they're used; for # many large, close-to-hardware circuits, we won't need the extra handling for # `global_phase` or recursive definition binding. # # During normalisation, be sure to reference 'parameters' and related things from 'self' not # 'target' so we can take advantage of any caching we might be doing. if isinstance(parameters, dict): raw_mapping = parameters if flat_input else self._unroll_param_dict(parameters) our_parameters = self._unsorted_parameters() if strict and (extras := raw_mapping.keys() - our_parameters): raise CircuitError( f"Cannot bind parameters ({', '.join(str(x) for x in extras)}) not present in" " the circuit." ) parameter_binds = _ParameterBindsDict(raw_mapping, our_parameters) else: our_parameters = self.parameters if len(parameters) != len(our_parameters): raise ValueError( "Mismatching number of values and parameters. For partial binding " "please pass a dictionary of {parameter: value} pairs." ) parameter_binds = _ParameterBindsSequence(our_parameters, parameters) # Clear out the parameter table for the relevant entries, since we'll be binding those. # Any new references to parameters are reinserted as part of the bind. target._parameters = None # This is deliberately eager, because we want the side effect of clearing the table. all_references = [ (parameter, value, target._parameter_table.pop(parameter, ())) for parameter, value in parameter_binds.items() ] seen_operations = {} # The meat of the actual binding for regular operations. for to_bind, bound_value, references in all_references: update_parameters = ( tuple(bound_value.parameters) if isinstance(bound_value, ParameterExpression) else () ) for operation, index in references: seen_operations[id(operation)] = operation assignee = operation.params[index] if isinstance(assignee, ParameterExpression): new_parameter = assignee.assign(to_bind, bound_value) for parameter in update_parameters: if parameter not in target._parameter_table: target._parameter_table[parameter] = ParameterReferences(()) target._parameter_table[parameter].add((operation, index)) if not new_parameter.parameters: if new_parameter.is_real(): new_parameter = ( int(new_parameter) if new_parameter._symbol_expr.is_integer else float(new_parameter) ) else: new_parameter = complex(new_parameter) new_parameter = operation.validate_parameter(new_parameter) elif isinstance(assignee, QuantumCircuit): new_parameter = assignee.assign_parameters( {to_bind: bound_value}, inplace=False, flat_input=True ) else: raise RuntimeError( # pragma: no cover f"Saw an unknown type during symbolic binding: {assignee}." " This may indicate an internal logic error in symbol tracking." ) operation.params[index] = new_parameter # After we've been through everything at the top level, make a single visit to each # operation we've seen, rebinding its definition if necessary. for operation in seen_operations.values(): if ( definition := getattr(operation, "_definition", None) ) is not None and definition.num_parameters: definition.assign_parameters( parameter_binds.mapping, inplace=True, flat_input=True, strict=False ) if isinstance(target.global_phase, ParameterExpression): new_phase = target.global_phase for parameter in new_phase.parameters & parameter_binds.mapping.keys(): new_phase = new_phase.assign(parameter, parameter_binds.mapping[parameter]) target.global_phase = new_phase # Finally, assign the parameters inside any of the calibrations. We don't track these in # the `ParameterTable`, so we manually reconstruct things. def map_calibration(qubits, parameters, schedule): modified = False new_parameters = list(parameters) for i, parameter in enumerate(new_parameters): if not isinstance(parameter, ParameterExpression): continue if not (contained := parameter.parameters & parameter_binds.mapping.keys()): continue for to_bind in contained: parameter = parameter.assign(to_bind, parameter_binds.mapping[to_bind]) if not parameter.parameters: parameter = ( int(parameter) if parameter._symbol_expr.is_integer else float(parameter) ) new_parameters[i] = parameter modified = True if modified: schedule.assign_parameters(parameter_binds.mapping) return (qubits, tuple(new_parameters)), schedule target._calibrations = defaultdict( dict, ( ( gate, dict( map_calibration(qubits, parameters, schedule) for (qubits, parameters), schedule in calibrations.items() ), ) for gate, calibrations in target._calibrations.items() ), ) return None if inplace else target @staticmethod def _unroll_param_dict( parameter_binds: Mapping[Parameter, ParameterValueType] ) -> Mapping[Parameter, ParameterValueType]: out = {} for parameter, value in parameter_binds.items(): if isinstance(parameter, ParameterVector): if len(parameter) != len(value): raise CircuitError( f"Parameter vector '{parameter.name}' has length {len(parameter)}," f" but was assigned to {len(value)} values." ) out.update(zip(parameter, value)) else: out[parameter] = value return out def bind_parameters( self, values: Union[Mapping[Parameter, float], Sequence[float]] ) -> "QuantumCircuit": """Assign numeric parameters to values yielding a new circuit. If the values are given as list or array they are bound to the circuit in the order of :attr:`parameters` (see the docstring for more details). To assign new Parameter objects or bind the values in-place, without yielding a new circuit, use the :meth:`assign_parameters` method. Args: values: ``{parameter: value, ...}`` or ``[value1, value2, ...]`` Raises: CircuitError: If values is a dict and contains parameters not present in the circuit. TypeError: If values contains a ParameterExpression. Returns: Copy of self with assignment substitution. """ if isinstance(values, dict): if any(isinstance(value, ParameterExpression) for value in values.values()): raise TypeError( "Found ParameterExpression in values; use assign_parameters() instead." ) return self.assign_parameters(values) else: if any(isinstance(value, ParameterExpression) for value in values): raise TypeError( "Found ParameterExpression in values; use assign_parameters() instead." ) return self.assign_parameters(values) def barrier(self, *qargs: QubitSpecifier, label=None) -> InstructionSet: """Apply :class:`~.library.Barrier`. If ``qargs`` is empty, applies to all qubits in the circuit. Args: qargs (QubitSpecifier): Specification for one or more qubit arguments. label (str): The string label of the barrier. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. """ from .barrier import Barrier qubits: list[QubitSpecifier] = [] if not qargs: # None qubits.extend(self.qubits) for qarg in qargs: if isinstance(qarg, QuantumRegister): qubits.extend([qarg[j] for j in range(qarg.size)]) elif isinstance(qarg, list): qubits.extend(qarg) elif isinstance(qarg, range): qubits.extend(list(qarg)) elif isinstance(qarg, slice): qubits.extend(self.qubits[qarg]) else: qubits.append(qarg) return self.append(Barrier(len(qubits), label=label), qubits, []) def delay( self, duration: ParameterValueType, qarg: QubitSpecifier | None = None, unit: str = "dt", ) -> InstructionSet: """Apply :class:`~.circuit.Delay`. If qarg is ``None``, applies to all qubits. When applying to multiple qubits, delays with the same duration will be created. Args: duration (int or float or ParameterExpression): duration of the delay. qarg (Object): qubit argument to apply this delay. unit (str): unit of the duration. Supported units: ``'s'``, ``'ms'``, ``'us'``, ``'ns'``, ``'ps'``, and ``'dt'``. Default is ``'dt'``, i.e. integer time unit depending on the target backend. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. Raises: CircuitError: if arguments have bad format. """ qubits: list[QubitSpecifier] = [] if qarg is None: # -> apply delays to all qubits for q in self.qubits: qubits.append(q) else: if isinstance(qarg, QuantumRegister): qubits.extend([qarg[j] for j in range(qarg.size)]) elif isinstance(qarg, list): qubits.extend(qarg) elif isinstance(qarg, (range, tuple)): qubits.extend(list(qarg)) elif isinstance(qarg, slice): qubits.extend(self.qubits[qarg]) else: qubits.append(qarg) instructions = InstructionSet(resource_requester=self._resolve_classical_resource) for q in qubits: inst: tuple[ Instruction, Sequence[QubitSpecifier] | None, Sequence[ClbitSpecifier] | None ] = (Delay(duration, unit), [q], []) self.append(*inst) instructions.add(*inst) return instructions def h(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.HGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.h import HGate return self.append(HGate(), [qubit], []) def ch( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CHGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.h import CHGate return self.append( CHGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def i(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.IGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.i import IGate return self.append(IGate(), [qubit], []) def id(self, qubit: QubitSpecifier) -> InstructionSet: # pylint: disable=invalid-name """Apply :class:`~qiskit.circuit.library.IGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. See Also: QuantumCircuit.i: the same function. """ return self.i(qubit) def ms(self, theta: ParameterValueType, qubits: Sequence[QubitSpecifier]) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MSGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. qubits: The qubits to apply the gate to. Returns: A handle to the instructions created. """ # pylint: disable=cyclic-import from .library.generalized_gates.gms import MSGate return self.append(MSGate(len(qubits), theta), qubits) def p(self, theta: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.PhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: THe angle of the rotation. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.p import PhaseGate return self.append(PhaseGate(theta), [qubit], []) def cp( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CPhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.p import CPhaseGate return self.append( CPhaseGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def mcp( self, lam: ParameterValueType, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCPhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: lam: The angle of the rotation. control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ from .library.standard_gates.p import MCPhaseGate num_ctrl_qubits = len(control_qubits) return self.append( MCPhaseGate(lam, num_ctrl_qubits), control_qubits[:] + [target_qubit], [] ) def r( self, theta: ParameterValueType, phi: ParameterValueType, qubit: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. phi: The angle of the axis of rotation in the x-y plane. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.r import RGate return self.append(RGate(theta, phi), [qubit], []) def rv( self, vx: ParameterValueType, vy: ParameterValueType, vz: ParameterValueType, qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RVGate`. For the full matrix form of this gate, see the underlying gate documentation. Rotation around an arbitrary rotation axis :math:`v`, where :math:`|v|` is the angle of rotation in radians. Args: vx: x-component of the rotation axis. vy: y-component of the rotation axis. vz: z-component of the rotation axis. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.generalized_gates.rv import RVGate return self.append(RVGate(vx, vy, vz), [qubit], []) def rccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RCCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ from .library.standard_gates.x import RCCXGate return self.append(RCCXGate(), [control_qubit1, control_qubit2, target_qubit], []) def rcccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, control_qubit3: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RC3XGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. control_qubit3: The qubit(s) used as the third control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ from .library.standard_gates.x import RC3XGate return self.append( RC3XGate(), [control_qubit1, control_qubit2, control_qubit3, target_qubit], [] ) def rx( self, theta: ParameterValueType, qubit: QubitSpecifier, label: str | None = None ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ from .library.standard_gates.rx import RXGate return self.append(RXGate(theta, label=label), [qubit], []) def crx( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.rx import CRXGate return self.append( CRXGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def rxx( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RXXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rxx import RXXGate return self.append(RXXGate(theta), [qubit1, qubit2], []) def ry( self, theta: ParameterValueType, qubit: QubitSpecifier, label: str | None = None ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ from .library.standard_gates.ry import RYGate return self.append(RYGate(theta, label=label), [qubit], []) def cry( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.ry import CRYGate return self.append( CRYGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def ryy( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RYYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.ryy import RYYGate return self.append(RYYGate(theta), [qubit1, qubit2], []) def rz(self, phi: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: phi: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rz import RZGate return self.append(RZGate(phi), [qubit], []) def crz( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.rz import CRZGate return self.append( CRZGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def rzx( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rzx import RZXGate return self.append(RZXGate(theta), [qubit1, qubit2], []) def rzz( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rzz import RZZGate return self.append(RZZGate(theta), [qubit1, qubit2], []) def ecr(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.ECRGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.ecr import ECRGate return self.append(ECRGate(), [qubit1, qubit2], []) def s(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.s import SGate return self.append(SGate(), [qubit], []) def sdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.s import SdgGate return self.append(SdgGate(), [qubit], []) def cs( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.s import CSGate return self.append( CSGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def csdg( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.s import CSdgGate return self.append( CSdgGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def swap(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.swap import SwapGate return self.append(SwapGate(), [qubit1, qubit2], []) def iswap(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.iSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.iswap import iSwapGate return self.append(iSwapGate(), [qubit1, qubit2], []) def cswap( self, control_qubit: QubitSpecifier, target_qubit1: QubitSpecifier, target_qubit2: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit1: The qubit(s) targeted by the gate. target_qubit2: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. ``'1'``). Defaults to controlling on the ``'1'`` state. Returns: A handle to the instructions created. """ from .library.standard_gates.swap import CSwapGate return self.append( CSwapGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit1, target_qubit2], [], ) def fredkin( self, control_qubit: QubitSpecifier, target_qubit1: QubitSpecifier, target_qubit2: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit1: The qubit(s) targeted by the gate. target_qubit2: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. See Also: QuantumCircuit.cswap: the same function with a different name. """ return self.cswap(control_qubit, target_qubit1, target_qubit2) def sx(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.sx import SXGate return self.append(SXGate(), [qubit], []) def sxdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SXdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.sx import SXdgGate return self.append(SXdgGate(), [qubit], []) def csx( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.sx import CSXGate return self.append( CSXGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def t(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.TGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.t import TGate return self.append(TGate(), [qubit], []) def tdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.TdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.t import TdgGate return self.append(TdgGate(), [qubit], []) def u( self, theta: ParameterValueType, phi: ParameterValueType, lam: ParameterValueType, qubit: QubitSpecifier, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.UGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The :math:`\theta` rotation angle of the gate. phi: The :math:`\phi` rotation angle of the gate. lam: The :math:`\lambda` rotation angle of the gate. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.u import UGate return self.append(UGate(theta, phi, lam), [qubit], []) def cu( self, theta: ParameterValueType, phi: ParameterValueType, lam: ParameterValueType, gamma: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CUGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The :math:`\theta` rotation angle of the gate. phi: The :math:`\phi` rotation angle of the gate. lam: The :math:`\lambda` rotation angle of the gate. gamma: The global phase applied of the U gate, if applied. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.u import CUGate return self.append( CUGate(theta, phi, lam, gamma, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def x(self, qubit: QubitSpecifier, label: str | None = None) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.XGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ from .library.standard_gates.x import XGate return self.append(XGate(label=label), [qubit], []) def cx( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.x import CXGate return self.append( CXGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def cnot( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. See Also: QuantumCircuit.cx: the same function with a different name. """ return self.cx(control_qubit, target_qubit, label, ctrl_state) def dcx(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.DCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.dcx import DCXGate return self.append(DCXGate(), [qubit1, qubit2], []) def ccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.x import CCXGate return self.append( CCXGate(ctrl_state=ctrl_state), [control_qubit1, control_qubit2, target_qubit], [], ) def toffoli( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. See Also: QuantumCircuit.ccx: the same gate with a different name. """ return self.ccx(control_qubit1, control_qubit2, target_qubit) def mcx( self, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ancilla_qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, mode: str = "noancilla", ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCXGate`. The multi-cX gate can be implemented using different techniques, which use different numbers of ancilla qubits and have varying circuit depth. These modes are: - ``'noancilla'``: Requires 0 ancilla qubits. - ``'recursion'``: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0. - ``'v-chain'``: Requires 2 less ancillas than the number of control qubits. - ``'v-chain-dirty'``: Same as for the clean ancillas (but the circuit will be longer). For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. ancilla_qubits: The qubits used as the ancillae, if the mode requires them. mode: The choice of mode, explained further above. Returns: A handle to the instructions created. Raises: ValueError: if the given mode is not known, or if too few ancilla qubits are passed. AttributeError: if no ancilla qubits are passed, but some are needed. """ from .library.standard_gates.x import MCXGrayCode, MCXRecursive, MCXVChain num_ctrl_qubits = len(control_qubits) available_implementations = { "noancilla": MCXGrayCode(num_ctrl_qubits), "recursion": MCXRecursive(num_ctrl_qubits), "v-chain": MCXVChain(num_ctrl_qubits, False), "v-chain-dirty": MCXVChain(num_ctrl_qubits, dirty_ancillas=True), # outdated, previous names "advanced": MCXRecursive(num_ctrl_qubits), "basic": MCXVChain(num_ctrl_qubits, dirty_ancillas=False), "basic-dirty-ancilla": MCXVChain(num_ctrl_qubits, dirty_ancillas=True), } # check ancilla input if ancilla_qubits: _ = self.qbit_argument_conversion(ancilla_qubits) try: gate = available_implementations[mode] except KeyError as ex: all_modes = list(available_implementations.keys()) raise ValueError( f"Unsupported mode ({mode}) selected, choose one of {all_modes}" ) from ex if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0: required = gate.num_ancilla_qubits if ancilla_qubits is None: raise AttributeError(f"No ancillas provided, but {required} are needed!") # convert ancilla qubits to a list if they were passed as int or qubit if not hasattr(ancilla_qubits, "__len__"): ancilla_qubits = [ancilla_qubits] if len(ancilla_qubits) < required: actually = len(ancilla_qubits) raise ValueError(f"At least {required} ancillas required, but {actually} given.") # size down if too many ancillas were provided ancilla_qubits = ancilla_qubits[:required] else: ancilla_qubits = [] return self.append(gate, control_qubits[:] + [target_qubit] + ancilla_qubits[:], []) def mct( self, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ancilla_qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, mode: str = "noancilla", ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCXGate`. The multi-cX gate can be implemented using different techniques, which use different numbers of ancilla qubits and have varying circuit depth. These modes are: - ``'noancilla'``: Requires 0 ancilla qubits. - ``'recursion'``: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0. - ``'v-chain'``: Requires 2 less ancillas than the number of control qubits. - ``'v-chain-dirty'``: Same as for the clean ancillas (but the circuit will be longer). For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. ancilla_qubits: The qubits used as the ancillae, if the mode requires them. mode: The choice of mode, explained further above. Returns: A handle to the instructions created. Raises: ValueError: if the given mode is not known, or if too few ancilla qubits are passed. AttributeError: if no ancilla qubits are passed, but some are needed. See Also: QuantumCircuit.mcx: the same gate with a different name. """ return self.mcx(control_qubits, target_qubit, ancilla_qubits, mode) def y(self, qubit: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.YGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.y import YGate return self.append(YGate(), [qubit], []) def cy( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the controls. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.y import CYGate return self.append( CYGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def z(self, qubit: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.ZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.z import ZGate return self.append(ZGate(), [qubit], []) def cz( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the controls. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.z import CZGate return self.append( CZGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def ccz( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '10'). Defaults to controlling on the '11' state. Returns: A handle to the instructions created. """ from .library.standard_gates.z import CCZGate return self.append( CCZGate(label=label, ctrl_state=ctrl_state), [control_qubit1, control_qubit2, target_qubit], [], ) def pauli( self, pauli_string: str, qubits: Sequence[QubitSpecifier], ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.PauliGate`. Args: pauli_string: A string representing the Pauli operator to apply, e.g. 'XX'. qubits: The qubits to apply this gate to. Returns: A handle to the instructions created. """ from qiskit.circuit.library.generalized_gates.pauli import PauliGate return self.append(PauliGate(pauli_string), qubits, []) def _push_scope( self, qubits: Iterable[Qubit] = (), clbits: Iterable[Clbit] = (), registers: Iterable[Register] = (), allow_jumps: bool = True, forbidden_message: Optional[str] = None, ): """Add a scope for collecting instructions into this circuit. This should only be done by the control-flow context managers, which will handle cleaning up after themselves at the end as well. Args: qubits: Any qubits that this scope should automatically use. clbits: Any clbits that this scope should automatically use. allow_jumps: Whether this scope allows jumps to be used within it. forbidden_message: If given, all attempts to add instructions to this scope will raise a :exc:`.CircuitError` with this message. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.builder import ControlFlowBuilderBlock # Chain resource requests so things like registers added to inner scopes via conditions are # requested in the outer scope as well. if self._control_flow_scopes: resource_requester = self._control_flow_scopes[-1].request_classical_resource else: resource_requester = self._resolve_classical_resource self._control_flow_scopes.append( ControlFlowBuilderBlock( qubits, clbits, resource_requester=resource_requester, registers=registers, allow_jumps=allow_jumps, forbidden_message=forbidden_message, ) ) def _pop_scope(self) -> "qiskit.circuit.controlflow.builder.ControlFlowBuilderBlock": """Finish a scope used in the control-flow builder interface, and return it to the caller. This should only be done by the control-flow context managers, since they naturally synchronise the creation and deletion of stack elements.""" return self._control_flow_scopes.pop() def _peek_previous_instruction_in_scope(self) -> CircuitInstruction: """Return the instruction 3-tuple of the most recent instruction in the current scope, even if that scope is currently under construction. This function is only intended for use by the control-flow ``if``-statement builders, which may need to modify a previous instruction.""" if self._control_flow_scopes: return self._control_flow_scopes[-1].peek() if not self._data: raise CircuitError("This circuit contains no instructions.") return self._data[-1] def _pop_previous_instruction_in_scope(self) -> CircuitInstruction: """Return the instruction 3-tuple of the most recent instruction in the current scope, even if that scope is currently under construction, and remove it from that scope. This function is only intended for use by the control-flow ``if``-statement builders, which may need to replace a previous instruction with another. """ if self._control_flow_scopes: return self._control_flow_scopes[-1].pop() if not self._data: raise CircuitError("This circuit contains no instructions.") instruction = self._data.pop() if isinstance(instruction.operation, Instruction): self._update_parameter_table_on_instruction_removal(instruction) return instruction def _update_parameter_table_on_instruction_removal(self, instruction: CircuitInstruction): """Update the :obj:`.ParameterTable` of this circuit given that an instance of the given ``instruction`` has just been removed from the circuit. .. note:: This does not account for the possibility for the same instruction instance being added more than once to the circuit. At the time of writing (2021-11-17, main commit 271a82f) there is a defensive ``deepcopy`` of parameterised instructions inside :meth:`.QuantumCircuit.append`, so this should be safe. Trying to account for it would involve adding a potentially quadratic-scaling loop to check each entry in ``data``. """ atomic_parameters: list[tuple[Parameter, int]] = [] for index, parameter in enumerate(instruction.operation.params): if isinstance(parameter, (ParameterExpression, QuantumCircuit)): atomic_parameters.extend((p, index) for p in parameter.parameters) for atomic_parameter, index in atomic_parameters: new_entries = self._parameter_table[atomic_parameter].copy() new_entries.discard((instruction.operation, index)) if not new_entries: del self._parameter_table[atomic_parameter] # Invalidate cache. self._parameters = None else: self._parameter_table[atomic_parameter] = new_entries @typing.overload def while_loop( self, condition: tuple[ClassicalRegister | Clbit, int] | expr.Expr, body: None, qubits: None, clbits: None, *, label: str | None, ) -> "qiskit.circuit.controlflow.while_loop.WhileLoopContext": ... @typing.overload def while_loop( self, condition: tuple[ClassicalRegister | Clbit, int] | expr.Expr, body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None, ) -> InstructionSet: ... def while_loop(self, condition, body=None, qubits=None, clbits=None, *, label=None): """Create a ``while`` loop on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :obj:`~qiskit.circuit.controlflow.WhileLoopOp` with the given ``body``. If ``body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which will automatically build a :obj:`~qiskit.circuit.controlflow.WhileLoopOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. Example usage:: from qiskit.circuit import QuantumCircuit, Clbit, Qubit bits = [Qubit(), Qubit(), Clbit()] qc = QuantumCircuit(bits) with qc.while_loop((bits[2], 0)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) Args: condition (Tuple[Union[ClassicalRegister, Clbit], int]): An equality condition to be checked prior to executing ``body``. The left-hand side of the condition must be a :obj:`~ClassicalRegister` or a :obj:`~Clbit`, and the right-hand side must be an integer or boolean. body (Optional[QuantumCircuit]): The loop body to be repeatedly executed. Omit this to use the context-manager mode. qubits (Optional[Sequence[Qubit]]): The circuit qubits over which the loop body should be run. Omit this to use the context-manager mode. clbits (Optional[Sequence[Clbit]]): The circuit clbits over which the loop body should be run. Omit this to use the context-manager mode. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or WhileLoopContext: If used in context-manager mode, then this should be used as a ``with`` resource, which will infer the block content and operands on exit. If the full form is used, then this returns a handle to the instructions created. Raises: CircuitError: if an incorrect calling convention is used. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.while_loop import WhileLoopOp, WhileLoopContext if isinstance(condition, expr.Expr): condition = self._validate_expr(condition) else: condition = (self._resolve_classical_resource(condition[0]), condition[1]) if body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'while_loop' as a context manager," " you cannot pass qubits or clbits." ) return WhileLoopContext(self, condition, label=label) elif qubits is None or clbits is None: raise CircuitError( "When using 'while_loop' with a body, you must pass qubits and clbits." ) return self.append(WhileLoopOp(condition, body, label), qubits, clbits) @typing.overload def for_loop( self, indexset: Iterable[int], loop_parameter: Parameter | None, body: None, qubits: None, clbits: None, *, label: str | None, ) -> "qiskit.circuit.controlflow.for_loop.ForLoopContext": ... @typing.overload def for_loop( self, indexset: Iterable[int], loop_parameter: Union[Parameter, None], body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None, ) -> InstructionSet: ... def for_loop( self, indexset, loop_parameter=None, body=None, qubits=None, clbits=None, *, label=None ): """Create a ``for`` loop on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :class:`~qiskit.circuit.ForLoopOp` with the given ``body``. If ``body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which, when entered, provides a loop variable (unless one is given, in which case it will be reused) and will automatically build a :class:`~qiskit.circuit.ForLoopOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. For example:: from qiskit import QuantumCircuit qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)) as i: qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) Args: indexset (Iterable[int]): A collection of integers to loop over. Always necessary. loop_parameter (Optional[Parameter]): The parameter used within ``body`` to which the values from ``indexset`` will be assigned. In the context-manager form, if this argument is not supplied, then a loop parameter will be allocated for you and returned as the value of the ``with`` statement. This will only be bound into the circuit if it is used within the body. If this argument is ``None`` in the manual form of this method, ``body`` will be repeated once for each of the items in ``indexset`` but their values will be ignored. body (Optional[QuantumCircuit]): The loop body to be repeatedly executed. Omit this to use the context-manager mode. qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the loop body should be run. Omit this to use the context-manager mode. clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the loop body should be run. Omit this to use the context-manager mode. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or ForLoopContext: depending on the call signature, either a context manager for creating the for loop (it will automatically be added to the circuit at the end of the block), or an :obj:`~InstructionSet` handle to the appended loop operation. Raises: CircuitError: if an incorrect calling convention is used. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.for_loop import ForLoopOp, ForLoopContext if body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'for_loop' as a context manager, you cannot pass qubits or clbits." ) return ForLoopContext(self, indexset, loop_parameter, label=label) elif qubits is None or clbits is None: raise CircuitError( "When using 'for_loop' with a body, you must pass qubits and clbits." ) return self.append(ForLoopOp(indexset, loop_parameter, body, label), qubits, clbits) @typing.overload def if_test( self, condition: tuple[ClassicalRegister | Clbit, int], true_body: None, qubits: None, clbits: None, *, label: str | None, ) -> "qiskit.circuit.controlflow.if_else.IfContext": ... @typing.overload def if_test( self, condition: tuple[ClassicalRegister | Clbit, int], true_body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None = None, ) -> InstructionSet: ... def if_test( self, condition, true_body=None, qubits=None, clbits=None, *, label=None, ): """Create an ``if`` statement on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :obj:`~qiskit.circuit.IfElseOp` with the given ``true_body``, and there will be no branch for the ``false`` condition (see also the :meth:`.if_else` method). However, if ``true_body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which can be used to build ``if`` statements. The return value of the ``with`` statement is a chainable context manager, which can be used to create subsequent ``else`` blocks. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. For example:: from qiskit.circuit import QuantumCircuit, Qubit, Clbit bits = [Qubit(), Qubit(), Qubit(), Clbit(), Clbit()] qc = QuantumCircuit(bits) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.h(0) qc.cx(0, 1) qc.measure(0, 1) with qc.if_test((bits[3], 0)) as else_: qc.x(2) with else_: qc.h(2) qc.z(2) Args: condition (Tuple[Union[ClassicalRegister, Clbit], int]): A condition to be evaluated at circuit runtime which, if true, will trigger the evaluation of ``true_body``. Can be specified as either a tuple of a ``ClassicalRegister`` to be tested for equality with a given ``int``, or as a tuple of a ``Clbit`` to be compared to either a ``bool`` or an ``int``. true_body (Optional[QuantumCircuit]): The circuit body to be run if ``condition`` is true. qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the if/else should be run. clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the if/else should be run. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or IfContext: depending on the call signature, either a context manager for creating the ``if`` block (it will automatically be added to the circuit at the end of the block), or an :obj:`~InstructionSet` handle to the appended conditional operation. Raises: CircuitError: If the provided condition references Clbits outside the enclosing circuit. CircuitError: if an incorrect calling convention is used. Returns: A handle to the instruction created. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.if_else import IfElseOp, IfContext if isinstance(condition, expr.Expr): condition = self._validate_expr(condition) else: condition = (self._resolve_classical_resource(condition[0]), condition[1]) if true_body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'if_test' as a context manager, you cannot pass qubits or clbits." ) # We can only allow jumps if we're in a loop block, but the default path (no scopes) # also allows adding jumps to support the more verbose internal mode. in_loop = bool(self._control_flow_scopes and self._control_flow_scopes[-1].allow_jumps) return IfContext(self, condition, in_loop=in_loop, label=label) elif qubits is None or clbits is None: raise CircuitError("When using 'if_test' with a body, you must pass qubits and clbits.") return self.append(IfElseOp(condition, true_body, None, label), qubits, clbits) def if_else( self, condition: tuple[ClassicalRegister, int] | tuple[Clbit, int] | tuple[Clbit, bool], true_body: "QuantumCircuit", false_body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], label: str | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.IfElseOp`. .. note:: This method does not have an associated context-manager form, because it is already handled by the :meth:`.if_test` method. You can use the ``else`` part of that with something such as:: from qiskit.circuit import QuantumCircuit, Qubit, Clbit bits = [Qubit(), Qubit(), Clbit()] qc = QuantumCircuit(bits) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) with qc.if_test((bits[2], 0)) as else_: qc.h(0) with else_: qc.x(0) Args: condition: A condition to be evaluated at circuit runtime which, if true, will trigger the evaluation of ``true_body``. Can be specified as either a tuple of a ``ClassicalRegister`` to be tested for equality with a given ``int``, or as a tuple of a ``Clbit`` to be compared to either a ``bool`` or an ``int``. true_body: The circuit body to be run if ``condition`` is true. false_body: The circuit to be run if ``condition`` is false. qubits: The circuit qubits over which the if/else should be run. clbits: The circuit clbits over which the if/else should be run. label: The string label of the instruction in the circuit. Raises: CircuitError: If the provided condition references Clbits outside the enclosing circuit. Returns: A handle to the instruction created. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.if_else import IfElseOp if isinstance(condition, expr.Expr): condition = self._validate_expr(condition) else: condition = (self._resolve_classical_resource(condition[0]), condition[1]) return self.append(IfElseOp(condition, true_body, false_body, label), qubits, clbits) @typing.overload def switch( self, target: Union[ClbitSpecifier, ClassicalRegister], cases: None, qubits: None, clbits: None, *, label: Optional[str], ) -> "qiskit.circuit.controlflow.switch_case.SwitchContext": ... @typing.overload def switch( self, target: Union[ClbitSpecifier, ClassicalRegister], cases: Iterable[Tuple[typing.Any, QuantumCircuit]], qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: Optional[str], ) -> InstructionSet: ... def switch(self, target, cases=None, qubits=None, clbits=None, *, label=None): """Create a ``switch``/``case`` structure on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :class:`.SwitchCaseOp` with the given case structure. If ``cases`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which will automatically build a :class:`.SwitchCaseOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. Example usage:: from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister qreg = QuantumRegister(3) creg = ClassicalRegister(3) qc = QuantumCircuit(qreg, creg) qc.h([0, 1, 2]) qc.measure([0, 1, 2], [0, 1, 2]) with qc.switch(creg) as case: with case(0): qc.x(0) with case(1, 2): qc.z(1) with case(case.DEFAULT): qc.cx(0, 1) Args: target (Union[ClassicalRegister, Clbit]): The classical value to switch one. This must be integer-like. cases (Iterable[Tuple[typing.Any, QuantumCircuit]]): A sequence of case specifiers. Each tuple defines one case body (the second item). The first item of the tuple can be either a single integer value, the special value :data:`.CASE_DEFAULT`, or a tuple of several integer values. Each of the integer values will be tried in turn; control will then pass to the body corresponding to the first match. :data:`.CASE_DEFAULT` matches all possible values. Omit in context-manager form. qubits (Sequence[Qubit]): The circuit qubits over which all case bodies execute. Omit in context-manager form. clbits (Sequence[Clbit]): The circuit clbits over which all case bodies execute. Omit in context-manager form. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or SwitchCaseContext: If used in context-manager mode, then this should be used as a ``with`` resource, which will return an object that can be repeatedly entered to produce cases for the switch statement. If the full form is used, then this returns a handle to the instructions created. Raises: CircuitError: if an incorrect calling convention is used. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.switch_case import SwitchCaseOp, SwitchContext if isinstance(target, expr.Expr): target = self._validate_expr(target) else: target = self._resolve_classical_resource(target) if cases is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'switch' as a context manager, you cannot pass qubits or clbits." ) in_loop = bool(self._control_flow_scopes and self._control_flow_scopes[-1].allow_jumps) return SwitchContext(self, target, in_loop=in_loop, label=label) if qubits is None or clbits is None: raise CircuitError("When using 'switch' with cases, you must pass qubits and clbits.") return self.append(SwitchCaseOp(target, cases, label=label), qubits, clbits) def break_loop(self) -> InstructionSet: """Apply :class:`~qiskit.circuit.BreakLoopOp`. .. warning:: If you are using the context-manager "builder" forms of :meth:`.if_test`, :meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are within a loop context, because otherwise the "resource width" of the operation cannot be determined. This would quickly lead to invalid circuits, and so if you are trying to construct a reusable loop body (without the context managers), you must also use the non-context-manager form of :meth:`.if_test` and :meth:`.if_else`. Take care that the :obj:`.BreakLoopOp` instruction must span all the resources of its containing loop, not just the immediate scope. Returns: A handle to the instruction created. Raises: CircuitError: if this method was called within a builder context, but not contained within a loop. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.break_loop import BreakLoopOp, BreakLoopPlaceholder if self._control_flow_scopes: operation = BreakLoopPlaceholder() resources = operation.placeholder_resources() return self.append(operation, resources.qubits, resources.clbits) return self.append(BreakLoopOp(self.num_qubits, self.num_clbits), self.qubits, self.clbits) def continue_loop(self) -> InstructionSet: """Apply :class:`~qiskit.circuit.ContinueLoopOp`. .. warning:: If you are using the context-manager "builder" forms of :meth:`.if_test`, :meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are within a loop context, because otherwise the "resource width" of the operation cannot be determined. This would quickly lead to invalid circuits, and so if you are trying to construct a reusable loop body (without the context managers), you must also use the non-context-manager form of :meth:`.if_test` and :meth:`.if_else`. Take care that the :class:`~qiskit.circuit.ContinueLoopOp` instruction must span all the resources of its containing loop, not just the immediate scope. Returns: A handle to the instruction created. Raises: CircuitError: if this method was called within a builder context, but not contained within a loop. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.continue_loop import ContinueLoopOp, ContinueLoopPlaceholder if self._control_flow_scopes: operation = ContinueLoopPlaceholder() resources = operation.placeholder_resources() return self.append(operation, resources.qubits, resources.clbits) return self.append( ContinueLoopOp(self.num_qubits, self.num_clbits), self.qubits, self.clbits ) def add_calibration( self, gate: Union[Gate, str], qubits: Sequence[int], # Schedule has the type `qiskit.pulse.Schedule`, but `qiskit.pulse` cannot be imported # while this module is, and so Sphinx will not accept a forward reference to it. Sphinx # needs the types available at runtime, whereas mypy will accept it, because it handles the # type checking by static analysis. schedule, params: Sequence[ParameterValueType] | None = None, ) -> None: """Register a low-level, custom pulse definition for the given gate. Args: gate (Union[Gate, str]): Gate information. qubits (Union[int, Tuple[int]]): List of qubits to be measured. schedule (Schedule): Schedule information. params (Optional[List[Union[float, Parameter]]]): A list of parameters. Raises: Exception: if the gate is of type string and params is None. """ def _format(operand): try: # Using float/complex value as a dict key is not good idea. # This makes the mapping quite sensitive to the rounding error. # However, the mechanism is already tied to the execution model (i.e. pulse gate) # and we cannot easily update this rule. # The same logic exists in DAGCircuit.add_calibration. evaluated = complex(operand) if np.isreal(evaluated): evaluated = float(evaluated.real) if evaluated.is_integer(): evaluated = int(evaluated) return evaluated except TypeError: # Unassigned parameter return operand if isinstance(gate, Gate): params = gate.params gate = gate.name if params is not None: params = tuple(map(_format, params)) else: params = () self._calibrations[gate][(tuple(qubits), params)] = schedule # Functions only for scheduled circuits def qubit_duration(self, *qubits: Union[Qubit, int]) -> float: """Return the duration between the start and stop time of the first and last instructions, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Args: *qubits: Qubits within ``self`` to include. Returns: Return the duration between the first start and last stop time of non-delay instructions """ return self.qubit_stop_time(*qubits) - self.qubit_start_time(*qubits) def qubit_start_time(self, *qubits: Union[Qubit, int]) -> float: """Return the start time of the first instruction, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Return 0 if there are no instructions over qubits Args: *qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating indices of ``self.qubits``. Returns: Return the start time of the first instruction, excluding delays, over the qubits Raises: CircuitError: if ``self`` is a not-yet scheduled circuit. """ if self.duration is None: # circuit has only delays, this is kind of scheduled for instruction in self._data: if not isinstance(instruction.operation, Delay): raise CircuitError( "qubit_start_time undefined. Circuit must be scheduled first." ) return 0 qubits = [self.qubits[q] if isinstance(q, int) else q for q in qubits] starts = {q: 0 for q in qubits} dones = {q: False for q in qubits} for instruction in self._data: for q in qubits: if q in instruction.qubits: if isinstance(instruction.operation, Delay): if not dones[q]: starts[q] += instruction.operation.duration else: dones[q] = True if len(qubits) == len([done for done in dones.values() if done]): # all done return min(start for start in starts.values()) return 0 # If there are no instructions over bits def qubit_stop_time(self, *qubits: Union[Qubit, int]) -> float: """Return the stop time of the last instruction, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Return 0 if there are no instructions over qubits Args: *qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating indices of ``self.qubits``. Returns: Return the stop time of the last instruction, excluding delays, over the qubits Raises: CircuitError: if ``self`` is a not-yet scheduled circuit. """ if self.duration is None: # circuit has only delays, this is kind of scheduled for instruction in self._data: if not isinstance(instruction.operation, Delay): raise CircuitError( "qubit_stop_time undefined. Circuit must be scheduled first." ) return 0 qubits = [self.qubits[q] if isinstance(q, int) else q for q in qubits] stops = {q: self.duration for q in qubits} dones = {q: False for q in qubits} for instruction in reversed(self._data): for q in qubits: if q in instruction.qubits: if isinstance(instruction.operation, Delay): if not dones[q]: stops[q] -= instruction.operation.duration else: dones[q] = True if len(qubits) == len([done for done in dones.values() if done]): # all done return max(stop for stop in stops.values()) return 0 # If there are no instructions over bits class _ParameterBindsDict: __slots__ = ("mapping", "allowed_keys") def __init__(self, mapping, allowed_keys): self.mapping = mapping self.allowed_keys = allowed_keys def items(self): """Iterator through all the keys in the mapping that we care about. Wrapping the main mapping allows us to avoid reconstructing a new 'dict', but just use the given 'mapping' without any copy / reconstruction.""" for parameter, value in self.mapping.items(): if parameter in self.allowed_keys: yield parameter, value class _ParameterBindsSequence: __slots__ = ("parameters", "values", "mapping_cache") def __init__(self, parameters, values): self.parameters = parameters self.values = values self.mapping_cache = None def items(self): """Iterator through all the keys in the mapping that we care about.""" return zip(self.parameters, self.values) @property def mapping(self): """Cached version of a mapping. This is only generated on demand.""" if self.mapping_cache is None: self.mapping_cache = dict(zip(self.parameters, self.values)) return self.mapping_cache # Used by the OQ2 exporter. Just needs to have enough parameters to support the largest standard # (non-controlled) gate in our standard library. We have to use the same `Parameter` instances each # time so the equality comparisons will work. _QASM2_FIXED_PARAMETERS = [Parameter("param0"), Parameter("param1"), Parameter("param2")] def _qasm2_custom_operation_statement( instruction, existing_gate_names, gates_to_define, bit_labels ): operation = _qasm2_define_custom_operation( instruction.operation, existing_gate_names, gates_to_define ) # Insert qasm representation of the original instruction if instruction.clbits: bits = itertools.chain(instruction.qubits, instruction.clbits) else: bits = instruction.qubits bits_qasm = ",".join(bit_labels[j] for j in bits) instruction_qasm = f"{_instruction_qasm2(operation)} {bits_qasm};" return instruction_qasm def _qasm2_define_custom_operation(operation, existing_gate_names, gates_to_define): """Extract a custom definition from the given operation, and append any necessary additional subcomponents' definitions to the ``gates_to_define`` ordered dictionary. Returns a potentially new :class:`.Instruction`, which should be used for the :meth:`~.Instruction.qasm` call (it may have been renamed).""" # pylint: disable=cyclic-import from qiskit.circuit import library as lib from qiskit.qasm2 import QASM2ExportError if operation.name in existing_gate_names: return operation # Check instructions names or label are valid escaped = _qasm_escape_name(operation.name, "gate_") if escaped != operation.name: operation = operation.copy(name=escaped) # These are built-in gates that are known to be safe to construct by passing the correct number # of `Parameter` instances positionally, and have no other information. We can't guarantee that # if they've been subclassed, though. This is a total hack; ideally we'd be able to inspect the # "calling" signatures of Qiskit `Gate` objects to know whether they're safe to re-parameterise. known_good_parameterized = { lib.PhaseGate, lib.RGate, lib.RXGate, lib.RXXGate, lib.RYGate, lib.RYYGate, lib.RZGate, lib.RZXGate, lib.RZZGate, lib.XXMinusYYGate, lib.XXPlusYYGate, lib.UGate, lib.U1Gate, lib.U2Gate, lib.U3Gate, } # In known-good situations we want to use a manually parametrised object as the source of the # definition, but still continue to return the given object as the call-site object. if type(operation) in known_good_parameterized: parameterized_operation = type(operation)(*_QASM2_FIXED_PARAMETERS[: len(operation.params)]) elif hasattr(operation, "_qasm2_decomposition"): new_op = operation._qasm2_decomposition() parameterized_operation = operation = new_op.copy( name=_qasm_escape_name(new_op.name, "gate_") ) else: parameterized_operation = operation # If there's an _equal_ operation in the existing circuits to be defined, then our job is done. previous_definition_source, _ = gates_to_define.get(operation.name, (None, None)) if parameterized_operation == previous_definition_source: return operation # Otherwise, if there's a naming clash, we need a unique name. if operation.name in gates_to_define: operation = _rename_operation(operation) new_name = operation.name if parameterized_operation.params: parameters_qasm = ( "(" + ",".join(f"param{i}" for i in range(len(parameterized_operation.params))) + ")" ) else: parameters_qasm = "" if operation.num_qubits == 0: raise QASM2ExportError( f"OpenQASM 2 cannot represent '{operation.name}, which acts on zero qubits." ) if operation.num_clbits != 0: raise QASM2ExportError( f"OpenQASM 2 cannot represent '{operation.name}', which acts on {operation.num_clbits}" " classical bits." ) qubits_qasm = ",".join(f"q{i}" for i in range(parameterized_operation.num_qubits)) parameterized_definition = getattr(parameterized_operation, "definition", None) if parameterized_definition is None: gates_to_define[new_name] = ( parameterized_operation, f"opaque {new_name}{parameters_qasm} {qubits_qasm};", ) else: qubit_labels = {bit: f"q{i}" for i, bit in enumerate(parameterized_definition.qubits)} body_qasm = " ".join( _qasm2_custom_operation_statement( instruction, existing_gate_names, gates_to_define, qubit_labels ) for instruction in parameterized_definition.data ) # if an inner operation has the same name as the actual operation, it needs to be renamed if operation.name in gates_to_define: operation = _rename_operation(operation) new_name = operation.name definition_qasm = f"gate {new_name}{parameters_qasm} {qubits_qasm} {{ {body_qasm} }}" gates_to_define[new_name] = (parameterized_operation, definition_qasm) return operation def _rename_operation(operation): """Returns the operation with a new name following this pattern: {operation name}_{operation id}""" new_name = f"{operation.name}_{id(operation)}" updated_operation = operation.copy(name=new_name) return updated_operation def _qasm_escape_name(name: str, prefix: str) -> str: """Returns a valid OpenQASM identifier, using `prefix` as a prefix if necessary. `prefix` must itself be a valid identifier.""" # Replace all non-ASCII-word characters (letters, digits, underscore) with the underscore. escaped_name = re.sub(r"\W", "_", name, flags=re.ASCII) if ( not escaped_name or escaped_name[0] not in string.ascii_lowercase or escaped_name in QASM2_RESERVED ): escaped_name = prefix + escaped_name return escaped_name def _instruction_qasm2(operation): """Return an OpenQASM 2 string for the instruction.""" from qiskit.qasm2 import QASM2ExportError # pylint: disable=cyclic-import if operation.name == "c3sx": qasm2_call = "c3sqrtx" else: qasm2_call = operation.name if operation.params: qasm2_call = "{}({})".format( qasm2_call, ",".join([pi_check(i, output="qasm", eps=1e-12) for i in operation.params]), ) if operation.condition is not None: if not isinstance(operation.condition[0], ClassicalRegister): raise QASM2ExportError( "OpenQASM 2 can only condition on registers, but got '{operation.condition[0]}'" ) qasm2_call = ( "if(%s==%d) " % (operation.condition[0].name, operation.condition[1]) + qasm2_call ) return qasm2_call def _make_unique(name: str, already_defined: collections.abc.Set[str]) -> str: """Generate a name by suffixing the given stem that is unique within the defined set.""" if name not in already_defined: return name used = {in_use[len(name) :] for in_use in already_defined if in_use.startswith(name)} characters = (string.digits + string.ascii_letters) if name else string.ascii_letters for parts in itertools.chain.from_iterable( itertools.product(characters, repeat=n) for n in itertools.count(1) ): suffix = "".join(parts) if suffix not in used: return name + suffix # This isn't actually reachable because the above loop is infinite. return name def _bit_argument_conversion(specifier, bit_sequence, bit_set, type_) -> list[Bit]: """Get the list of bits referred to by the specifier ``specifier``. Valid types for ``specifier`` are integers, bits of the correct type (as given in ``type_``), or iterables of one of those two scalar types. Integers are interpreted as indices into the sequence ``bit_sequence``. All allowed bits must be in ``bit_set`` (which should implement fast lookup), which is assumed to contain the same bits as ``bit_sequence``. Returns: List[Bit]: a list of the specified bits from ``bits``. Raises: CircuitError: if an incorrect type or index is encountered, if the same bit is specified more than once, or if the specifier is to a bit not in the ``bit_set``. """ # The duplication between this function and `_bit_argument_conversion_scalar` is so that fast # paths return as quickly as possible, and all valid specifiers will resolve without needing to # try/catch exceptions (which is too slow for inner-loop code). if isinstance(specifier, type_): if specifier in bit_set: return [specifier] raise CircuitError(f"Bit '{specifier}' is not in the circuit.") if isinstance(specifier, (int, np.integer)): try: return [bit_sequence[specifier]] except IndexError as ex: raise CircuitError( f"Index {specifier} out of range for size {len(bit_sequence)}." ) from ex # Slices can't raise IndexError - they just return an empty list. if isinstance(specifier, slice): return bit_sequence[specifier] try: return [ _bit_argument_conversion_scalar(index, bit_sequence, bit_set, type_) for index in specifier ] except TypeError as ex: message = ( f"Incorrect bit type: expected '{type_.__name__}' but got '{type(specifier).__name__}'" if isinstance(specifier, Bit) else f"Invalid bit index: '{specifier}' of type '{type(specifier)}'" ) raise CircuitError(message) from ex def _bit_argument_conversion_scalar(specifier, bit_sequence, bit_set, type_): if isinstance(specifier, type_): if specifier in bit_set: return specifier raise CircuitError(f"Bit '{specifier}' is not in the circuit.") if isinstance(specifier, (int, np.integer)): try: return bit_sequence[specifier] except IndexError as ex: raise CircuitError( f"Index {specifier} out of range for size {len(bit_sequence)}." ) from ex message = ( f"Incorrect bit type: expected '{type_.__name__}' but got '{type(specifier).__name__}'" if isinstance(specifier, Bit) else f"Invalid bit index: '{specifier}' of type '{type(specifier)}'" ) raise CircuitError(message)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A wrapper class for the purposes of validating modifications to QuantumCircuit.data while maintaining the interface of a python list.""" from collections.abc import MutableSequence import qiskit._accelerate.circuit from .exceptions import CircuitError from .instruction import Instruction from .operation import Operation CircuitInstruction = qiskit._accelerate.circuit.CircuitInstruction class QuantumCircuitData(MutableSequence): """A wrapper class for the purposes of validating modifications to QuantumCircuit.data while maintaining the interface of a python list.""" def __init__(self, circuit): self._circuit = circuit def __getitem__(self, i): return self._circuit._data[i] def __setitem__(self, key, value): # For now (Terra 0.21), the `QuantumCircuit.data` setter is meant to perform validation, so # we do the same qubit checks that `QuantumCircuit.append` would do. if isinstance(value, CircuitInstruction): operation, qargs, cargs = value.operation, value.qubits, value.clbits else: # Handle the legacy 3-tuple format. operation, qargs, cargs = value value = self._resolve_legacy_value(operation, qargs, cargs) self._circuit._data[key] = value if isinstance(value.operation, Instruction): self._circuit._update_parameter_table(value.operation) def _resolve_legacy_value(self, operation, qargs, cargs) -> CircuitInstruction: """Resolve the old-style 3-tuple into the new :class:`CircuitInstruction` type.""" if not isinstance(operation, Operation) and hasattr(operation, "to_instruction"): operation = operation.to_instruction() if not isinstance(operation, Operation): raise CircuitError("object is not an Operation.") expanded_qargs = [self._circuit.qbit_argument_conversion(qarg) for qarg in qargs or []] expanded_cargs = [self._circuit.cbit_argument_conversion(carg) for carg in cargs or []] if isinstance(operation, Instruction): broadcast_args = list(operation.broadcast_arguments(expanded_qargs, expanded_cargs)) else: broadcast_args = list( Instruction.broadcast_arguments(operation, expanded_qargs, expanded_cargs) ) if len(broadcast_args) > 1: raise CircuitError( "QuantumCircuit.data modification does not support argument broadcasting." ) qargs, cargs = broadcast_args[0] self._circuit._check_dups(qargs) return CircuitInstruction(operation, tuple(qargs), tuple(cargs)) def insert(self, index, value): self._circuit._data.insert(index, CircuitInstruction(None, (), ())) try: self[index] = value except CircuitError: del self._circuit._data[index] raise def __iter__(self): return iter(self._circuit._data) def __delitem__(self, i): del self._circuit._data[i] def __len__(self): return len(self._circuit._data) def __cast(self, other): return list(other._circuit._data) if isinstance(other, QuantumCircuitData) else other def __repr__(self): return repr(list(self._circuit._data)) def __lt__(self, other): return list(self._circuit._data) < self.__cast(other) def __le__(self, other): return list(self._circuit._data) <= self.__cast(other) def __eq__(self, other): return self._circuit._data == self.__cast(other) def __gt__(self, other): return list(self._circuit._data) > self.__cast(other) def __ge__(self, other): return list(self._circuit._data) >= self.__cast(other) def __add__(self, other): return list(self._circuit._data) + self.__cast(other) def __radd__(self, other): return self.__cast(other) + list(self._circuit._data) def __mul__(self, n): return list(self._circuit._data) * n def __rmul__(self, n): return n * list(self._circuit._data) def sort(self, *args, **kwargs): """In-place stable sort. Accepts arguments of list.sort.""" data = list(self._circuit._data) data.sort(*args, **kwargs) self._circuit._data.clear() self._circuit._data.reserve(len(data)) self._circuit._data.extend(data) def copy(self): """Returns a shallow copy of instruction list.""" return list(self._circuit._data)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ This module contains utility functions for circuits. """ import math import numpy from qiskit import _numpy_compat from qiskit.exceptions import QiskitError from qiskit.circuit.exceptions import CircuitError from .parametervector import ParameterVectorElement def sort_parameters(parameters): """Sort an iterable of :class:`.Parameter` instances into a canonical order, respecting the ordering relationships between elements of :class:`.ParameterVector`\\ s.""" def key(parameter): if isinstance(parameter, ParameterVectorElement): return (parameter.vector.name, parameter.index) return (parameter.name,) return sorted(parameters, key=key) def _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=None): r""" Compute the controlled version of the input matrix with qiskit ordering. This function computes the controlled unitary with :math:`n` control qubits and :math:`m` target qubits, .. math:: V_n^j(U_{2^m}) = (U_{2^m} \otimes |j\rangle\!\langle j|) + (I_{2^m} \otimes (I_{2^n} - |j\rangle\!\langle j|)). where :math:`|j\rangle \in \mathcal{H}^{2^n}` is the control state. Args: base_mat (ndarray): unitary to be controlled num_ctrl_qubits (int): number of controls for new unitary ctrl_state (int or str or None): The control state in decimal or as a bitstring (e.g. '111'). If None, use 2**num_ctrl_qubits-1. Returns: ndarray: controlled version of base matrix. Raises: QiskitError: unrecognized mode or invalid ctrl_state """ num_target = int(math.log2(base_mat.shape[0])) ctrl_dim = 2**num_ctrl_qubits ctrl_grnd = numpy.repeat([[1], [0]], [1, ctrl_dim - 1]) if ctrl_state is None: ctrl_state = ctrl_dim - 1 elif isinstance(ctrl_state, str): ctrl_state = int(ctrl_state, 2) if isinstance(ctrl_state, int): if not 0 <= ctrl_state < ctrl_dim: raise QiskitError("Invalid control state value specified.") else: raise QiskitError("Invalid control state type specified.") ctrl_proj = numpy.diag(numpy.roll(ctrl_grnd, ctrl_state)) full_mat = numpy.kron(numpy.eye(2**num_target), numpy.eye(ctrl_dim) - ctrl_proj) + numpy.kron( base_mat, ctrl_proj ) return full_mat def _ctrl_state_to_int(ctrl_state, num_ctrl_qubits): """Convert ctrl_state to int. Args: ctrl_state (None, str, int): ctrl_state. If None, set to 2**num_ctrl_qubits-1. If str, convert to int. If int, pass. num_ctrl_qubits (int): The number of control qubits. Return: int: ctrl_state Raises: CircuitError: invalid ctrl_state """ ctrl_state_std = None if isinstance(ctrl_state, str): try: assert len(ctrl_state) == num_ctrl_qubits ctrl_state = int(ctrl_state, 2) except ValueError as ex: raise CircuitError("invalid control bit string: " + ctrl_state) from ex except AssertionError as ex: raise CircuitError("invalid control bit string: length != num_ctrl_qubits") from ex if isinstance(ctrl_state, int): if 0 <= ctrl_state < 2**num_ctrl_qubits: ctrl_state_std = ctrl_state else: raise CircuitError("invalid control state specification") elif ctrl_state is None: ctrl_state_std = 2**num_ctrl_qubits - 1 else: raise CircuitError(f"invalid control state specification: {repr(ctrl_state)}") return ctrl_state_std def with_gate_array(base_array): """Class decorator that adds an ``__array__`` method to a :class:`.Gate` instance that returns a singleton nonwritable view onto the complex matrix described by ``base_array``.""" nonwritable = numpy.array(base_array, dtype=numpy.complex128) nonwritable.setflags(write=False) def __array__(_self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): dtype = nonwritable.dtype if dtype is None else dtype return numpy.array(nonwritable, dtype=dtype, copy=copy) def decorator(cls): if hasattr(cls, "__array__"): raise RuntimeError("Refusing to decorate a class that already has '__array__' defined.") cls.__array__ = __array__ return cls return decorator def with_controlled_gate_array(base_array, num_ctrl_qubits, cached_states=None): """Class decorator that adds an ``__array__`` method to a :class:`.ControlledGate` instance that returns singleton nonwritable views onto a relevant precomputed complex matrix for the given control state. If ``cached_states`` is not given, then all possible control states are precomputed. If it is given, it should be an iterable of integers, and only these control states will be cached.""" base = numpy.asarray(base_array, dtype=numpy.complex128) def matrix_for_control_state(state): out = numpy.asarray( _compute_control_matrix(base, num_ctrl_qubits, state), dtype=numpy.complex128, ) out.setflags(write=False) return out if cached_states is None: nonwritables = [matrix_for_control_state(state) for state in range(2**num_ctrl_qubits)] def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): arr = nonwritables[self.ctrl_state] dtype = arr.dtype if dtype is None else dtype return numpy.array(arr, dtype=dtype, copy=copy) else: nonwritables = {state: matrix_for_control_state(state) for state in cached_states} def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): if (arr := nonwritables.get(self.ctrl_state)) is not None: dtype = arr.dtype if dtype is None else dtype return numpy.array(arr, dtype=dtype, copy=copy) if copy is False and copy is not _numpy_compat.COPY_ONLY_IF_NEEDED: raise ValueError("could not produce matrix without calculation") return numpy.asarray( _compute_control_matrix(base, num_ctrl_qubits, self.ctrl_state), dtype=dtype ) def decorator(cls): if hasattr(cls, "__array__"): raise RuntimeError("Refusing to decorate a class that already has '__array__' defined.") cls.__array__ = __array__ return cls return decorator
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """User-space constructor functions for the expression tree, which do some of the inference and lifting boilerplate work.""" # pylint: disable=redefined-builtin,redefined-outer-name from __future__ import annotations __all__ = [ "lift", "bit_not", "logic_not", "bit_and", "bit_or", "bit_xor", "logic_and", "logic_or", "equal", "not_equal", "less", "less_equal", "greater", "greater_equal", "lift_legacy_condition", ] import enum import typing from .expr import Expr, Var, Value, Unary, Binary, Cast from .. import types if typing.TYPE_CHECKING: import qiskit class _CastKind(enum.Enum): EQUAL = enum.auto() """The two types are equal; no cast node is required at all.""" IMPLICIT = enum.auto() """The 'from' type can be cast to the 'to' type implicitly. A ``Cast(implicit=True)`` node is the minimum required to specify this.""" LOSSLESS = enum.auto() """The 'from' type can be cast to the 'to' type explicitly, and the cast will be lossless. This requires a ``Cast(implicit=False)`` node, but there's no danger from inserting one.""" DANGEROUS = enum.auto() """The 'from' type has a defined cast to the 'to' type, but depending on the value, it may lose data. A user would need to manually specify casts.""" NONE = enum.auto() """There is no casting permitted from the 'from' type to the 'to' type.""" def _uint_cast(from_: types.Uint, to_: types.Uint, /) -> _CastKind: if from_.width == to_.width: return _CastKind.EQUAL if from_.width < to_.width: return _CastKind.LOSSLESS return _CastKind.DANGEROUS _ALLOWED_CASTS = { (types.Bool, types.Bool): lambda _a, _b, /: _CastKind.EQUAL, (types.Bool, types.Uint): lambda _a, _b, /: _CastKind.LOSSLESS, (types.Uint, types.Bool): lambda _a, _b, /: _CastKind.IMPLICIT, (types.Uint, types.Uint): _uint_cast, } def _cast_kind(from_: types.Type, to_: types.Type, /) -> _CastKind: if (coercer := _ALLOWED_CASTS.get((from_.kind, to_.kind))) is None: return _CastKind.NONE return coercer(from_, to_) def _coerce_lossless(expr: Expr, type: types.Type) -> Expr: """Coerce ``expr`` to ``type`` by inserting a suitable :class:`Cast` node, if the cast is lossless. Otherwise, raise a ``TypeError``.""" kind = _cast_kind(expr.type, type) if kind is _CastKind.EQUAL: return expr if kind is _CastKind.IMPLICIT: return Cast(expr, type, implicit=True) if kind is _CastKind.LOSSLESS: return Cast(expr, type, implicit=False) if kind is _CastKind.DANGEROUS: raise TypeError(f"cannot cast '{expr}' to '{type}' without loss of precision") raise TypeError(f"no cast is defined to take '{expr}' to '{type}'") def lift_legacy_condition( condition: tuple[qiskit.circuit.Clbit | qiskit.circuit.ClassicalRegister, int], / ) -> Expr: """Lift a legacy two-tuple equality condition into a new-style :class:`Expr`. Examples: Taking an old-style conditional instruction and getting an :class:`Expr` from its condition:: from qiskit.circuit import ClassicalRegister from qiskit.circuit.library import HGate from qiskit.circuit.classical import expr cr = ClassicalRegister(2) instr = HGate().c_if(cr, 3) lifted = expr.lift_legacy_condition(instr.condition) """ from qiskit.circuit import Clbit # pylint: disable=cyclic-import target, value = condition if isinstance(target, Clbit): bool_ = types.Bool() return Var(target, bool_) if value else Unary(Unary.Op.LOGIC_NOT, Var(target, bool_), bool_) left = Var(target, types.Uint(width=target.size)) if value.bit_length() > target.size: left = Cast(left, types.Uint(width=value.bit_length()), implicit=True) right = Value(value, left.type) return Binary(Binary.Op.EQUAL, left, right, types.Bool()) def lift(value: typing.Any, /, type: types.Type | None = None) -> Expr: """Lift the given Python ``value`` to a :class:`~.expr.Value` or :class:`~.expr.Var`. If an explicit ``type`` is given, the typing in the output will reflect that. Examples: Lifting simple circuit objects to be :class:`~.expr.Var` instances:: >>> from qiskit.circuit import Clbit, ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.lift(Clbit()) Var(<clbit>, Bool()) >>> expr.lift(ClassicalRegister(3, "c")) Var(ClassicalRegister(3, "c"), Uint(3)) The type of the return value can be influenced, if the given value could be interpreted losslessly as the given type (use :func:`cast` to perform a full set of casting operations, include lossy ones):: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr, types >>> expr.lift(ClassicalRegister(3, "c"), types.Uint(5)) Var(ClassicalRegister(3, "c"), Uint(5)) >>> expr.lift(5, types.Uint(4)) Value(5, Uint(4)) """ if isinstance(value, Expr): if type is not None: raise ValueError("use 'cast' to cast existing expressions, not 'lift'") return value from qiskit.circuit import Clbit, ClassicalRegister # pylint: disable=cyclic-import inferred: types.Type if value is True or value is False or isinstance(value, Clbit): inferred = types.Bool() constructor = Value if value is True or value is False else Var elif isinstance(value, ClassicalRegister): inferred = types.Uint(width=value.size) constructor = Var elif isinstance(value, int): if value < 0: raise ValueError("cannot represent a negative value") inferred = types.Uint(width=value.bit_length() or 1) constructor = Value else: raise TypeError(f"failed to infer a type for '{value}'") if type is None: type = inferred if types.is_supertype(type, inferred): return constructor(value, type) raise TypeError( f"the explicit type '{type}' is not suitable for representing '{value}';" f" it must be non-strict supertype of '{inferred}'" ) def cast(operand: typing.Any, type: types.Type, /) -> Expr: """Create an explicit cast from the given value to the given type. Examples: Add an explicit cast node that explicitly casts a higher precision type to a lower precision one:: >>> from qiskit.circuit.classical import expr, types >>> value = expr.value(5, types.Uint(32)) >>> expr.cast(value, types.Uint(8)) Cast(Value(5, types.Uint(32)), types.Uint(8), implicit=False) """ operand = lift(operand) if _cast_kind(operand.type, type) is _CastKind.NONE: raise TypeError(f"cannot cast '{operand}' to '{type}'") return Cast(operand, type) def bit_not(operand: typing.Any, /) -> Expr: """Create a bitwise 'not' expression node from the given value, resolving any implicit casts and lifting the value into a :class:`Value` node if required. Examples: Bitwise negation of a :class:`.ClassicalRegister`:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_not(ClassicalRegister(3, "c")) Unary(Unary.Op.BIT_NOT, Var(ClassicalRegister(3, 'c'), Uint(3)), Uint(3)) """ operand = lift(operand) if operand.type.kind not in (types.Bool, types.Uint): raise TypeError(f"cannot apply '{Unary.Op.BIT_NOT}' to type '{operand.type}'") return Unary(Unary.Op.BIT_NOT, operand, operand.type) def logic_not(operand: typing.Any, /) -> Expr: """Create a logical 'not' expression node from the given value, resolving any implicit casts and lifting the value into a :class:`Value` node if required. Examples: Logical negation of a :class:`.ClassicalRegister`:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.logic_not(ClassicalRegister(3, "c")) Unary(\ Unary.Op.LOGIC_NOT, \ Cast(Var(ClassicalRegister(3, 'c'), Uint(3)), Bool(), implicit=True), \ Bool()) """ operand = _coerce_lossless(lift(operand), types.Bool()) return Unary(Unary.Op.LOGIC_NOT, operand, operand.type) def _lift_binary_operands(left: typing.Any, right: typing.Any) -> tuple[Expr, Expr]: """Lift two binary operands simultaneously, inferring the widths of integer literals in either position to match the other operand.""" left_int = isinstance(left, int) and not isinstance(left, bool) right_int = isinstance(right, int) and not isinstance(right, bool) if not (left_int or right_int): left = lift(left) right = lift(right) elif not right_int: right = lift(right) if right.type.kind is types.Uint: if left.bit_length() > right.type.width: raise TypeError( f"integer literal '{left}' is wider than the other operand '{right}'" ) left = Value(left, right.type) else: left = lift(left) elif not left_int: left = lift(left) if left.type.kind is types.Uint: if right.bit_length() > left.type.width: raise TypeError( f"integer literal '{right}' is wider than the other operand '{left}'" ) right = Value(right, left.type) else: right = lift(right) else: # Both are `int`, so we take our best case to make things work. uint = types.Uint(max(left.bit_length(), right.bit_length(), 1)) left = Value(left, uint) right = Value(right, uint) return left, right def _binary_bitwise(op: Binary.Op, left: typing.Any, right: typing.Any) -> Expr: left, right = _lift_binary_operands(left, right) type: types.Type if left.type.kind is right.type.kind is types.Bool: type = types.Bool() elif left.type.kind is types.Uint and right.type.kind is types.Uint: if left.type != right.type: raise TypeError( "binary bitwise operations are defined between unsigned integers of the same width," f" but got {left.type.width} and {right.type.width}." ) type = left.type else: raise TypeError(f"invalid types for '{op}': '{left.type}' and '{right.type}'") return Binary(op, left, right, type) def bit_and(left: typing.Any, right: typing.Any, /) -> Expr: """Create a bitwise 'and' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Bitwise 'and' of a classical register and an integer literal:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_and(ClassicalRegister(3, "c"), 0b111) Binary(\ Binary.Op.BIT_AND, \ Var(ClassicalRegister(3, 'c'), Uint(3)), \ Value(7, Uint(3)), \ Uint(3)) """ return _binary_bitwise(Binary.Op.BIT_AND, left, right) def bit_or(left: typing.Any, right: typing.Any, /) -> Expr: """Create a bitwise 'or' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Bitwise 'or' of a classical register and an integer literal:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_or(ClassicalRegister(3, "c"), 0b101) Binary(\ Binary.Op.BIT_OR, \ Var(ClassicalRegister(3, 'c'), Uint(3)), \ Value(5, Uint(3)), \ Uint(3)) """ return _binary_bitwise(Binary.Op.BIT_OR, left, right) def bit_xor(left: typing.Any, right: typing.Any, /) -> Expr: """Create a bitwise 'exclusive or' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Bitwise 'exclusive or' of a classical register and an integer literal:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_xor(ClassicalRegister(3, "c"), 0b101) Binary(\ Binary.Op.BIT_XOR, \ Var(ClassicalRegister(3, 'c'), Uint(3)), \ Value(5, Uint(3)), \ Uint(3)) """ return _binary_bitwise(Binary.Op.BIT_XOR, left, right) def _binary_logical(op: Binary.Op, left: typing.Any, right: typing.Any) -> Expr: bool_ = types.Bool() left = _coerce_lossless(lift(left), bool_) right = _coerce_lossless(lift(right), bool_) return Binary(op, left, right, bool_) def logic_and(left: typing.Any, right: typing.Any, /) -> Expr: """Create a logical 'and' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Logical 'and' of two classical bits:: >>> from qiskit.circuit import Clbit >>> from qiskit.circuit.classical import expr >>> expr.logical_and(Clbit(), Clbit()) Binary(Binary.Op.LOGIC_AND, Var(<clbit 0>, Bool()), Var(<clbit 1>, Bool()), Bool()) """ return _binary_logical(Binary.Op.LOGIC_AND, left, right) def logic_or(left: typing.Any, right: typing.Any, /) -> Expr: """Create a logical 'or' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Logical 'or' of two classical bits >>> from qiskit.circuit import Clbit >>> from qiskit.circuit.classical import expr >>> expr.logical_and(Clbit(), Clbit()) Binary(Binary.Op.LOGIC_OR, Var(<clbit 0>, Bool()), Var(<clbit 1>, Bool()), Bool()) """ return _binary_logical(Binary.Op.LOGIC_OR, left, right) def _equal_like(op: Binary.Op, left: typing.Any, right: typing.Any) -> Expr: left, right = _lift_binary_operands(left, right) if left.type.kind is not right.type.kind: raise TypeError(f"invalid types for '{op}': '{left.type}' and '{right.type}'") type = types.greater(left.type, right.type) return Binary(op, _coerce_lossless(left, type), _coerce_lossless(right, type), types.Bool()) def equal(left: typing.Any, right: typing.Any, /) -> Expr: """Create an 'equal' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Equality between a classical register and an integer:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.equal(ClassicalRegister(3, "c"), 7) Binary(Binary.Op.EQUAL, \ Var(ClassicalRegister(3, "c"), Uint(3)), \ Value(7, Uint(3)), \ Uint(3)) """ return _equal_like(Binary.Op.EQUAL, left, right) def not_equal(left: typing.Any, right: typing.Any, /) -> Expr: """Create a 'not equal' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Inequality between a classical register and an integer:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.not_equal(ClassicalRegister(3, "c"), 7) Binary(Binary.Op.NOT_EQUAL, \ Var(ClassicalRegister(3, "c"), Uint(3)), \ Value(7, Uint(3)), \ Uint(3)) """ return _equal_like(Binary.Op.NOT_EQUAL, left, right) def _binary_relation(op: Binary.Op, left: typing.Any, right: typing.Any) -> Expr: left, right = _lift_binary_operands(left, right) if left.type.kind is not right.type.kind or left.type.kind is types.Bool: raise TypeError(f"invalid types for '{op}': '{left.type}' and '{right.type}'") type = types.greater(left.type, right.type) return Binary(op, _coerce_lossless(left, type), _coerce_lossless(right, type), types.Bool()) def less(left: typing.Any, right: typing.Any, /) -> Expr: """Create a 'less than' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Query if a classical register is less than an integer:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "c"), 5) Binary(Binary.Op.LESS, \ Var(ClassicalRegister(3, "c"), Uint(3)), \ Value(5, Uint(3)), \ Uint(3)) """ return _binary_relation(Binary.Op.LESS, left, right) def less_equal(left: typing.Any, right: typing.Any, /) -> Expr: """Create a 'less than or equal to' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Query if a classical register is less than or equal to another:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "a"), ClassicalRegister(3, "b")) Binary(Binary.Op.LESS_EQUAL, \ Var(ClassicalRegister(3, "a"), Uint(3)), \ Var(ClassicalRegister(3, "b"), Uint(3)), \ Uint(3)) """ return _binary_relation(Binary.Op.LESS_EQUAL, left, right) def greater(left: typing.Any, right: typing.Any, /) -> Expr: """Create a 'greater than' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Query if a classical register is greater than an integer:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "c"), 5) Binary(Binary.Op.GREATER, \ Var(ClassicalRegister(3, "c"), Uint(3)), \ Value(5, Uint(3)), \ Uint(3)) """ return _binary_relation(Binary.Op.GREATER, left, right) def greater_equal(left: typing.Any, right: typing.Any, /) -> Expr: """Create a 'greater than or equal to' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Query if a classical register is greater than or equal to another:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "a"), ClassicalRegister(3, "b")) Binary(Binary.Op.GREATER_EQUAL, \ Var(ClassicalRegister(3, "a"), Uint(3)), \ Var(ClassicalRegister(3, "b"), Uint(3)), \ Uint(3)) """ return _binary_relation(Binary.Op.GREATER_EQUAL, left, right)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Expression-tree nodes.""" # Given the nature of the tree representation and that there are helper functions associated with # many of the classes whose arguments naturally share names with themselves, it's inconvenient to # use synonyms everywhere. This goes for the builtin 'type' as well. # pylint: disable=redefined-builtin,redefined-outer-name from __future__ import annotations __all__ = [ "Expr", "Var", "Value", "Cast", "Unary", "Binary", ] import abc import enum import typing from .. import types if typing.TYPE_CHECKING: import qiskit _T_co = typing.TypeVar("_T_co", covariant=True) # If adding nodes, remember to update `visitors.ExprVisitor` as well. class Expr(abc.ABC): """Root base class of all nodes in the expression tree. The base case should never be instantiated directly. This must not be subclassed by users; subclasses form the internal data of the representation of expressions, and it does not make sense to add more outside of Qiskit library code. All subclasses are responsible for setting their ``type`` attribute in their ``__init__``, and should not call the parent initialiser.""" __slots__ = ("type",) type: types.Type # Sentinel to prevent instantiation of the base class. @abc.abstractmethod def __init__(self): # pragma: no cover pass def accept( self, visitor: qiskit.circuit.classical.expr.ExprVisitor[_T_co], / ) -> _T_co: # pragma: no cover """Call the relevant ``visit_*`` method on the given :class:`ExprVisitor`. The usual entry point for a simple visitor is to construct it, and then call :meth:`accept` on the root object to be visited. For example:: expr = ... visitor = MyVisitor() visitor.accept(expr) Subclasses of :class:`Expr` should override this to call the correct virtual method on the visitor. This implements double dispatch with the visitor.""" return visitor.visit_generic(self) @typing.final class Cast(Expr): """A cast from one type to another, implied by the use of an expression in a different context.""" __slots__ = ("operand", "implicit") def __init__(self, operand: Expr, type: types.Type, implicit: bool = False): self.type = type self.operand = operand self.implicit = implicit def accept(self, visitor, /): return visitor.visit_cast(self) def __eq__(self, other): return ( isinstance(other, Cast) and self.type == other.type and self.operand == other.operand and self.implicit == other.implicit ) def __repr__(self): return f"Cast({self.operand}, {self.type}, implicit={self.implicit})" @typing.final class Var(Expr): """A classical variable.""" __slots__ = ("var",) def __init__( self, var: qiskit.circuit.Clbit | qiskit.circuit.ClassicalRegister, type: types.Type ): self.type = type self.var = var def accept(self, visitor, /): return visitor.visit_var(self) def __eq__(self, other): return isinstance(other, Var) and self.type == other.type and self.var == other.var def __repr__(self): return f"Var({self.var}, {self.type})" @typing.final class Value(Expr): """A single scalar value.""" __slots__ = ("value",) def __init__(self, value: typing.Any, type: types.Type): self.type = type self.value = value def accept(self, visitor, /): return visitor.visit_value(self) def __eq__(self, other): return isinstance(other, Value) and self.type == other.type and self.value == other.value def __repr__(self): return f"Value({self.value}, {self.type})" @typing.final class Unary(Expr): """A unary expression. Args: op: The opcode describing which operation is being done. operand: The operand of the operation. type: The resolved type of the result. """ __slots__ = ("op", "operand") class Op(enum.Enum): """Enumeration of the opcodes for unary operations. The bitwise negation :data:`BIT_NOT` takes a single bit or an unsigned integer of known width, and returns a value of the same type. The logical negation :data:`LOGIC_NOT` takes an input that is implicitly coerced to a Boolean, and returns a Boolean. """ # If adding opcodes, remember to add helper constructor functions in `constructors.py`. # The opcode integers should be considered a public interface; they are used by # serialisation formats that may transfer data between different versions of Qiskit. BIT_NOT = 1 """Bitwise negation. ``~operand``.""" LOGIC_NOT = 2 """Logical negation. ``!operand``.""" def __str__(self): return f"Unary.{super().__str__()}" def __repr__(self): return f"Unary.{super().__repr__()}" def __init__(self, op: Unary.Op, operand: Expr, type: types.Type): self.op = op self.operand = operand self.type = type def accept(self, visitor, /): return visitor.visit_unary(self) def __eq__(self, other): return ( isinstance(other, Unary) and self.type == other.type and self.op is other.op and self.operand == other.operand ) def __repr__(self): return f"Unary({self.op}, {self.operand}, {self.type})" @typing.final class Binary(Expr): """A binary expression. Args: op: The opcode describing which operation is being done. left: The left-hand operand. right: The right-hand operand. type: The resolved type of the result. """ __slots__ = ("op", "left", "right") class Op(enum.Enum): """Enumeration of the opcodes for binary operations. The bitwise operations :data:`BIT_AND`, :data:`BIT_OR` and :data:`BIT_XOR` apply to two operands of the same type, which must be a single bit or an unsigned integer of fixed width. The resultant type is the same as the two input types. The logical operations :data:`LOGIC_AND` and :data:`LOGIC_OR` first implicitly coerce their arguments to Booleans, and then apply the logical operation. The resultant type is always Boolean. The binary mathematical relations :data:`EQUAL`, :data:`NOT_EQUAL`, :data:`LESS`, :data:`LESS_EQUAL`, :data:`GREATER` and :data:`GREATER_EQUAL` take unsigned integers (with an implicit cast to make them the same width), and return a Boolean. """ # If adding opcodes, remember to add helper constructor functions in `constructors.py` # The opcode integers should be considered a public interface; they are used by # serialisation formats that may transfer data between different versions of Qiskit. BIT_AND = 1 """Bitwise "and". ``lhs & rhs``.""" BIT_OR = 2 """Bitwise "or". ``lhs | rhs``.""" BIT_XOR = 3 """Bitwise "exclusive or". ``lhs ^ rhs``.""" LOGIC_AND = 4 """Logical "and". ``lhs && rhs``.""" LOGIC_OR = 5 """Logical "or". ``lhs || rhs``.""" EQUAL = 6 """Numeric equality. ``lhs == rhs``.""" NOT_EQUAL = 7 """Numeric inequality. ``lhs != rhs``.""" LESS = 8 """Numeric less than. ``lhs < rhs``.""" LESS_EQUAL = 9 """Numeric less than or equal to. ``lhs <= rhs``""" GREATER = 10 """Numeric greater than. ``lhs > rhs``.""" GREATER_EQUAL = 11 """Numeric greater than or equal to. ``lhs >= rhs``.""" def __str__(self): return f"Binary.{super().__str__()}" def __repr__(self): return f"Binary.{super().__repr__()}" def __init__(self, op: Binary.Op, left: Expr, right: Expr, type: types.Type): self.op = op self.left = left self.right = right self.type = type def accept(self, visitor, /): return visitor.visit_binary(self) def __eq__(self, other): return ( isinstance(other, Binary) and self.type == other.type and self.op is other.op and self.left == other.left and self.right == other.right ) def __repr__(self): return f"Binary({self.op}, {self.left}, {self.right}, {self.type})"
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. r""" .. _pulse_builder: ============= Pulse Builder ============= .. We actually want people to think of these functions as being defined within the ``qiskit.pulse`` namespace, not the submodule ``qiskit.pulse.builder``. .. currentmodule: qiskit.pulse Use the pulse builder DSL to write pulse programs with an imperative syntax. .. warning:: The pulse builder interface is still in active development. It may have breaking API changes without deprecation warnings in future releases until otherwise indicated. The pulse builder provides an imperative API for writing pulse programs with less difficulty than the :class:`~qiskit.pulse.Schedule` API. It contextually constructs a pulse schedule and then emits the schedule for execution. For example, to play a series of pulses on channels is as simple as: .. plot:: :include-source: from qiskit import pulse dc = pulse.DriveChannel d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) with pulse.build(name='pulse_programming_in') as pulse_prog: pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) pulse_prog.draw() To begin pulse programming we must first initialize our program builder context with :func:`build`, after which we can begin adding program statements. For example, below we write a simple program that :func:`play`\s a pulse: .. plot:: :include-source: from qiskit import execute, pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 1.0), d0) pulse_prog.draw() The builder initializes a :class:`.pulse.Schedule`, ``pulse_prog`` and then begins to construct the program within the context. The output pulse schedule will survive after the context is exited and can be executed like a normal Qiskit schedule using ``qiskit.execute(pulse_prog, backend)``. Pulse programming has a simple imperative style. This leaves the programmer to worry about the raw experimental physics of pulse programming and not constructing cumbersome data structures. We can optionally pass a :class:`~qiskit.providers.Backend` to :func:`build` to enable enhanced functionality. Below, we prepare a Bell state by automatically compiling the required pulses from their gate-level representations, while simultaneously applying a long decoupling pulse to a neighboring qubit. We terminate the experiment with a measurement to observe the state we prepared. This program which mixes circuits and pulses will be automatically lowered to be run as a pulse program: .. plot:: :include-source: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q # TODO: This example should use a real mock backend. backend = FakeOpenPulse3Q() d2 = pulse.DriveChannel(2) with pulse.build(backend) as bell_prep: pulse.u2(0, math.pi, 0) pulse.cx(0, 1) with pulse.build(backend) as decoupled_bell_prep_and_measure: # We call our bell state preparation schedule constructed above. with pulse.align_right(): pulse.call(bell_prep) pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2) pulse.barrier(0, 1, 2) registers = pulse.measure_all() decoupled_bell_prep_and_measure.draw() With the pulse builder we are able to blend programming on qubits and channels. While the pulse schedule is based on instructions that operate on channels, the pulse builder automatically handles the mapping from qubits to channels for you. In the example below we demonstrate some more features of the pulse builder: .. code-block:: import math from qiskit import pulse, QuantumCircuit from qiskit.pulse import library from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: # Create a pulse. gaussian_pulse = library.gaussian(10, 1.0, 2) # Get the qubit's corresponding drive channel from the backend. d0 = pulse.drive_channel(0) d1 = pulse.drive_channel(1) # Play a pulse at t=0. pulse.play(gaussian_pulse, d0) # Play another pulse directly after the previous pulse at t=10. pulse.play(gaussian_pulse, d0) # The default scheduling behavior is to schedule pulses in parallel # across channels. For example, the statement below # plays the same pulse on a different channel at t=0. pulse.play(gaussian_pulse, d1) # We also provide pulse scheduling alignment contexts. # The default alignment context is align_left. # The sequential context schedules pulse instructions sequentially in time. # This context starts at t=10 due to earlier pulses above. with pulse.align_sequential(): pulse.play(gaussian_pulse, d0) # Play another pulse after at t=20. pulse.play(gaussian_pulse, d1) # We can also nest contexts as each instruction is # contained in its local scheduling context. # The output of a child context is a context-schedule # with the internal instructions timing fixed relative to # one another. This is schedule is then called in the parent context. # Context starts at t=30. with pulse.align_left(): # Start at t=30. pulse.play(gaussian_pulse, d0) # Start at t=30. pulse.play(gaussian_pulse, d1) # Context ends at t=40. # Alignment context where all pulse instructions are # aligned to the right, ie., as late as possible. with pulse.align_right(): # Shift the phase of a pulse channel. pulse.shift_phase(math.pi, d1) # Starts at t=40. pulse.delay(100, d0) # Ends at t=140. # Starts at t=130. pulse.play(gaussian_pulse, d1) # Ends at t=140. # Acquire data for a qubit and store in a memory slot. pulse.acquire(100, 0, pulse.MemorySlot(0)) # We also support a variety of macros for common operations. # Measure all qubits. pulse.measure_all() # Delay on some qubits. # This requires knowledge of which channels belong to which qubits. # delay for 100 cycles on qubits 0 and 1. pulse.delay_qubits(100, 0, 1) # Call a quantum circuit. The pulse builder lazily constructs a quantum # circuit which is then transpiled and scheduled before inserting into # a pulse schedule. # NOTE: Quantum register indices correspond to physical qubit indices. qc = QuantumCircuit(2, 2) qc.cx(0, 1) pulse.call(qc) # Calling a small set of standard gates and decomposing to pulses is # also supported with more natural syntax. pulse.u3(0, math.pi, 0, 0) pulse.cx(0, 1) # It is also be possible to call a preexisting schedule tmp_sched = pulse.Schedule() tmp_sched += pulse.Play(gaussian_pulse, d0) pulse.call(tmp_sched) # We also support: # frequency instructions pulse.set_frequency(5.0e9, d0) # phase instructions pulse.shift_phase(0.1, d0) # offset contexts with pulse.phase_offset(math.pi, d0): pulse.play(gaussian_pulse, d0) The above is just a small taste of what is possible with the builder. See the rest of the module documentation for more information on its capabilities. .. autofunction:: build Channels ======== Methods to return the correct channels for the respective qubit indices. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) print(d0) .. parsed-literal:: DriveChannel(0) .. autofunction:: acquire_channel .. autofunction:: control_channels .. autofunction:: drive_channel .. autofunction:: measure_channel Instructions ============ Pulse instructions are available within the builder interface. Here's an example: .. plot:: :include-source: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.delay(20, d0) pulse.shift_phase(3.14/2, d0) pulse.set_phase(3.14, d0) pulse.shift_frequency(1e7, d0) pulse.set_frequency(5e9, d0) with pulse.build() as temp_sched: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0) pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0) pulse.call(temp_sched) pulse.acquire(30, a0, pulse.MemorySlot(0)) drive_sched.draw() .. autofunction:: acquire .. autofunction:: barrier .. autofunction:: call .. autofunction:: delay .. autofunction:: play .. autofunction:: reference .. autofunction:: set_frequency .. autofunction:: set_phase .. autofunction:: shift_frequency .. autofunction:: shift_phase .. autofunction:: snapshot Contexts ======== Builder aware contexts that modify the construction of a pulse program. For example an alignment context like :func:`align_right` may be used to align all pulses as late as possible in a pulse program. .. plot:: :include-source: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog.draw() .. autofunction:: align_equispaced .. autofunction:: align_func .. autofunction:: align_left .. autofunction:: align_right .. autofunction:: align_sequential .. autofunction:: circuit_scheduler_settings .. autofunction:: frequency_offset .. autofunction:: phase_offset .. autofunction:: transpiler_settings Macros ====== Macros help you add more complex functionality to your pulse program. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as measure_sched: mem_slot = pulse.measure(0) print(mem_slot) .. parsed-literal:: MemorySlot(0) .. autofunction:: measure .. autofunction:: measure_all .. autofunction:: delay_qubits Circuit Gates ============= To use circuit level gates within your pulse program call a circuit with :func:`call`. .. warning:: These will be removed in future versions with the release of a circuit builder interface in which it will be possible to calibrate a gate in terms of pulses and use that gate in a circuit. .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as u3_sched: pulse.u3(math.pi, 0, math.pi, 0) .. autofunction:: cx .. autofunction:: u1 .. autofunction:: u2 .. autofunction:: u3 .. autofunction:: x Utilities ========= The utility functions can be used to gather attributes about the backend and modify how the program is built. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as u3_sched: print('Number of qubits in backend: {}'.format(pulse.num_qubits())) samples = 160 print('There are {} samples in {} seconds'.format( samples, pulse.samples_to_seconds(160))) seconds = 1e-6 print('There are {} seconds in {} samples.'.format( seconds, pulse.seconds_to_samples(1e-6))) .. parsed-literal:: Number of qubits in backend: 1 There are 160 samples in 3.5555555555555554e-08 seconds There are 1e-06 seconds in 4500 samples. .. autofunction:: active_backend .. autofunction:: active_transpiler_settings .. autofunction:: active_circuit_scheduler_settings .. autofunction:: num_qubits .. autofunction:: qubit_channels .. autofunction:: samples_to_seconds .. autofunction:: seconds_to_samples """ import collections import contextvars import functools import itertools import uuid import warnings from contextlib import contextmanager from functools import singledispatchmethod from typing import ( Any, Callable, ContextManager, Dict, Iterable, List, Mapping, Optional, Set, Tuple, TypeVar, Union, NewType, ) import numpy as np from qiskit import circuit from qiskit.circuit.library import standard_gates as gates from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType from qiskit.pulse import ( channels as chans, configuration, exceptions, instructions, macros, library, transforms, ) from qiskit.providers.backend import BackendV2 from qiskit.pulse.instructions import directives from qiskit.pulse.schedule import Schedule, ScheduleBlock from qiskit.pulse.transforms.alignments import AlignmentKind #: contextvars.ContextVar[BuilderContext]: active builder BUILDER_CONTEXTVAR = contextvars.ContextVar("backend") T = TypeVar("T") StorageLocation = NewType("StorageLocation", Union[chans.MemorySlot, chans.RegisterSlot]) def _compile_lazy_circuit_before(function: Callable[..., T]) -> Callable[..., T]: """Decorator thats schedules and calls the lazily compiled circuit before executing the decorated builder method.""" @functools.wraps(function) def wrapper(self, *args, **kwargs): self._compile_lazy_circuit() return function(self, *args, **kwargs) return wrapper def _requires_backend(function: Callable[..., T]) -> Callable[..., T]: """Decorator a function to raise if it is called without a builder with a set backend. """ @functools.wraps(function) def wrapper(self, *args, **kwargs): if self.backend is None: raise exceptions.BackendNotSet( 'This function requires the builder to have a "backend" set.' ) return function(self, *args, **kwargs) return wrapper class _PulseBuilder: """Builder context class.""" __alignment_kinds__ = { "left": transforms.AlignLeft(), "right": transforms.AlignRight(), "sequential": transforms.AlignSequential(), } def __init__( self, backend=None, block: Optional[ScheduleBlock] = None, name: Optional[str] = None, default_alignment: Union[str, AlignmentKind] = "left", default_transpiler_settings: Mapping = None, default_circuit_scheduler_settings: Mapping = None, ): """Initialize the builder context. .. note:: At some point we may consider incorporating the builder into the :class:`~qiskit.pulse.Schedule` class. However, the risk of this is tying the user interface to the intermediate representation. For now we avoid this at the cost of some code duplication. Args: backend (Backend): Input backend to use in builder. If not set certain functionality will be unavailable. block: Initital ``ScheduleBlock`` to build on. name: Name of pulse program to be built. default_alignment: Default scheduling alignment for builder. One of ``left``, ``right``, ``sequential`` or an instance of :class:`~qiskit.pulse.transforms.alignments.AlignmentKind` subclass. default_transpiler_settings: Default settings for the transpiler. default_circuit_scheduler_settings: Default settings for the circuit to pulse scheduler. Raises: PulseError: When invalid ``default_alignment`` or `block` is specified. """ #: Backend: Backend instance for context builder. self._backend = backend #: Union[None, ContextVar]: Token for this ``_PulseBuilder``'s ``ContextVar``. self._backend_ctx_token = None #: QuantumCircuit: Lazily constructed quantum circuit self._lazy_circuit = None #: Dict[str, Any]: Transpiler setting dictionary. self._transpiler_settings = default_transpiler_settings or {} #: Dict[str, Any]: Scheduler setting dictionary. self._circuit_scheduler_settings = default_circuit_scheduler_settings or {} #: List[ScheduleBlock]: Stack of context. self._context_stack = [] #: str: Name of the output program self._name = name # Add root block if provided. Schedule will be built on top of this. if block is not None: if isinstance(block, ScheduleBlock): root_block = block elif isinstance(block, Schedule): root_block = self._naive_typecast_schedule(block) else: raise exceptions.PulseError( f"Input `block` type {block.__class__.__name__} is " "not a valid format. Specify a pulse program." ) self._context_stack.append(root_block) # Set default alignment context alignment = _PulseBuilder.__alignment_kinds__.get(default_alignment, default_alignment) if not isinstance(alignment, AlignmentKind): raise exceptions.PulseError( f"Given `default_alignment` {repr(default_alignment)} is " "not a valid transformation. Set one of " f'{", ".join(_PulseBuilder.__alignment_kinds__.keys())}, ' "or set an instance of `AlignmentKind` subclass." ) self.push_context(alignment) def __enter__(self) -> ScheduleBlock: """Enter this builder context and yield either the supplied schedule or the schedule created for the user. Returns: The schedule that the builder will build on. """ self._backend_ctx_token = BUILDER_CONTEXTVAR.set(self) output = self._context_stack[0] output._name = self._name or output.name return output @_compile_lazy_circuit_before def __exit__(self, exc_type, exc_val, exc_tb): """Exit the builder context and compile the built pulse program.""" self.compile() BUILDER_CONTEXTVAR.reset(self._backend_ctx_token) @property def backend(self): """Returns the builder backend if set. Returns: Optional[Backend]: The builder's backend. """ return self._backend @_compile_lazy_circuit_before def push_context(self, alignment: AlignmentKind): """Push new context to the stack.""" self._context_stack.append(ScheduleBlock(alignment_context=alignment)) @_compile_lazy_circuit_before def pop_context(self) -> ScheduleBlock: """Pop the last context from the stack.""" if len(self._context_stack) == 1: raise exceptions.PulseError("The root context cannot be popped out.") return self._context_stack.pop() def get_context(self) -> ScheduleBlock: """Get current context. Notes: New instruction can be added by `.append_subroutine` or `.append_instruction` method. Use above methods rather than directly accessing to the current context. """ return self._context_stack[-1] @property @_requires_backend def num_qubits(self): """Get the number of qubits in the backend.""" # backendV2 if isinstance(self.backend, BackendV2): return self.backend.num_qubits return self.backend.configuration().n_qubits @property def transpiler_settings(self) -> Mapping: """The builder's transpiler settings.""" return self._transpiler_settings @transpiler_settings.setter @_compile_lazy_circuit_before def transpiler_settings(self, settings: Mapping): self._compile_lazy_circuit() self._transpiler_settings = settings @property def circuit_scheduler_settings(self) -> Mapping: """The builder's circuit to pulse scheduler settings.""" return self._circuit_scheduler_settings @circuit_scheduler_settings.setter @_compile_lazy_circuit_before def circuit_scheduler_settings(self, settings: Mapping): self._compile_lazy_circuit() self._circuit_scheduler_settings = settings @_compile_lazy_circuit_before def compile(self) -> ScheduleBlock: """Compile and output the built pulse program.""" # Not much happens because we currently compile as we build. # This should be offloaded to a true compilation module # once we define a more sophisticated IR. while len(self._context_stack) > 1: current = self.pop_context() self.append_subroutine(current) return self._context_stack[0] def _compile_lazy_circuit(self): """Call a context QuantumCircuit (lazy circuit) and append the output pulse schedule to the builder's context schedule. Note that the lazy circuit is not stored as a call instruction. """ if self._lazy_circuit: lazy_circuit = self._lazy_circuit # reset lazy circuit self._lazy_circuit = self._new_circuit() self.call_subroutine(self._compile_circuit(lazy_circuit)) def _compile_circuit(self, circ) -> Schedule: """Take a QuantumCircuit and output the pulse schedule associated with the circuit.""" from qiskit import compiler # pylint: disable=cyclic-import transpiled_circuit = compiler.transpile(circ, self.backend, **self.transpiler_settings) sched = compiler.schedule( transpiled_circuit, self.backend, **self.circuit_scheduler_settings ) return sched def _new_circuit(self): """Create a new circuit for lazy circuit scheduling.""" return circuit.QuantumCircuit(self.num_qubits) @_compile_lazy_circuit_before def append_instruction(self, instruction: instructions.Instruction): """Add an instruction to the builder's context schedule. Args: instruction: Instruction to append. """ self._context_stack[-1].append(instruction) def append_reference(self, name: str, *extra_keys: str): """Add external program as a :class:`~qiskit.pulse.instructions.Reference` instruction. Args: name: Name of subroutine. extra_keys: Assistance keys to uniquely specify the subroutine. """ inst = instructions.Reference(name, *extra_keys) self.append_instruction(inst) @_compile_lazy_circuit_before def append_subroutine(self, subroutine: Union[Schedule, ScheduleBlock]): """Append a :class:`ScheduleBlock` to the builder's context schedule. This operation doesn't create a reference. Subroutine is directly appended to current context schedule. Args: subroutine: ScheduleBlock to append to the current context block. Raises: PulseError: When subroutine is not Schedule nor ScheduleBlock. """ if not isinstance(subroutine, (ScheduleBlock, Schedule)): raise exceptions.PulseError( f"'{subroutine.__class__.__name__}' is not valid data format in the builder. " "'Schedule' and 'ScheduleBlock' can be appended to the builder context." ) if len(subroutine) == 0: return if isinstance(subroutine, Schedule): subroutine = self._naive_typecast_schedule(subroutine) self._context_stack[-1].append(subroutine) @singledispatchmethod def call_subroutine( self, subroutine: Union[circuit.QuantumCircuit, Schedule, ScheduleBlock], name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): """Call a schedule or circuit defined outside of the current scope. The ``subroutine`` is appended to the context schedule as a call instruction. This logic just generates a convenient program representation in the compiler. Thus, this doesn't affect execution of inline subroutines. See :class:`~pulse.instructions.Call` for more details. Args: subroutine: Target schedule or circuit to append to the current context. name: Name of subroutine if defined. value_dict: Parameter object and assigned value mapping. This is more precise way to identify a parameter since mapping is managed with unique object id rather than name. Especially there is any name collision in a parameter table. kw_params: Parameter values to bind to the target subroutine with string parameter names. If there are parameter name overlapping, these parameters are updated with the same assigned value. Raises: PulseError: - When input subroutine is not valid data format. """ raise exceptions.PulseError( f"Subroutine type {subroutine.__class__.__name__} is " "not valid data format. Call QuantumCircuit, " "Schedule, or ScheduleBlock." ) @call_subroutine.register def _( self, target_block: ScheduleBlock, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_block) == 0: return # Create local parameter assignment local_assignment = {} for param_name, value in kw_params.items(): params = target_block.get_parameters(param_name) if not params: raise exceptions.PulseError( f"Parameter {param_name} is not defined in the target subroutine. " f'{", ".join(map(str, target_block.parameters))} can be specified.' ) for param in params: local_assignment[param] = value if value_dict: if local_assignment.keys() & value_dict.keys(): warnings.warn( "Some parameters provided by 'value_dict' conflict with one through " "keyword arguments. Parameter values in the keyword arguments " "are overridden by the dictionary values.", UserWarning, ) local_assignment.update(value_dict) if local_assignment: target_block = target_block.assign_parameters(local_assignment, inplace=False) if name is None: # Add unique string, not to accidentally override existing reference entry. keys = (target_block.name, uuid.uuid4().hex) else: keys = (name,) self.append_reference(*keys) self.get_context().assign_references({keys: target_block}, inplace=True) @call_subroutine.register def _( self, target_schedule: Schedule, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_schedule) == 0: return self.call_subroutine( self._naive_typecast_schedule(target_schedule), name=name, value_dict=value_dict, **kw_params, ) @call_subroutine.register def _( self, target_circuit: circuit.QuantumCircuit, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_circuit) == 0: return self._compile_lazy_circuit() self.call_subroutine( self._compile_circuit(target_circuit), name=name, value_dict=value_dict, **kw_params, ) @_requires_backend def call_gate(self, gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True): """Call the circuit ``gate`` in the pulse program. The qubits are assumed to be defined on physical qubits. If ``lazy == True`` this circuit will extend a lazily constructed quantum circuit. When an operation occurs that breaks the underlying circuit scheduling assumptions such as adding a pulse instruction or changing the alignment context the circuit will be transpiled and scheduled into pulses with the current active settings. Args: gate: Gate to call. qubits: Qubits to call gate on. lazy: If false the circuit will be transpiled and pulse scheduled immediately. Otherwise, it will extend the active lazy circuit as defined above. """ try: iter(qubits) except TypeError: qubits = (qubits,) if lazy: self._call_gate(gate, qubits) else: self._compile_lazy_circuit() self._call_gate(gate, qubits) self._compile_lazy_circuit() def _call_gate(self, gate, qargs): if self._lazy_circuit is None: self._lazy_circuit = self._new_circuit() self._lazy_circuit.append(gate, qargs=qargs) @staticmethod def _naive_typecast_schedule(schedule: Schedule): # Naively convert into ScheduleBlock from qiskit.pulse.transforms import inline_subroutines, flatten, pad preprocessed_schedule = inline_subroutines(flatten(schedule)) pad(preprocessed_schedule, inplace=True, pad_with=instructions.TimeBlockade) # default to left alignment, namely ASAP scheduling target_block = ScheduleBlock(name=schedule.name) for _, inst in preprocessed_schedule.instructions: target_block.append(inst, inplace=True) return target_block def get_dt(self): """Retrieve dt differently based on the type of Backend""" if isinstance(self.backend, BackendV2): return self.backend.dt return self.backend.configuration().dt def build( backend=None, schedule: Optional[ScheduleBlock] = None, name: Optional[str] = None, default_alignment: Optional[Union[str, AlignmentKind]] = "left", default_transpiler_settings: Optional[Dict[str, Any]] = None, default_circuit_scheduler_settings: Optional[Dict[str, Any]] = None, ) -> ContextManager[ScheduleBlock]: """Create a context manager for launching the imperative pulse builder DSL. To enter a building context and starting building a pulse program: .. code-block:: from qiskit import execute, pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 0.5), d0) While the output program ``pulse_prog`` cannot be executed as we are using a mock backend. If a real backend is being used, executing the program is done with: .. code-block:: python qiskit.execute(pulse_prog, backend) Args: backend (Backend): A Qiskit backend. If not supplied certain builder functionality will be unavailable. schedule: A pulse ``ScheduleBlock`` in which your pulse program will be built. name: Name of pulse program to be built. default_alignment: Default scheduling alignment for builder. One of ``left``, ``right``, ``sequential`` or an alignment context. default_transpiler_settings: Default settings for the transpiler. default_circuit_scheduler_settings: Default settings for the circuit to pulse scheduler. Returns: A new builder context which has the active builder initialized. """ return _PulseBuilder( backend=backend, block=schedule, name=name, default_alignment=default_alignment, default_transpiler_settings=default_transpiler_settings, default_circuit_scheduler_settings=default_circuit_scheduler_settings, ) # Builder Utilities def _active_builder() -> _PulseBuilder: """Get the active builder in the active context. Returns: The active active builder in this context. Raises: exceptions.NoActiveBuilder: If a pulse builder function is called outside of a builder context. """ try: return BUILDER_CONTEXTVAR.get() except LookupError as ex: raise exceptions.NoActiveBuilder( "A Pulse builder function was called outside of " "a builder context. Try calling within a builder " 'context, eg., "with pulse.build() as schedule: ...".' ) from ex def active_backend(): """Get the backend of the currently active builder context. Returns: Backend: The active backend in the currently active builder context. Raises: exceptions.BackendNotSet: If the builder does not have a backend set. """ builder = _active_builder().backend if builder is None: raise exceptions.BackendNotSet( 'This function requires the active builder to have a "backend" set.' ) return builder def append_schedule(schedule: Union[Schedule, ScheduleBlock]): """Call a schedule by appending to the active builder's context block. Args: schedule: Schedule or ScheduleBlock to append. """ _active_builder().append_subroutine(schedule) def append_instruction(instruction: instructions.Instruction): """Append an instruction to the active builder's context schedule. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.builder.append_instruction(pulse.Delay(10, d0)) print(pulse_prog.instructions) .. parsed-literal:: ((0, Delay(10, DriveChannel(0))),) """ _active_builder().append_instruction(instruction) def num_qubits() -> int: """Return number of qubits in the currently active backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.num_qubits()) .. parsed-literal:: 2 .. note:: Requires the active builder context to have a backend set. """ if isinstance(active_backend(), BackendV2): return active_backend().num_qubits return active_backend().configuration().n_qubits def seconds_to_samples(seconds: Union[float, np.ndarray]) -> Union[int, np.ndarray]: """Obtain the number of samples that will elapse in ``seconds`` on the active backend. Rounds down. Args: seconds: Time in seconds to convert to samples. Returns: The number of samples for the time to elapse """ dt = _active_builder().get_dt() if isinstance(seconds, np.ndarray): return (seconds / dt).astype(int) return int(seconds / dt) def samples_to_seconds(samples: Union[int, np.ndarray]) -> Union[float, np.ndarray]: """Obtain the time in seconds that will elapse for the input number of samples on the active backend. Args: samples: Number of samples to convert to time in seconds. Returns: The time that elapses in ``samples``. """ return samples * _active_builder().get_dt() def qubit_channels(qubit: int) -> Set[chans.Channel]: """Returns the set of channels associated with a qubit. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.qubit_channels(0)) .. parsed-literal:: {MeasureChannel(0), ControlChannel(0), DriveChannel(0), AcquireChannel(0), ControlChannel(1)} .. note:: Requires the active builder context to have a backend set. .. note:: A channel may still be associated with another qubit in this list such as in the case where significant crosstalk exists. """ # implement as the inner function to avoid API change for a patch release in 0.24.2. def get_qubit_channels_v2(backend: BackendV2, qubit: int): r"""Return a list of channels which operate on the given ``qubit``. Returns: List of ``Channel``\s operated on my the given ``qubit``. """ channels = [] # add multi-qubit channels for node_qubits in backend.coupling_map: if qubit in node_qubits: control_channel = backend.control_channel(node_qubits) if control_channel: channels.extend(control_channel) # add single qubit channels channels.append(backend.drive_channel(qubit)) channels.append(backend.measure_channel(qubit)) channels.append(backend.acquire_channel(qubit)) return channels # backendV2 if isinstance(active_backend(), BackendV2): return set(get_qubit_channels_v2(active_backend(), qubit)) return set(active_backend().configuration().get_qubit_channels(qubit)) def _qubits_to_channels(*channels_or_qubits: Union[int, chans.Channel]) -> Set[chans.Channel]: """Returns the unique channels of the input qubits.""" channels = set() for channel_or_qubit in channels_or_qubits: if isinstance(channel_or_qubit, int): channels |= qubit_channels(channel_or_qubit) elif isinstance(channel_or_qubit, chans.Channel): channels.add(channel_or_qubit) else: raise exceptions.PulseError( f'{channel_or_qubit} is not a "Channel" or qubit (integer).' ) return channels def active_transpiler_settings() -> Dict[str, Any]: """Return the current active builder context's transpiler settings. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() transpiler_settings = {'optimization_level': 3} with pulse.build(backend, default_transpiler_settings=transpiler_settings): print(pulse.active_transpiler_settings()) .. parsed-literal:: {'optimization_level': 3} """ return dict(_active_builder().transpiler_settings) def active_circuit_scheduler_settings() -> Dict[str, Any]: """Return the current active builder context's circuit scheduler settings. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() circuit_scheduler_settings = {'method': 'alap'} with pulse.build( backend, default_circuit_scheduler_settings=circuit_scheduler_settings): print(pulse.active_circuit_scheduler_settings()) .. parsed-literal:: {'method': 'alap'} """ return dict(_active_builder().circuit_scheduler_settings) # Contexts @contextmanager def align_left() -> ContextManager[None]: """Left alignment pulse scheduling context. Pulse instructions within this context are scheduled as early as possible by shifting them left to the earliest available time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_left(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=0 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_start_time(d0) == pulse_prog.ch_start_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignLeft()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_right() -> AlignmentKind: """Right alignment pulse scheduling context. Pulse instructions within this context are scheduled as late as possible by shifting them right to the latest available time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_stop_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignRight()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_sequential() -> AlignmentKind: """Sequential alignment pulse scheduling context. Pulse instructions within this context are scheduled sequentially in time such that no two instructions will be played at the same time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_sequential(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will also start at t=100 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_start_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignSequential()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_equispaced(duration: Union[int, ParameterExpression]) -> AlignmentKind: """Equispaced alignment pulse scheduling context. Pulse instructions within this context are scheduled with the same interval spacing such that the total length of the context block is ``duration``. If the total free ``duration`` cannot be evenly divided by the number of instructions within the context, the modulo is split and then prepended and appended to the returned schedule. Delay instructions are automatically inserted in between pulses. This context is convenient to write a schedule for periodical dynamic decoupling or the Hahn echo sequence. Examples: .. plot:: :include-source: from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) with pulse.build() as hahn_echo: with pulse.align_equispaced(duration=100): pulse.play(x90, d0) pulse.play(x180, d0) pulse.play(x90, d0) hahn_echo.draw() Args: duration: Duration of this context. This should be larger than the schedule duration. Yields: None Notes: The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the equispaced context for each channel, you should use the context independently for channels. """ builder = _active_builder() builder.push_context(transforms.AlignEquispaced(duration=duration)) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_func( duration: Union[int, ParameterExpression], func: Callable[[int], float] ) -> AlignmentKind: """Callback defined alignment pulse scheduling context. Pulse instructions within this context are scheduled at the location specified by arbitrary callback function `position` that takes integer index and returns the associated fractional location within [0, 1]. Delay instruction is automatically inserted in between pulses. This context may be convenient to write a schedule of arbitrary dynamical decoupling sequences such as Uhrig dynamical decoupling. Examples: .. plot:: :include-source: import numpy as np from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) def udd10_pos(j): return np.sin(np.pi*j/(2*10 + 2))**2 with pulse.build() as udd_sched: pulse.play(x90, d0) with pulse.align_func(duration=300, func=udd10_pos): for _ in range(10): pulse.play(x180, d0) pulse.play(x90, d0) udd_sched.draw() Args: duration: Duration of context. This should be larger than the schedule duration. func: A function that takes an index of sub-schedule and returns the fractional coordinate of of that sub-schedule. The returned value should be defined within [0, 1]. The pulse index starts from 1. Yields: None Notes: The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the numerical context for each channel, you need to apply the context independently to channels. """ builder = _active_builder() builder.push_context(transforms.AlignFunc(duration=duration, func=func)) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def general_transforms(alignment_context: AlignmentKind) -> ContextManager[None]: """Arbitrary alignment transformation defined by a subclass instance of :class:`~qiskit.pulse.transforms.alignments.AlignmentKind`. Args: alignment_context: Alignment context instance that defines schedule transformation. Yields: None Raises: PulseError: When input ``alignment_context`` is not ``AlignmentKind`` subclasses. """ if not isinstance(alignment_context, AlignmentKind): raise exceptions.PulseError("Input alignment context is not `AlignmentKind` subclass.") builder = _active_builder() builder.push_context(alignment_context) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def transpiler_settings(**settings) -> ContextManager[None]: """Set the currently active transpiler settings for this context. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.active_transpiler_settings()) with pulse.transpiler_settings(optimization_level=3): print(pulse.active_transpiler_settings()) .. parsed-literal:: {} {'optimization_level': 3} """ builder = _active_builder() curr_transpiler_settings = builder.transpiler_settings builder.transpiler_settings = collections.ChainMap(settings, curr_transpiler_settings) try: yield finally: builder.transpiler_settings = curr_transpiler_settings @contextmanager def circuit_scheduler_settings(**settings) -> ContextManager[None]: """Set the currently active circuit scheduler settings for this context. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.active_circuit_scheduler_settings()) with pulse.circuit_scheduler_settings(method='alap'): print(pulse.active_circuit_scheduler_settings()) .. parsed-literal:: {} {'method': 'alap'} """ builder = _active_builder() curr_circuit_scheduler_settings = builder.circuit_scheduler_settings builder.circuit_scheduler_settings = collections.ChainMap( settings, curr_circuit_scheduler_settings ) try: yield finally: builder.circuit_scheduler_settings = curr_circuit_scheduler_settings @contextmanager def phase_offset(phase: float, *channels: chans.PulseChannel) -> ContextManager[None]: """Shift the phase of input channels on entry into context and undo on exit. Examples: .. code-block:: import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: with pulse.phase_offset(math.pi, d0): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 3 Args: phase: Amount of phase offset in radians. channels: Channels to offset phase of. Yields: None """ for channel in channels: shift_phase(phase, channel) try: yield finally: for channel in channels: shift_phase(-phase, channel) @contextmanager def frequency_offset( frequency: float, *channels: chans.PulseChannel, compensate_phase: bool = False ) -> ContextManager[None]: """Shift the frequency of inputs channels on entry into context and undo on exit. Examples: .. code-block:: python :emphasize-lines: 7, 16 from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build(backend) as pulse_prog: # shift frequency by 1GHz with pulse.frequency_offset(1e9, d0): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 3 with pulse.build(backend) as pulse_prog: # Shift frequency by 1GHz. # Undo accumulated phase in the shifted frequency frame # when exiting the context. with pulse.frequency_offset(1e9, d0, compensate_phase=True): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 4 Args: frequency: Amount of frequency offset in Hz. channels: Channels to offset frequency of. compensate_phase: Compensate for accumulated phase accumulated with respect to the channels' frame at its initial frequency. Yields: None """ builder = _active_builder() # TODO: Need proper implementation of compensation. t0 may depend on the parent context. # For example, the instruction position within the equispaced context depends on # the current total number of instructions, thus adding more instruction after # offset context may change the t0 when the parent context is transformed. t0 = builder.get_context().duration for channel in channels: shift_frequency(frequency, channel) try: yield finally: if compensate_phase: duration = builder.get_context().duration - t0 accumulated_phase = 2 * np.pi * ((duration * builder.get_dt() * frequency) % 1) for channel in channels: shift_phase(-accumulated_phase, channel) for channel in channels: shift_frequency(-frequency, channel) # Channels def drive_channel(qubit: int) -> chans.DriveChannel: """Return ``DriveChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.drive_channel(0) == pulse.DriveChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().drive_channel(qubit) return active_backend().configuration().drive(qubit) def measure_channel(qubit: int) -> chans.MeasureChannel: """Return ``MeasureChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.measure_channel(0) == pulse.MeasureChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().measure_channel(qubit) return active_backend().configuration().measure(qubit) def acquire_channel(qubit: int) -> chans.AcquireChannel: """Return ``AcquireChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.acquire_channel(0) == pulse.AcquireChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().acquire_channel(qubit) return active_backend().configuration().acquire(qubit) def control_channels(*qubits: Iterable[int]) -> List[chans.ControlChannel]: """Return ``ControlChannel`` for ``qubit`` on the active builder backend. Return the secondary drive channel for the given qubit -- typically utilized for controlling multi-qubit interactions. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.control_channels(0, 1) == [pulse.ControlChannel(0)] .. note:: Requires the active builder context to have a backend set. Args: qubits: Tuple or list of ordered qubits of the form `(control_qubit, target_qubit)`. Returns: List of control channels associated with the supplied ordered list of qubits. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().control_channel(qubits) return active_backend().configuration().control(qubits=qubits) # Base Instructions def delay(duration: int, channel: chans.Channel, name: Optional[str] = None): """Delay on a ``channel`` for a ``duration``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.delay(10, d0) Args: duration: Number of cycles to delay for on ``channel``. channel: Channel to delay on. name: Name of the instruction. """ append_instruction(instructions.Delay(duration, channel, name=name)) def play( pulse: Union[library.Pulse, np.ndarray], channel: chans.PulseChannel, name: Optional[str] = None ): """Play a ``pulse`` on a ``channel``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(10, 1.0), d0) Args: pulse: Pulse to play. channel: Channel to play pulse on. name: Name of the pulse. """ if not isinstance(pulse, library.Pulse): pulse = library.Waveform(pulse) append_instruction(instructions.Play(pulse, channel, name=name)) def acquire( duration: int, qubit_or_channel: Union[int, chans.AcquireChannel], register: StorageLocation, **metadata: Union[configuration.Kernel, configuration.Discriminator], ): """Acquire for a ``duration`` on a ``channel`` and store the result in a ``register``. Examples: .. code-block:: from qiskit import pulse acq0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) with pulse.build() as pulse_prog: pulse.acquire(100, acq0, mem0) # measurement metadata kernel = pulse.configuration.Kernel('linear_discriminator') pulse.acquire(100, acq0, mem0, kernel=kernel) .. note:: The type of data acquire will depend on the execution ``meas_level``. Args: duration: Duration to acquire data for qubit_or_channel: Either the qubit to acquire data for or the specific :class:`~qiskit.pulse.channels.AcquireChannel` to acquire on. register: Location to store measured result. metadata: Additional metadata for measurement. See :class:`~qiskit.pulse.instructions.Acquire` for more information. Raises: exceptions.PulseError: If the register type is not supported. """ if isinstance(qubit_or_channel, int): qubit_or_channel = chans.AcquireChannel(qubit_or_channel) if isinstance(register, chans.MemorySlot): append_instruction( instructions.Acquire(duration, qubit_or_channel, mem_slot=register, **metadata) ) elif isinstance(register, chans.RegisterSlot): append_instruction( instructions.Acquire(duration, qubit_or_channel, reg_slot=register, **metadata) ) else: raise exceptions.PulseError(f'Register of type: "{type(register)}" is not supported') def set_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None): """Set the ``frequency`` of a pulse ``channel``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.set_frequency(1e9, d0) Args: frequency: Frequency in Hz to set channel to. channel: Channel to set frequency of. name: Name of the instruction. """ append_instruction(instructions.SetFrequency(frequency, channel, name=name)) def shift_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None): """Shift the ``frequency`` of a pulse ``channel``. Examples: .. code-block:: python :emphasize-lines: 6 from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.shift_frequency(1e9, d0) Args: frequency: Frequency in Hz to shift channel frequency by. channel: Channel to shift frequency of. name: Name of the instruction. """ append_instruction(instructions.ShiftFrequency(frequency, channel, name=name)) def set_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None): """Set the ``phase`` of a pulse ``channel``. Examples: .. code-block:: python :emphasize-lines: 8 import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.set_phase(math.pi, d0) Args: phase: Phase in radians to set channel carrier signal to. channel: Channel to set phase of. name: Name of the instruction. """ append_instruction(instructions.SetPhase(phase, channel, name=name)) def shift_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None): """Shift the ``phase`` of a pulse ``channel``. Examples: .. code-block:: import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.shift_phase(math.pi, d0) Args: phase: Phase in radians to shift channel carrier signal by. channel: Channel to shift phase of. name: Name of the instruction. """ append_instruction(instructions.ShiftPhase(phase, channel, name)) def snapshot(label: str, snapshot_type: str = "statevector"): """Simulator snapshot. Examples: .. code-block:: from qiskit import pulse with pulse.build() as pulse_prog: pulse.snapshot('first', 'statevector') Args: label: Label for snapshot. snapshot_type: Type of snapshot. """ append_instruction(instructions.Snapshot(label, snapshot_type=snapshot_type)) def call( target: Optional[Union[circuit.QuantumCircuit, Schedule, ScheduleBlock]], name: Optional[str] = None, value_dict: Optional[Dict[ParameterValueType, ParameterValueType]] = None, **kw_params: ParameterValueType, ): """Call the subroutine within the currently active builder context with arbitrary parameters which will be assigned to the target program. .. note:: If the ``target`` program is a :class:`.ScheduleBlock`, then a :class:`.Reference` instruction will be created and appended to the current context. The ``target`` program will be immediately assigned to the current scope as a subroutine. If the ``target`` program is :class:`.Schedule`, it will be wrapped by the :class:`.Call` instruction and appended to the current context to avoid a mixed representation of :class:`.ScheduleBlock` and :class:`.Schedule`. If the ``target`` program is a :class:`.QuantumCircuit` it will be scheduled and the new :class:`.Schedule` will be added as a :class:`.Call` instruction. Examples: 1. Calling a schedule block (recommended) .. code-block:: from qiskit import circuit, pulse from qiskit.providers.fake_provider import FakeBogotaV2 backend = FakeBogotaV2() with pulse.build() as x_sched: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) with pulse.build() as pulse_prog: pulse.call(x_sched) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play( Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0) ), name="block0", transform=AlignLeft() ), name="block1", transform=AlignLeft() ) The actual program is stored in the reference table attached to the schedule. .. code-block:: print(pulse_prog.references) .. parsed-literal:: ReferenceManager: - ('block0', '634b3b50bd684e26a673af1fbd2d6c81'): ScheduleBlock(Play(Gaussian(... In addition, you can call a parameterized target program with parameter assignment. .. code-block:: amp = circuit.Parameter("amp") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0)) with pulse.build() as pulse_prog: pulse.call(subroutine, amp=0.1) pulse.call(subroutine, amp=0.3) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play( Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0) ), name="block2", transform=AlignLeft() ), ScheduleBlock( Play( Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(0) ), name="block2", transform=AlignLeft() ), name="block3", transform=AlignLeft() ) If there is a name collision between parameters, you can distinguish them by specifying each parameter object in a python dictionary. For example, .. code-block:: amp1 = circuit.Parameter('amp') amp2 = circuit.Parameter('amp') with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, amp2, 40), pulse.DriveChannel(1)) with pulse.build() as pulse_prog: pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.3}) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play(Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0)), Play(Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(1)), name="block4", transform=AlignLeft() ), name="block5", transform=AlignLeft() ) 2. Calling a schedule .. code-block:: x_sched = backend.instruction_schedule_map.get("x", (0,)) with pulse.build(backend) as pulse_prog: pulse.call(x_sched) print(pulse_prog) .. parsed-literal:: ScheduleBlock( Call( Schedule( ( 0, Play( Drag( duration=160, amp=(0.18989731546729305+0j), sigma=40, beta=-1.201258305015517, name='drag_86a8' ), DriveChannel(0), name='drag_86a8' ) ), name="x" ), name='x' ), name="block6", transform=AlignLeft() ) Currently, the backend calibrated gates are provided in the form of :class:`~.Schedule`. The parameter assignment mechanism is available also for schedules. However, the called schedule is not treated as a reference. 3. Calling a quantum circuit .. code-block:: backend = FakeBogotaV2() qc = circuit.QuantumCircuit(1) qc.x(0) with pulse.build(backend) as pulse_prog: pulse.call(qc) print(pulse_prog) .. parsed-literal:: ScheduleBlock( Call( Schedule( ( 0, Play( Drag( duration=160, amp=(0.18989731546729305+0j), sigma=40, beta=-1.201258305015517, name='drag_86a8' ), DriveChannel(0), name='drag_86a8' ) ), name="circuit-87" ), name='circuit-87' ), name="block7", transform=AlignLeft() ) .. warning:: Calling a circuit from a schedule is not encouraged. Currently, the Qiskit execution model is migrating toward the pulse gate model, where schedules are attached to circuits through the :meth:`.QuantumCircuit.add_calibration` method. Args: target: Target circuit or pulse schedule to call. name: Optional. A unique name of subroutine if defined. When the name is explicitly provided, one cannot call different schedule blocks with the same name. value_dict: Optional. Parameters assigned to the ``target`` program. If this dictionary is provided, the ``target`` program is copied and then stored in the main built schedule and its parameters are assigned to the given values. This dictionary is keyed on :class:`~.Parameter` objects, allowing parameter name collision to be avoided. kw_params: Alternative way to provide parameters. Since this is keyed on the string parameter name, the parameters having the same name are all updated together. If you want to avoid name collision, use ``value_dict`` with :class:`~.Parameter` objects instead. """ _active_builder().call_subroutine(target, name, value_dict, **kw_params) def reference(name: str, *extra_keys: str): """Refer to undefined subroutine by string keys. A :class:`~qiskit.pulse.instructions.Reference` instruction is implicitly created and a schedule can be separately registered to the reference at a later stage. .. code-block:: python from qiskit import pulse with pulse.build() as main_prog: pulse.reference("x_gate", "q0") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) main_prog.assign_references(subroutine_dict={("x_gate", "q0"): subroutine}) Args: name: Name of subroutine. extra_keys: Helper keys to uniquely specify the subroutine. """ _active_builder().append_reference(name, *extra_keys) # Directives def barrier(*channels_or_qubits: Union[chans.Channel, int], name: Optional[str] = None): """Barrier directive for a set of channels and qubits. This directive prevents the compiler from moving instructions across the barrier. Consider the case where we want to enforce that one pulse happens after another on separate channels, this can be done with: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build(backend) as barrier_pulse_prog: pulse.play(pulse.Constant(10, 1.0), d0) pulse.barrier(d0, d1) pulse.play(pulse.Constant(10, 1.0), d1) Of course this could have been accomplished with: .. code-block:: from qiskit.pulse import transforms with pulse.build(backend) as aligned_pulse_prog: with pulse.align_sequential(): pulse.play(pulse.Constant(10, 1.0), d0) pulse.play(pulse.Constant(10, 1.0), d1) barrier_pulse_prog = transforms.target_qobj_transform(barrier_pulse_prog) aligned_pulse_prog = transforms.target_qobj_transform(aligned_pulse_prog) assert barrier_pulse_prog == aligned_pulse_prog The barrier allows the pulse compiler to take care of more advanced scheduling alignment operations across channels. For example in the case where we are calling an outside circuit or schedule and want to align a pulse at the end of one call: .. code-block:: import math d0 = pulse.DriveChannel(0) with pulse.build(backend) as pulse_prog: with pulse.align_right(): pulse.x(1) # Barrier qubit 1 and d0. pulse.barrier(1, d0) # Due to barrier this will play before the gate on qubit 1. pulse.play(pulse.Constant(10, 1.0), d0) # This will end at the same time as the pulse above due to # the barrier. pulse.x(1) .. note:: Requires the active builder context to have a backend set if qubits are barriered on. Args: channels_or_qubits: Channels or qubits to barrier. name: Name for the barrier """ channels = _qubits_to_channels(*channels_or_qubits) if len(channels) > 1: append_instruction(directives.RelativeBarrier(*channels, name=name)) # Macros def macro(func: Callable): """Wrap a Python function and activate the parent builder context at calling time. This enables embedding Python functions as builder macros. This generates a new :class:`pulse.Schedule` that is embedded in the parent builder context with every call of the decorated macro function. The decorated macro function will behave as if the function code was embedded inline in the parent builder context after parameter substitution. Examples: .. plot:: :include-source: from qiskit import pulse @pulse.macro def measure(qubit: int): pulse.play(pulse.GaussianSquare(16384, 256, 15872), pulse.measure_channel(qubit)) mem_slot = pulse.MemorySlot(qubit) pulse.acquire(16384, pulse.acquire_channel(qubit), mem_slot) return mem_slot with pulse.build(backend=backend) as sched: mem_slot = measure(0) print(f"Qubit measured into {mem_slot}") sched.draw() Args: func: The Python function to enable as a builder macro. There are no requirements on the signature of the function, any calls to pulse builder methods will be added to builder context the wrapped function is called from. Returns: Callable: The wrapped ``func``. """ func_name = getattr(func, "__name__", repr(func)) @functools.wraps(func) def wrapper(*args, **kwargs): _builder = _active_builder() # activate the pulse builder before calling the function with build(backend=_builder.backend, name=func_name) as built: output = func(*args, **kwargs) _builder.call_subroutine(built) return output return wrapper def measure( qubits: Union[List[int], int], registers: Union[List[StorageLocation], StorageLocation] = None, ) -> Union[List[StorageLocation], StorageLocation]: """Measure a qubit within the currently active builder context. At the pulse level a measurement is composed of both a stimulus pulse and an acquisition instruction which tells the systems measurement unit to acquire data and process it. We provide this measurement macro to automate the process for you, but if desired full control is still available with :func:`acquire` and :func:`play`. To use the measurement it is as simple as specifying the qubit you wish to measure: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() qubit = 0 with pulse.build(backend) as pulse_prog: # Do something to the qubit. qubit_drive_chan = pulse.drive_channel(0) pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan) # Measure the qubit. reg = pulse.measure(qubit) For now it is not possible to do much with the handle to ``reg`` but in the future we will support using this handle to a result register to build up ones program. It is also possible to supply this register: .. code-block:: with pulse.build(backend) as pulse_prog: pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan) # Measure the qubit. mem0 = pulse.MemorySlot(0) reg = pulse.measure(qubit, mem0) assert reg == mem0 .. note:: Requires the active builder context to have a backend set. Args: qubits: Physical qubit to measure. registers: Register to store result in. If not selected the current behavior is to return the :class:`MemorySlot` with the same index as ``qubit``. This register will be returned. Returns: The ``register`` the qubit measurement result will be stored in. """ backend = active_backend() try: qubits = list(qubits) except TypeError: qubits = [qubits] if registers is None: registers = [chans.MemorySlot(qubit) for qubit in qubits] else: try: registers = list(registers) except TypeError: registers = [registers] measure_sched = macros.measure( qubits=qubits, backend=backend, qubit_mem_slots={qubit: register.index for qubit, register in zip(qubits, registers)}, ) # note this is not a subroutine. # just a macro to automate combination of stimulus and acquisition. # prepare unique reference name based on qubit and memory slot index. qubits_repr = "&".join(map(str, qubits)) mslots_repr = "&".join((str(r.index) for r in registers)) _active_builder().call_subroutine(measure_sched, name=f"measure_{qubits_repr}..{mslots_repr}") if len(qubits) == 1: return registers[0] else: return registers def measure_all() -> List[chans.MemorySlot]: r"""Measure all qubits within the currently active builder context. A simple macro function to measure all of the qubits in the device at the same time. This is useful for handling device ``meas_map`` and single measurement constraints. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: # Measure all qubits and return associated registers. regs = pulse.measure_all() .. note:: Requires the active builder context to have a backend set. Returns: The ``register``\s the qubit measurement results will be stored in. """ backend = active_backend() qubits = range(num_qubits()) registers = [chans.MemorySlot(qubit) for qubit in qubits] measure_sched = macros.measure( qubits=qubits, backend=backend, qubit_mem_slots={qubit: qubit for qubit in qubits}, ) # note this is not a subroutine. # just a macro to automate combination of stimulus and acquisition. _active_builder().call_subroutine(measure_sched, name="measure_all") return registers def delay_qubits(duration: int, *qubits: Union[int, Iterable[int]]): r"""Insert delays on all of the :class:`channels.Channel`\s that correspond to the input ``qubits`` at the same time. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q backend = FakeOpenPulse3Q() with pulse.build(backend) as pulse_prog: # Delay for 100 cycles on qubits 0, 1 and 2. regs = pulse.delay_qubits(100, 0, 1, 2) .. note:: Requires the active builder context to have a backend set. Args: duration: Duration to delay for. qubits: Physical qubits to delay on. Delays will be inserted based on the channels returned by :func:`pulse.qubit_channels`. """ qubit_chans = set(itertools.chain.from_iterable(qubit_channels(qubit) for qubit in qubits)) with align_left(): for chan in qubit_chans: delay(duration, chan) # Gate instructions def call_gate(gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True): """Call a gate and lazily schedule it to its corresponding pulse instruction. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.pulse import builder from qiskit.circuit.library import standard_gates as gates from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: builder.call_gate(gates.CXGate(), (0, 1)) We can see the role of the transpiler in scheduling gates by optimizing away two consecutive CNOT gates: .. code-block:: with pulse.build(backend) as pulse_prog: with pulse.transpiler_settings(optimization_level=3): builder.call_gate(gates.CXGate(), (0, 1)) builder.call_gate(gates.CXGate(), (0, 1)) assert pulse_prog == pulse.Schedule() .. note:: If multiple gates are called in a row they may be optimized by the transpiler, depending on the :func:`pulse.active_transpiler_settings``. .. note:: Requires the active builder context to have a backend set. Args: gate: Circuit gate instance to call. qubits: Qubits to call gate on. lazy: If ``false`` the gate will be compiled immediately, otherwise it will be added onto a lazily evaluated quantum circuit to be compiled when the builder is forced to by a circuit assumption being broken, such as the inclusion of a pulse instruction or new alignment context. """ _active_builder().call_gate(gate, qubits, lazy=lazy) def cx(control: int, target: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.CXGate` on the input physical qubits. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.cx(0, 1) """ call_gate(gates.CXGate(), (control, target)) def u1(theta: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U1Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u1(math.pi, 1) """ call_gate(gates.U1Gate(theta), qubit) def u2(phi: float, lam: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U2Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u2(0, math.pi, 1) """ call_gate(gates.U2Gate(phi, lam), qubit) def u3(theta: float, phi: float, lam: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U3Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u3(math.pi, 0, math.pi, 1) """ call_gate(gates.U3Gate(theta, phi, lam), qubit) def x(qubit: int): """Call a :class:`~qiskit.circuit.library.standard_gates.XGate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.x(0) """ call_gate(gates.XGate(), qubit)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. "Circuit operation representing a ``for`` loop." import warnings from typing import Iterable, Optional, Union from qiskit.circuit.parameter import Parameter from qiskit.circuit.exceptions import CircuitError from qiskit.circuit.quantumcircuit import QuantumCircuit from .control_flow import ControlFlowOp class ForLoopOp(ControlFlowOp): """A circuit operation which repeatedly executes a subcircuit (``body``) parameterized by a parameter ``loop_parameter`` through the set of integer values provided in ``indexset``. Parameters: indexset: A collection of integers to loop over. loop_parameter: The placeholder parameterizing ``body`` to which the values from ``indexset`` will be assigned. body: The loop body to be repeatedly executed. label: An optional label for identifying the instruction. **Circuit symbol:** .. parsed-literal:: ┌───────────┐ q_0: ┤0 ├ │ │ q_1: ┤1 ├ │ for_loop │ q_2: ┤2 ├ │ │ c_0: ╡0 ╞ └───────────┘ """ def __init__( self, indexset: Iterable[int], loop_parameter: Union[Parameter, None], body: QuantumCircuit, label: Optional[str] = None, ): num_qubits = body.num_qubits num_clbits = body.num_clbits super().__init__( "for_loop", num_qubits, num_clbits, [indexset, loop_parameter, body], label=label ) @property def params(self): return self._params @params.setter def params(self, parameters): indexset, loop_parameter, body = parameters if not isinstance(loop_parameter, (Parameter, type(None))): raise CircuitError( "ForLoopOp expects a loop_parameter parameter to " "be either of type Parameter or None, but received " f"{type(loop_parameter)}." ) if not isinstance(body, QuantumCircuit): raise CircuitError( "ForLoopOp expects a body parameter to be of type " f"QuantumCircuit, but received {type(body)}." ) if body.num_qubits != self.num_qubits or body.num_clbits != self.num_clbits: raise CircuitError( "Attempted to assign a body parameter with a num_qubits or " "num_clbits different than that of the ForLoopOp. " f"ForLoopOp num_qubits/clbits: {self.num_qubits}/{self.num_clbits} " f"Supplied body num_qubits/clbits: {body.num_qubits}/{body.num_clbits}." ) if ( loop_parameter is not None and loop_parameter not in body.parameters and loop_parameter.name in (p.name for p in body.parameters) ): warnings.warn( "The Parameter provided as a loop_parameter was not found " "on the loop body and so no binding of the indexset to loop " "parameter will occur. A different Parameter of the same name " f"({loop_parameter.name}) was found. If you intended to loop " "over that Parameter, please use that Parameter instance as " "the loop_parameter.", stacklevel=2, ) # Consume indexset into a tuple unless it was provided as a range. # Preserve ranges so that they can be exported as OpenQASM3 ranges. indexset = indexset if isinstance(indexset, range) else tuple(indexset) self._params = [indexset, loop_parameter, body] @property def blocks(self): return (self._params[2],) def replace_blocks(self, blocks): (body,) = blocks return ForLoopOp(self.params[0], self.params[1], body, label=self.label) class ForLoopContext: """A context manager for building up ``for`` loops onto circuits in a natural order, without having to construct the loop body first. Within the block, a lot of the bookkeeping is done for you; you do not need to keep track of which qubits and clbits you are using, for example, and a loop parameter will be allocated for you, if you do not supply one yourself. All normal methods of accessing the qubits on the underlying :obj:`~QuantumCircuit` will work correctly, and resolve into correct accesses within the interior block. You generally should never need to instantiate this object directly. Instead, use :obj:`.QuantumCircuit.for_loop` in its context-manager form, i.e. by not supplying a ``body`` or sets of qubits and clbits. Example usage:: import math from qiskit import QuantumCircuit qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)) as i: qc.rx(i * math.pi/4, 0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) This context should almost invariably be created by a :meth:`.QuantumCircuit.for_loop` call, and the resulting instance is a "friend" of the calling circuit. The context will manipulate the circuit's defined scopes when it is entered (by pushing a new scope onto the stack) and exited (by popping its scope, building it, and appending the resulting :obj:`.ForLoopOp`). .. warning:: This is an internal interface and no part of it should be relied upon outside of Qiskit Terra. """ # Class-level variable keep track of the number of auto-generated loop variables, so we don't # get naming clashes. _generated_loop_parameters = 0 __slots__ = ( "_circuit", "_generate_loop_parameter", "_loop_parameter", "_indexset", "_label", "_used", ) def __init__( self, circuit: QuantumCircuit, indexset: Iterable[int], loop_parameter: Optional[Parameter] = None, *, label: Optional[str] = None, ): self._circuit = circuit self._generate_loop_parameter = loop_parameter is None self._loop_parameter = loop_parameter # We can pass through `range` instances because OpenQASM 3 has native support for this type # of iterator set. self._indexset = indexset if isinstance(indexset, range) else tuple(indexset) self._label = label self._used = False def __enter__(self): if self._used: raise CircuitError("A for-loop context manager cannot be re-entered.") self._used = True self._circuit._push_scope() if self._generate_loop_parameter: self._loop_parameter = Parameter(f"_loop_i_{self._generated_loop_parameters}") type(self)._generated_loop_parameters += 1 return self._loop_parameter def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: # If we're leaving the context manager because an exception was raised, there's nothing # to do except restore the circuit state. self._circuit._pop_scope() return False scope = self._circuit._pop_scope() # Loops do not need to pass any further resources in, because this scope itself defines the # extent of ``break`` and ``continue`` statements. body = scope.build(scope.qubits, scope.clbits) # We always bind the loop parameter if the user gave it to us, even if it isn't actually # used, because they requested we do that by giving us a parameter. However, if they asked # us to auto-generate a parameter, then we only add it if they actually used it, to avoid # using unnecessary resources. if self._generate_loop_parameter and self._loop_parameter not in body.parameters: loop_parameter = None else: loop_parameter = self._loop_parameter self._circuit.append( ForLoopOp(self._indexset, loop_parameter, body, label=self._label), tuple(body.qubits), tuple(body.clbits), ) return False
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Gate described by the time evolution of a Hermitian Hamiltonian operator. """ from __future__ import annotations import math import typing from numbers import Number import numpy as np from qiskit import _numpy_compat from qiskit.circuit.gate import Gate from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister from qiskit.circuit.parameterexpression import ParameterExpression from qiskit.circuit.exceptions import CircuitError from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.quantum_info.operators.predicates import is_hermitian_matrix from .generalized_gates.unitary import UnitaryGate if typing.TYPE_CHECKING: from qiskit.quantum_info.operators.base_operator import BaseOperator class HamiltonianGate(Gate): r"""Class for representing evolution by a Hamiltonian operator as a gate. This gate resolves to a :class:`~.library.UnitaryGate` as :math:`U(t) = \exp(-i t H)`, which can be decomposed into basis gates if it is 2 qubits or less, or simulated directly in Aer for more qubits. """ def __init__( self, data: np.ndarray | Gate | BaseOperator, time: float | ParameterExpression, label: str | None = None, ) -> None: """ Args: data: A hermitian operator. time: Time evolution parameter. label: Unitary name for backend [Default: ``None``]. Raises: ValueError: if input data is not an N-qubit unitary operator. """ if hasattr(data, "to_matrix"): # If input is Gate subclass or some other class object that has # a to_matrix method this will call that method. data = data.to_matrix() elif hasattr(data, "to_operator"): # If input is a BaseOperator subclass this attempts to convert # the object to an Operator so that we can extract the underlying # numpy matrix from `Operator.data`. data = data.to_operator().data # Convert to np array in case not already an array data = np.asarray(data, dtype=complex) # Check input is unitary if not is_hermitian_matrix(data): raise ValueError("Input matrix is not Hermitian.") if isinstance(time, Number) and time != np.real(time): raise ValueError("Evolution time is not real.") # Check input is N-qubit matrix input_dim, output_dim = data.shape num_qubits = int(math.log2(input_dim)) if input_dim != output_dim or 2**num_qubits != input_dim: raise ValueError("Input matrix is not an N-qubit operator.") # Store instruction params super().__init__("hamiltonian", num_qubits, [data, time], label=label) def __eq__(self, other): if not isinstance(other, HamiltonianGate): return False if self.label != other.label: return False operators_eq = matrix_equal(self.params[0], other.params[0], ignore_phase=False) times_eq = self.params[1] == other.params[1] return operators_eq and times_eq def __array__(self, dtype=None, copy=None): """Return matrix for the unitary.""" import scipy.linalg if copy is False: raise ValueError("unable to avoid copy while creating an array as requested") try: time = float(self.params[1]) except TypeError as ex: raise TypeError( "Unable to generate Unitary matrix for " "unbound t parameter {}".format(self.params[1]) ) from ex arr = scipy.linalg.expm(-1j * self.params[0] * time) dtype = complex if dtype is None else dtype return np.array(arr, dtype=dtype, copy=_numpy_compat.COPY_ONLY_IF_NEEDED) def inverse(self, annotated: bool = False): """Return the adjoint of the unitary.""" return self.adjoint() def conjugate(self): """Return the conjugate of the Hamiltonian.""" return HamiltonianGate(np.conj(self.params[0]), -self.params[1]) def adjoint(self): """Return the adjoint of the unitary.""" return HamiltonianGate(self.params[0], -self.params[1]) def transpose(self): """Return the transpose of the Hamiltonian.""" return HamiltonianGate(np.transpose(self.params[0]), self.params[1]) def _define(self): """Calculate a subcircuit that implements this unitary.""" q = QuantumRegister(self.num_qubits, "q") qc = QuantumCircuit(q, name=self.name) qc._append(UnitaryGate(self.to_matrix()), q[:], []) self.definition = qc def validate_parameter(self, parameter): """Hamiltonian parameter has to be an ndarray, operator or float.""" if isinstance(parameter, (float, int, np.ndarray)): return parameter elif isinstance(parameter, ParameterExpression) and len(parameter.parameters) == 0: return float(parameter) else: raise CircuitError(f"invalid param type {type(parameter)} for gate {self.name}")
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Piecewise polynomial Chebyshev approximation to a given f(x).""" from __future__ import annotations from typing import Callable import numpy as np from numpy.polynomial.chebyshev import Chebyshev from qiskit.circuit import QuantumRegister, AncillaRegister from qiskit.circuit.library.blueprintcircuit import BlueprintCircuit from qiskit.circuit.exceptions import CircuitError from .piecewise_polynomial_pauli_rotations import PiecewisePolynomialPauliRotations class PiecewiseChebyshev(BlueprintCircuit): r"""Piecewise Chebyshev approximation to an input function. For a given function :math:`f(x)` and degree :math:`d`, this class implements a piecewise polynomial Chebyshev approximation on :math:`n` qubits to :math:`f(x)` on the given intervals. All the polynomials in the approximation are of degree :math:`d`. The values of the parameters are calculated according to [1] and see [2] for a more detailed explanation of the circuit construction and how it acts on the qubits. Examples: .. plot:: :include-source: import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2 pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits) pw_approximation._build() qc = QuantumCircuit(pw_approximation.num_qubits) qc.h(list(range(num_state_qubits))) qc.append(pw_approximation.to_instruction(), qc.qubits) qc.draw(output='mpl') References: [1]: Haener, T., Roetteler, M., & Svore, K. M. (2018). Optimizing Quantum Circuits for Arithmetic. `arXiv:1805.12445 <http://arxiv.org/abs/1805.12445>`_ [2]: Carrera Vazquez, A., Hiptmair, H., & Woerner, S. (2022). Enhancing the Quantum Linear Systems Algorithm Using Richardson Extrapolation. `ACM Transactions on Quantum Computing 3, 1, Article 2 <https://doi.org/10.1145/3490631>`_ """ def __init__( self, f_x: float | Callable[[int], float], degree: int | None = None, breakpoints: list[int] | None = None, num_state_qubits: int | None = None, name: str = "pw_cheb", ) -> None: r""" Args: f_x: the function to be approximated. Constant functions should be specified as f_x = constant. degree: the degree of the polynomials. Defaults to ``1``. breakpoints: the breakpoints to define the piecewise-linear function. Defaults to the full interval. num_state_qubits: number of qubits representing the state. name: The name of the circuit object. """ super().__init__(name=name) # define internal parameters self._num_state_qubits = None # Store parameters self._f_x = f_x self._degree = degree if degree is not None else 1 self._breakpoints = breakpoints if breakpoints is not None else [0] self._polynomials: list[list[float]] | None = None self.num_state_qubits = num_state_qubits def _check_configuration(self, raise_on_failure: bool = True) -> bool: """Check if the current configuration is valid.""" valid = True if self._f_x is None: valid = False if raise_on_failure: raise AttributeError("The function to be approximated has not been set.") if self._degree is None: valid = False if raise_on_failure: raise AttributeError("The degree of the polynomials has not been set.") if self._breakpoints is None: valid = False if raise_on_failure: raise AttributeError("The breakpoints have not been set.") if self.num_state_qubits is None: valid = False if raise_on_failure: raise AttributeError("The number of qubits has not been set.") if self.num_qubits < self.num_state_qubits + 1: valid = False if raise_on_failure: raise CircuitError( "Not enough qubits in the circuit, need at least " "{}.".format(self.num_state_qubits + 1) ) return valid @property def f_x(self) -> float | Callable[[int], float]: """The function to be approximated. Returns: The function to be approximated. """ return self._f_x @f_x.setter def f_x(self, f_x: float | Callable[[int], float] | None) -> None: """Set the function to be approximated. Note that this may change the underlying quantum register, if the number of state qubits changes. Args: f_x: The new function to be approximated. """ if self._f_x is None or f_x != self._f_x: self._invalidate() self._f_x = f_x self._reset_registers(self.num_state_qubits) @property def degree(self) -> int: """The degree of the polynomials. Returns: The degree of the polynomials. """ return self._degree @degree.setter def degree(self, degree: int | None) -> None: """Set the error tolerance. Note that this may change the underlying quantum register, if the number of state qubits changes. Args: degree: The new degree. """ if self._degree is None or degree != self._degree: self._invalidate() self._degree = degree self._reset_registers(self.num_state_qubits) @property def breakpoints(self) -> list[int]: """The breakpoints for the piecewise approximation. Returns: The breakpoints for the piecewise approximation. """ breakpoints = self._breakpoints # it the state qubits are set ensure that the breakpoints match beginning and end if self.num_state_qubits is not None: num_states = 2**self.num_state_qubits # If the last breakpoint is < num_states, add the identity polynomial if breakpoints[-1] < num_states: breakpoints = breakpoints + [num_states] # If the first breakpoint is > 0, add the identity polynomial if breakpoints[0] > 0: breakpoints = [0] + breakpoints return breakpoints @breakpoints.setter def breakpoints(self, breakpoints: list[int] | None) -> None: """Set the breakpoints for the piecewise approximation. Note that this may change the underlying quantum register, if the number of state qubits changes. Args: breakpoints: The new breakpoints for the piecewise approximation. """ if self._breakpoints is None or breakpoints != self._breakpoints: self._invalidate() self._breakpoints = breakpoints if breakpoints is not None else [0] self._reset_registers(self.num_state_qubits) @property def polynomials(self) -> list[list[float]]: """The polynomials for the piecewise approximation. Returns: The polynomials for the piecewise approximation. Raises: TypeError: If the input function is not in the correct format. """ if self.num_state_qubits is None: return [[]] # note this must be the private attribute since we handle missing breakpoints at # 0 and 2 ^ num_qubits here (e.g. if the function we approximate is not defined at 0 # and the user takes that into account we just add an identity) breakpoints = self._breakpoints # Need to take into account the case in which no breakpoints were provided in first place if breakpoints == [0]: breakpoints = [0, 2**self.num_state_qubits] num_intervals = len(breakpoints) # Calculate the polynomials polynomials = [] for i in range(0, num_intervals - 1): # Calculate the polynomial approximating the function on the current interval try: # If the function is constant don't call Chebyshev (not necessary and gives errors) if isinstance(self.f_x, (float, int)): # Append directly to list of polynomials polynomials.append([self.f_x]) else: poly = Chebyshev.interpolate( self.f_x, self.degree, domain=[breakpoints[i], breakpoints[i + 1]] ) # Convert polynomial to the standard basis and rescale it for the rotation gates poly = 2 * poly.convert(kind=np.polynomial.Polynomial).coef # Convert to list and append polynomials.append(poly.tolist()) except ValueError as err: raise TypeError( " <lambda>() missing 1 required positional argument: '" + self.f_x.__code__.co_varnames[0] + "'." + " Constant functions should be specified as 'f_x = constant'." ) from err # If the last breakpoint is < 2 ** num_qubits, add the identity polynomial if breakpoints[-1] < 2**self.num_state_qubits: polynomials = polynomials + [[2 * np.arcsin(1)]] # If the first breakpoint is > 0, add the identity polynomial if breakpoints[0] > 0: polynomials = [[2 * np.arcsin(1)]] + polynomials return polynomials @polynomials.setter def polynomials(self, polynomials: list[list[float]] | None) -> None: """Set the polynomials for the piecewise approximation. Note that this may change the underlying quantum register, if the number of state qubits changes. Args: polynomials: The new breakpoints for the piecewise approximation. """ if self._polynomials is None or polynomials != self._polynomials: self._invalidate() self._polynomials = polynomials self._reset_registers(self.num_state_qubits) @property def num_state_qubits(self) -> int: r"""The number of state qubits representing the state :math:`|x\rangle`. Returns: The number of state qubits. """ return self._num_state_qubits @num_state_qubits.setter def num_state_qubits(self, num_state_qubits: int | None) -> None: """Set the number of state qubits. Note that this may change the underlying quantum register, if the number of state qubits changes. Args: num_state_qubits: The new number of qubits. """ if self._num_state_qubits is None or num_state_qubits != self._num_state_qubits: self._invalidate() self._num_state_qubits = num_state_qubits # Set breakpoints if they haven't been set if num_state_qubits is not None and self._breakpoints is None: self.breakpoints = [0, 2**num_state_qubits] self._reset_registers(num_state_qubits) def _reset_registers(self, num_state_qubits: int | None) -> None: """Reset the registers.""" self.qregs = [] if num_state_qubits is not None: qr_state = QuantumRegister(num_state_qubits, "state") qr_target = QuantumRegister(1, "target") self.qregs = [qr_state, qr_target] num_ancillas = num_state_qubits if num_ancillas > 0: qr_ancilla = AncillaRegister(num_ancillas) self.add_register(qr_ancilla) def _build(self): """Build the circuit if not already build. The operation is considered successful when q_objective is :math:`|1>`""" if self._is_built: return super()._build() poly_r = PiecewisePolynomialPauliRotations( self.num_state_qubits, self.breakpoints, self.polynomials, name=self.name ) # qr_state = self.qubits[: self.num_state_qubits] # qr_target = [self.qubits[self.num_state_qubits]] # qr_ancillas = self.qubits[self.num_state_qubits + 1 :] # Apply polynomial approximation self.append(poly_r.to_gate(), self.qubits)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Piecewise-polynomially-controlled Pauli rotations.""" from __future__ import annotations from typing import List, Optional import numpy as np from qiskit.circuit import QuantumRegister, AncillaRegister, QuantumCircuit from qiskit.circuit.exceptions import CircuitError from .functional_pauli_rotations import FunctionalPauliRotations from .polynomial_pauli_rotations import PolynomialPauliRotations from .integer_comparator import IntegerComparator class PiecewisePolynomialPauliRotations(FunctionalPauliRotations): r"""Piecewise-polynomially-controlled Pauli rotations. This class implements a piecewise polynomial (not necessarily continuous) function, :math:`f(x)`, on qubit amplitudes, which is defined through breakpoints and coefficients as follows. Suppose the breakpoints :math:`(x_0, ..., x_J)` are a subset of :math:`[0, 2^n-1]`, where :math:`n` is the number of state qubits. Further on, denote the corresponding coefficients by :math:`[a_{j,1},...,a_{j,d}]`, where :math:`d` is the highest degree among all polynomials. Then :math:`f(x)` is defined as: .. math:: f(x) = \begin{cases} 0, x < x_0 \\ \sum_{i=0}^{i=d}a_{j,i}/2 x^i, x_j \leq x < x_{j+1} \end{cases} where if given the same number of breakpoints as polynomials, we implicitly assume :math:`x_{J+1} = 2^n`. .. note:: Note the :math:`1/2` factor in the coefficients of :math:`f(x)`, this is consistent with Qiskit's Pauli rotations. Examples: >>> from qiskit import QuantumCircuit >>> from qiskit.circuit.library.arithmetic.piecewise_polynomial_pauli_rotations import\ ... PiecewisePolynomialPauliRotations >>> qubits, breakpoints, coeffs = (2, [0, 2], [[0, -1.2],[-1, 1, 3]]) >>> poly_r = PiecewisePolynomialPauliRotations(num_state_qubits=qubits, ...breakpoints=breakpoints, coeffs=coeffs) >>> >>> qc = QuantumCircuit(poly_r.num_qubits) >>> qc.h(list(range(qubits))); >>> qc.append(poly_r.to_instruction(), list(range(qc.num_qubits))); >>> qc.draw() ┌───┐┌──────────┐ q_0: ┤ H ├┤0 ├ ├───┤│ │ q_1: ┤ H ├┤1 ├ └───┘│ │ q_2: ─────┤2 ├ │ pw_poly │ q_3: ─────┤3 ├ │ │ q_4: ─────┤4 ├ │ │ q_5: ─────┤5 ├ └──────────┘ References: [1]: Haener, T., Roetteler, M., & Svore, K. M. (2018). Optimizing Quantum Circuits for Arithmetic. `arXiv:1805.12445 <http://arxiv.org/abs/1805.12445>`_ [2]: Carrera Vazquez, A., Hiptmair, R., & Woerner, S. (2022). Enhancing the Quantum Linear Systems Algorithm using Richardson Extrapolation. `ACM Transactions on Quantum Computing 3, 1, Article 2 <https://doi.org/10.1145/3490631>`_ """ def __init__( self, num_state_qubits: Optional[int] = None, breakpoints: Optional[List[int]] = None, coeffs: Optional[List[List[float]]] = None, basis: str = "Y", name: str = "pw_poly", ) -> None: """ Args: num_state_qubits: The number of qubits representing the state. breakpoints: The breakpoints to define the piecewise-linear function. Defaults to ``[0]``. coeffs: The coefficients of the polynomials for different segments of the piecewise-linear function. ``coeffs[j][i]`` is the coefficient of the i-th power of x for the j-th polynomial. Defaults to linear: ``[[1]]``. basis: The type of Pauli rotation (``'X'``, ``'Y'``, ``'Z'``). name: The name of the circuit. """ # store parameters self._breakpoints = breakpoints if breakpoints is not None else [0] self._coeffs = coeffs if coeffs is not None else [[1]] # store a list of coefficients as homogeneous polynomials adding 0's where necessary self._hom_coeffs = [] self._degree = len(max(self._coeffs, key=len)) - 1 for poly in self._coeffs: self._hom_coeffs.append(poly + [0] * (self._degree + 1 - len(poly))) super().__init__(num_state_qubits=num_state_qubits, basis=basis, name=name) @property def breakpoints(self) -> List[int]: """The breakpoints of the piecewise polynomial function. The function is polynomial in the intervals ``[point_i, point_{i+1}]`` where the last point implicitly is ``2**(num_state_qubits + 1)``. Returns: The list of breakpoints. """ if ( self.num_state_qubits is not None and len(self._breakpoints) == len(self.coeffs) and self._breakpoints[-1] < 2**self.num_state_qubits ): return self._breakpoints + [2**self.num_state_qubits] return self._breakpoints @breakpoints.setter def breakpoints(self, breakpoints: List[int]) -> None: """Set the breakpoints. Args: breakpoints: The new breakpoints. """ self._invalidate() self._breakpoints = breakpoints if self.num_state_qubits and breakpoints: self._reset_registers(self.num_state_qubits) @property def coeffs(self) -> List[List[float]]: """The coefficients of the polynomials. Returns: The polynomial coefficients per interval as nested lists. """ return self._coeffs @coeffs.setter def coeffs(self, coeffs: List[List[float]]) -> None: """Set the polynomials. Args: coeffs: The new polynomials. """ self._invalidate() self._coeffs = coeffs # update the homogeneous polynomials and degree self._hom_coeffs = [] self._degree = len(max(self._coeffs, key=len)) - 1 for poly in self._coeffs: self._hom_coeffs.append(poly + [0] * (self._degree + 1 - len(poly))) if self.num_state_qubits and coeffs: self._reset_registers(self.num_state_qubits) @property def mapped_coeffs(self) -> List[List[float]]: """The coefficients mapped to the internal representation, since we only compare x>=breakpoint. Returns: The mapped coefficients. """ mapped_coeffs = [] # First polynomial mapped_coeffs.append(self._hom_coeffs[0]) for i in range(1, len(self._hom_coeffs)): mapped_coeffs.append([]) for j in range(0, self._degree + 1): mapped_coeffs[i].append(self._hom_coeffs[i][j] - self._hom_coeffs[i - 1][j]) return mapped_coeffs @property def contains_zero_breakpoint(self) -> bool | np.bool_: """Whether 0 is the first breakpoint. Returns: True, if 0 is the first breakpoint, otherwise False. """ return np.isclose(0, self.breakpoints[0]) def evaluate(self, x: float) -> float: """Classically evaluate the piecewise polynomial rotation. Args: x: Value to be evaluated at. Returns: Value of piecewise polynomial function at x. """ y = 0 for i in range(0, len(self.breakpoints)): y = y + (x >= self.breakpoints[i]) * (np.poly1d(self.mapped_coeffs[i][::-1])(x)) return y def _check_configuration(self, raise_on_failure: bool = True) -> bool: """Check if the current configuration is valid.""" valid = True if self.num_state_qubits is None: valid = False if raise_on_failure: raise AttributeError("The number of qubits has not been set.") if self.num_qubits < self.num_state_qubits + 1: valid = False if raise_on_failure: raise CircuitError( "Not enough qubits in the circuit, need at least " "{}.".format(self.num_state_qubits + 1) ) if len(self.breakpoints) != len(self.coeffs) + 1: valid = False if raise_on_failure: raise ValueError("Mismatching number of breakpoints and polynomials.") return valid def _reset_registers(self, num_state_qubits: Optional[int]) -> None: """Reset the registers.""" self.qregs = [] if num_state_qubits: qr_state = QuantumRegister(num_state_qubits) qr_target = QuantumRegister(1) self.qregs = [qr_state, qr_target] # Calculate number of ancilla qubits required num_ancillas = num_state_qubits + 1 if self.contains_zero_breakpoint: num_ancillas -= 1 if num_ancillas > 0: qr_ancilla = AncillaRegister(num_ancillas) self.add_register(qr_ancilla) def _build(self): """If not already built, build the circuit.""" if self._is_built: return super()._build() circuit = QuantumCircuit(*self.qregs, name=self.name) qr_state = circuit.qubits[: self.num_state_qubits] qr_target = [circuit.qubits[self.num_state_qubits]] # Ancilla for the comparator circuit qr_ancilla = circuit.qubits[self.num_state_qubits + 1 :] # apply comparators and controlled linear rotations for i, point in enumerate(self.breakpoints[:-1]): if i == 0 and self.contains_zero_breakpoint: # apply rotation poly_r = PolynomialPauliRotations( num_state_qubits=self.num_state_qubits, coeffs=self.mapped_coeffs[i], basis=self.basis, ) circuit.append(poly_r.to_gate(), qr_state[:] + qr_target) else: # apply Comparator comp = IntegerComparator(num_state_qubits=self.num_state_qubits, value=point) qr_state_full = qr_state[:] + [qr_ancilla[0]] # add compare qubit qr_remaining_ancilla = qr_ancilla[1:] # take remaining ancillas circuit.append( comp.to_gate(), qr_state_full[:] + qr_remaining_ancilla[: comp.num_ancillas] ) # apply controlled rotation poly_r = PolynomialPauliRotations( num_state_qubits=self.num_state_qubits, coeffs=self.mapped_coeffs[i], basis=self.basis, ) circuit.append( poly_r.to_gate().control(), [qr_ancilla[0]] + qr_state[:] + qr_target ) # uncompute comparator circuit.append( comp.to_gate().inverse(), qr_state_full[:] + qr_remaining_ancilla[: comp.num_ancillas], ) self.append(circuit.to_gate(), self.qubits)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Multiple-Control, Multiple-Target Gate.""" from __future__ import annotations from collections.abc import Callable from qiskit import circuit from qiskit.circuit import ControlledGate, Gate, Qubit, QuantumRegister, QuantumCircuit from qiskit.exceptions import QiskitError from ..standard_gates import XGate, YGate, ZGate, HGate, TGate, TdgGate, SGate, SdgGate class MCMT(QuantumCircuit): """The multi-controlled multi-target gate, for an arbitrary singly controlled target gate. For example, the H gate controlled on 3 qubits and acting on 2 target qubit is represented as: .. parsed-literal:: ───■──── │ ───■──── │ ───■──── ┌──┴───┐ ┤0 ├ │ 2-H │ ┤1 ├ └──────┘ This default implementations requires no ancilla qubits, by broadcasting the target gate to the number of target qubits and using Qiskit's generic control routine to control the broadcasted target on the control qubits. If ancilla qubits are available, a more efficient variant using the so-called V-chain decomposition can be used. This is implemented in :class:`~qiskit.circuit.library.MCMTVChain`. """ def __init__( self, gate: Gate | Callable[[QuantumCircuit, Qubit, Qubit], circuit.Instruction], num_ctrl_qubits: int, num_target_qubits: int, ) -> None: """Create a new multi-control multi-target gate. Args: gate: The gate to be applied controlled on the control qubits and applied to the target qubits. Can be either a Gate or a circuit method. If it is a callable, it will be casted to a Gate. num_ctrl_qubits: The number of control qubits. num_target_qubits: The number of target qubits. Raises: AttributeError: If the gate cannot be casted to a controlled gate. AttributeError: If the number of controls or targets is 0. """ if num_ctrl_qubits == 0 or num_target_qubits == 0: raise AttributeError("Need at least one control and one target qubit.") # set the internal properties and determine the number of qubits self.gate = self._identify_gate(gate) self.num_ctrl_qubits = num_ctrl_qubits self.num_target_qubits = num_target_qubits num_qubits = num_ctrl_qubits + num_target_qubits + self.num_ancilla_qubits # initialize the circuit object super().__init__(num_qubits, name="mcmt") self._label = f"{num_target_qubits}-{self.gate.name.capitalize()}" # build the circuit self._build() def _build(self): """Define the MCMT gate without ancillas.""" if self.num_target_qubits == 1: # no broadcasting needed (makes for better circuit diagrams) broadcasted_gate = self.gate else: broadcasted = QuantumCircuit(self.num_target_qubits, name=self._label) for target in list(range(self.num_target_qubits)): broadcasted.append(self.gate, [target], []) broadcasted_gate = broadcasted.to_gate() mcmt_gate = broadcasted_gate.control(self.num_ctrl_qubits) self.append(mcmt_gate, self.qubits, []) @property def num_ancilla_qubits(self): """Return the number of ancillas.""" return 0 def _identify_gate(self, gate): """Case the gate input to a gate.""" valid_gates = { "ch": HGate(), "cx": XGate(), "cy": YGate(), "cz": ZGate(), "h": HGate(), "s": SGate(), "sdg": SdgGate(), "x": XGate(), "y": YGate(), "z": ZGate(), "t": TGate(), "tdg": TdgGate(), } if isinstance(gate, ControlledGate): base_gate = gate.base_gate elif isinstance(gate, Gate): if gate.num_qubits != 1: raise AttributeError("Base gate must act on one qubit only.") base_gate = gate elif isinstance(gate, QuantumCircuit): if gate.num_qubits != 1: raise AttributeError( "The circuit you specified as control gate can only have one qubit!" ) base_gate = gate.to_gate() # raises error if circuit contains non-unitary instructions else: if callable(gate): # identify via name of the passed function name = gate.__name__ elif isinstance(gate, str): name = gate else: raise AttributeError(f"Invalid gate specified: {gate}") base_gate = valid_gates[name] return base_gate def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return the controlled version of the MCMT circuit.""" if ctrl_state is None: # TODO add ctrl state implementation by adding X gates return MCMT(self.gate, self.num_ctrl_qubits + num_ctrl_qubits, self.num_target_qubits) return super().control(num_ctrl_qubits, label, ctrl_state) def inverse(self): """Return the inverse MCMT circuit, which is itself.""" return MCMT(self.gate, self.num_ctrl_qubits, self.num_target_qubits) class MCMTVChain(MCMT): """The MCMT implementation using the CCX V-chain. This implementation requires ancillas but is decomposed into a much shallower circuit than the default implementation in :class:`~qiskit.circuit.library.MCMT`. **Expanded Circuit:** .. plot:: from qiskit.circuit.library import MCMTVChain, ZGate from qiskit.tools.jupyter.library import _generate_circuit_library_visualization circuit = MCMTVChain(ZGate(), 2, 2) _generate_circuit_library_visualization(circuit.decompose()) **Examples:** >>> from qiskit.circuit.library import HGate >>> MCMTVChain(HGate(), 3, 2).draw() q_0: ──■────────────────────────■── │ │ q_1: ──■────────────────────────■── │ │ q_2: ──┼────■──────────────■────┼── │ │ ┌───┐ │ │ q_3: ──┼────┼──┤ H ├───────┼────┼── │ │ └─┬─┘┌───┐ │ │ q_4: ──┼────┼────┼──┤ H ├──┼────┼── ┌─┴─┐ │ │ └─┬─┘ │ ┌─┴─┐ q_5: ┤ X ├──■────┼────┼────■──┤ X ├ └───┘┌─┴─┐ │ │ ┌─┴─┐└───┘ q_6: ─────┤ X ├──■────■──┤ X ├───── └───┘ └───┘ """ def _build(self): """Define the MCMT gate.""" control_qubits = self.qubits[: self.num_ctrl_qubits] target_qubits = self.qubits[ self.num_ctrl_qubits : self.num_ctrl_qubits + self.num_target_qubits ] ancilla_qubits = self.qubits[self.num_ctrl_qubits + self.num_target_qubits :] if len(ancilla_qubits) > 0: master_control = ancilla_qubits[-1] else: master_control = control_qubits[0] self._ccx_v_chain_rule(control_qubits, ancilla_qubits, reverse=False) for qubit in target_qubits: self.append(self.gate.control(), [master_control, qubit], []) self._ccx_v_chain_rule(control_qubits, ancilla_qubits, reverse=True) @property def num_ancilla_qubits(self): """Return the number of ancilla qubits required.""" return max(0, self.num_ctrl_qubits - 1) def _ccx_v_chain_rule( self, control_qubits: QuantumRegister | list[Qubit], ancilla_qubits: QuantumRegister | list[Qubit], reverse: bool = False, ) -> None: """Get the rule for the CCX V-chain. The CCX V-chain progressively computes the CCX of the control qubits and puts the final result in the last ancillary qubit. Args: control_qubits: The control qubits. ancilla_qubits: The ancilla qubits. reverse: If True, compute the chain down to the qubit. If False, compute upwards. Returns: The rule for the (reversed) CCX V-chain. Raises: QiskitError: If an insufficient number of ancilla qubits was provided. """ if len(ancilla_qubits) == 0: return if len(ancilla_qubits) < len(control_qubits) - 1: raise QiskitError("Insufficient number of ancilla qubits.") iterations = list(enumerate(range(2, len(control_qubits)))) if not reverse: self.ccx(control_qubits[0], control_qubits[1], ancilla_qubits[0]) for i, j in iterations: self.ccx(control_qubits[j], ancilla_qubits[i], ancilla_qubits[i + 1]) else: for i, j in reversed(iterations): self.ccx(control_qubits[j], ancilla_qubits[i], ancilla_qubits[i + 1]) self.ccx(control_qubits[0], control_qubits[1], ancilla_qubits[0]) def inverse(self): return MCMTVChain(self.gate, self.num_ctrl_qubits, self.num_target_qubits)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Arbitrary unitary circuit instruction. """ import numpy from qiskit.circuit import Gate, ControlledGate from qiskit.circuit import QuantumCircuit from qiskit.circuit import QuantumRegister, Qubit from qiskit.circuit.exceptions import CircuitError from qiskit.circuit._utils import _compute_control_matrix from qiskit.circuit.library.standard_gates import UGate from qiskit.extensions.quantum_initializer import isometry from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.quantum_info.operators.predicates import is_unitary_matrix from qiskit.quantum_info.synthesis.one_qubit_decompose import OneQubitEulerDecomposer from qiskit.quantum_info.synthesis.two_qubit_decompose import two_qubit_cnot_decompose from qiskit.extensions.exceptions import ExtensionError _DECOMPOSER1Q = OneQubitEulerDecomposer("U") class UnitaryGate(Gate): """Class quantum gates specified by a unitary matrix. Example: We can create a unitary gate from a unitary matrix then add it to a quantum circuit. The matrix can also be directly applied to the quantum circuit, see :meth:`.QuantumCircuit.unitary`. .. code-block:: python from qiskit import QuantumCircuit from qiskit.extensions import UnitaryGate matrix = [[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]] gate = UnitaryGate(matrix) circuit = QuantumCircuit(2) circuit.append(gate, [0, 1]) """ def __init__(self, data, label=None): """Create a gate from a numeric unitary matrix. Args: data (matrix or Operator): unitary operator. label (str): unitary name for backend [Default: None]. Raises: ExtensionError: if input data is not an N-qubit unitary operator. """ if hasattr(data, "to_matrix"): # If input is Gate subclass or some other class object that has # a to_matrix method this will call that method. data = data.to_matrix() elif hasattr(data, "to_operator"): # If input is a BaseOperator subclass this attempts to convert # the object to an Operator so that we can extract the underlying # numpy matrix from `Operator.data`. data = data.to_operator().data # Convert to numpy array in case not already an array data = numpy.array(data, dtype=complex) # Check input is unitary if not is_unitary_matrix(data): raise ExtensionError("Input matrix is not unitary.") # Check input is N-qubit matrix input_dim, output_dim = data.shape num_qubits = int(numpy.log2(input_dim)) if input_dim != output_dim or 2**num_qubits != input_dim: raise ExtensionError("Input matrix is not an N-qubit operator.") # Store instruction params super().__init__("unitary", num_qubits, [data], label=label) def __eq__(self, other): if not isinstance(other, UnitaryGate): return False if self.label != other.label: return False # Should we match unitaries as equal if they are equal # up to global phase? return matrix_equal(self.params[0], other.params[0], ignore_phase=True) def __array__(self, dtype=None): """Return matrix for the unitary.""" # pylint: disable=unused-argument return self.params[0] def inverse(self): """Return the adjoint of the unitary.""" return self.adjoint() def conjugate(self): """Return the conjugate of the unitary.""" return UnitaryGate(numpy.conj(self.to_matrix())) def adjoint(self): """Return the adjoint of the unitary.""" return self.transpose().conjugate() def transpose(self): """Return the transpose of the unitary.""" return UnitaryGate(numpy.transpose(self.to_matrix())) def _define(self): """Calculate a subcircuit that implements this unitary.""" if self.num_qubits == 1: q = QuantumRegister(1, "q") qc = QuantumCircuit(q, name=self.name) theta, phi, lam, global_phase = _DECOMPOSER1Q.angles_and_phase(self.to_matrix()) qc._append(UGate(theta, phi, lam), [q[0]], []) qc.global_phase = global_phase self.definition = qc elif self.num_qubits == 2: self.definition = two_qubit_cnot_decompose(self.to_matrix()) else: from qiskit.quantum_info.synthesis.qsd import ( # pylint: disable=cyclic-import qs_decomposition, ) self.definition = qs_decomposition(self.to_matrix()) def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return controlled version of gate Args: num_ctrl_qubits (int): number of controls to add to gate (default=1) label (str): optional gate label ctrl_state (int or str or None): The control state in decimal or as a bit string (e.g. '1011'). If None, use 2**num_ctrl_qubits-1. Returns: UnitaryGate: controlled version of gate. Raises: QiskitError: Invalid ctrl_state. ExtensionError: Non-unitary controlled unitary. """ mat = self.to_matrix() cmat = _compute_control_matrix(mat, num_ctrl_qubits, ctrl_state=None) iso = isometry.Isometry(cmat, 0, 0) return ControlledGate( "c-unitary", num_qubits=self.num_qubits + num_ctrl_qubits, params=[mat], label=label, num_ctrl_qubits=num_ctrl_qubits, definition=iso.definition, ctrl_state=ctrl_state, base_gate=self.copy(), ) def _qasm2_decomposition(self): """Return an unparameterized version of ourselves, so the OQ2 exporter doesn't choke on the non-standard things in our `params` field.""" out = self.definition.to_gate() out.name = self.name return out def validate_parameter(self, parameter): """Unitary gate parameter has to be an ndarray.""" if isinstance(parameter, numpy.ndarray): return parameter else: raise CircuitError(f"invalid param type {type(parameter)} in gate {self.name}") def unitary(self, obj, qubits, label=None): """Apply unitary gate specified by ``obj`` to ``qubits``. Args: obj (matrix or Operator): unitary operator. qubits (Union[int, Tuple[int]]): The circuit qubits to apply the transformation to. label (str): unitary name for backend [Default: None]. Returns: QuantumCircuit: The quantum circuit. Raises: ExtensionError: if input data is not an N-qubit unitary operator. Example: Apply a gate specified by a unitary matrix to a quantum circuit .. code-block:: python from qiskit import QuantumCircuit matrix = [[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]] circuit = QuantumCircuit(2) circuit.unitary(matrix, [0, 1]) """ gate = UnitaryGate(obj, label=label) if isinstance(qubits, QuantumRegister): qubits = qubits[:] # for single qubit unitary gate, allow an 'int' or a 'list of ints' as qubits. if gate.num_qubits == 1: if isinstance(qubits, (int, Qubit)) or len(qubits) > 1: qubits = [qubits] return self.append(gate, qubits, []) QuantumCircuit.unitary = unitary
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The EfficientSU2 2-local circuit.""" from __future__ import annotations import typing from collections.abc import Callable from numpy import pi from qiskit.circuit import QuantumCircuit from qiskit.circuit.library.standard_gates import RYGate, RZGate, CXGate from .two_local import TwoLocal if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import class EfficientSU2(TwoLocal): r"""The hardware efficient SU(2) 2-local circuit. The ``EfficientSU2`` circuit consists of layers of single qubit operations spanned by SU(2) and :math:`CX` entanglements. This is a heuristic pattern that can be used to prepare trial wave functions for variational quantum algorithms or classification circuit for machine learning. SU(2) stands for special unitary group of degree 2, its elements are :math:`2 \times 2` unitary matrices with determinant 1, such as the Pauli rotation gates. On 3 qubits and using the Pauli :math:`Y` and :math:`Z` su2_gates as single qubit gates, the hardware efficient SU(2) circuit is represented by: .. parsed-literal:: ┌──────────┐┌──────────┐ ░ ░ ░ ┌───────────┐┌───────────┐ ┤ RY(θ[0]) ├┤ RZ(θ[3]) ├─░────────■───░─ ... ─░─┤ RY(θ[12]) ├┤ RZ(θ[15]) ├ ├──────────┤├──────────┤ ░ ┌─┴─┐ ░ ░ ├───────────┤├───────────┤ ┤ RY(θ[1]) ├┤ RZ(θ[4]) ├─░───■──┤ X ├─░─ ... ─░─┤ RY(θ[13]) ├┤ RZ(θ[16]) ├ ├──────────┤├──────────┤ ░ ┌─┴─┐└───┘ ░ ░ ├───────────┤├───────────┤ ┤ RY(θ[2]) ├┤ RZ(θ[5]) ├─░─┤ X ├──────░─ ... ─░─┤ RY(θ[14]) ├┤ RZ(θ[17]) ├ └──────────┘└──────────┘ ░ └───┘ ░ ░ └───────────┘└───────────┘ See :class:`~qiskit.circuit.library.RealAmplitudes` for more detail on the possible arguments and options such as skipping unentanglement qubits, which apply here too. Examples: >>> circuit = EfficientSU2(3, reps=1) >>> print(circuit) ┌──────────┐┌──────────┐ ┌──────────┐┌──────────┐ q_0: ┤ RY(θ[0]) ├┤ RZ(θ[3]) ├──■────■──┤ RY(θ[6]) ├┤ RZ(θ[9]) ├───────────── ├──────────┤├──────────┤┌─┴─┐ │ └──────────┘├──────────┤┌───────────┐ q_1: ┤ RY(θ[1]) ├┤ RZ(θ[4]) ├┤ X ├──┼───────■──────┤ RY(θ[7]) ├┤ RZ(θ[10]) ├ ├──────────┤├──────────┤└───┘┌─┴─┐ ┌─┴─┐ ├──────────┤├───────────┤ q_2: ┤ RY(θ[2]) ├┤ RZ(θ[5]) ├─────┤ X ├───┤ X ├────┤ RY(θ[8]) ├┤ RZ(θ[11]) ├ └──────────┘└──────────┘ └───┘ └───┘ └──────────┘└───────────┘ >>> ansatz = EfficientSU2(4, su2_gates=['rx', 'y'], entanglement='circular', reps=1) >>> qc = QuantumCircuit(4) # create a circuit and append the RY variational form >>> qc.compose(ansatz, inplace=True) >>> qc.draw() ┌──────────┐┌───┐┌───┐ ┌──────────┐ ┌───┐ q_0: ┤ RX(θ[0]) ├┤ Y ├┤ X ├──■──┤ RX(θ[4]) ├───┤ Y ├───────────────────── ├──────────┤├───┤└─┬─┘┌─┴─┐└──────────┘┌──┴───┴───┐ ┌───┐ q_1: ┤ RX(θ[1]) ├┤ Y ├──┼──┤ X ├─────■──────┤ RX(θ[5]) ├───┤ Y ├───────── ├──────────┤├───┤ │ └───┘ ┌─┴─┐ └──────────┘┌──┴───┴───┐┌───┐ q_2: ┤ RX(θ[2]) ├┤ Y ├──┼──────────┤ X ├─────────■──────┤ RX(θ[6]) ├┤ Y ├ ├──────────┤├───┤ │ └───┘ ┌─┴─┐ ├──────────┤├───┤ q_3: ┤ RX(θ[3]) ├┤ Y ├──■──────────────────────┤ X ├────┤ RX(θ[7]) ├┤ Y ├ └──────────┘└───┘ └───┘ └──────────┘└───┘ """ def __init__( self, num_qubits: int | None = None, su2_gates: str | type | qiskit.circuit.Instruction | QuantumCircuit | list[str | type | qiskit.circuit.Instruction | QuantumCircuit] | None = None, entanglement: str | list[list[int]] | Callable[[int], list[int]] = "reverse_linear", reps: int = 3, skip_unentangled_qubits: bool = False, skip_final_rotation_layer: bool = False, parameter_prefix: str = "θ", insert_barriers: bool = False, initial_state: QuantumCircuit | None = None, name: str = "EfficientSU2", flatten: bool | None = None, ) -> None: """ Args: num_qubits: The number of qubits of the EfficientSU2 circuit. reps: Specifies how often the structure of a rotation layer followed by an entanglement layer is repeated. su2_gates: The SU(2) single qubit gates to apply in single qubit gate layers. If only one gate is provided, the same gate is applied to each qubit. If a list of gates is provided, all gates are applied to each qubit in the provided order. entanglement: Specifies the entanglement structure. Can be a string ('full', 'linear' , 'reverse_linear', 'circular' or 'sca'), a list of integer-pairs specifying the indices of qubits entangled with one another, or a callable returning such a list provided with the index of the entanglement layer. Default to 'reverse_linear' entanglement. Note that 'reverse_linear' entanglement provides the same unitary as 'full' with fewer entangling gates. See the Examples section of :class:`~qiskit.circuit.library.TwoLocal` for more detail. initial_state: A `QuantumCircuit` object to prepend to the circuit. skip_unentangled_qubits: If True, the single qubit gates are only applied to qubits that are entangled with another qubit. If False, the single qubit gates are applied to each qubit in the Ansatz. Defaults to False. skip_final_rotation_layer: If False, a rotation layer is added at the end of the ansatz. If True, no rotation layer is added. parameter_prefix: The parameterized gates require a parameter to be defined, for which we use :class:`~qiskit.circuit.ParameterVector`. insert_barriers: If True, barriers are inserted in between each layer. If False, no barriers are inserted. flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you're using this circuit for anything besides visualization its **strongly** recommended to set this flag to ``True`` to avoid a large performance overhead for parameter binding. """ if su2_gates is None: su2_gates = [RYGate, RZGate] super().__init__( num_qubits=num_qubits, rotation_blocks=su2_gates, entanglement_blocks=CXGate, entanglement=entanglement, reps=reps, skip_unentangled_qubits=skip_unentangled_qubits, skip_final_rotation_layer=skip_final_rotation_layer, parameter_prefix=parameter_prefix, insert_barriers=insert_barriers, initial_state=initial_state, name=name, flatten=flatten, ) @property def parameter_bounds(self) -> list[tuple[float, float]]: """Return the parameter bounds. Returns: The parameter bounds. """ return self.num_parameters * [(-pi, pi)]
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The n-local circuit class.""" from __future__ import annotations import typing from collections.abc import Callable, Mapping, Sequence from itertools import combinations import numpy from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister from qiskit.circuit import Instruction, Parameter, ParameterVector, ParameterExpression from qiskit.exceptions import QiskitError from ..blueprintcircuit import BlueprintCircuit if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import class NLocal(BlueprintCircuit): """The n-local circuit class. The structure of the n-local circuit are alternating rotation and entanglement layers. In both layers, parameterized circuit-blocks act on the circuit in a defined way. In the rotation layer, the blocks are applied stacked on top of each other, while in the entanglement layer according to the ``entanglement`` strategy. The circuit blocks can have arbitrary sizes (smaller equal to the number of qubits in the circuit). Each layer is repeated ``reps`` times, and by default a final rotation layer is appended. For instance, a rotation block on 2 qubits and an entanglement block on 4 qubits using ``'linear'`` entanglement yields the following circuit. .. parsed-literal:: ┌──────┐ ░ ┌──────┐ ░ ┌──────┐ ┤0 ├─░─┤0 ├──────────────── ... ─░─┤0 ├ │ Rot │ ░ │ │┌──────┐ ░ │ Rot │ ┤1 ├─░─┤1 ├┤0 ├──────── ... ─░─┤1 ├ ├──────┤ ░ │ Ent ││ │┌──────┐ ░ ├──────┤ ┤0 ├─░─┤2 ├┤1 ├┤0 ├ ... ─░─┤0 ├ │ Rot │ ░ │ ││ Ent ││ │ ░ │ Rot │ ┤1 ├─░─┤3 ├┤2 ├┤1 ├ ... ─░─┤1 ├ ├──────┤ ░ └──────┘│ ││ Ent │ ░ ├──────┤ ┤0 ├─░─────────┤3 ├┤2 ├ ... ─░─┤0 ├ │ Rot │ ░ └──────┘│ │ ░ │ Rot │ ┤1 ├─░─────────────────┤3 ├ ... ─░─┤1 ├ └──────┘ ░ └──────┘ ░ └──────┘ | | +---------------------------------+ repeated reps times If specified, barriers can be inserted in between every block. If an initial state object is provided, it is added in front of the NLocal. """ def __init__( self, num_qubits: int | None = None, rotation_blocks: QuantumCircuit | list[QuantumCircuit] | qiskit.circuit.Instruction | list[qiskit.circuit.Instruction] | None = None, entanglement_blocks: QuantumCircuit | list[QuantumCircuit] | qiskit.circuit.Instruction | list[qiskit.circuit.Instruction] | None = None, entanglement: list[int] | list[list[int]] | None = None, reps: int = 1, insert_barriers: bool = False, parameter_prefix: str = "θ", overwrite_block_parameters: bool | list[list[Parameter]] = True, skip_final_rotation_layer: bool = False, skip_unentangled_qubits: bool = False, initial_state: QuantumCircuit | None = None, name: str | None = "nlocal", flatten: bool | None = None, ) -> None: """ Args: num_qubits: The number of qubits of the circuit. rotation_blocks: The blocks used in the rotation layers. If multiple are passed, these will be applied one after another (like new sub-layers). entanglement_blocks: The blocks used in the entanglement layers. If multiple are passed, these will be applied one after another. To use different entanglements for the sub-layers, see :meth:`get_entangler_map`. entanglement: The indices specifying on which qubits the input blocks act. If ``None``, the entanglement blocks are applied at the top of the circuit. reps: Specifies how often the rotation blocks and entanglement blocks are repeated. insert_barriers: If ``True``, barriers are inserted in between each layer. If ``False``, no barriers are inserted. parameter_prefix: The prefix used if default parameters are generated. overwrite_block_parameters: If the parameters in the added blocks should be overwritten. If ``False``, the parameters in the blocks are not changed. skip_final_rotation_layer: Whether a final rotation layer is added to the circuit. skip_unentangled_qubits: If ``True``, the rotation gates act only on qubits that are entangled. If ``False``, the rotation gates act on all qubits. initial_state: A :class:`.QuantumCircuit` object which can be used to describe an initial state prepended to the NLocal circuit. name: The name of the circuit. flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you're using this circuit for anything besides visualization its **strongly** recommended to set this flag to ``True`` to avoid a large performance overhead for parameter binding. Raises: ValueError: If ``reps`` parameter is less than or equal to 0. TypeError: If ``reps`` parameter is not an int value. """ super().__init__(name=name) self._num_qubits: int | None = None self._insert_barriers = insert_barriers self._reps = reps self._entanglement_blocks: list[QuantumCircuit] = [] self._rotation_blocks: list[QuantumCircuit] = [] self._prepended_blocks: list[QuantumCircuit] = [] self._prepended_entanglement: list[list[list[int]] | str] = [] self._appended_blocks: list[QuantumCircuit] = [] self._appended_entanglement: list[list[list[int]] | str] = [] self._entanglement = None self._entangler_maps = None self._ordered_parameters: ParameterVector | list[Parameter] = ParameterVector( name=parameter_prefix ) self._overwrite_block_parameters = overwrite_block_parameters self._skip_final_rotation_layer = skip_final_rotation_layer self._skip_unentangled_qubits = skip_unentangled_qubits self._initial_state: QuantumCircuit | None = None self._initial_state_circuit: QuantumCircuit | None = None self._bounds: list[tuple[float | None, float | None]] | None = None self._flatten = flatten if int(reps) != reps: raise TypeError("The value of reps should be int") if reps < 0: raise ValueError("The value of reps should be larger than or equal to 0") if num_qubits is not None: self.num_qubits = num_qubits if entanglement_blocks is not None: self.entanglement_blocks = entanglement_blocks if rotation_blocks is not None: self.rotation_blocks = rotation_blocks if entanglement is not None: self.entanglement = entanglement if initial_state is not None: self.initial_state = initial_state @property def num_qubits(self) -> int: """Returns the number of qubits in this circuit. Returns: The number of qubits. """ return self._num_qubits if self._num_qubits is not None else 0 @num_qubits.setter def num_qubits(self, num_qubits: int) -> None: """Set the number of qubits for the n-local circuit. Args: The new number of qubits. """ if self._num_qubits != num_qubits: # invalidate the circuit self._invalidate() self._num_qubits = num_qubits self.qregs = [QuantumRegister(num_qubits, name="q")] @property def flatten(self) -> bool: """Returns whether the circuit is wrapped in nested gates/instructions or flattened.""" return bool(self._flatten) @flatten.setter def flatten(self, flatten: bool) -> None: self._invalidate() self._flatten = flatten def _convert_to_block(self, layer: typing.Any) -> QuantumCircuit: """Try to convert ``layer`` to a QuantumCircuit. Args: layer: The object to be converted to an NLocal block / Instruction. Returns: The layer converted to a circuit. Raises: TypeError: If the input cannot be converted to a circuit. """ if isinstance(layer, QuantumCircuit): return layer if isinstance(layer, Instruction): circuit = QuantumCircuit(layer.num_qubits) circuit.append(layer, list(range(layer.num_qubits))) return circuit try: circuit = QuantumCircuit(layer.num_qubits) circuit.append(layer.to_instruction(), list(range(layer.num_qubits))) return circuit except AttributeError: pass raise TypeError(f"Adding a {type(layer)} to an NLocal is not supported.") @property def rotation_blocks(self) -> list[QuantumCircuit]: """The blocks in the rotation layers. Returns: The blocks in the rotation layers. """ return self._rotation_blocks @rotation_blocks.setter def rotation_blocks( self, blocks: QuantumCircuit | list[QuantumCircuit] | Instruction | list[Instruction] ) -> None: """Set the blocks in the rotation layers. Args: blocks: The new blocks for the rotation layers. """ # cannot check for the attribute ``'__len__'`` because a circuit also has this attribute if not isinstance(blocks, (list, numpy.ndarray)): blocks = [blocks] self._invalidate() self._rotation_blocks = [self._convert_to_block(block) for block in blocks] @property def entanglement_blocks(self) -> list[QuantumCircuit]: """The blocks in the entanglement layers. Returns: The blocks in the entanglement layers. """ return self._entanglement_blocks @entanglement_blocks.setter def entanglement_blocks( self, blocks: QuantumCircuit | list[QuantumCircuit] | Instruction | list[Instruction] ) -> None: """Set the blocks in the entanglement layers. Args: blocks: The new blocks for the entanglement layers. """ # cannot check for the attribute ``'__len__'`` because a circuit also has this attribute if not isinstance(blocks, (list, numpy.ndarray)): blocks = [blocks] self._invalidate() self._entanglement_blocks = [self._convert_to_block(block) for block in blocks] @property def entanglement( self, ) -> str | list[str] | list[list[str]] | list[int] | list[list[int]] | list[ list[list[int]] ] | list[list[list[list[int]]]] | Callable[[int], str] | Callable[[int], list[list[int]]]: """Get the entanglement strategy. Returns: The entanglement strategy, see :meth:`get_entangler_map` for more detail on how the format is interpreted. """ return self._entanglement @entanglement.setter def entanglement( self, entanglement: str | list[str] | list[list[str]] | list[int] | list[list[int]] | list[list[list[int]]] | list[list[list[list[int]]]] | Callable[[int], str] | Callable[[int], list[list[int]]] | None, ) -> None: """Set the entanglement strategy. Args: entanglement: The entanglement strategy. See :meth:`get_entangler_map` for more detail on the supported formats. """ self._invalidate() self._entanglement = entanglement @property def num_layers(self) -> int: """Return the number of layers in the n-local circuit. Returns: The number of layers in the circuit. """ return 2 * self._reps + int(not self._skip_final_rotation_layer) def _check_configuration(self, raise_on_failure: bool = True) -> bool: """Check if the configuration of the NLocal class is valid. Args: raise_on_failure: Whether to raise on failure. Returns: True, if the configuration is valid and the circuit can be constructed. Otherwise an ValueError is raised. Raises: ValueError: If the blocks are not set. ValueError: If the number of repetitions is not set. ValueError: If the qubit indices are not set. ValueError: If the number of qubit indices does not match the number of blocks. ValueError: If an index in the repetitions list exceeds the number of blocks. ValueError: If the number of repetitions does not match the number of block-wise parameters. ValueError: If a specified qubit index is larger than the (manually set) number of qubits. """ valid = True if self.num_qubits is None: valid = False if raise_on_failure: raise ValueError("No number of qubits specified.") # check no needed parameters are None if self.entanglement_blocks is None and self.rotation_blocks is None: valid = False if raise_on_failure: raise ValueError("The blocks are not set.") return valid @property def ordered_parameters(self) -> list[Parameter]: """The parameters used in the underlying circuit. This includes float values and duplicates. Examples: >>> # prepare circuit ... >>> print(nlocal) ┌───────┐┌──────────┐┌──────────┐┌──────────┐ q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├ └───────┘└──────────┘└──────────┘└──────────┘ >>> nlocal.parameters {Parameter(θ[1]), Parameter(θ[3])} >>> nlocal.ordered_parameters [1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])] Returns: The parameters objects used in the circuit. """ if isinstance(self._ordered_parameters, ParameterVector): self._ordered_parameters.resize(self.num_parameters_settable) return list(self._ordered_parameters) return self._ordered_parameters @ordered_parameters.setter def ordered_parameters(self, parameters: ParameterVector | list[Parameter]) -> None: """Set the parameters used in the underlying circuit. Args: The parameters to be used in the underlying circuit. Raises: ValueError: If the length of ordered parameters does not match the number of parameters in the circuit and they are not a ``ParameterVector`` (which could be resized to fit the number of parameters). """ if ( not isinstance(parameters, ParameterVector) and len(parameters) != self.num_parameters_settable ): raise ValueError( "The length of ordered parameters must be equal to the number of " "settable parameters in the circuit ({}), but is {}".format( self.num_parameters_settable, len(parameters) ) ) self._ordered_parameters = parameters self._invalidate() @property def insert_barriers(self) -> bool: """If barriers are inserted in between the layers or not. Returns: ``True``, if barriers are inserted in between the layers, ``False`` if not. """ return self._insert_barriers @insert_barriers.setter def insert_barriers(self, insert_barriers: bool) -> None: """Specify whether barriers should be inserted in between the layers or not. Args: insert_barriers: If True, barriers are inserted, if False not. """ # if insert_barriers changes, we have to invalidate the circuit definition, # if it is the same as before we can leave the NLocal instance as it is if insert_barriers is not self._insert_barriers: self._invalidate() self._insert_barriers = insert_barriers def get_unentangled_qubits(self) -> set[int]: """Get the indices of unentangled qubits in a set. Returns: The unentangled qubits. """ entangled_qubits = set() for i in range(self._reps): for j, block in enumerate(self.entanglement_blocks): entangler_map = self.get_entangler_map(i, j, block.num_qubits) entangled_qubits.update([idx for indices in entangler_map for idx in indices]) unentangled_qubits = set(range(self.num_qubits)) - entangled_qubits return unentangled_qubits @property def num_parameters_settable(self) -> int: """The number of total parameters that can be set to distinct values. This does not change when the parameters are bound or exchanged for same parameters, and therefore is different from ``num_parameters`` which counts the number of unique :class:`~qiskit.circuit.Parameter` objects currently in the circuit. Returns: The number of parameters originally available in the circuit. Note: This quantity does not require the circuit to be built yet. """ num = 0 for i in range(self._reps): for j, block in enumerate(self.entanglement_blocks): entangler_map = self.get_entangler_map(i, j, block.num_qubits) num += len(entangler_map) * len(get_parameters(block)) if self._skip_unentangled_qubits: unentangled_qubits = self.get_unentangled_qubits() num_rot = 0 for block in self.rotation_blocks: block_indices = [ list(range(j * block.num_qubits, (j + 1) * block.num_qubits)) for j in range(self.num_qubits // block.num_qubits) ] if self._skip_unentangled_qubits: block_indices = [ indices for indices in block_indices if set(indices).isdisjoint(unentangled_qubits) ] num_rot += len(block_indices) * len(get_parameters(block)) num += num_rot * (self._reps + int(not self._skip_final_rotation_layer)) return num @property def reps(self) -> int: """The number of times rotation and entanglement block are repeated. Returns: The number of repetitions. """ return self._reps @reps.setter def reps(self, repetitions: int) -> None: """Set the repetitions. If the repetitions are `0`, only one rotation layer with no entanglement layers is applied (unless ``self.skip_final_rotation_layer`` is set to ``True``). Args: repetitions: The new repetitions. Raises: ValueError: If reps setter has parameter repetitions < 0. """ if repetitions < 0: raise ValueError("The repetitions should be larger than or equal to 0") if repetitions != self._reps: self._invalidate() self._reps = repetitions def print_settings(self) -> str: """Returns information about the setting. Returns: The class name and the attributes/parameters of the instance as ``str``. """ ret = f"NLocal: {self.__class__.__name__}\n" params = "" for key, value in self.__dict__.items(): if key[0] == "_": params += f"-- {key[1:]}: {value}\n" ret += f"{params}" return ret @property def preferred_init_points(self) -> list[float] | None: """The initial points for the parameters. Can be stored as initial guess in optimization. Returns: The initial values for the parameters, or None, if none have been set. """ return None # pylint: disable=too-many-return-statements def get_entangler_map( self, rep_num: int, block_num: int, num_block_qubits: int ) -> Sequence[Sequence[int]]: """Get the entangler map for in the repetition ``rep_num`` and the block ``block_num``. The entangler map for the current block is derived from the value of ``self.entanglement``. Below the different cases are listed, where ``i`` and ``j`` denote the repetition number and the block number, respectively, and ``n`` the number of qubits in the block. =================================== ======================================================== entanglement type entangler map =================================== ======================================================== ``None`` ``[[0, ..., n - 1]]`` ``str`` (e.g ``'full'``) the specified connectivity on ``n`` qubits ``List[int]`` [``entanglement``] ``List[List[int]]`` ``entanglement`` ``List[List[List[int]]]`` ``entanglement[i]`` ``List[List[List[List[int]]]]`` ``entanglement[i][j]`` ``List[str]`` the connectivity specified in ``entanglement[i]`` ``List[List[str]]`` the connectivity specified in ``entanglement[i][j]`` ``Callable[int, str]`` same as ``List[str]`` ``Callable[int, List[List[int]]]`` same as ``List[List[List[int]]]`` =================================== ======================================================== Note that all indices are to be taken modulo the length of the array they act on, i.e. no out-of-bounds index error will be raised but we re-iterate from the beginning of the list. Args: rep_num: The current repetition we are in. block_num: The block number within the entanglement layers. num_block_qubits: The number of qubits in the block. Returns: The entangler map for the current block in the current repetition. Raises: ValueError: If the value of ``entanglement`` could not be cast to a corresponding entangler map. """ i, j, n = rep_num, block_num, num_block_qubits entanglement = self._entanglement # entanglement is None if entanglement is None: return [list(range(n))] # entanglement is callable if callable(entanglement): entanglement = entanglement(i) # entanglement is str if isinstance(entanglement, str): return get_entangler_map(n, self.num_qubits, entanglement, offset=i) # check if entanglement is list of something if not isinstance(entanglement, (tuple, list)): raise ValueError(f"Invalid value of entanglement: {entanglement}") num_i = len(entanglement) # entanglement is List[str] if all(isinstance(en, str) for en in entanglement): return get_entangler_map(n, self.num_qubits, entanglement[i % num_i], offset=i) # entanglement is List[int] if all(isinstance(en, (int, numpy.integer)) for en in entanglement): return [[int(en) for en in entanglement]] # check if entanglement is List[List] if not all(isinstance(en, (tuple, list)) for en in entanglement): raise ValueError(f"Invalid value of entanglement: {entanglement}") num_j = len(entanglement[i % num_i]) # entanglement is List[List[str]] if all(isinstance(e2, str) for en in entanglement for e2 in en): return get_entangler_map( n, self.num_qubits, entanglement[i % num_i][j % num_j], offset=i ) # entanglement is List[List[int]] if all(isinstance(e2, (int, numpy.int32, numpy.int64)) for en in entanglement for e2 in en): for ind, en in enumerate(entanglement): entanglement[ind] = tuple(map(int, en)) return entanglement # check if entanglement is List[List[List]] if not all(isinstance(e2, (tuple, list)) for en in entanglement for e2 in en): raise ValueError(f"Invalid value of entanglement: {entanglement}") # entanglement is List[List[List[int]]] if all( isinstance(e3, (int, numpy.int32, numpy.int64)) for en in entanglement for e2 in en for e3 in e2 ): for en in entanglement: for ind, e2 in enumerate(en): en[ind] = tuple(map(int, e2)) return entanglement[i % num_i] # check if entanglement is List[List[List[List]]] if not all(isinstance(e3, (tuple, list)) for en in entanglement for e2 in en for e3 in e2): raise ValueError(f"Invalid value of entanglement: {entanglement}") # entanglement is List[List[List[List[int]]]] if all( isinstance(e4, (int, numpy.int32, numpy.int64)) for en in entanglement for e2 in en for e3 in e2 for e4 in e3 ): for en in entanglement: for e2 in en: for ind, e3 in enumerate(e2): e2[ind] = tuple(map(int, e3)) return entanglement[i % num_i][j % num_j] raise ValueError(f"Invalid value of entanglement: {entanglement}") @property def initial_state(self) -> QuantumCircuit: """Return the initial state that is added in front of the n-local circuit. Returns: The initial state. """ return self._initial_state @initial_state.setter def initial_state(self, initial_state: QuantumCircuit) -> None: """Set the initial state. Args: initial_state: The new initial state. Raises: ValueError: If the number of qubits has been set before and the initial state does not match the number of qubits. """ self._initial_state = initial_state self._invalidate() @property def parameter_bounds(self) -> list[tuple[float, float]] | None: """The parameter bounds for the unbound parameters in the circuit. Returns: A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded parameter in the corresponding direction. If ``None`` is returned, problem is fully unbounded. """ if not self._is_built: self._build() return self._bounds @parameter_bounds.setter def parameter_bounds(self, bounds: list[tuple[float, float]]) -> None: """Set the parameter bounds. Args: bounds: The new parameter bounds. """ self._bounds = bounds def add_layer( self, other: QuantumCircuit | qiskit.circuit.Instruction, entanglement: list[int] | str | list[list[int]] | None = None, front: bool = False, ) -> "NLocal": """Append another layer to the NLocal. Args: other: The layer to compose, can be another NLocal, an Instruction or Gate, or a QuantumCircuit. entanglement: The entanglement or qubit indices. front: If True, ``other`` is appended to the front, else to the back. Returns: self, such that chained composes are possible. Raises: TypeError: If `other` is not compatible, i.e. is no Instruction and does not have a `to_instruction` method. """ block = self._convert_to_block(other) if entanglement is None: entanglement = [list(range(block.num_qubits))] elif isinstance(entanglement, list) and not isinstance(entanglement[0], list): entanglement = [entanglement] if front: self._prepended_blocks += [block] self._prepended_entanglement += [entanglement] else: self._appended_blocks += [block] self._appended_entanglement += [entanglement] if isinstance(entanglement, list): num_qubits = 1 + max(max(indices) for indices in entanglement) if num_qubits > self.num_qubits: self._invalidate() # rebuild circuit self.num_qubits = num_qubits # modify the circuit accordingly if front is False and self._is_built: if self._insert_barriers and len(self.data) > 0: self.barrier() if isinstance(entanglement, str): entangler_map: Sequence[Sequence[int]] = get_entangler_map( block.num_qubits, self.num_qubits, entanglement ) else: entangler_map = entanglement layer = QuantumCircuit(self.num_qubits) for i in entangler_map: params = self.ordered_parameters[-len(get_parameters(block)) :] parameterized_block = self._parameterize_block(block, params=params) layer.compose(parameterized_block, i, inplace=True) self.compose(layer, inplace=True) else: # cannot prepend a block currently, just rebuild self._invalidate() return self def assign_parameters( self, parameters: Mapping[Parameter, ParameterExpression | float] | Sequence[ParameterExpression | float], inplace: bool = False, **kwargs, ) -> QuantumCircuit | None: """Assign parameters to the n-local circuit. This method also supports passing a list instead of a dictionary. If a list is passed, the list must have the same length as the number of unbound parameters in the circuit. The parameters are assigned in the order of the parameters in :meth:`ordered_parameters`. Returns: A copy of the NLocal circuit with the specified parameters. Raises: AttributeError: If the parameters are given as list and do not match the number of parameters. """ if parameters is None or len(parameters) == 0: return self if not self._is_built: self._build() return super().assign_parameters(parameters, inplace=inplace, **kwargs) def _parameterize_block( self, block, param_iter=None, rep_num=None, block_num=None, indices=None, params=None ): """Convert ``block`` to a circuit of correct width and parameterized using the iterator.""" if self._overwrite_block_parameters: # check if special parameters should be used # pylint: disable=assignment-from-none if params is None: params = self._parameter_generator(rep_num, block_num, indices) if params is None: params = [next(param_iter) for _ in range(len(get_parameters(block)))] update = dict(zip(block.parameters, params)) return block.assign_parameters(update) return block.copy() def _build_rotation_layer(self, circuit, param_iter, i): """Build a rotation layer.""" # if the unentangled qubits are skipped, compute the set of qubits that are not entangled if self._skip_unentangled_qubits: unentangled_qubits = self.get_unentangled_qubits() # iterate over all rotation blocks for j, block in enumerate(self.rotation_blocks): # create a new layer layer = QuantumCircuit(*self.qregs) # we apply the rotation gates stacked on top of each other, i.e. # if we have 4 qubits and a rotation block of width 2, we apply two instances block_indices = [ list(range(k * block.num_qubits, (k + 1) * block.num_qubits)) for k in range(self.num_qubits // block.num_qubits) ] # if unentangled qubits should not be acted on, remove all operations that # touch an unentangled qubit if self._skip_unentangled_qubits: block_indices = [ indices for indices in block_indices if set(indices).isdisjoint(unentangled_qubits) ] # apply the operations in the layer for indices in block_indices: parameterized_block = self._parameterize_block(block, param_iter, i, j, indices) layer.compose(parameterized_block, indices, inplace=True) # add the layer to the circuit circuit.compose(layer, inplace=True) def _build_entanglement_layer(self, circuit, param_iter, i): """Build an entanglement layer.""" # iterate over all entanglement blocks for j, block in enumerate(self.entanglement_blocks): # create a new layer and get the entangler map for this block layer = QuantumCircuit(*self.qregs) entangler_map = self.get_entangler_map(i, j, block.num_qubits) # apply the operations in the layer for indices in entangler_map: parameterized_block = self._parameterize_block(block, param_iter, i, j, indices) layer.compose(parameterized_block, indices, inplace=True) # add the layer to the circuit circuit.compose(layer, inplace=True) def _build_additional_layers(self, circuit, which): if which == "appended": blocks = self._appended_blocks entanglements = self._appended_entanglement elif which == "prepended": blocks = reversed(self._prepended_blocks) entanglements = reversed(self._prepended_entanglement) else: raise ValueError("`which` must be either `appended` or `prepended`.") for block, ent in zip(blocks, entanglements): layer = QuantumCircuit(*self.qregs) if isinstance(ent, str): ent = get_entangler_map(block.num_qubits, self.num_qubits, ent) for indices in ent: layer.compose(block, indices, inplace=True) circuit.compose(layer, inplace=True) def _build(self) -> None: """If not already built, build the circuit.""" if self._is_built: return super()._build() if self.num_qubits == 0: return if not self._flatten: circuit = QuantumCircuit(*self.qregs, name=self.name) else: circuit = self # use the initial state as starting circuit, if it is set if self.initial_state: circuit.compose(self.initial_state.copy(), inplace=True) param_iter = iter(self.ordered_parameters) # build the prepended layers self._build_additional_layers(circuit, "prepended") # main loop to build the entanglement and rotation layers for i in range(self.reps): # insert barrier if specified and there is a preceding layer if self._insert_barriers and (i > 0 or len(self._prepended_blocks) > 0): circuit.barrier() # build the rotation layer self._build_rotation_layer(circuit, param_iter, i) # barrier in between rotation and entanglement layer if self._insert_barriers and len(self._rotation_blocks) > 0: circuit.barrier() # build the entanglement layer self._build_entanglement_layer(circuit, param_iter, i) # add the final rotation layer if not self._skip_final_rotation_layer: if self.insert_barriers and self.reps > 0: circuit.barrier() self._build_rotation_layer(circuit, param_iter, self.reps) # add the appended layers self._build_additional_layers(circuit, "appended") # cast global phase to float if it has no free parameters if isinstance(circuit.global_phase, ParameterExpression): try: circuit.global_phase = float(circuit.global_phase) except TypeError: # expression contains free parameters pass if not self._flatten: try: block = circuit.to_gate() except QiskitError: block = circuit.to_instruction() self.append(block, self.qubits) # pylint: disable=unused-argument def _parameter_generator(self, rep: int, block: int, indices: list[int]) -> Parameter | None: """If certain blocks should use certain parameters this method can be overridden.""" return None def get_parameters(block: QuantumCircuit | Instruction) -> list[Parameter]: """Return the list of Parameters objects inside a circuit or instruction. This is required since, in a standard gate the parameters are not necessarily Parameter objects (e.g. U3Gate(0.1, 0.2, 0.3).params == [0.1, 0.2, 0.3]) and instructions and circuits do not have the same interface for parameters. """ if isinstance(block, QuantumCircuit): return list(block.parameters) else: return [p for p in block.params if isinstance(p, ParameterExpression)] def get_entangler_map( num_block_qubits: int, num_circuit_qubits: int, entanglement: str, offset: int = 0 ) -> Sequence[tuple[int, ...]]: """Get an entangler map for an arbitrary number of qubits. Args: num_block_qubits: The number of qubits of the entangling block. num_circuit_qubits: The number of qubits of the circuit. entanglement: The entanglement strategy. offset: The block offset, can be used if the entanglements differ per block. See mode ``sca`` for instance. Returns: The entangler map using mode ``entanglement`` to scatter a block of ``num_block_qubits`` qubits on ``num_circuit_qubits`` qubits. Raises: ValueError: If the entanglement mode ist not supported. """ n, m = num_circuit_qubits, num_block_qubits if m > n: raise ValueError( "The number of block qubits must be smaller or equal to the number of " "qubits in the circuit." ) if entanglement == "pairwise" and num_block_qubits > 2: raise ValueError("Pairwise entanglement is not defined for blocks with more than 2 qubits.") if entanglement == "full": return list(combinations(list(range(n)), m)) elif entanglement == "reverse_linear": # reverse linear connectivity. In the case of m=2 and the entanglement_block='cx' # then it's equivalent to 'full' entanglement reverse = [tuple(range(n - i - m, n - i)) for i in range(n - m + 1)] return reverse elif entanglement in ["linear", "circular", "sca", "pairwise"]: linear = [tuple(range(i, i + m)) for i in range(n - m + 1)] # if the number of block qubits is 1, we don't have to add the 'circular' part if entanglement == "linear" or m == 1: return linear if entanglement == "pairwise": return linear[::2] + linear[1::2] # circular equals linear plus top-bottom entanglement (if there's space for it) if n > m: circular = [tuple(range(n - m + 1, n)) + (0,)] + linear else: circular = linear if entanglement == "circular": return circular # sca is circular plus shift and reverse shifted = circular[-offset:] + circular[:-offset] if offset % 2 == 1: # if odd, reverse the qubit indices sca = [ind[::-1] for ind in shifted] else: sca = shifted return sca else: raise ValueError(f"Unsupported entanglement type: {entanglement}")
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The two-local gate circuit.""" from __future__ import annotations import typing from collections.abc import Callable, Sequence from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit import Gate, Instruction, Parameter from .n_local import NLocal from ..standard_gates import ( IGate, XGate, YGate, ZGate, RXGate, RYGate, RZGate, HGate, SGate, SdgGate, TGate, TdgGate, RXXGate, RYYGate, RZXGate, RZZGate, SwapGate, CXGate, CYGate, CZGate, CRXGate, CRYGate, CRZGate, CHGate, ) if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import class TwoLocal(NLocal): r"""The two-local circuit. The two-local circuit is a parameterized circuit consisting of alternating rotation layers and entanglement layers. The rotation layers are single qubit gates applied on all qubits. The entanglement layer uses two-qubit gates to entangle the qubits according to a strategy set using ``entanglement``. Both the rotation and entanglement gates can be specified as string (e.g. ``'ry'`` or ``'cx'``), as gate-type (e.g. ``RYGate`` or ``CXGate``) or as QuantumCircuit (e.g. a 1-qubit circuit or 2-qubit circuit). A set of default entanglement strategies is provided: * ``'full'`` entanglement is each qubit is entangled with all the others. * ``'linear'`` entanglement is qubit :math:`i` entangled with qubit :math:`i + 1`, for all :math:`i \in \{0, 1, ... , n - 2\}`, where :math:`n` is the total number of qubits. * ``'reverse_linear'`` entanglement is qubit :math:`i` entangled with qubit :math:`i + 1`, for all :math:`i \in \{n-2, n-3, ... , 1, 0\}`, where :math:`n` is the total number of qubits. Note that if ``entanglement_blocks = 'cx'`` then this option provides the same unitary as ``'full'`` with fewer entangling gates. * ``'pairwise'`` entanglement is one layer where qubit :math:`i` is entangled with qubit :math:`i + 1`, for all even values of :math:`i`, and then a second layer where qubit :math:`i` is entangled with qubit :math:`i + 1`, for all odd values of :math:`i`. * ``'circular'`` entanglement is linear entanglement but with an additional entanglement of the first and last qubit before the linear part. * ``'sca'`` (shifted-circular-alternating) entanglement is a generalized and modified version of the proposed circuit 14 in `Sim et al. <https://arxiv.org/abs/1905.10876>`__. It consists of circular entanglement where the 'long' entanglement connecting the first with the last qubit is shifted by one each block. Furthermore the role of control and target qubits are swapped every block (therefore alternating). The entanglement can further be specified using an entangler map, which is a list of index pairs, such as >>> entangler_map = [(0, 1), (1, 2), (2, 0)] If different entanglements per block should be used, provide a list of entangler maps. See the examples below on how this can be used. >>> entanglement = [entangler_map_layer_1, entangler_map_layer_2, ... ] Barriers can be inserted in between the different layers for better visualization using the ``insert_barriers`` attribute. For each parameterized gate a new parameter is generated using a :class:`~qiskit.circuit.library.ParameterVector`. The name of these parameters can be chosen using the ``parameter_prefix``. Examples: >>> two = TwoLocal(3, 'ry', 'cx', 'linear', reps=2, insert_barriers=True) >>> print(two) # decompose the layers into standard gates ┌──────────┐ ░ ░ ┌──────────┐ ░ ░ ┌──────────┐ q_0: ┤ Ry(θ[0]) ├─░───■────────░─┤ Ry(θ[3]) ├─░───■────────░─┤ Ry(θ[6]) ├ ├──────────┤ ░ ┌─┴─┐ ░ ├──────────┤ ░ ┌─┴─┐ ░ ├──────────┤ q_1: ┤ Ry(θ[1]) ├─░─┤ X ├──■───░─┤ Ry(θ[4]) ├─░─┤ X ├──■───░─┤ Ry(θ[7]) ├ ├──────────┤ ░ └───┘┌─┴─┐ ░ ├──────────┤ ░ └───┘┌─┴─┐ ░ ├──────────┤ q_2: ┤ Ry(θ[2]) ├─░──────┤ X ├─░─┤ Ry(θ[5]) ├─░──────┤ X ├─░─┤ Ry(θ[8]) ├ └──────────┘ ░ └───┘ ░ └──────────┘ ░ └───┘ ░ └──────────┘ >>> two = TwoLocal(3, ['ry','rz'], 'cz', 'full', reps=1, insert_barriers=True) >>> qc = QuantumCircuit(3) >>> qc += two >>> print(qc.decompose().draw()) ┌──────────┐┌──────────┐ ░ ░ ┌──────────┐ ┌──────────┐ q_0: ┤ Ry(θ[0]) ├┤ Rz(θ[3]) ├─░──■──■─────░─┤ Ry(θ[6]) ├─┤ Rz(θ[9]) ├ ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤┌┴──────────┤ q_1: ┤ Ry(θ[1]) ├┤ Rz(θ[4]) ├─░──■──┼──■──░─┤ Ry(θ[7]) ├┤ Rz(θ[10]) ├ ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤├───────────┤ q_2: ┤ Ry(θ[2]) ├┤ Rz(θ[5]) ├─░─────■──■──░─┤ Ry(θ[8]) ├┤ Rz(θ[11]) ├ └──────────┘└──────────┘ ░ ░ └──────────┘└───────────┘ >>> entangler_map = [[0, 1], [1, 2], [2, 0]] # circular entanglement for 3 qubits >>> two = TwoLocal(3, 'x', 'crx', entangler_map, reps=1) >>> print(two) # note: no barriers inserted this time! ┌───┐ ┌──────────┐┌───┐ q_0: |0>┤ X ├─────■───────────────────────┤ Rx(θ[2]) ├┤ X ├ ├───┤┌────┴─────┐ ┌───┐└─────┬────┘└───┘ q_1: |0>┤ X ├┤ Rx(θ[0]) ├─────■──────┤ X ├──────┼────────── ├───┤└──────────┘┌────┴─────┐└───┘ │ ┌───┐ q_2: |0>┤ X ├────────────┤ Rx(θ[1]) ├───────────■─────┤ X ├ └───┘ └──────────┘ └───┘ >>> entangler_map = [[0, 3], [0, 2]] # entangle the first and last two-way >>> two = TwoLocal(4, [], 'cry', entangler_map, reps=1) >>> circuit = two + two >>> print(circuit.decompose().draw()) # note, that the parameters are the same! q_0: ─────■───────────■───────────■───────────■────── │ │ │ │ q_1: ─────┼───────────┼───────────┼───────────┼────── │ ┌────┴─────┐ │ ┌────┴─────┐ q_2: ─────┼──────┤ Ry(θ[1]) ├─────┼──────┤ Ry(θ[1]) ├ ┌────┴─────┐└──────────┘┌────┴─────┐└──────────┘ q_3: ┤ Ry(θ[0]) ├────────────┤ Ry(θ[0]) ├──────────── └──────────┘ └──────────┘ >>> layer_1 = [(0, 1), (0, 2)] >>> layer_2 = [(1, 2)] >>> two = TwoLocal(3, 'x', 'cx', [layer_1, layer_2], reps=2, insert_barriers=True) >>> print(two) ┌───┐ ░ ░ ┌───┐ ░ ░ ┌───┐ q_0: ┤ X ├─░───■────■───░─┤ X ├─░───────░─┤ X ├ ├───┤ ░ ┌─┴─┐ │ ░ ├───┤ ░ ░ ├───┤ q_1: ┤ X ├─░─┤ X ├──┼───░─┤ X ├─░───■───░─┤ X ├ ├───┤ ░ └───┘┌─┴─┐ ░ ├───┤ ░ ┌─┴─┐ ░ ├───┤ q_2: ┤ X ├─░──────┤ X ├─░─┤ X ├─░─┤ X ├─░─┤ X ├ └───┘ ░ └───┘ ░ └───┘ ░ └───┘ ░ └───┘ """ def __init__( self, num_qubits: int | None = None, rotation_blocks: str | type | qiskit.circuit.Instruction | QuantumCircuit | list[str | type | qiskit.circuit.Instruction | QuantumCircuit] | None = None, entanglement_blocks: str | type | qiskit.circuit.Instruction | QuantumCircuit | list[str | type | qiskit.circuit.Instruction | QuantumCircuit] | None = None, entanglement: str | list[list[int]] | Callable[[int], list[int]] = "full", reps: int = 3, skip_unentangled_qubits: bool = False, skip_final_rotation_layer: bool = False, parameter_prefix: str = "θ", insert_barriers: bool = False, initial_state: QuantumCircuit | None = None, name: str = "TwoLocal", flatten: bool | None = None, ) -> None: """ Args: num_qubits: The number of qubits of the two-local circuit. rotation_blocks: The gates used in the rotation layer. Can be specified via the name of a gate (e.g. ``'ry'``) or the gate type itself (e.g. :class:`.RYGate`). If only one gate is provided, the gate same gate is applied to each qubit. If a list of gates is provided, all gates are applied to each qubit in the provided order. See the Examples section for more detail. entanglement_blocks: The gates used in the entanglement layer. Can be specified in the same format as ``rotation_blocks``. entanglement: Specifies the entanglement structure. Can be a string (``'full'``, ``'linear'``, ``'reverse_linear'``, ``'circular'`` or ``'sca'``), a list of integer-pairs specifying the indices of qubits entangled with one another, or a callable returning such a list provided with the index of the entanglement layer. Default to ``'full'`` entanglement. Note that if ``entanglement_blocks = 'cx'``, then ``'full'`` entanglement provides the same unitary as ``'reverse_linear'`` but the latter option has fewer entangling gates. See the Examples section for more detail. reps: Specifies how often a block consisting of a rotation layer and entanglement layer is repeated. skip_unentangled_qubits: If ``True``, the single qubit gates are only applied to qubits that are entangled with another qubit. If ``False``, the single qubit gates are applied to each qubit in the ansatz. Defaults to ``False``. skip_final_rotation_layer: If ``False``, a rotation layer is added at the end of the ansatz. If ``True``, no rotation layer is added. parameter_prefix: The parameterized gates require a parameter to be defined, for which we use instances of :class:`~qiskit.circuit.Parameter`. The name of each parameter will be this specified prefix plus its index. insert_barriers: If ``True``, barriers are inserted in between each layer. If ``False``, no barriers are inserted. Defaults to ``False``. initial_state: A :class:`.QuantumCircuit` object to prepend to the circuit. flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you're using this circuit for anything besides visualization its **strongly** recommended to set this flag to ``True`` to avoid a large performance overhead for parameter binding. """ super().__init__( num_qubits=num_qubits, rotation_blocks=rotation_blocks, entanglement_blocks=entanglement_blocks, entanglement=entanglement, reps=reps, skip_final_rotation_layer=skip_final_rotation_layer, skip_unentangled_qubits=skip_unentangled_qubits, insert_barriers=insert_barriers, initial_state=initial_state, parameter_prefix=parameter_prefix, name=name, flatten=flatten, ) def _convert_to_block(self, layer: str | type | Gate | QuantumCircuit) -> QuantumCircuit: """For a layer provided as str (e.g. ``'ry'``) or type (e.g. :class:`.RYGate`) this function returns the according layer type along with the number of parameters (e.g. ``(RYGate, 1)``). Args: layer: The qubit layer. Returns: The specified layer with the required number of parameters. Raises: TypeError: The type of ``layer`` is invalid. ValueError: The type of ``layer`` is str but the name is unknown. ValueError: The type of ``layer`` is type but the layer type is unknown. Note: Outlook: If layers knew their number of parameters as static property, we could also allow custom layer types. """ if isinstance(layer, QuantumCircuit): return layer # check the list of valid layers # this could be a lot easier if the standard layers would have ``name`` and ``num_params`` # as static types, which might be something they should have anyway theta = Parameter("θ") valid_layers = { "ch": CHGate(), "cx": CXGate(), "cy": CYGate(), "cz": CZGate(), "crx": CRXGate(theta), "cry": CRYGate(theta), "crz": CRZGate(theta), "h": HGate(), "i": IGate(), "id": IGate(), "iden": IGate(), "rx": RXGate(theta), "rxx": RXXGate(theta), "ry": RYGate(theta), "ryy": RYYGate(theta), "rz": RZGate(theta), "rzx": RZXGate(theta), "rzz": RZZGate(theta), "s": SGate(), "sdg": SdgGate(), "swap": SwapGate(), "x": XGate(), "y": YGate(), "z": ZGate(), "t": TGate(), "tdg": TdgGate(), } # try to exchange `layer` from a string to a gate instance if isinstance(layer, str): try: layer = valid_layers[layer] except KeyError as ex: raise ValueError(f"Unknown layer name `{layer}`.") from ex # try to exchange `layer` from a type to a gate instance if isinstance(layer, type): # iterate over the layer types and look for the specified layer instance = None for gate in valid_layers.values(): if isinstance(gate, layer): instance = gate if instance is None: raise ValueError(f"Unknown layer type`{layer}`.") layer = instance if isinstance(layer, Instruction): circuit = QuantumCircuit(layer.num_qubits) circuit.append(layer, list(range(layer.num_qubits))) return circuit raise TypeError( f"Invalid input type {type(layer)}. " + "`layer` must be a type, str or QuantumCircuit." ) def get_entangler_map( self, rep_num: int, block_num: int, num_block_qubits: int ) -> Sequence[Sequence[int]]: """Overloading to handle the special case of 1 qubit where the entanglement are ignored.""" if self.num_qubits <= 1: return [] return super().get_entangler_map(rep_num, block_num, num_block_qubits)
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=too-many-function-args, unexpected-keyword-arg """THIS FILE IS DEPRECATED AND WILL BE REMOVED IN RELEASE 0.9. """ import warnings from qiskit.converters import dag_to_circuit, circuit_to_dag from qiskit.transpiler import CouplingMap from qiskit import compiler from qiskit.transpiler.preset_passmanagers import (default_pass_manager_simulator, default_pass_manager) def transpile(circuits, backend=None, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """transpile one or more circuits. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile backend (BaseBackend): a backend to compile for basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): coupling map (perhaps custom) to target in mapping initial_layout (Layout or dict or list): Initial position of virtual qubits on physical qubits. The final layout is not guaranteed to be the same, as the transpiler may permute qubits through swaps or other means. seed_mapper (int): random seed for the swap_mapper pass_manager (PassManager): a pass_manager for the transpiler stages Returns: QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s). Raises: TranspilerError: in case of bad inputs to transpiler or errors in passes """ warnings.warn("qiskit.transpiler.transpile() has been deprecated and will be " "removed in the 0.9 release. Use qiskit.compiler.transpile() instead.", DeprecationWarning) return compiler.transpile(circuits=circuits, backend=backend, basis_gates=basis_gates, coupling_map=coupling_map, initial_layout=initial_layout, seed_transpiler=seed_mapper, pass_manager=pass_manager) def transpile_dag(dag, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """Deprecated - Use qiskit.compiler.transpile for transpiling from circuits to circuits. Transform a dag circuit into another dag circuit (transpile), through consecutive passes on the dag. Args: dag (DAGCircuit): dag circuit to transform via transpilation basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): A graph of coupling:: [ [control0(int), target0(int)], [control1(int), target1(int)], ] eg. [[0, 2], [1, 2], [1, 3], [3, 4]} initial_layout (Layout or None): A layout object seed_mapper (int): random seed_mapper for the swap mapper pass_manager (PassManager): pass manager instance for the transpilation process If None, a default set of passes are run. Otherwise, the passes defined in it will run. If contains no passes in it, no dag transformations occur. Returns: DAGCircuit: transformed dag """ warnings.warn("transpile_dag has been deprecated and will be removed in the " "0.9 release. Circuits can be transpiled directly to other " "circuits with the transpile function.", DeprecationWarning) if basis_gates is None: basis_gates = ['u1', 'u2', 'u3', 'cx', 'id'] if pass_manager is None: # default set of passes # if a coupling map is given compile to the map if coupling_map: pass_manager = default_pass_manager(basis_gates, CouplingMap(coupling_map), initial_layout, seed_transpiler=seed_mapper) else: pass_manager = default_pass_manager_simulator(basis_gates) # run the passes specified by the pass manager # TODO return the property set too. See #1086 name = dag.name circuit = dag_to_circuit(dag) circuit = pass_manager.run(circuit) dag = circuit_to_dag(circuit) dag.name = name return dag
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Helper function for converting a circuit to a dag""" import copy from qiskit.dagcircuit.dagcircuit import DAGCircuit def circuit_to_dag(circuit, copy_operations=True, *, qubit_order=None, clbit_order=None): """Build a ``DAGCircuit`` object from a ``QuantumCircuit``. Args: circuit (QuantumCircuit): the input circuit. copy_operations (bool): Deep copy the operation objects in the :class:`~.QuantumCircuit` for the output :class:`~.DAGCircuit`. This should only be set to ``False`` if the input :class:`~.QuantumCircuit` will not be used anymore as the operations in the output :class:`~.DAGCircuit` will be shared instances and modifications to operations in the :class:`~.DAGCircuit` will be reflected in the :class:`~.QuantumCircuit` (and vice versa). qubit_order (Iterable[Qubit] or None): the order that the qubits should be indexed in the output DAG. Defaults to the same order as in the circuit. clbit_order (Iterable[Clbit] or None): the order that the clbits should be indexed in the output DAG. Defaults to the same order as in the circuit. Return: DAGCircuit: the DAG representing the input circuit. Raises: ValueError: if the ``qubit_order`` or ``clbit_order`` parameters do not match the bits in the circuit. Example: .. code-block:: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) """ dagcircuit = DAGCircuit() dagcircuit.name = circuit.name dagcircuit.global_phase = circuit.global_phase dagcircuit.calibrations = circuit.calibrations dagcircuit.metadata = circuit.metadata if qubit_order is None: qubits = circuit.qubits elif len(qubit_order) != circuit.num_qubits or set(qubit_order) != set(circuit.qubits): raise ValueError("'qubit_order' does not contain exactly the same qubits as the circuit") else: qubits = qubit_order if clbit_order is None: clbits = circuit.clbits elif len(clbit_order) != circuit.num_clbits or set(clbit_order) != set(circuit.clbits): raise ValueError("'clbit_order' does not contain exactly the same clbits as the circuit") else: clbits = clbit_order dagcircuit.add_qubits(qubits) dagcircuit.add_clbits(clbits) for register in circuit.qregs: dagcircuit.add_qreg(register) for register in circuit.cregs: dagcircuit.add_creg(register) for instruction in circuit.data: op = instruction.operation if copy_operations: op = copy.deepcopy(op) dagcircuit.apply_operation_back(op, instruction.qubits, instruction.clbits) dagcircuit.duration = circuit.duration dagcircuit.unit = circuit.unit return dagcircuit
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Helper function for converting a circuit to an instruction.""" from qiskit.exceptions import QiskitError from qiskit.circuit.instruction import Instruction from qiskit.circuit.quantumregister import QuantumRegister from qiskit.circuit.classicalregister import ClassicalRegister, Clbit def circuit_to_instruction(circuit, parameter_map=None, equivalence_library=None, label=None): """Build an :class:`~.circuit.Instruction` object from a :class:`.QuantumCircuit`. The instruction is anonymous (not tied to a named quantum register), and so can be inserted into another circuit. The instruction will have the same string name as the circuit. Args: circuit (QuantumCircuit): the input circuit. parameter_map (dict): For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the instruction. If None, existing circuit parameters will also parameterize the instruction. equivalence_library (EquivalenceLibrary): Optional equivalence library where the converted instruction will be registered. label (str): Optional instruction label. Raises: QiskitError: if parameter_map is not compatible with circuit Return: qiskit.circuit.Instruction: an instruction equivalent to the action of the input circuit. Upon decomposition, this instruction will yield the components comprising the original circuit. Example: .. code-block:: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.converters import circuit_to_instruction q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) circuit_to_instruction(circ) """ # pylint: disable=cyclic-import from qiskit.circuit.quantumcircuit import QuantumCircuit if parameter_map is None: parameter_dict = {p: p for p in circuit.parameters} else: parameter_dict = circuit._unroll_param_dict(parameter_map) if parameter_dict.keys() != circuit.parameters: raise QiskitError( ( "parameter_map should map all circuit parameters. " "Circuit parameters: {}, parameter_map: {}" ).format(circuit.parameters, parameter_dict) ) out_instruction = Instruction( name=circuit.name, num_qubits=circuit.num_qubits, num_clbits=circuit.num_clbits, params=[*parameter_dict.values()], label=label, ) out_instruction.condition = None target = circuit.assign_parameters(parameter_dict, inplace=False) if equivalence_library is not None: equivalence_library.add_equivalence(out_instruction, target) regs = [] if out_instruction.num_qubits > 0: q = QuantumRegister(out_instruction.num_qubits, "q") regs.append(q) if out_instruction.num_clbits > 0: c = ClassicalRegister(out_instruction.num_clbits, "c") regs.append(c) qubit_map = {bit: q[idx] for idx, bit in enumerate(circuit.qubits)} clbit_map = {bit: c[idx] for idx, bit in enumerate(circuit.clbits)} definition = [ instruction.replace( qubits=[qubit_map[y] for y in instruction.qubits], clbits=[clbit_map[y] for y in instruction.clbits], ) for instruction in target.data ] # fix condition for rule in definition: condition = getattr(rule.operation, "condition", None) if condition: reg, val = condition if isinstance(reg, Clbit): rule.operation.condition = (clbit_map[reg], val) elif reg.size == c.size: rule.operation.condition = (c, val) else: raise QiskitError( "Cannot convert condition in circuit with " "multiple classical registers to instruction" ) qc = QuantumCircuit(*regs, name=out_instruction.name) for instruction in definition: qc._append(instruction) if circuit.global_phase: qc.global_phase = circuit.global_phase out_instruction.definition = qc return out_instruction
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Helper function for converting a dag to a circuit.""" import copy from qiskit.circuit import QuantumCircuit, CircuitInstruction def dag_to_circuit(dag, copy_operations=True): """Build a ``QuantumCircuit`` object from a ``DAGCircuit``. Args: dag (DAGCircuit): the input dag. copy_operations (bool): Deep copy the operation objects in the :class:`~.DAGCircuit` for the output :class:`~.QuantumCircuit`. This should only be set to ``False`` if the input :class:`~.DAGCircuit` will not be used anymore as the operations in the output :class:`~.QuantumCircuit` will be shared instances and modifications to operations in the :class:`~.DAGCircuit` will be reflected in the :class:`~.QuantumCircuit` (and vice versa). Return: QuantumCircuit: the circuit representing the input dag. Example: .. plot:: :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate from qiskit.converters import dag_to_circuit q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) circuit = dag_to_circuit(dag) circuit.draw('mpl') """ name = dag.name or None circuit = QuantumCircuit( dag.qubits, dag.clbits, *dag.qregs.values(), *dag.cregs.values(), name=name, global_phase=dag.global_phase, ) circuit.metadata = dag.metadata circuit.calibrations = dag.calibrations for node in dag.topological_op_nodes(): op = node.op if copy_operations: op = copy.deepcopy(op) circuit._append(CircuitInstruction(op, node.qargs, node.cargs)) circuit.duration = dag.duration circuit.unit = dag.unit return circuit
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Objects to represent the information at a node in the DAGCircuit.""" from __future__ import annotations import typing import uuid import qiskit._accelerate.circuit from qiskit.circuit import ( Clbit, ClassicalRegister, ControlFlowOp, IfElseOp, WhileLoopOp, SwitchCaseOp, ForLoopOp, Parameter, QuantumCircuit, ) from qiskit.circuit.classical import expr if typing.TYPE_CHECKING: from qiskit.dagcircuit import DAGCircuit DAGNode = qiskit._accelerate.circuit.DAGNode DAGOpNode = qiskit._accelerate.circuit.DAGOpNode DAGInNode = qiskit._accelerate.circuit.DAGInNode DAGOutNode = qiskit._accelerate.circuit.DAGOutNode def _legacy_condition_eq(cond1, cond2, bit_indices1, bit_indices2) -> bool: if cond1 is cond2 is None: return True elif None in (cond1, cond2): return False target1, val1 = cond1 target2, val2 = cond2 if val1 != val2: return False if isinstance(target1, Clbit) and isinstance(target2, Clbit): return bit_indices1[target1] == bit_indices2[target2] if isinstance(target1, ClassicalRegister) and isinstance(target2, ClassicalRegister): return target1.size == target2.size and all( bit_indices1[t1] == bit_indices2[t2] for t1, t2 in zip(target1, target2) ) return False def _circuit_to_dag(circuit: QuantumCircuit, node_qargs, node_cargs, bit_indices) -> DAGCircuit: """Get a :class:`.DAGCircuit` of the given :class:`.QuantumCircuit`. The bits in the output will be ordered in a canonical order based on their indices in the outer DAG, as defined by the ``bit_indices`` mapping and the ``node_{q,c}args`` arguments.""" from qiskit.converters import circuit_to_dag # pylint: disable=cyclic-import def sort_key(bits): outer, _inner = bits return bit_indices[outer] return circuit_to_dag( circuit, copy_operations=False, qubit_order=[ inner for _outer, inner in sorted(zip(node_qargs, circuit.qubits), key=sort_key) ], clbit_order=[ inner for _outer, inner in sorted(zip(node_cargs, circuit.clbits), key=sort_key) ], ) def _make_expr_key(bit_indices): def key(var): if isinstance(var, Clbit): return bit_indices.get(var) if isinstance(var, ClassicalRegister): return [bit_indices.get(bit) for bit in var] return None return key def _condition_op_eq(node1, node2, bit_indices1, bit_indices2): cond1 = node1.op.condition cond2 = node2.op.condition if isinstance(cond1, expr.Expr) and isinstance(cond2, expr.Expr): if not expr.structurally_equivalent( cond1, cond2, _make_expr_key(bit_indices1), _make_expr_key(bit_indices2) ): return False elif isinstance(cond1, expr.Expr) or isinstance(cond2, expr.Expr): return False elif not _legacy_condition_eq(cond1, cond2, bit_indices1, bit_indices2): return False return len(node1.op.blocks) == len(node2.op.blocks) and all( _circuit_to_dag(block1, node1.qargs, node1.cargs, bit_indices1) == _circuit_to_dag(block2, node2.qargs, node2.cargs, bit_indices2) for block1, block2 in zip(node1.op.blocks, node2.op.blocks) ) def _switch_case_eq(node1, node2, bit_indices1, bit_indices2): target1 = node1.op.target target2 = node2.op.target if isinstance(target1, expr.Expr) and isinstance(target2, expr.Expr): if not expr.structurally_equivalent( target1, target2, _make_expr_key(bit_indices1), _make_expr_key(bit_indices2) ): return False elif isinstance(target1, Clbit) and isinstance(target2, Clbit): if bit_indices1[target1] != bit_indices2[target2]: return False elif isinstance(target1, ClassicalRegister) and isinstance(target2, ClassicalRegister): if target1.size != target2.size or any( bit_indices1[b1] != bit_indices2[b2] for b1, b2 in zip(target1, target2) ): return False else: return False cases1 = [case for case, _ in node1.op.cases_specifier()] cases2 = [case for case, _ in node2.op.cases_specifier()] return ( len(cases1) == len(cases2) and all(set(labels1) == set(labels2) for labels1, labels2 in zip(cases1, cases2)) and len(node1.op.blocks) == len(node2.op.blocks) and all( _circuit_to_dag(block1, node1.qargs, node1.cargs, bit_indices1) == _circuit_to_dag(block2, node2.qargs, node2.cargs, bit_indices2) for block1, block2 in zip(node1.op.blocks, node2.op.blocks) ) ) def _for_loop_eq(node1, node2, bit_indices1, bit_indices2): indexset1, param1, body1 = node1.op.params indexset2, param2, body2 = node2.op.params if indexset1 != indexset2: return False if (param1 is None and param2 is not None) or (param1 is not None and param2 is None): return False if param1 is not None and param2 is not None: sentinel = Parameter(str(uuid.uuid4())) body1 = ( body1.assign_parameters({param1: sentinel}, inplace=False) if param1 in body1.parameters else body1 ) body2 = ( body2.assign_parameters({param2: sentinel}, inplace=False) if param2 in body2.parameters else body2 ) return _circuit_to_dag(body1, node1.qargs, node1.cargs, bit_indices1) == _circuit_to_dag( body2, node2.qargs, node2.cargs, bit_indices2 ) _SEMANTIC_EQ_CONTROL_FLOW = { IfElseOp: _condition_op_eq, WhileLoopOp: _condition_op_eq, SwitchCaseOp: _switch_case_eq, ForLoopOp: _for_loop_eq, } _SEMANTIC_EQ_SYMMETRIC = frozenset({"barrier", "swap", "break_loop", "continue_loop"}) # Note: called from dag_node.rs. def _semantic_eq(node1, node2, bit_indices1, bit_indices2): """ Check if DAG nodes are considered equivalent, e.g., as a node_match for :func:`rustworkx.is_isomorphic_node_match`. Args: node1 (DAGOpNode, DAGInNode, DAGOutNode): A node to compare. node2 (DAGOpNode, DAGInNode, DAGOutNode): The other node to compare. bit_indices1 (dict): Dictionary mapping Bit instances to their index within the circuit containing node1 bit_indices2 (dict): Dictionary mapping Bit instances to their index within the circuit containing node2 Return: Bool: If node1 == node2 """ if not isinstance(node1, DAGOpNode) or not isinstance(node1, DAGOpNode): return type(node1) is type(node2) and bit_indices1.get(node1.wire) == bit_indices2.get( node2.wire ) if isinstance(node1.op, ControlFlowOp) and isinstance(node2.op, ControlFlowOp): # While control-flow operations aren't represented natively in the DAG, we have to do # some unpleasant dispatching and very manual handling. Once they have more first-class # support we'll still be dispatching, but it'll look more appropriate (like the dispatch # based on `DAGOpNode`/`DAGInNode`/`DAGOutNode` that already exists) and less like we're # duplicating code from the `ControlFlowOp` classes. if type(node1.op) is not type(node2.op): return False comparer = _SEMANTIC_EQ_CONTROL_FLOW.get(type(node1.op)) if comparer is None: # pragma: no cover raise RuntimeError(f"unhandled control-flow operation: {type(node1.op)}") return comparer(node1, node2, bit_indices1, bit_indices2) node1_qargs = [bit_indices1[qarg] for qarg in node1.qargs] node1_cargs = [bit_indices1[carg] for carg in node1.cargs] node2_qargs = [bit_indices2[qarg] for qarg in node2.qargs] node2_cargs = [bit_indices2[carg] for carg in node2.cargs] # For barriers, qarg order is not significant so compare as sets if node1.op.name == node2.op.name and node1.name in _SEMANTIC_EQ_SYMMETRIC: node1_qargs = set(node1_qargs) node1_cargs = set(node1_cargs) node2_qargs = set(node2_qargs) node2_cargs = set(node2_cargs) return ( node1_qargs == node2_qargs and node1_cargs == node2_cargs and _legacy_condition_eq( getattr(node1.op, "condition", None), getattr(node2.op, "condition", None), bit_indices1, bit_indices2, ) and node1.op == node2.op ) # Bind semantic_eq from Python to Rust implementation DAGNode.semantic_eq = staticmethod(_semantic_eq)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2023, 2024. # # 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. """ Statevector Sampler class """ from __future__ import annotations import warnings from dataclasses import dataclass from typing import Iterable import numpy as np from numpy.typing import NDArray from qiskit import ClassicalRegister, QiskitError, QuantumCircuit from qiskit.circuit import ControlFlowOp from qiskit.quantum_info import Statevector from .base import BaseSamplerV2 from .base.validation import _has_measure from .containers import ( BitArray, DataBin, PrimitiveResult, SamplerPubResult, SamplerPubLike, ) from .containers.sampler_pub import SamplerPub from .containers.bit_array import _min_num_bytes from .primitive_job import PrimitiveJob from .utils import bound_circuit_to_instruction @dataclass class _MeasureInfo: creg_name: str num_bits: int num_bytes: int qreg_indices: list[int] class StatevectorSampler(BaseSamplerV2): """ Simple implementation of :class:`BaseSamplerV2` using full state vector simulation. This class is implemented via :class:`~.Statevector` which turns provided circuits into pure state vectors, and is therefore incompatible with mid-circuit measurements (although other implementations may be). As seen in the example below, this sampler supports providing arrays of parameter value sets to bind against a single circuit. Each tuple of ``(circuit, <optional> parameter values, <optional> shots)``, called a sampler primitive unified bloc (PUB), produces its own array-valued result. The :meth:`~run` method can be given many pubs at once. .. code-block:: python from qiskit.circuit import ( Parameter, QuantumCircuit, ClassicalRegister, QuantumRegister ) from qiskit.primitives import StatevectorSampler import matplotlib.pyplot as plt import numpy as np # Define our circuit registers, including classical registers # called 'alpha' and 'beta'. qreg = QuantumRegister(3) alpha = ClassicalRegister(2, "alpha") beta = ClassicalRegister(1, "beta") # Define a quantum circuit with two parameters. circuit = QuantumCircuit(qreg, alpha, beta) circuit.h(0) circuit.cx(0, 1) circuit.cx(1, 2) circuit.ry(Parameter("a"), 0) circuit.rz(Parameter("b"), 0) circuit.cx(1, 2) circuit.cx(0, 1) circuit.h(0) circuit.measure([0, 1], alpha) circuit.measure([2], beta) # Define a sweep over parameter values, where the second axis is over. # the two parameters in the circuit. params = np.vstack([ np.linspace(-np.pi, np.pi, 100), np.linspace(-4 * np.pi, 4 * np.pi, 100) ]).T # Instantiate a new statevector simulation based sampler object. sampler = StatevectorSampler() # Start a job that will return shots for all 100 parameter value sets. pub = (circuit, params) job = sampler.run([pub], shots=256) # Extract the result for the 0th pub (this example only has one pub). result = job.result()[0] # There is one BitArray object for each ClassicalRegister in the # circuit. Here, we can see that the BitArray for alpha contains data # for all 100 sweep points, and that it is indeed storing data for 2 # bits over 256 shots. assert result.data.alpha.shape == (100,) assert result.data.alpha.num_bits == 2 assert result.data.alpha.num_shots == 256 # We can work directly with a binary array in performant applications. raw = result.data.alpha.array # For small registers where it is anticipated to have many counts # associated with the same bitstrings, we can turn the data from, # for example, the 22nd sweep index into a dictionary of counts. counts = result.data.alpha.get_counts(22) # Or, convert into a list of bitstrings that preserve shot order. bitstrings = result.data.alpha.get_bitstrings(22) print(bitstrings) """ def __init__(self, *, default_shots: int = 1024, seed: np.random.Generator | int | None = None): """ Args: default_shots: The default shots for the sampler if not specified during run. seed: The seed or Generator object for random number generation. If None, a random seeded default RNG will be used. """ self._default_shots = default_shots self._seed = seed @property def default_shots(self) -> int: """Return the default shots""" return self._default_shots @property def seed(self) -> np.random.Generator | int | None: """Return the seed or Generator object for random number generation.""" return self._seed def run( self, pubs: Iterable[SamplerPubLike], *, shots: int | None = None ) -> PrimitiveJob[PrimitiveResult[SamplerPubResult]]: if shots is None: shots = self._default_shots coerced_pubs = [SamplerPub.coerce(pub, shots) for pub in pubs] if any(len(pub.circuit.cregs) == 0 for pub in coerced_pubs): warnings.warn( "One of your circuits has no output classical registers and so the result " "will be empty. Did you mean to add measurement instructions?", UserWarning, ) job = PrimitiveJob(self._run, coerced_pubs) job._submit() return job def _run(self, pubs: Iterable[SamplerPub]) -> PrimitiveResult[SamplerPubResult]: results = [self._run_pub(pub) for pub in pubs] return PrimitiveResult(results) def _run_pub(self, pub: SamplerPub) -> SamplerPubResult: circuit, qargs, meas_info = _preprocess_circuit(pub.circuit) bound_circuits = pub.parameter_values.bind_all(circuit) arrays = { item.creg_name: np.zeros( bound_circuits.shape + (pub.shots, item.num_bytes), dtype=np.uint8 ) for item in meas_info } for index, bound_circuit in np.ndenumerate(bound_circuits): final_state = Statevector(bound_circuit_to_instruction(bound_circuit)) final_state.seed(self._seed) if qargs: samples = final_state.sample_memory(shots=pub.shots, qargs=qargs) else: samples = [""] * pub.shots samples_array = np.array([np.fromiter(sample, dtype=np.uint8) for sample in samples]) for item in meas_info: ary = _samples_to_packed_array(samples_array, item.num_bits, item.qreg_indices) arrays[item.creg_name][index] = ary meas = { item.creg_name: BitArray(arrays[item.creg_name], item.num_bits) for item in meas_info } return SamplerPubResult(DataBin(**meas, shape=pub.shape), metadata={"shots": pub.shots}) def _preprocess_circuit(circuit: QuantumCircuit): num_bits_dict = {creg.name: creg.size for creg in circuit.cregs} mapping = _final_measurement_mapping(circuit) qargs = sorted(set(mapping.values())) qargs_index = {v: k for k, v in enumerate(qargs)} circuit = circuit.remove_final_measurements(inplace=False) if _has_control_flow(circuit): raise QiskitError("StatevectorSampler cannot handle ControlFlowOp") if _has_measure(circuit): raise QiskitError("StatevectorSampler cannot handle mid-circuit measurements") # num_qubits is used as sentinel to fill 0 in _samples_to_packed_array sentinel = len(qargs) indices = {key: [sentinel] * val for key, val in num_bits_dict.items()} for key, qreg in mapping.items(): creg, ind = key indices[creg.name][ind] = qargs_index[qreg] meas_info = [ _MeasureInfo( creg_name=name, num_bits=num_bits, num_bytes=_min_num_bytes(num_bits), qreg_indices=indices[name], ) for name, num_bits in num_bits_dict.items() ] return circuit, qargs, meas_info def _samples_to_packed_array( samples: NDArray[np.uint8], num_bits: int, indices: list[int] ) -> NDArray[np.uint8]: # samples of `Statevector.sample_memory` will be in the order of # qubit_last, ..., qubit_1, qubit_0. # reverse the sample order into qubit_0, qubit_1, ..., qubit_last and # pad 0 in the rightmost to be used for the sentinel introduced by _preprocess_circuit. ary = np.pad(samples[:, ::-1], ((0, 0), (0, 1)), constant_values=0) # place samples in the order of clbit_last, ..., clbit_1, clbit_0 ary = ary[:, indices[::-1]] # pad 0 in the left to align the number to be mod 8 # since np.packbits(bitorder='big') pads 0 to the right. pad_size = -num_bits % 8 ary = np.pad(ary, ((0, 0), (pad_size, 0)), constant_values=0) # pack bits in big endian order ary = np.packbits(ary, axis=-1) return ary def _final_measurement_mapping(circuit: QuantumCircuit) -> dict[tuple[ClassicalRegister, int], int]: """Return the final measurement mapping for the circuit. Parameters: circuit: Input quantum circuit. Returns: Mapping of classical bits to qubits for final measurements. """ active_qubits = set(range(circuit.num_qubits)) active_cbits = set(range(circuit.num_clbits)) # Find final measurements starting in back mapping = {} for item in circuit[::-1]: if item.operation.name == "measure": loc = circuit.find_bit(item.clbits[0]) cbit = loc.index qbit = circuit.find_bit(item.qubits[0]).index if cbit in active_cbits and qbit in active_qubits: for creg in loc.registers: mapping[creg] = qbit active_cbits.remove(cbit) elif item.operation.name not in ["barrier", "delay"]: for qq in item.qubits: _temp_qubit = circuit.find_bit(qq).index if _temp_qubit in active_qubits: active_qubits.remove(_temp_qubit) if not active_cbits or not active_qubits: break return mapping def _has_control_flow(circuit: QuantumCircuit) -> bool: return any(isinstance(instruction.operation, ControlFlowOp) for instruction in circuit)
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. r""" =================== Overview of Sampler =================== Sampler class calculates probabilities or quasi-probabilities of bitstrings from quantum circuits. A sampler is initialized with an empty parameter set. The sampler is used to create a :class:`~qiskit.providers.JobV1`, via the :meth:`qiskit.primitives.Sampler.run()` method. This method is called with the following parameters * quantum circuits (:math:`\psi_i(\theta)`): list of (parameterized) quantum circuits. (a list of :class:`~qiskit.circuit.QuantumCircuit` objects) * parameter values (:math:`\theta_k`): list of sets of parameter values to be bound to the parameters of the quantum circuits. (list of list of float) The method returns a :class:`~qiskit.providers.JobV1` object, calling :meth:`qiskit.providers.JobV1.result()` yields a :class:`~qiskit.primitives.SamplerResult` object, which contains probabilities or quasi-probabilities of bitstrings, plus optional metadata like error bars in the samples. Here is an example of how sampler is used. .. code-block:: python from qiskit.primitives import Sampler from qiskit import QuantumCircuit from qiskit.circuit.library import RealAmplitudes # a Bell circuit bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) bell.measure_all() # two parameterized circuits pqc = RealAmplitudes(num_qubits=2, reps=2) pqc.measure_all() pqc2 = RealAmplitudes(num_qubits=2, reps=3) pqc2.measure_all() theta1 = [0, 1, 1, 2, 3, 5] theta2 = [0, 1, 2, 3, 4, 5, 6, 7] # initialization of the sampler sampler = Sampler() # Sampler runs a job on the Bell circuit job = sampler.run(circuits=[bell], parameter_values=[[]], parameters=[[]]) job_result = job.result() print([q.binary_probabilities() for q in job_result.quasi_dists]) # Sampler runs a job on the parameterized circuits job2 = sampler.run( circuits=[pqc, pqc2], parameter_values=[theta1, theta2], parameters=[pqc.parameters, pqc2.parameters]) job_result = job2.result() print([q.binary_probabilities() for q in job_result.quasi_dists]) """ from __future__ import annotations from abc import abstractmethod from collections.abc import Sequence from copy import copy from typing import Generic, TypeVar from qiskit.circuit import QuantumCircuit from qiskit.circuit.parametertable import ParameterView from qiskit.providers import JobV1 as Job from .base_primitive import BasePrimitive T = TypeVar("T", bound=Job) class BaseSampler(BasePrimitive, Generic[T]): """Sampler base class Base class of Sampler that calculates quasi-probabilities of bitstrings from quantum circuits. """ __hash__ = None def __init__( self, *, options: dict | None = None, ): """ Args: options: Default options. """ self._circuits = [] self._parameters = [] super().__init__(options) def run( self, circuits: QuantumCircuit | Sequence[QuantumCircuit], parameter_values: Sequence[float] | Sequence[Sequence[float]] | None = None, **run_options, ) -> T: """Run the job of the sampling of bitstrings. Args: circuits: One of more circuit objects. parameter_values: Parameters to be bound to the circuit. run_options: Backend runtime options used for circuit execution. Returns: The job object of the result of the sampler. The i-th result corresponds to ``circuits[i]`` evaluated with parameters bound as ``parameter_values[i]``. Raises: ValueError: Invalid arguments are given. """ # Singular validation circuits = self._validate_circuits(circuits) parameter_values = self._validate_parameter_values( parameter_values, default=[()] * len(circuits), ) # Cross-validation self._cross_validate_circuits_parameter_values(circuits, parameter_values) # Options run_opts = copy(self.options) run_opts.update_options(**run_options) return self._run( circuits, parameter_values, **run_opts.__dict__, ) @abstractmethod def _run( self, circuits: tuple[QuantumCircuit, ...], parameter_values: tuple[tuple[float, ...], ...], **run_options, ) -> T: raise NotImplementedError("The subclass of BaseSampler must implment `_run` method.") # TODO: validate measurement gates are present @classmethod def _validate_circuits( cls, circuits: Sequence[QuantumCircuit] | QuantumCircuit, ) -> tuple[QuantumCircuit, ...]: circuits = super()._validate_circuits(circuits) for i, circuit in enumerate(circuits): if circuit.num_clbits == 0: raise ValueError( f"The {i}-th circuit does not have any classical bit. " "Sampler requires classical bits, plus measurements " "on the desired qubits." ) return circuits @property def circuits(self) -> tuple[QuantumCircuit, ...]: """Quantum circuits to be sampled. Returns: The quantum circuits to be sampled. """ return tuple(self._circuits) @property def parameters(self) -> tuple[ParameterView, ...]: """Parameters of quantum circuits. Returns: List of the parameters in each quantum circuit. """ return tuple(self._parameters)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2024. # # 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. """ Estimator Pub class """ from __future__ import annotations from numbers import Real from collections.abc import Mapping from typing import Tuple, Union import numpy as np from qiskit import QuantumCircuit from .bindings_array import BindingsArray, BindingsArrayLike from .observables_array import ObservablesArray, ObservablesArrayLike from .shape import ShapedMixin # Public API classes __all__ = ["EstimatorPubLike"] class EstimatorPub(ShapedMixin): """Primitive Unified Bloc for any Estimator primitive. An estimator pub is essentially a tuple ``(circuit, observables, parameter_values, precision)``. If precision is provided this should be used for the target precision of an estimator, if ``precision=None`` the estimator will determine the target precision. """ __slots__ = ("_circuit", "_observables", "_parameter_values", "_precision", "_shape") def __init__( self, circuit: QuantumCircuit, observables: ObservablesArray, parameter_values: BindingsArray | None = None, precision: float | None = None, validate: bool = True, ): """Initialize an estimator pub. Args: circuit: A quantum circuit. observables: An observables array. parameter_values: A bindings array, if the circuit is parametric. precision: An optional target precision for expectation value estimates. validate: Whether to validate arguments during initialization. Raises: ValueError: If the ``observables`` and ``parameter_values`` are not broadcastable, that is, if their shapes, when right-aligned, do not agree or equal 1. """ super().__init__() self._circuit = circuit self._observables = observables self._parameter_values = parameter_values or BindingsArray() self._precision = precision # for ShapedMixin try: # _shape has to be defined to properly be Shaped, so we can't put it in validation self._shape = np.broadcast_shapes(self.observables.shape, self.parameter_values.shape) except ValueError as ex: raise ValueError( f"The observables shape {self.observables.shape} and the " f"parameter values shape {self.parameter_values.shape} are not broadcastable." ) from ex if validate: self.validate() @property def circuit(self) -> QuantumCircuit: """A quantum circuit.""" return self._circuit @property def observables(self) -> ObservablesArray: """An observables array.""" return self._observables @property def parameter_values(self) -> BindingsArray: """A bindings array.""" return self._parameter_values @property def precision(self) -> float | None: """The target precision for expectation value estimates (optional).""" return self._precision @classmethod def coerce(cls, pub: EstimatorPubLike, precision: float | None = None) -> EstimatorPub: """Coerce :class:`~.EstimatorPubLike` into :class:`~.EstimatorPub`. Args: pub: A compatible object for coercion. precision: an optional default precision to use if not already specified by the pub-like object. Returns: An estimator pub. """ # Validate precision kwarg if provided if precision is not None: if not isinstance(precision, Real): raise TypeError(f"precision must be a real number, not {type(precision)}.") if precision < 0: raise ValueError("precision must be non-negative") if isinstance(pub, EstimatorPub): if pub.precision is None and precision is not None: return cls( circuit=pub.circuit, observables=pub.observables, parameter_values=pub.parameter_values, precision=precision, validate=False, # Assume Pub is already validated ) return pub if isinstance(pub, QuantumCircuit): raise ValueError( f"An invalid Estimator pub-like was given ({type(pub)}). " "If you want to run a single pub, you need to wrap it with `[]` like " "`estimator.run([(circuit, observables, param_values)])` " "instead of `estimator.run((circuit, observables, param_values))`." ) if len(pub) not in [2, 3, 4]: raise ValueError( f"The length of pub must be 2, 3 or 4, but length {len(pub)} is given." ) circuit = pub[0] observables = ObservablesArray.coerce(pub[1]) if len(pub) > 2 and pub[2] is not None: values = pub[2] if not isinstance(values, (BindingsArray, Mapping)): values = {tuple(circuit.parameters): values} parameter_values = BindingsArray.coerce(values) else: parameter_values = None if len(pub) > 3 and pub[3] is not None: precision = pub[3] return cls( circuit=circuit, observables=observables, parameter_values=parameter_values, precision=precision, validate=True, ) def validate(self): """Validate the pub.""" if not isinstance(self.circuit, QuantumCircuit): raise TypeError("circuit must be QuantumCircuit.") self.observables.validate() self.parameter_values.validate() if self.precision is not None: if not isinstance(self.precision, Real): raise TypeError(f"precision must be a real number, not {type(self.precision)}.") if self.precision < 0: raise ValueError("precision must be non-negative.") # Cross validate circuits and observables for i, observable in np.ndenumerate(self.observables): num_qubits = len(next(iter(observable))) if self.circuit.num_qubits != num_qubits: raise ValueError( f"The number of qubits of the circuit ({self.circuit.num_qubits}) does " f"not match the number of qubits of the {i}-th observable ({num_qubits})." ) # Cross validate circuits and parameter_values num_parameters = self.parameter_values.num_parameters if num_parameters != self.circuit.num_parameters: raise ValueError( f"The number of values ({num_parameters}) does not match " f"the number of parameters ({self.circuit.num_parameters}) for the circuit." ) EstimatorPubLike = Union[ EstimatorPub, Tuple[QuantumCircuit, ObservablesArrayLike], Tuple[QuantumCircuit, ObservablesArrayLike, BindingsArrayLike], Tuple[QuantumCircuit, ObservablesArrayLike, BindingsArrayLike, Real], ] """A Pub (Primitive Unified Bloc) for an Estimator primitive. A fully specified estimator pub is a tuple ``(circuit, observables, parameter_values, precision)``. If precision is provided this should be used for the target precision of an estimator, if ``precision=None`` the estimator will determine the target precision. .. note:: An Estimator Pub can also be initialized in the following formats which will be converted to the full Pub tuple: * ``(circuit, observables)`` * ``(circuit, observables, parameter_values)`` """
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2024. # # 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. """ Sampler Pub class """ from __future__ import annotations from collections.abc import Mapping from numbers import Integral from typing import Tuple, Union from qiskit import QuantumCircuit from qiskit.circuit import CircuitInstruction from .bindings_array import BindingsArray, BindingsArrayLike from .shape import ShapedMixin # Public API classes __all__ = ["SamplerPubLike"] class SamplerPub(ShapedMixin): """Pub (Primitive Unified Bloc) for a Sampler. Pub is composed of tuple (circuit, parameter_values, shots). If shots are provided this number of shots will be run with the sampler, if ``shots=None`` the number of run shots is determined by the sampler. """ def __init__( self, circuit: QuantumCircuit, parameter_values: BindingsArray | None = None, shots: int | None = None, validate: bool = True, ): """Initialize a sampler pub. Args: circuit: A quantum circuit. parameter_values: A bindings array. shots: A specific number of shots to run with. This value takes precedence over any value owed by or supplied to a sampler. validate: If ``True``, the input data is validated during initialization. """ super().__init__() self._circuit = circuit self._parameter_values = parameter_values or BindingsArray() self._shots = shots self._shape = self._parameter_values.shape if validate: self.validate() @property def circuit(self) -> QuantumCircuit: """A quantum circuit.""" return self._circuit @property def parameter_values(self) -> BindingsArray: """A bindings array.""" return self._parameter_values @property def shots(self) -> int | None: """An specific number of shots to run with (optional). This value takes precedence over any value owed by or supplied to a sampler. """ return self._shots @classmethod def coerce(cls, pub: SamplerPubLike, shots: int | None = None) -> SamplerPub: """Coerce a :class:`~.SamplerPubLike` object into a :class:`~.SamplerPub` instance. Args: pub: An object to coerce. shots: An optional default number of shots to use if not already specified by the pub-like object. Returns: A coerced sampler pub. """ # Validate shots kwarg if provided if shots is not None: if not isinstance(shots, Integral) or isinstance(shots, bool): raise TypeError("shots must be an integer") if shots <= 0: raise ValueError("shots must be positive") if isinstance(pub, SamplerPub): if pub.shots is None and shots is not None: return cls( circuit=pub.circuit, parameter_values=pub.parameter_values, shots=shots, validate=False, # Assume Pub is already validated ) return pub if isinstance(pub, QuantumCircuit): return cls(circuit=pub, shots=shots, validate=True) if isinstance(pub, CircuitInstruction): raise ValueError( f"An invalid Sampler pub-like was given ({type(pub)}). " "If you want to run a single circuit, " "you need to wrap it with `[]` like `sampler.run([circuit])` " "instead of `sampler.run(circuit)`." ) if len(pub) not in [1, 2, 3]: raise ValueError( f"The length of pub must be 1, 2 or 3, but length {len(pub)} is given." ) circuit = pub[0] if len(pub) > 1 and pub[1] is not None: values = pub[1] if not isinstance(values, (BindingsArray, Mapping)): values = {tuple(circuit.parameters): values} parameter_values = BindingsArray.coerce(values) else: parameter_values = None if len(pub) > 2 and pub[2] is not None: shots = pub[2] return cls(circuit=circuit, parameter_values=parameter_values, shots=shots, validate=True) def validate(self): """Validate the pub.""" if not isinstance(self.circuit, QuantumCircuit): raise TypeError("circuit must be QuantumCircuit.") self.parameter_values.validate() if self.shots is not None: if not isinstance(self.shots, Integral) or isinstance(self.shots, bool): raise TypeError("shots must be an integer") if self.shots <= 0: raise ValueError("shots must be positive") # Cross validate circuits and parameter values num_parameters = self.parameter_values.num_parameters if num_parameters != self.circuit.num_parameters: message = ( f"The number of values ({num_parameters}) does not match " f"the number of parameters ({self.circuit.num_parameters}) for the circuit." ) if num_parameters == 0: message += ( " Note that if you want to run a single pub, you need to wrap it with `[]` like " "`sampler.run([(circuit, param_values)])` instead of " "`sampler.run((circuit, param_values))`." ) raise ValueError(message) SamplerPubLike = Union[ QuantumCircuit, Tuple[QuantumCircuit], Tuple[QuantumCircuit, BindingsArrayLike], Tuple[QuantumCircuit, BindingsArrayLike, Union[Integral, None]], ] """A Pub (Primitive Unified Bloc) for a Sampler. A fully specified sample Pub is a tuple ``(circuit, parameter_values, shots)``. If shots are provided this number of shots will be run with the sampler, if ``shots=None`` the number of run shots is determined by the sampler. .. note:: A Sampler Pub can also be initialized in the following formats which will be converted to the full Pub tuple: * ``circuit`` * ``(circuit,)`` * ``(circuit, parameter_values)`` """
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. """Contains functions used by the basic provider simulators. """ from __future__ import annotations from string import ascii_uppercase, ascii_lowercase import numpy as np import qiskit.circuit.library.standard_gates as gates from qiskit.exceptions import QiskitError # Single qubit gates supported by ``single_gate_params``. SINGLE_QUBIT_GATES = { "U": gates.UGate, "u": gates.UGate, "u1": gates.U1Gate, "u2": gates.U2Gate, "u3": gates.U3Gate, "h": gates.HGate, "p": gates.PhaseGate, "s": gates.SGate, "sdg": gates.SdgGate, "sx": gates.SXGate, "sxdg": gates.SXdgGate, "t": gates.TGate, "tdg": gates.TdgGate, "x": gates.XGate, "y": gates.YGate, "z": gates.ZGate, "id": gates.IGate, "i": gates.IGate, "r": gates.RGate, "rx": gates.RXGate, "ry": gates.RYGate, "rz": gates.RZGate, } def single_gate_matrix(gate: str, params: list[float] | None = None) -> np.ndarray: """Get the matrix for a single qubit. Args: gate: the single qubit gate name params: the operation parameters op['params'] Returns: array: A numpy array representing the matrix Raises: QiskitError: If a gate outside the supported set is passed in for the ``Gate`` argument. """ if params is None: params = [] if gate in SINGLE_QUBIT_GATES: gc = SINGLE_QUBIT_GATES[gate] else: raise QiskitError("Gate is not a valid basis gate for this simulator: %s" % gate) return gc(*params).to_matrix() # Two qubit gates WITHOUT parameters: name -> matrix TWO_QUBIT_GATES = { "CX": gates.CXGate().to_matrix(), "cx": gates.CXGate().to_matrix(), "ecr": gates.ECRGate().to_matrix(), "cy": gates.CYGate().to_matrix(), "cz": gates.CZGate().to_matrix(), "swap": gates.SwapGate().to_matrix(), "iswap": gates.iSwapGate().to_matrix(), "ch": gates.CHGate().to_matrix(), "cs": gates.CSGate().to_matrix(), "csdg": gates.CSdgGate().to_matrix(), "csx": gates.CSXGate().to_matrix(), "dcx": gates.DCXGate().to_matrix(), } # Two qubit gates WITH parameters: name -> class TWO_QUBIT_GATES_WITH_PARAMETERS = { "cp": gates.CPhaseGate, "crx": gates.CRXGate, "cry": gates.CRYGate, "crz": gates.CRZGate, "cu": gates.CUGate, "cu1": gates.CU1Gate, "cu3": gates.CU3Gate, "rxx": gates.RXXGate, "ryy": gates.RYYGate, "rzz": gates.RZZGate, "rzx": gates.RZXGate, "xx_minus_yy": gates.XXMinusYYGate, "xx_plus_yy": gates.XXPlusYYGate, } # Three qubit gates: name -> matrix THREE_QUBIT_GATES = { "ccx": gates.CCXGate().to_matrix(), "ccz": gates.CCZGate().to_matrix(), "rccx": gates.RCCXGate().to_matrix(), "cswap": gates.CSwapGate().to_matrix(), } def einsum_matmul_index(gate_indices: list[int], number_of_qubits: int) -> str: """Return the index string for Numpy.einsum matrix-matrix multiplication. The returned indices are to perform a matrix multiplication A.B where the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and M <= N, and identity matrices are implied on the subsystems where A has no support on B. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Right indices for the N-qubit input and output tensor tens_r = ascii_uppercase[:number_of_qubits] # Combine indices into matrix multiplication string format # for numpy.einsum function return f"{mat_l}{mat_r}, {tens_lin}{tens_r}->{tens_lout}{tens_r}" def einsum_vecmul_index(gate_indices: list[int], number_of_qubits: int) -> str: """Return the index string for Numpy.einsum matrix-vector multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Combine indices into matrix multiplication string format # for numpy.einsum function return f"{mat_l}{mat_r}, {tens_lin}->{tens_lout}" def _einsum_matmul_index_helper( gate_indices: list[int], number_of_qubits: int ) -> tuple[str, str, str, str]: """Return the index string for Numpy.einsum matrix multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for that may be combined into a Numpy.einsum function string. Raises: QiskitError: if the total number of qubits plus the number of contracted indices is greater than 26. """ # Since we use ASCII alphabet for einsum index labels we are limited # to 26 total free left (lowercase) and 26 right (uppercase) indexes. # The rank of the contracted tensor reduces this as we need to use that # many characters for the contracted indices if len(gate_indices) + number_of_qubits > 26: raise QiskitError("Total number of free indexes limited to 26") # Indices for N-qubit input tensor tens_in = ascii_lowercase[:number_of_qubits] # Indices for the N-qubit output tensor tens_out = list(tens_in) # Left and right indices for the M-qubit multiplying tensor mat_left = "" mat_right = "" # Update left indices for mat and output for pos, idx in enumerate(reversed(gate_indices)): mat_left += ascii_lowercase[-1 - pos] mat_right += tens_in[-1 - idx] tens_out[-1 - idx] = ascii_lowercase[-1 - pos] tens_out = "".join(tens_out) # Combine indices into matrix multiplication string format # for numpy.einsum function return mat_left, mat_right, tens_in, tens_out
https://github.com/swe-train/qiskit__qiskit
swe-train
import sys import os current_dir = os.getcwd() sys.path.append(current_dir) from quantum_circuit import QuantumCircuit # import qiskit.providers.fake_provider from qiskit.transpiler import CouplingMap import qiskit_ibm_runtime.fake_provider from Backend.backend import Backend class FakeBackend(Backend): def __init__(self, backend_name : str) -> None: self.backend = FakeBackend.get_ibm_fake_backend(backend_name=backend_name) @staticmethod def get_ibm_fake_backend_name_list() -> list[str]: ibm_dir = dir(qiskit_ibm_runtime.fake_provider) return [val for val in ibm_dir if '__' not in val and 'Fake' in val] @staticmethod def get_ibm_fake_backend(backend_name : str): try: return getattr(qiskit_ibm_runtime.fake_provider, backend_name)() except: pass fake_backend_name = FakeBackend.get_ibm_fake_backend_name_list() for backend in fake_backend_name: backend = FakeBackend.get_ibm_fake_backend(backend) if backend is not None: try: if backend.name == backend_name: return backend except: pass return None @staticmethod def get_ibm_fake_backend_names_with_limit(min_qubit : int = 1, max_qubit: int = float('inf')) -> list[str]: limited_backend = [] fake_backend_name = FakeBackend.get_ibm_fake_backend_name_list() for backend in fake_backend_name: backend = FakeBackend.get_ibm_fake_backend(backend) if backend is not None: try: num_qubit = backend.num_qubits if num_qubit >= min_qubit and num_qubit <= max_qubit: limited_backend.append(backend.name) except: pass return limited_backend if __name__ == "__main__": print(FakeBackend.get_ibm_fake_backend_name_list()) backend = FakeBackend('fake_auckland') qc = QuantumCircuit(2) qc.x(0) qc.h(1) qc.measure_all() print(qc.draw()) job = backend.run(qc) print(job.result()) qc_transpile = backend.traspile_qiskit(qc)[0] print(qc_transpile.draw()) job = backend.run(qc_transpile) print(job.result())
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2024. # # 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. """Generic BackendV2 class that with a simulated ``run``.""" from __future__ import annotations import warnings from collections.abc import Iterable import numpy as np from qiskit import pulse from qiskit.pulse.instruction_schedule_map import InstructionScheduleMap from qiskit.circuit import QuantumCircuit, Instruction from qiskit.circuit.controlflow import ( IfElseOp, WhileLoopOp, ForLoopOp, SwitchCaseOp, BreakLoopOp, ContinueLoopOp, ) from qiskit.circuit.library.standard_gates import get_standard_gate_name_mapping from qiskit.exceptions import QiskitError from qiskit.transpiler import CouplingMap, Target, InstructionProperties, QubitProperties from qiskit.providers import Options from qiskit.providers.basic_provider import BasicSimulator from qiskit.providers.backend import BackendV2 from qiskit.providers.models import ( PulseDefaults, Command, ) from qiskit.qobj import PulseQobjInstruction, PulseLibraryItem from qiskit.utils import optionals as _optionals # Noise default values/ranges for duration and error of supported # instructions. There are two possible formats: # - (min_duration, max_duration, min_error, max_error), # if the defaults are ranges. # - (duration, error), if the defaults are fixed values. _NOISE_DEFAULTS = { "cx": (7.992e-08, 8.99988e-07, 1e-5, 5e-3), "ecr": (7.992e-08, 8.99988e-07, 1e-5, 5e-3), "cz": (7.992e-08, 8.99988e-07, 1e-5, 5e-3), "id": (2.997e-08, 5.994e-08, 9e-5, 1e-4), "rz": (0.0, 0.0), "sx": (2.997e-08, 5.994e-08, 9e-5, 1e-4), "x": (2.997e-08, 5.994e-08, 9e-5, 1e-4), "measure": (6.99966e-07, 1.500054e-06, 1e-5, 5e-3), "delay": (None, None), "reset": (None, None), } # Fallback values for gates with unknown noise default ranges. _NOISE_DEFAULTS_FALLBACK = { "1-q": (2.997e-08, 5.994e-08, 9e-5, 1e-4), "multi-q": (7.992e-08, 8.99988e-07, 5e-3), } # Ranges to sample qubit properties from. _QUBIT_PROPERTIES = { "dt": 0.222e-9, "t1": (100e-6, 200e-6), "t2": (100e-6, 200e-6), "frequency": (5e9, 5.5e9), } # The number of samples determines the pulse durations of the corresponding # instructions. This default defines pulses with durations in multiples of # 16 dt for consistency with the pulse granularity of real IBM devices, but # keeps the number smaller than what would be realistic for # manageability. If needed, more realistic durations could be added in the # future (order of 160dt for 1q gates, 1760dt for 2q gates and measure). _PULSE_LIBRARY = [ PulseLibraryItem(name="pulse_1", samples=np.linspace(0, 1.0, 16, dtype=np.complex128)), # 16dt PulseLibraryItem(name="pulse_2", samples=np.linspace(0, 1.0, 32, dtype=np.complex128)), # 32dt PulseLibraryItem(name="pulse_3", samples=np.linspace(0, 1.0, 64, dtype=np.complex128)), # 64dt ] class GenericBackendV2(BackendV2): """Generic :class:`~.BackendV2` implementation with a configurable constructor. This class will return a :class:`~.BackendV2` instance that runs on a local simulator (in the spirit of fake backends) and contains all the necessary information to test backend-interfacing components, such as the transpiler. A :class:`.GenericBackendV2` instance can be constructed from as little as a specified ``num_qubits``, but users can additionally configure the basis gates, coupling map, ability to run dynamic circuits (control flow instructions), instruction calibrations and dtm. The remainder of the backend properties are generated by randomly sampling from default ranges extracted from historical IBM backend data. The seed for this random generation can be fixed to ensure the reproducibility of the backend output. This backend only supports gates in the standard library, if you need a more flexible backend, there is always the option to directly instantiate a :class:`.Target` object to use for transpilation. """ def __init__( self, num_qubits: int, basis_gates: list[str] | None = None, *, coupling_map: list[list[int]] | CouplingMap | None = None, control_flow: bool = False, calibrate_instructions: bool | InstructionScheduleMap | None = None, dtm: float | None = None, seed: int | None = None, ): """ Args: num_qubits: Number of qubits that will be used to construct the backend's target. Note that, while there is no limit in the size of the target that can be constructed, this backend runs on local noisy simulators, and these might present limitations in the number of qubits that can be simulated. basis_gates: List of basis gate names to be supported by the target. These must be part of the standard qiskit circuit library. The default set of basis gates is ``["id", "rz", "sx", "x", "cx"]`` The ``"reset"``, ``"delay"``, and ``"measure"`` instructions are always supported by default, even if not specified via ``basis_gates``. coupling_map: Optional coupling map for the backend. Multiple formats are supported: #. :class:`~.CouplingMap` instance #. List, must be given as an edge list representing the two qubit interactions supported by the backend, for example: ``[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]`` If ``coupling_map`` is specified, it must match the number of qubits specified in ``num_qubits``. If ``coupling_map`` is not specified, a fully connected coupling map will be generated with ``num_qubits`` qubits. control_flow: Flag to enable control flow directives on the target (defaults to False). calibrate_instructions: Instruction calibration settings, this argument supports both boolean and :class:`.InstructionScheduleMap` as input types, and is ``None`` by default: #. If ``calibrate_instructions==None``, no calibrations will be added to the target. #. If ``calibrate_instructions==True``, all gates will be calibrated for all qubits using the default pulse schedules generated internally. #. If ``calibrate_instructions==False``, all gates will be "calibrated" for all qubits with an empty pulse schedule. #. If an :class:`.InstructionScheduleMap` instance is given, the calibrations in this instruction schedule map will be appended to the target instead of the default pulse schedules (this allows for custom calibrations). dtm: System time resolution of output signals in nanoseconds. None by default. seed: Optional seed for generation of default values. """ super().__init__( provider=None, name=f"generic_backend_{num_qubits}q", description=f"This is a device with {num_qubits} qubits and generic settings.", backend_version="", ) self._sim = None self._rng = np.random.default_rng(seed=seed) self._dtm = dtm self._num_qubits = num_qubits self._control_flow = control_flow self._calibrate_instructions = calibrate_instructions self._supported_gates = get_standard_gate_name_mapping() if coupling_map is None: self._coupling_map = CouplingMap().from_full(num_qubits) else: if isinstance(coupling_map, CouplingMap): self._coupling_map = coupling_map else: self._coupling_map = CouplingMap(coupling_map) if num_qubits != self._coupling_map.size(): raise QiskitError( f"The number of qubits (got {num_qubits}) must match " f"the size of the provided coupling map (got {self._coupling_map.size()})." ) self._basis_gates = ( basis_gates if basis_gates is not None else ["cx", "id", "rz", "sx", "x"] ) for name in ["reset", "delay", "measure"]: if name not in self._basis_gates: self._basis_gates.append(name) self._build_generic_target() self._build_default_channels() @property def target(self): return self._target @property def max_circuits(self): return None @property def dtm(self) -> float: """Return the system time resolution of output signals""" # converting `dtm` from nanoseconds to seconds return self._dtm * 1e-9 if self._dtm is not None else None @property def meas_map(self) -> list[list[int]]: return self._target.concurrent_measurements def _build_default_channels(self) -> None: channels_map = { "acquire": {(i,): [pulse.AcquireChannel(i)] for i in range(self.num_qubits)}, "drive": {(i,): [pulse.DriveChannel(i)] for i in range(self.num_qubits)}, "measure": {(i,): [pulse.MeasureChannel(i)] for i in range(self.num_qubits)}, "control": { (edge): [pulse.ControlChannel(i)] for i, edge in enumerate(self._coupling_map) }, } setattr(self, "channels_map", channels_map) def _get_noise_defaults(self, name: str, num_qubits: int) -> tuple: """Return noise default values/ranges for duration and error of supported instructions. There are two possible formats: - (min_duration, max_duration, min_error, max_error), if the defaults are ranges. - (duration, error), if the defaults are fixed values. """ if name in _NOISE_DEFAULTS: return _NOISE_DEFAULTS[name] if num_qubits == 1: return _NOISE_DEFAULTS_FALLBACK["1-q"] return _NOISE_DEFAULTS_FALLBACK["multi-q"] def _get_calibration_sequence( self, inst: str, num_qubits: int, qargs: tuple[int] ) -> list[PulseQobjInstruction]: """Return calibration pulse sequence for given instruction (defined by name and num_qubits) acting on qargs. """ pulse_library = _PULSE_LIBRARY # Note that the calibration pulses are different for # 1q gates vs 2q gates vs measurement instructions. if inst == "measure": sequence = [ PulseQobjInstruction( name="acquire", duration=1792, t0=0, qubits=qargs, memory_slot=qargs, ) ] + [PulseQobjInstruction(name=pulse_library[1].name, ch=f"m{i}", t0=0) for i in qargs] return sequence if num_qubits == 1: return [ PulseQobjInstruction(name="fc", ch=f"u{qargs[0]}", t0=0, phase="-P0"), PulseQobjInstruction(name=pulse_library[0].name, ch=f"d{qargs[0]}", t0=0), ] return [ PulseQobjInstruction(name=pulse_library[1].name, ch=f"d{qargs[0]}", t0=0), PulseQobjInstruction(name=pulse_library[2].name, ch=f"u{qargs[0]}", t0=0), PulseQobjInstruction(name=pulse_library[1].name, ch=f"d{qargs[1]}", t0=0), PulseQobjInstruction(name="fc", ch=f"d{qargs[1]}", t0=0, phase=2.1), ] def _generate_calibration_defaults(self) -> PulseDefaults: """Generate pulse calibration defaults as specified with `self._calibrate_instructions`. If `self._calibrate_instructions` is True, the pulse schedules will be generated from a series of default calibration sequences. If `self._calibrate_instructions` is False, the pulse schedules will contain empty calibration sequences, but still be generated and added to the target. """ # If self._calibrate_instructions==True, this method # will generate default pulse schedules for all gates in self._basis_gates, # except for `delay` and `reset`. calibration_buffer = self._basis_gates.copy() for inst in ["delay", "reset"]: calibration_buffer.remove(inst) # List of calibration commands (generated from sequences of PulseQobjInstructions) # corresponding to each calibrated instruction. Note that the calibration pulses # are different for 1q gates vs 2q gates vs measurement instructions. cmd_def = [] for inst in calibration_buffer: num_qubits = self._supported_gates[inst].num_qubits qarg_set = self._coupling_map if num_qubits > 1 else list(range(self.num_qubits)) if inst == "measure": cmd_def.append( Command( name=inst, qubits=qarg_set, sequence=( self._get_calibration_sequence(inst, num_qubits, qarg_set) if self._calibrate_instructions else [] ), ) ) else: for qarg in qarg_set: qubits = [qarg] if num_qubits == 1 else qarg cmd_def.append( Command( name=inst, qubits=qubits, sequence=( self._get_calibration_sequence(inst, num_qubits, qubits) if self._calibrate_instructions else [] ), ) ) qubit_freq_est = np.random.normal(4.8, scale=0.01, size=self.num_qubits).tolist() meas_freq_est = np.linspace(6.4, 6.6, self.num_qubits).tolist() return PulseDefaults( qubit_freq_est=qubit_freq_est, meas_freq_est=meas_freq_est, buffer=0, pulse_library=_PULSE_LIBRARY, cmd_def=cmd_def, ) def _build_generic_target(self): """This method generates a :class:`~.Target` instance with default qubit, instruction and calibration properties. """ # the qubit properties are sampled from default ranges properties = _QUBIT_PROPERTIES self._target = Target( description=f"Generic Target with {self._num_qubits} qubits", num_qubits=self._num_qubits, dt=properties["dt"], qubit_properties=[ QubitProperties( t1=self._rng.uniform(properties["t1"][0], properties["t1"][1]), t2=self._rng.uniform(properties["t2"][0], properties["t2"][1]), frequency=self._rng.uniform( properties["frequency"][0], properties["frequency"][1] ), ) for _ in range(self._num_qubits) ], concurrent_measurements=[list(range(self._num_qubits))], ) # Generate instruction schedule map with calibrations to add to target. calibration_inst_map = None if self._calibrate_instructions is not None: if isinstance(self._calibrate_instructions, InstructionScheduleMap): calibration_inst_map = self._calibrate_instructions else: defaults = self._generate_calibration_defaults() calibration_inst_map = defaults.instruction_schedule_map # Iterate over gates, generate noise params from defaults, # and add instructions, noise and calibrations to target. for name in self._basis_gates: if name not in self._supported_gates: raise QiskitError( f"Provided basis gate {name} is not an instruction " f"in the standard qiskit circuit library." ) gate = self._supported_gates[name] noise_params = self._get_noise_defaults(name, gate.num_qubits) self._add_noisy_instruction_to_target(gate, noise_params, calibration_inst_map) if self._control_flow: self._target.add_instruction(IfElseOp, name="if_else") self._target.add_instruction(WhileLoopOp, name="while_loop") self._target.add_instruction(ForLoopOp, name="for_loop") self._target.add_instruction(SwitchCaseOp, name="switch_case") self._target.add_instruction(BreakLoopOp, name="break") self._target.add_instruction(ContinueLoopOp, name="continue") def _add_noisy_instruction_to_target( self, instruction: Instruction, noise_params: tuple[float, ...] | None, calibration_inst_map: InstructionScheduleMap | None, ) -> None: """Add instruction properties to target for specified instruction. Args: instruction: Instance of instruction to be added to the target noise_params: Error and duration noise values/ranges to include in instruction properties. calibration_inst_map: Instruction schedule map with calibration defaults """ qarg_set = self._coupling_map if instruction.num_qubits > 1 else range(self.num_qubits) props = {} for qarg in qarg_set: try: qargs = tuple(qarg) except TypeError: qargs = (qarg,) duration, error = ( noise_params if len(noise_params) == 2 else (self._rng.uniform(*noise_params[:2]), self._rng.uniform(*noise_params[2:])) ) if ( calibration_inst_map is not None and instruction.name not in ["reset", "delay"] and qarg in calibration_inst_map.qubits_with_instruction(instruction.name) ): # Do NOT call .get method. This parses Qobj immediately. # This operation is computationally expensive and should be bypassed. calibration_entry = calibration_inst_map._get_calibration_entry( instruction.name, qargs ) else: calibration_entry = None if duration is not None and len(noise_params) > 2: # Ensure exact conversion of duration from seconds to dt dt = _QUBIT_PROPERTIES["dt"] rounded_duration = round(duration / dt) * dt # Clamp rounded duration to be between min and max values duration = max(noise_params[0], min(rounded_duration, noise_params[1])) props.update({qargs: InstructionProperties(duration, error, calibration_entry)}) self._target.add_instruction(instruction, props) # The "measure" instruction calibrations need to be added qubit by qubit, once the # instruction has been added to the target. if calibration_inst_map is not None and instruction.name == "measure": for qarg in calibration_inst_map.qubits_with_instruction(instruction.name): try: qargs = tuple(qarg) except TypeError: qargs = (qarg,) # Do NOT call .get method. This parses Qobj immediately. # This operation is computationally expensive and should be bypassed. calibration_entry = calibration_inst_map._get_calibration_entry( instruction.name, qargs ) for qubit in qargs: if qubit < self.num_qubits: self._target[instruction.name][(qubit,)].calibration = calibration_entry def run(self, run_input, **options): """Run on the backend using a simulator. This method runs circuit jobs (an individual or a list of :class:`~.QuantumCircuit` ) and pulse jobs (an individual or a list of :class:`~.Schedule` or :class:`~.ScheduleBlock`) using :class:`~.BasicSimulator` or Aer simulator and returns a :class:`~qiskit.providers.Job` object. If qiskit-aer is installed, jobs will be run using the ``AerSimulator`` with noise model of the backend. Otherwise, jobs will be run using the ``BasicSimulator`` simulator without noise. Noisy simulations of pulse jobs are not yet supported in :class:`~.GenericBackendV2`. Args: run_input (QuantumCircuit or Schedule or ScheduleBlock or list): An individual or a list of :class:`~qiskit.circuit.QuantumCircuit`, :class:`~qiskit.pulse.ScheduleBlock`, or :class:`~qiskit.pulse.Schedule` objects to run on the backend. options: Any kwarg options to pass to the backend for running the config. If a key is also present in the options attribute/object, then the expectation is that the value specified will be used instead of what's set in the options object. Returns: Job: The job object for the run Raises: QiskitError: If a pulse job is supplied and qiskit_aer is not installed. """ circuits = run_input pulse_job = None if isinstance(circuits, (pulse.Schedule, pulse.ScheduleBlock)): pulse_job = True elif isinstance(circuits, QuantumCircuit): pulse_job = False elif isinstance(circuits, list): if circuits: if all(isinstance(x, (pulse.Schedule, pulse.ScheduleBlock)) for x in circuits): pulse_job = True elif all(isinstance(x, QuantumCircuit) for x in circuits): pulse_job = False if pulse_job is None: # submitted job is invalid raise QiskitError( "Invalid input object %s, must be either a " "QuantumCircuit, Schedule, or a list of either" % circuits ) if pulse_job: # pulse job raise QiskitError("Pulse simulation is currently not supported for V2 backends.") # circuit job if not _optionals.HAS_AER: warnings.warn("Aer not found using BasicSimulator and no noise", RuntimeWarning) if self._sim is None: self._setup_sim() self._sim._options = self._options job = self._sim.run(circuits, **options) return job def _setup_sim(self) -> None: if _optionals.HAS_AER: from qiskit_aer import AerSimulator from qiskit_aer.noise import NoiseModel self._sim = AerSimulator() noise_model = NoiseModel.from_backend(self) self._sim.set_options(noise_model=noise_model) # Update backend default too to avoid overwriting # it when run() is called self.set_options(noise_model=noise_model) else: self._sim = BasicSimulator() @classmethod def _default_options(cls) -> Options: with warnings.catch_warnings(): # TODO remove catch once aer release without Provider ABC warnings.filterwarnings( "ignore", category=DeprecationWarning, message=".+abstract Provider and ProviderV1.+", ) if _optionals.HAS_AER: from qiskit_aer import AerSimulator return AerSimulator._default_options() else: return BasicSimulator._default_options() def drive_channel(self, qubit: int): drive_channels_map = getattr(self, "channels_map", {}).get("drive", {}) qubits = (qubit,) if qubits in drive_channels_map: return drive_channels_map[qubits][0] return None def measure_channel(self, qubit: int): measure_channels_map = getattr(self, "channels_map", {}).get("measure", {}) qubits = (qubit,) if qubits in measure_channels_map: return measure_channels_map[qubits][0] return None def acquire_channel(self, qubit: int): acquire_channels_map = getattr(self, "channels_map", {}).get("acquire", {}) qubits = (qubit,) if qubits in acquire_channels_map: return acquire_channels_map[qubits][0] return None def control_channel(self, qubits: Iterable[int]): control_channels_map = getattr(self, "channels_map", {}).get("control", {}) qubits = tuple(qubits) if qubits in control_channels_map: return control_channels_map[qubits] return []
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. r""" .. _pulse_builder: ============= Pulse Builder ============= .. We actually want people to think of these functions as being defined within the ``qiskit.pulse`` namespace, not the submodule ``qiskit.pulse.builder``. .. currentmodule: qiskit.pulse Use the pulse builder DSL to write pulse programs with an imperative syntax. .. warning:: The pulse builder interface is still in active development. It may have breaking API changes without deprecation warnings in future releases until otherwise indicated. The pulse builder provides an imperative API for writing pulse programs with less difficulty than the :class:`~qiskit.pulse.Schedule` API. It contextually constructs a pulse schedule and then emits the schedule for execution. For example, to play a series of pulses on channels is as simple as: .. plot:: :include-source: from qiskit import pulse dc = pulse.DriveChannel d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) with pulse.build(name='pulse_programming_in') as pulse_prog: pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) pulse_prog.draw() To begin pulse programming we must first initialize our program builder context with :func:`build`, after which we can begin adding program statements. For example, below we write a simple program that :func:`play`\s a pulse: .. plot:: :include-source: from qiskit import execute, pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 1.0), d0) pulse_prog.draw() The builder initializes a :class:`.pulse.Schedule`, ``pulse_prog`` and then begins to construct the program within the context. The output pulse schedule will survive after the context is exited and can be executed like a normal Qiskit schedule using ``qiskit.execute(pulse_prog, backend)``. Pulse programming has a simple imperative style. This leaves the programmer to worry about the raw experimental physics of pulse programming and not constructing cumbersome data structures. We can optionally pass a :class:`~qiskit.providers.Backend` to :func:`build` to enable enhanced functionality. Below, we prepare a Bell state by automatically compiling the required pulses from their gate-level representations, while simultaneously applying a long decoupling pulse to a neighboring qubit. We terminate the experiment with a measurement to observe the state we prepared. This program which mixes circuits and pulses will be automatically lowered to be run as a pulse program: .. plot:: :include-source: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q # TODO: This example should use a real mock backend. backend = FakeOpenPulse3Q() d2 = pulse.DriveChannel(2) with pulse.build(backend) as bell_prep: pulse.u2(0, math.pi, 0) pulse.cx(0, 1) with pulse.build(backend) as decoupled_bell_prep_and_measure: # We call our bell state preparation schedule constructed above. with pulse.align_right(): pulse.call(bell_prep) pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2) pulse.barrier(0, 1, 2) registers = pulse.measure_all() decoupled_bell_prep_and_measure.draw() With the pulse builder we are able to blend programming on qubits and channels. While the pulse schedule is based on instructions that operate on channels, the pulse builder automatically handles the mapping from qubits to channels for you. In the example below we demonstrate some more features of the pulse builder: .. code-block:: import math from qiskit import pulse, QuantumCircuit from qiskit.pulse import library from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: # Create a pulse. gaussian_pulse = library.gaussian(10, 1.0, 2) # Get the qubit's corresponding drive channel from the backend. d0 = pulse.drive_channel(0) d1 = pulse.drive_channel(1) # Play a pulse at t=0. pulse.play(gaussian_pulse, d0) # Play another pulse directly after the previous pulse at t=10. pulse.play(gaussian_pulse, d0) # The default scheduling behavior is to schedule pulses in parallel # across channels. For example, the statement below # plays the same pulse on a different channel at t=0. pulse.play(gaussian_pulse, d1) # We also provide pulse scheduling alignment contexts. # The default alignment context is align_left. # The sequential context schedules pulse instructions sequentially in time. # This context starts at t=10 due to earlier pulses above. with pulse.align_sequential(): pulse.play(gaussian_pulse, d0) # Play another pulse after at t=20. pulse.play(gaussian_pulse, d1) # We can also nest contexts as each instruction is # contained in its local scheduling context. # The output of a child context is a context-schedule # with the internal instructions timing fixed relative to # one another. This is schedule is then called in the parent context. # Context starts at t=30. with pulse.align_left(): # Start at t=30. pulse.play(gaussian_pulse, d0) # Start at t=30. pulse.play(gaussian_pulse, d1) # Context ends at t=40. # Alignment context where all pulse instructions are # aligned to the right, ie., as late as possible. with pulse.align_right(): # Shift the phase of a pulse channel. pulse.shift_phase(math.pi, d1) # Starts at t=40. pulse.delay(100, d0) # Ends at t=140. # Starts at t=130. pulse.play(gaussian_pulse, d1) # Ends at t=140. # Acquire data for a qubit and store in a memory slot. pulse.acquire(100, 0, pulse.MemorySlot(0)) # We also support a variety of macros for common operations. # Measure all qubits. pulse.measure_all() # Delay on some qubits. # This requires knowledge of which channels belong to which qubits. # delay for 100 cycles on qubits 0 and 1. pulse.delay_qubits(100, 0, 1) # Call a quantum circuit. The pulse builder lazily constructs a quantum # circuit which is then transpiled and scheduled before inserting into # a pulse schedule. # NOTE: Quantum register indices correspond to physical qubit indices. qc = QuantumCircuit(2, 2) qc.cx(0, 1) pulse.call(qc) # Calling a small set of standard gates and decomposing to pulses is # also supported with more natural syntax. pulse.u3(0, math.pi, 0, 0) pulse.cx(0, 1) # It is also be possible to call a preexisting schedule tmp_sched = pulse.Schedule() tmp_sched += pulse.Play(gaussian_pulse, d0) pulse.call(tmp_sched) # We also support: # frequency instructions pulse.set_frequency(5.0e9, d0) # phase instructions pulse.shift_phase(0.1, d0) # offset contexts with pulse.phase_offset(math.pi, d0): pulse.play(gaussian_pulse, d0) The above is just a small taste of what is possible with the builder. See the rest of the module documentation for more information on its capabilities. .. autofunction:: build Channels ======== Methods to return the correct channels for the respective qubit indices. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) print(d0) .. parsed-literal:: DriveChannel(0) .. autofunction:: acquire_channel .. autofunction:: control_channels .. autofunction:: drive_channel .. autofunction:: measure_channel Instructions ============ Pulse instructions are available within the builder interface. Here's an example: .. plot:: :include-source: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.delay(20, d0) pulse.shift_phase(3.14/2, d0) pulse.set_phase(3.14, d0) pulse.shift_frequency(1e7, d0) pulse.set_frequency(5e9, d0) with pulse.build() as temp_sched: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0) pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0) pulse.call(temp_sched) pulse.acquire(30, a0, pulse.MemorySlot(0)) drive_sched.draw() .. autofunction:: acquire .. autofunction:: barrier .. autofunction:: call .. autofunction:: delay .. autofunction:: play .. autofunction:: reference .. autofunction:: set_frequency .. autofunction:: set_phase .. autofunction:: shift_frequency .. autofunction:: shift_phase .. autofunction:: snapshot Contexts ======== Builder aware contexts that modify the construction of a pulse program. For example an alignment context like :func:`align_right` may be used to align all pulses as late as possible in a pulse program. .. plot:: :include-source: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog.draw() .. autofunction:: align_equispaced .. autofunction:: align_func .. autofunction:: align_left .. autofunction:: align_right .. autofunction:: align_sequential .. autofunction:: circuit_scheduler_settings .. autofunction:: frequency_offset .. autofunction:: phase_offset .. autofunction:: transpiler_settings Macros ====== Macros help you add more complex functionality to your pulse program. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as measure_sched: mem_slot = pulse.measure(0) print(mem_slot) .. parsed-literal:: MemorySlot(0) .. autofunction:: measure .. autofunction:: measure_all .. autofunction:: delay_qubits Circuit Gates ============= To use circuit level gates within your pulse program call a circuit with :func:`call`. .. warning:: These will be removed in future versions with the release of a circuit builder interface in which it will be possible to calibrate a gate in terms of pulses and use that gate in a circuit. .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as u3_sched: pulse.u3(math.pi, 0, math.pi, 0) .. autofunction:: cx .. autofunction:: u1 .. autofunction:: u2 .. autofunction:: u3 .. autofunction:: x Utilities ========= The utility functions can be used to gather attributes about the backend and modify how the program is built. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as u3_sched: print('Number of qubits in backend: {}'.format(pulse.num_qubits())) samples = 160 print('There are {} samples in {} seconds'.format( samples, pulse.samples_to_seconds(160))) seconds = 1e-6 print('There are {} seconds in {} samples.'.format( seconds, pulse.seconds_to_samples(1e-6))) .. parsed-literal:: Number of qubits in backend: 1 There are 160 samples in 3.5555555555555554e-08 seconds There are 1e-06 seconds in 4500 samples. .. autofunction:: active_backend .. autofunction:: active_transpiler_settings .. autofunction:: active_circuit_scheduler_settings .. autofunction:: num_qubits .. autofunction:: qubit_channels .. autofunction:: samples_to_seconds .. autofunction:: seconds_to_samples """ import collections import contextvars import functools import itertools import uuid import warnings from contextlib import contextmanager from functools import singledispatchmethod from typing import ( Any, Callable, ContextManager, Dict, Iterable, List, Mapping, Optional, Set, Tuple, TypeVar, Union, NewType, ) import numpy as np from qiskit import circuit from qiskit.circuit.library import standard_gates as gates from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType from qiskit.pulse import ( channels as chans, configuration, exceptions, instructions, macros, library, transforms, ) from qiskit.providers.backend import BackendV2 from qiskit.pulse.instructions import directives from qiskit.pulse.schedule import Schedule, ScheduleBlock from qiskit.pulse.transforms.alignments import AlignmentKind #: contextvars.ContextVar[BuilderContext]: active builder BUILDER_CONTEXTVAR = contextvars.ContextVar("backend") T = TypeVar("T") StorageLocation = NewType("StorageLocation", Union[chans.MemorySlot, chans.RegisterSlot]) def _compile_lazy_circuit_before(function: Callable[..., T]) -> Callable[..., T]: """Decorator thats schedules and calls the lazily compiled circuit before executing the decorated builder method.""" @functools.wraps(function) def wrapper(self, *args, **kwargs): self._compile_lazy_circuit() return function(self, *args, **kwargs) return wrapper def _requires_backend(function: Callable[..., T]) -> Callable[..., T]: """Decorator a function to raise if it is called without a builder with a set backend. """ @functools.wraps(function) def wrapper(self, *args, **kwargs): if self.backend is None: raise exceptions.BackendNotSet( 'This function requires the builder to have a "backend" set.' ) return function(self, *args, **kwargs) return wrapper class _PulseBuilder: """Builder context class.""" __alignment_kinds__ = { "left": transforms.AlignLeft(), "right": transforms.AlignRight(), "sequential": transforms.AlignSequential(), } def __init__( self, backend=None, block: Optional[ScheduleBlock] = None, name: Optional[str] = None, default_alignment: Union[str, AlignmentKind] = "left", default_transpiler_settings: Mapping = None, default_circuit_scheduler_settings: Mapping = None, ): """Initialize the builder context. .. note:: At some point we may consider incorporating the builder into the :class:`~qiskit.pulse.Schedule` class. However, the risk of this is tying the user interface to the intermediate representation. For now we avoid this at the cost of some code duplication. Args: backend (Backend): Input backend to use in builder. If not set certain functionality will be unavailable. block: Initital ``ScheduleBlock`` to build on. name: Name of pulse program to be built. default_alignment: Default scheduling alignment for builder. One of ``left``, ``right``, ``sequential`` or an instance of :class:`~qiskit.pulse.transforms.alignments.AlignmentKind` subclass. default_transpiler_settings: Default settings for the transpiler. default_circuit_scheduler_settings: Default settings for the circuit to pulse scheduler. Raises: PulseError: When invalid ``default_alignment`` or `block` is specified. """ #: Backend: Backend instance for context builder. self._backend = backend #: Union[None, ContextVar]: Token for this ``_PulseBuilder``'s ``ContextVar``. self._backend_ctx_token = None #: QuantumCircuit: Lazily constructed quantum circuit self._lazy_circuit = None #: Dict[str, Any]: Transpiler setting dictionary. self._transpiler_settings = default_transpiler_settings or {} #: Dict[str, Any]: Scheduler setting dictionary. self._circuit_scheduler_settings = default_circuit_scheduler_settings or {} #: List[ScheduleBlock]: Stack of context. self._context_stack = [] #: str: Name of the output program self._name = name # Add root block if provided. Schedule will be built on top of this. if block is not None: if isinstance(block, ScheduleBlock): root_block = block elif isinstance(block, Schedule): root_block = self._naive_typecast_schedule(block) else: raise exceptions.PulseError( f"Input `block` type {block.__class__.__name__} is " "not a valid format. Specify a pulse program." ) self._context_stack.append(root_block) # Set default alignment context alignment = _PulseBuilder.__alignment_kinds__.get(default_alignment, default_alignment) if not isinstance(alignment, AlignmentKind): raise exceptions.PulseError( f"Given `default_alignment` {repr(default_alignment)} is " "not a valid transformation. Set one of " f'{", ".join(_PulseBuilder.__alignment_kinds__.keys())}, ' "or set an instance of `AlignmentKind` subclass." ) self.push_context(alignment) def __enter__(self) -> ScheduleBlock: """Enter this builder context and yield either the supplied schedule or the schedule created for the user. Returns: The schedule that the builder will build on. """ self._backend_ctx_token = BUILDER_CONTEXTVAR.set(self) output = self._context_stack[0] output._name = self._name or output.name return output @_compile_lazy_circuit_before def __exit__(self, exc_type, exc_val, exc_tb): """Exit the builder context and compile the built pulse program.""" self.compile() BUILDER_CONTEXTVAR.reset(self._backend_ctx_token) @property def backend(self): """Returns the builder backend if set. Returns: Optional[Backend]: The builder's backend. """ return self._backend @_compile_lazy_circuit_before def push_context(self, alignment: AlignmentKind): """Push new context to the stack.""" self._context_stack.append(ScheduleBlock(alignment_context=alignment)) @_compile_lazy_circuit_before def pop_context(self) -> ScheduleBlock: """Pop the last context from the stack.""" if len(self._context_stack) == 1: raise exceptions.PulseError("The root context cannot be popped out.") return self._context_stack.pop() def get_context(self) -> ScheduleBlock: """Get current context. Notes: New instruction can be added by `.append_subroutine` or `.append_instruction` method. Use above methods rather than directly accessing to the current context. """ return self._context_stack[-1] @property @_requires_backend def num_qubits(self): """Get the number of qubits in the backend.""" # backendV2 if isinstance(self.backend, BackendV2): return self.backend.num_qubits return self.backend.configuration().n_qubits @property def transpiler_settings(self) -> Mapping: """The builder's transpiler settings.""" return self._transpiler_settings @transpiler_settings.setter @_compile_lazy_circuit_before def transpiler_settings(self, settings: Mapping): self._compile_lazy_circuit() self._transpiler_settings = settings @property def circuit_scheduler_settings(self) -> Mapping: """The builder's circuit to pulse scheduler settings.""" return self._circuit_scheduler_settings @circuit_scheduler_settings.setter @_compile_lazy_circuit_before def circuit_scheduler_settings(self, settings: Mapping): self._compile_lazy_circuit() self._circuit_scheduler_settings = settings @_compile_lazy_circuit_before def compile(self) -> ScheduleBlock: """Compile and output the built pulse program.""" # Not much happens because we currently compile as we build. # This should be offloaded to a true compilation module # once we define a more sophisticated IR. while len(self._context_stack) > 1: current = self.pop_context() self.append_subroutine(current) return self._context_stack[0] def _compile_lazy_circuit(self): """Call a context QuantumCircuit (lazy circuit) and append the output pulse schedule to the builder's context schedule. Note that the lazy circuit is not stored as a call instruction. """ if self._lazy_circuit: lazy_circuit = self._lazy_circuit # reset lazy circuit self._lazy_circuit = self._new_circuit() self.call_subroutine(self._compile_circuit(lazy_circuit)) def _compile_circuit(self, circ) -> Schedule: """Take a QuantumCircuit and output the pulse schedule associated with the circuit.""" from qiskit import compiler # pylint: disable=cyclic-import transpiled_circuit = compiler.transpile(circ, self.backend, **self.transpiler_settings) sched = compiler.schedule( transpiled_circuit, self.backend, **self.circuit_scheduler_settings ) return sched def _new_circuit(self): """Create a new circuit for lazy circuit scheduling.""" return circuit.QuantumCircuit(self.num_qubits) @_compile_lazy_circuit_before def append_instruction(self, instruction: instructions.Instruction): """Add an instruction to the builder's context schedule. Args: instruction: Instruction to append. """ self._context_stack[-1].append(instruction) def append_reference(self, name: str, *extra_keys: str): """Add external program as a :class:`~qiskit.pulse.instructions.Reference` instruction. Args: name: Name of subroutine. extra_keys: Assistance keys to uniquely specify the subroutine. """ inst = instructions.Reference(name, *extra_keys) self.append_instruction(inst) @_compile_lazy_circuit_before def append_subroutine(self, subroutine: Union[Schedule, ScheduleBlock]): """Append a :class:`ScheduleBlock` to the builder's context schedule. This operation doesn't create a reference. Subroutine is directly appended to current context schedule. Args: subroutine: ScheduleBlock to append to the current context block. Raises: PulseError: When subroutine is not Schedule nor ScheduleBlock. """ if not isinstance(subroutine, (ScheduleBlock, Schedule)): raise exceptions.PulseError( f"'{subroutine.__class__.__name__}' is not valid data format in the builder. " "'Schedule' and 'ScheduleBlock' can be appended to the builder context." ) if len(subroutine) == 0: return if isinstance(subroutine, Schedule): subroutine = self._naive_typecast_schedule(subroutine) self._context_stack[-1].append(subroutine) @singledispatchmethod def call_subroutine( self, subroutine: Union[circuit.QuantumCircuit, Schedule, ScheduleBlock], name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): """Call a schedule or circuit defined outside of the current scope. The ``subroutine`` is appended to the context schedule as a call instruction. This logic just generates a convenient program representation in the compiler. Thus, this doesn't affect execution of inline subroutines. See :class:`~pulse.instructions.Call` for more details. Args: subroutine: Target schedule or circuit to append to the current context. name: Name of subroutine if defined. value_dict: Parameter object and assigned value mapping. This is more precise way to identify a parameter since mapping is managed with unique object id rather than name. Especially there is any name collision in a parameter table. kw_params: Parameter values to bind to the target subroutine with string parameter names. If there are parameter name overlapping, these parameters are updated with the same assigned value. Raises: PulseError: - When input subroutine is not valid data format. """ raise exceptions.PulseError( f"Subroutine type {subroutine.__class__.__name__} is " "not valid data format. Call QuantumCircuit, " "Schedule, or ScheduleBlock." ) @call_subroutine.register def _( self, target_block: ScheduleBlock, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_block) == 0: return # Create local parameter assignment local_assignment = {} for param_name, value in kw_params.items(): params = target_block.get_parameters(param_name) if not params: raise exceptions.PulseError( f"Parameter {param_name} is not defined in the target subroutine. " f'{", ".join(map(str, target_block.parameters))} can be specified.' ) for param in params: local_assignment[param] = value if value_dict: if local_assignment.keys() & value_dict.keys(): warnings.warn( "Some parameters provided by 'value_dict' conflict with one through " "keyword arguments. Parameter values in the keyword arguments " "are overridden by the dictionary values.", UserWarning, ) local_assignment.update(value_dict) if local_assignment: target_block = target_block.assign_parameters(local_assignment, inplace=False) if name is None: # Add unique string, not to accidentally override existing reference entry. keys = (target_block.name, uuid.uuid4().hex) else: keys = (name,) self.append_reference(*keys) self.get_context().assign_references({keys: target_block}, inplace=True) @call_subroutine.register def _( self, target_schedule: Schedule, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_schedule) == 0: return self.call_subroutine( self._naive_typecast_schedule(target_schedule), name=name, value_dict=value_dict, **kw_params, ) @call_subroutine.register def _( self, target_circuit: circuit.QuantumCircuit, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_circuit) == 0: return self._compile_lazy_circuit() self.call_subroutine( self._compile_circuit(target_circuit), name=name, value_dict=value_dict, **kw_params, ) @_requires_backend def call_gate(self, gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True): """Call the circuit ``gate`` in the pulse program. The qubits are assumed to be defined on physical qubits. If ``lazy == True`` this circuit will extend a lazily constructed quantum circuit. When an operation occurs that breaks the underlying circuit scheduling assumptions such as adding a pulse instruction or changing the alignment context the circuit will be transpiled and scheduled into pulses with the current active settings. Args: gate: Gate to call. qubits: Qubits to call gate on. lazy: If false the circuit will be transpiled and pulse scheduled immediately. Otherwise, it will extend the active lazy circuit as defined above. """ try: iter(qubits) except TypeError: qubits = (qubits,) if lazy: self._call_gate(gate, qubits) else: self._compile_lazy_circuit() self._call_gate(gate, qubits) self._compile_lazy_circuit() def _call_gate(self, gate, qargs): if self._lazy_circuit is None: self._lazy_circuit = self._new_circuit() self._lazy_circuit.append(gate, qargs=qargs) @staticmethod def _naive_typecast_schedule(schedule: Schedule): # Naively convert into ScheduleBlock from qiskit.pulse.transforms import inline_subroutines, flatten, pad preprocessed_schedule = inline_subroutines(flatten(schedule)) pad(preprocessed_schedule, inplace=True, pad_with=instructions.TimeBlockade) # default to left alignment, namely ASAP scheduling target_block = ScheduleBlock(name=schedule.name) for _, inst in preprocessed_schedule.instructions: target_block.append(inst, inplace=True) return target_block def get_dt(self): """Retrieve dt differently based on the type of Backend""" if isinstance(self.backend, BackendV2): return self.backend.dt return self.backend.configuration().dt def build( backend=None, schedule: Optional[ScheduleBlock] = None, name: Optional[str] = None, default_alignment: Optional[Union[str, AlignmentKind]] = "left", default_transpiler_settings: Optional[Dict[str, Any]] = None, default_circuit_scheduler_settings: Optional[Dict[str, Any]] = None, ) -> ContextManager[ScheduleBlock]: """Create a context manager for launching the imperative pulse builder DSL. To enter a building context and starting building a pulse program: .. code-block:: from qiskit import execute, pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 0.5), d0) While the output program ``pulse_prog`` cannot be executed as we are using a mock backend. If a real backend is being used, executing the program is done with: .. code-block:: python qiskit.execute(pulse_prog, backend) Args: backend (Backend): A Qiskit backend. If not supplied certain builder functionality will be unavailable. schedule: A pulse ``ScheduleBlock`` in which your pulse program will be built. name: Name of pulse program to be built. default_alignment: Default scheduling alignment for builder. One of ``left``, ``right``, ``sequential`` or an alignment context. default_transpiler_settings: Default settings for the transpiler. default_circuit_scheduler_settings: Default settings for the circuit to pulse scheduler. Returns: A new builder context which has the active builder initialized. """ return _PulseBuilder( backend=backend, block=schedule, name=name, default_alignment=default_alignment, default_transpiler_settings=default_transpiler_settings, default_circuit_scheduler_settings=default_circuit_scheduler_settings, ) # Builder Utilities def _active_builder() -> _PulseBuilder: """Get the active builder in the active context. Returns: The active active builder in this context. Raises: exceptions.NoActiveBuilder: If a pulse builder function is called outside of a builder context. """ try: return BUILDER_CONTEXTVAR.get() except LookupError as ex: raise exceptions.NoActiveBuilder( "A Pulse builder function was called outside of " "a builder context. Try calling within a builder " 'context, eg., "with pulse.build() as schedule: ...".' ) from ex def active_backend(): """Get the backend of the currently active builder context. Returns: Backend: The active backend in the currently active builder context. Raises: exceptions.BackendNotSet: If the builder does not have a backend set. """ builder = _active_builder().backend if builder is None: raise exceptions.BackendNotSet( 'This function requires the active builder to have a "backend" set.' ) return builder def append_schedule(schedule: Union[Schedule, ScheduleBlock]): """Call a schedule by appending to the active builder's context block. Args: schedule: Schedule or ScheduleBlock to append. """ _active_builder().append_subroutine(schedule) def append_instruction(instruction: instructions.Instruction): """Append an instruction to the active builder's context schedule. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.builder.append_instruction(pulse.Delay(10, d0)) print(pulse_prog.instructions) .. parsed-literal:: ((0, Delay(10, DriveChannel(0))),) """ _active_builder().append_instruction(instruction) def num_qubits() -> int: """Return number of qubits in the currently active backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.num_qubits()) .. parsed-literal:: 2 .. note:: Requires the active builder context to have a backend set. """ if isinstance(active_backend(), BackendV2): return active_backend().num_qubits return active_backend().configuration().n_qubits def seconds_to_samples(seconds: Union[float, np.ndarray]) -> Union[int, np.ndarray]: """Obtain the number of samples that will elapse in ``seconds`` on the active backend. Rounds down. Args: seconds: Time in seconds to convert to samples. Returns: The number of samples for the time to elapse """ dt = _active_builder().get_dt() if isinstance(seconds, np.ndarray): return (seconds / dt).astype(int) return int(seconds / dt) def samples_to_seconds(samples: Union[int, np.ndarray]) -> Union[float, np.ndarray]: """Obtain the time in seconds that will elapse for the input number of samples on the active backend. Args: samples: Number of samples to convert to time in seconds. Returns: The time that elapses in ``samples``. """ return samples * _active_builder().get_dt() def qubit_channels(qubit: int) -> Set[chans.Channel]: """Returns the set of channels associated with a qubit. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.qubit_channels(0)) .. parsed-literal:: {MeasureChannel(0), ControlChannel(0), DriveChannel(0), AcquireChannel(0), ControlChannel(1)} .. note:: Requires the active builder context to have a backend set. .. note:: A channel may still be associated with another qubit in this list such as in the case where significant crosstalk exists. """ # implement as the inner function to avoid API change for a patch release in 0.24.2. def get_qubit_channels_v2(backend: BackendV2, qubit: int): r"""Return a list of channels which operate on the given ``qubit``. Returns: List of ``Channel``\s operated on my the given ``qubit``. """ channels = [] # add multi-qubit channels for node_qubits in backend.coupling_map: if qubit in node_qubits: control_channel = backend.control_channel(node_qubits) if control_channel: channels.extend(control_channel) # add single qubit channels channels.append(backend.drive_channel(qubit)) channels.append(backend.measure_channel(qubit)) channels.append(backend.acquire_channel(qubit)) return channels # backendV2 if isinstance(active_backend(), BackendV2): return set(get_qubit_channels_v2(active_backend(), qubit)) return set(active_backend().configuration().get_qubit_channels(qubit)) def _qubits_to_channels(*channels_or_qubits: Union[int, chans.Channel]) -> Set[chans.Channel]: """Returns the unique channels of the input qubits.""" channels = set() for channel_or_qubit in channels_or_qubits: if isinstance(channel_or_qubit, int): channels |= qubit_channels(channel_or_qubit) elif isinstance(channel_or_qubit, chans.Channel): channels.add(channel_or_qubit) else: raise exceptions.PulseError( f'{channel_or_qubit} is not a "Channel" or qubit (integer).' ) return channels def active_transpiler_settings() -> Dict[str, Any]: """Return the current active builder context's transpiler settings. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() transpiler_settings = {'optimization_level': 3} with pulse.build(backend, default_transpiler_settings=transpiler_settings): print(pulse.active_transpiler_settings()) .. parsed-literal:: {'optimization_level': 3} """ return dict(_active_builder().transpiler_settings) def active_circuit_scheduler_settings() -> Dict[str, Any]: """Return the current active builder context's circuit scheduler settings. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() circuit_scheduler_settings = {'method': 'alap'} with pulse.build( backend, default_circuit_scheduler_settings=circuit_scheduler_settings): print(pulse.active_circuit_scheduler_settings()) .. parsed-literal:: {'method': 'alap'} """ return dict(_active_builder().circuit_scheduler_settings) # Contexts @contextmanager def align_left() -> ContextManager[None]: """Left alignment pulse scheduling context. Pulse instructions within this context are scheduled as early as possible by shifting them left to the earliest available time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_left(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=0 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_start_time(d0) == pulse_prog.ch_start_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignLeft()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_right() -> AlignmentKind: """Right alignment pulse scheduling context. Pulse instructions within this context are scheduled as late as possible by shifting them right to the latest available time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_stop_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignRight()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_sequential() -> AlignmentKind: """Sequential alignment pulse scheduling context. Pulse instructions within this context are scheduled sequentially in time such that no two instructions will be played at the same time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_sequential(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will also start at t=100 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_start_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignSequential()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_equispaced(duration: Union[int, ParameterExpression]) -> AlignmentKind: """Equispaced alignment pulse scheduling context. Pulse instructions within this context are scheduled with the same interval spacing such that the total length of the context block is ``duration``. If the total free ``duration`` cannot be evenly divided by the number of instructions within the context, the modulo is split and then prepended and appended to the returned schedule. Delay instructions are automatically inserted in between pulses. This context is convenient to write a schedule for periodical dynamic decoupling or the Hahn echo sequence. Examples: .. plot:: :include-source: from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) with pulse.build() as hahn_echo: with pulse.align_equispaced(duration=100): pulse.play(x90, d0) pulse.play(x180, d0) pulse.play(x90, d0) hahn_echo.draw() Args: duration: Duration of this context. This should be larger than the schedule duration. Yields: None Notes: The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the equispaced context for each channel, you should use the context independently for channels. """ builder = _active_builder() builder.push_context(transforms.AlignEquispaced(duration=duration)) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_func( duration: Union[int, ParameterExpression], func: Callable[[int], float] ) -> AlignmentKind: """Callback defined alignment pulse scheduling context. Pulse instructions within this context are scheduled at the location specified by arbitrary callback function `position` that takes integer index and returns the associated fractional location within [0, 1]. Delay instruction is automatically inserted in between pulses. This context may be convenient to write a schedule of arbitrary dynamical decoupling sequences such as Uhrig dynamical decoupling. Examples: .. plot:: :include-source: import numpy as np from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) def udd10_pos(j): return np.sin(np.pi*j/(2*10 + 2))**2 with pulse.build() as udd_sched: pulse.play(x90, d0) with pulse.align_func(duration=300, func=udd10_pos): for _ in range(10): pulse.play(x180, d0) pulse.play(x90, d0) udd_sched.draw() Args: duration: Duration of context. This should be larger than the schedule duration. func: A function that takes an index of sub-schedule and returns the fractional coordinate of of that sub-schedule. The returned value should be defined within [0, 1]. The pulse index starts from 1. Yields: None Notes: The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the numerical context for each channel, you need to apply the context independently to channels. """ builder = _active_builder() builder.push_context(transforms.AlignFunc(duration=duration, func=func)) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def general_transforms(alignment_context: AlignmentKind) -> ContextManager[None]: """Arbitrary alignment transformation defined by a subclass instance of :class:`~qiskit.pulse.transforms.alignments.AlignmentKind`. Args: alignment_context: Alignment context instance that defines schedule transformation. Yields: None Raises: PulseError: When input ``alignment_context`` is not ``AlignmentKind`` subclasses. """ if not isinstance(alignment_context, AlignmentKind): raise exceptions.PulseError("Input alignment context is not `AlignmentKind` subclass.") builder = _active_builder() builder.push_context(alignment_context) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def transpiler_settings(**settings) -> ContextManager[None]: """Set the currently active transpiler settings for this context. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.active_transpiler_settings()) with pulse.transpiler_settings(optimization_level=3): print(pulse.active_transpiler_settings()) .. parsed-literal:: {} {'optimization_level': 3} """ builder = _active_builder() curr_transpiler_settings = builder.transpiler_settings builder.transpiler_settings = collections.ChainMap(settings, curr_transpiler_settings) try: yield finally: builder.transpiler_settings = curr_transpiler_settings @contextmanager def circuit_scheduler_settings(**settings) -> ContextManager[None]: """Set the currently active circuit scheduler settings for this context. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.active_circuit_scheduler_settings()) with pulse.circuit_scheduler_settings(method='alap'): print(pulse.active_circuit_scheduler_settings()) .. parsed-literal:: {} {'method': 'alap'} """ builder = _active_builder() curr_circuit_scheduler_settings = builder.circuit_scheduler_settings builder.circuit_scheduler_settings = collections.ChainMap( settings, curr_circuit_scheduler_settings ) try: yield finally: builder.circuit_scheduler_settings = curr_circuit_scheduler_settings @contextmanager def phase_offset(phase: float, *channels: chans.PulseChannel) -> ContextManager[None]: """Shift the phase of input channels on entry into context and undo on exit. Examples: .. code-block:: import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: with pulse.phase_offset(math.pi, d0): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 3 Args: phase: Amount of phase offset in radians. channels: Channels to offset phase of. Yields: None """ for channel in channels: shift_phase(phase, channel) try: yield finally: for channel in channels: shift_phase(-phase, channel) @contextmanager def frequency_offset( frequency: float, *channels: chans.PulseChannel, compensate_phase: bool = False ) -> ContextManager[None]: """Shift the frequency of inputs channels on entry into context and undo on exit. Examples: .. code-block:: python :emphasize-lines: 7, 16 from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build(backend) as pulse_prog: # shift frequency by 1GHz with pulse.frequency_offset(1e9, d0): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 3 with pulse.build(backend) as pulse_prog: # Shift frequency by 1GHz. # Undo accumulated phase in the shifted frequency frame # when exiting the context. with pulse.frequency_offset(1e9, d0, compensate_phase=True): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 4 Args: frequency: Amount of frequency offset in Hz. channels: Channels to offset frequency of. compensate_phase: Compensate for accumulated phase accumulated with respect to the channels' frame at its initial frequency. Yields: None """ builder = _active_builder() # TODO: Need proper implementation of compensation. t0 may depend on the parent context. # For example, the instruction position within the equispaced context depends on # the current total number of instructions, thus adding more instruction after # offset context may change the t0 when the parent context is transformed. t0 = builder.get_context().duration for channel in channels: shift_frequency(frequency, channel) try: yield finally: if compensate_phase: duration = builder.get_context().duration - t0 accumulated_phase = 2 * np.pi * ((duration * builder.get_dt() * frequency) % 1) for channel in channels: shift_phase(-accumulated_phase, channel) for channel in channels: shift_frequency(-frequency, channel) # Channels def drive_channel(qubit: int) -> chans.DriveChannel: """Return ``DriveChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.drive_channel(0) == pulse.DriveChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().drive_channel(qubit) return active_backend().configuration().drive(qubit) def measure_channel(qubit: int) -> chans.MeasureChannel: """Return ``MeasureChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.measure_channel(0) == pulse.MeasureChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().measure_channel(qubit) return active_backend().configuration().measure(qubit) def acquire_channel(qubit: int) -> chans.AcquireChannel: """Return ``AcquireChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.acquire_channel(0) == pulse.AcquireChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().acquire_channel(qubit) return active_backend().configuration().acquire(qubit) def control_channels(*qubits: Iterable[int]) -> List[chans.ControlChannel]: """Return ``ControlChannel`` for ``qubit`` on the active builder backend. Return the secondary drive channel for the given qubit -- typically utilized for controlling multi-qubit interactions. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.control_channels(0, 1) == [pulse.ControlChannel(0)] .. note:: Requires the active builder context to have a backend set. Args: qubits: Tuple or list of ordered qubits of the form `(control_qubit, target_qubit)`. Returns: List of control channels associated with the supplied ordered list of qubits. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().control_channel(qubits) return active_backend().configuration().control(qubits=qubits) # Base Instructions def delay(duration: int, channel: chans.Channel, name: Optional[str] = None): """Delay on a ``channel`` for a ``duration``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.delay(10, d0) Args: duration: Number of cycles to delay for on ``channel``. channel: Channel to delay on. name: Name of the instruction. """ append_instruction(instructions.Delay(duration, channel, name=name)) def play( pulse: Union[library.Pulse, np.ndarray], channel: chans.PulseChannel, name: Optional[str] = None ): """Play a ``pulse`` on a ``channel``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(10, 1.0), d0) Args: pulse: Pulse to play. channel: Channel to play pulse on. name: Name of the pulse. """ if not isinstance(pulse, library.Pulse): pulse = library.Waveform(pulse) append_instruction(instructions.Play(pulse, channel, name=name)) def acquire( duration: int, qubit_or_channel: Union[int, chans.AcquireChannel], register: StorageLocation, **metadata: Union[configuration.Kernel, configuration.Discriminator], ): """Acquire for a ``duration`` on a ``channel`` and store the result in a ``register``. Examples: .. code-block:: from qiskit import pulse acq0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) with pulse.build() as pulse_prog: pulse.acquire(100, acq0, mem0) # measurement metadata kernel = pulse.configuration.Kernel('linear_discriminator') pulse.acquire(100, acq0, mem0, kernel=kernel) .. note:: The type of data acquire will depend on the execution ``meas_level``. Args: duration: Duration to acquire data for qubit_or_channel: Either the qubit to acquire data for or the specific :class:`~qiskit.pulse.channels.AcquireChannel` to acquire on. register: Location to store measured result. metadata: Additional metadata for measurement. See :class:`~qiskit.pulse.instructions.Acquire` for more information. Raises: exceptions.PulseError: If the register type is not supported. """ if isinstance(qubit_or_channel, int): qubit_or_channel = chans.AcquireChannel(qubit_or_channel) if isinstance(register, chans.MemorySlot): append_instruction( instructions.Acquire(duration, qubit_or_channel, mem_slot=register, **metadata) ) elif isinstance(register, chans.RegisterSlot): append_instruction( instructions.Acquire(duration, qubit_or_channel, reg_slot=register, **metadata) ) else: raise exceptions.PulseError(f'Register of type: "{type(register)}" is not supported') def set_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None): """Set the ``frequency`` of a pulse ``channel``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.set_frequency(1e9, d0) Args: frequency: Frequency in Hz to set channel to. channel: Channel to set frequency of. name: Name of the instruction. """ append_instruction(instructions.SetFrequency(frequency, channel, name=name)) def shift_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None): """Shift the ``frequency`` of a pulse ``channel``. Examples: .. code-block:: python :emphasize-lines: 6 from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.shift_frequency(1e9, d0) Args: frequency: Frequency in Hz to shift channel frequency by. channel: Channel to shift frequency of. name: Name of the instruction. """ append_instruction(instructions.ShiftFrequency(frequency, channel, name=name)) def set_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None): """Set the ``phase`` of a pulse ``channel``. Examples: .. code-block:: python :emphasize-lines: 8 import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.set_phase(math.pi, d0) Args: phase: Phase in radians to set channel carrier signal to. channel: Channel to set phase of. name: Name of the instruction. """ append_instruction(instructions.SetPhase(phase, channel, name=name)) def shift_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None): """Shift the ``phase`` of a pulse ``channel``. Examples: .. code-block:: import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.shift_phase(math.pi, d0) Args: phase: Phase in radians to shift channel carrier signal by. channel: Channel to shift phase of. name: Name of the instruction. """ append_instruction(instructions.ShiftPhase(phase, channel, name)) def snapshot(label: str, snapshot_type: str = "statevector"): """Simulator snapshot. Examples: .. code-block:: from qiskit import pulse with pulse.build() as pulse_prog: pulse.snapshot('first', 'statevector') Args: label: Label for snapshot. snapshot_type: Type of snapshot. """ append_instruction(instructions.Snapshot(label, snapshot_type=snapshot_type)) def call( target: Optional[Union[circuit.QuantumCircuit, Schedule, ScheduleBlock]], name: Optional[str] = None, value_dict: Optional[Dict[ParameterValueType, ParameterValueType]] = None, **kw_params: ParameterValueType, ): """Call the subroutine within the currently active builder context with arbitrary parameters which will be assigned to the target program. .. note:: If the ``target`` program is a :class:`.ScheduleBlock`, then a :class:`.Reference` instruction will be created and appended to the current context. The ``target`` program will be immediately assigned to the current scope as a subroutine. If the ``target`` program is :class:`.Schedule`, it will be wrapped by the :class:`.Call` instruction and appended to the current context to avoid a mixed representation of :class:`.ScheduleBlock` and :class:`.Schedule`. If the ``target`` program is a :class:`.QuantumCircuit` it will be scheduled and the new :class:`.Schedule` will be added as a :class:`.Call` instruction. Examples: 1. Calling a schedule block (recommended) .. code-block:: from qiskit import circuit, pulse from qiskit.providers.fake_provider import FakeBogotaV2 backend = FakeBogotaV2() with pulse.build() as x_sched: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) with pulse.build() as pulse_prog: pulse.call(x_sched) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play( Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0) ), name="block0", transform=AlignLeft() ), name="block1", transform=AlignLeft() ) The actual program is stored in the reference table attached to the schedule. .. code-block:: print(pulse_prog.references) .. parsed-literal:: ReferenceManager: - ('block0', '634b3b50bd684e26a673af1fbd2d6c81'): ScheduleBlock(Play(Gaussian(... In addition, you can call a parameterized target program with parameter assignment. .. code-block:: amp = circuit.Parameter("amp") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0)) with pulse.build() as pulse_prog: pulse.call(subroutine, amp=0.1) pulse.call(subroutine, amp=0.3) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play( Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0) ), name="block2", transform=AlignLeft() ), ScheduleBlock( Play( Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(0) ), name="block2", transform=AlignLeft() ), name="block3", transform=AlignLeft() ) If there is a name collision between parameters, you can distinguish them by specifying each parameter object in a python dictionary. For example, .. code-block:: amp1 = circuit.Parameter('amp') amp2 = circuit.Parameter('amp') with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, amp2, 40), pulse.DriveChannel(1)) with pulse.build() as pulse_prog: pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.3}) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play(Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0)), Play(Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(1)), name="block4", transform=AlignLeft() ), name="block5", transform=AlignLeft() ) 2. Calling a schedule .. code-block:: x_sched = backend.instruction_schedule_map.get("x", (0,)) with pulse.build(backend) as pulse_prog: pulse.call(x_sched) print(pulse_prog) .. parsed-literal:: ScheduleBlock( Call( Schedule( ( 0, Play( Drag( duration=160, amp=(0.18989731546729305+0j), sigma=40, beta=-1.201258305015517, name='drag_86a8' ), DriveChannel(0), name='drag_86a8' ) ), name="x" ), name='x' ), name="block6", transform=AlignLeft() ) Currently, the backend calibrated gates are provided in the form of :class:`~.Schedule`. The parameter assignment mechanism is available also for schedules. However, the called schedule is not treated as a reference. 3. Calling a quantum circuit .. code-block:: backend = FakeBogotaV2() qc = circuit.QuantumCircuit(1) qc.x(0) with pulse.build(backend) as pulse_prog: pulse.call(qc) print(pulse_prog) .. parsed-literal:: ScheduleBlock( Call( Schedule( ( 0, Play( Drag( duration=160, amp=(0.18989731546729305+0j), sigma=40, beta=-1.201258305015517, name='drag_86a8' ), DriveChannel(0), name='drag_86a8' ) ), name="circuit-87" ), name='circuit-87' ), name="block7", transform=AlignLeft() ) .. warning:: Calling a circuit from a schedule is not encouraged. Currently, the Qiskit execution model is migrating toward the pulse gate model, where schedules are attached to circuits through the :meth:`.QuantumCircuit.add_calibration` method. Args: target: Target circuit or pulse schedule to call. name: Optional. A unique name of subroutine if defined. When the name is explicitly provided, one cannot call different schedule blocks with the same name. value_dict: Optional. Parameters assigned to the ``target`` program. If this dictionary is provided, the ``target`` program is copied and then stored in the main built schedule and its parameters are assigned to the given values. This dictionary is keyed on :class:`~.Parameter` objects, allowing parameter name collision to be avoided. kw_params: Alternative way to provide parameters. Since this is keyed on the string parameter name, the parameters having the same name are all updated together. If you want to avoid name collision, use ``value_dict`` with :class:`~.Parameter` objects instead. """ _active_builder().call_subroutine(target, name, value_dict, **kw_params) def reference(name: str, *extra_keys: str): """Refer to undefined subroutine by string keys. A :class:`~qiskit.pulse.instructions.Reference` instruction is implicitly created and a schedule can be separately registered to the reference at a later stage. .. code-block:: python from qiskit import pulse with pulse.build() as main_prog: pulse.reference("x_gate", "q0") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) main_prog.assign_references(subroutine_dict={("x_gate", "q0"): subroutine}) Args: name: Name of subroutine. extra_keys: Helper keys to uniquely specify the subroutine. """ _active_builder().append_reference(name, *extra_keys) # Directives def barrier(*channels_or_qubits: Union[chans.Channel, int], name: Optional[str] = None): """Barrier directive for a set of channels and qubits. This directive prevents the compiler from moving instructions across the barrier. Consider the case where we want to enforce that one pulse happens after another on separate channels, this can be done with: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build(backend) as barrier_pulse_prog: pulse.play(pulse.Constant(10, 1.0), d0) pulse.barrier(d0, d1) pulse.play(pulse.Constant(10, 1.0), d1) Of course this could have been accomplished with: .. code-block:: from qiskit.pulse import transforms with pulse.build(backend) as aligned_pulse_prog: with pulse.align_sequential(): pulse.play(pulse.Constant(10, 1.0), d0) pulse.play(pulse.Constant(10, 1.0), d1) barrier_pulse_prog = transforms.target_qobj_transform(barrier_pulse_prog) aligned_pulse_prog = transforms.target_qobj_transform(aligned_pulse_prog) assert barrier_pulse_prog == aligned_pulse_prog The barrier allows the pulse compiler to take care of more advanced scheduling alignment operations across channels. For example in the case where we are calling an outside circuit or schedule and want to align a pulse at the end of one call: .. code-block:: import math d0 = pulse.DriveChannel(0) with pulse.build(backend) as pulse_prog: with pulse.align_right(): pulse.x(1) # Barrier qubit 1 and d0. pulse.barrier(1, d0) # Due to barrier this will play before the gate on qubit 1. pulse.play(pulse.Constant(10, 1.0), d0) # This will end at the same time as the pulse above due to # the barrier. pulse.x(1) .. note:: Requires the active builder context to have a backend set if qubits are barriered on. Args: channels_or_qubits: Channels or qubits to barrier. name: Name for the barrier """ channels = _qubits_to_channels(*channels_or_qubits) if len(channels) > 1: append_instruction(directives.RelativeBarrier(*channels, name=name)) # Macros def macro(func: Callable): """Wrap a Python function and activate the parent builder context at calling time. This enables embedding Python functions as builder macros. This generates a new :class:`pulse.Schedule` that is embedded in the parent builder context with every call of the decorated macro function. The decorated macro function will behave as if the function code was embedded inline in the parent builder context after parameter substitution. Examples: .. plot:: :include-source: from qiskit import pulse @pulse.macro def measure(qubit: int): pulse.play(pulse.GaussianSquare(16384, 256, 15872), pulse.measure_channel(qubit)) mem_slot = pulse.MemorySlot(qubit) pulse.acquire(16384, pulse.acquire_channel(qubit), mem_slot) return mem_slot with pulse.build(backend=backend) as sched: mem_slot = measure(0) print(f"Qubit measured into {mem_slot}") sched.draw() Args: func: The Python function to enable as a builder macro. There are no requirements on the signature of the function, any calls to pulse builder methods will be added to builder context the wrapped function is called from. Returns: Callable: The wrapped ``func``. """ func_name = getattr(func, "__name__", repr(func)) @functools.wraps(func) def wrapper(*args, **kwargs): _builder = _active_builder() # activate the pulse builder before calling the function with build(backend=_builder.backend, name=func_name) as built: output = func(*args, **kwargs) _builder.call_subroutine(built) return output return wrapper def measure( qubits: Union[List[int], int], registers: Union[List[StorageLocation], StorageLocation] = None, ) -> Union[List[StorageLocation], StorageLocation]: """Measure a qubit within the currently active builder context. At the pulse level a measurement is composed of both a stimulus pulse and an acquisition instruction which tells the systems measurement unit to acquire data and process it. We provide this measurement macro to automate the process for you, but if desired full control is still available with :func:`acquire` and :func:`play`. To use the measurement it is as simple as specifying the qubit you wish to measure: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() qubit = 0 with pulse.build(backend) as pulse_prog: # Do something to the qubit. qubit_drive_chan = pulse.drive_channel(0) pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan) # Measure the qubit. reg = pulse.measure(qubit) For now it is not possible to do much with the handle to ``reg`` but in the future we will support using this handle to a result register to build up ones program. It is also possible to supply this register: .. code-block:: with pulse.build(backend) as pulse_prog: pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan) # Measure the qubit. mem0 = pulse.MemorySlot(0) reg = pulse.measure(qubit, mem0) assert reg == mem0 .. note:: Requires the active builder context to have a backend set. Args: qubits: Physical qubit to measure. registers: Register to store result in. If not selected the current behavior is to return the :class:`MemorySlot` with the same index as ``qubit``. This register will be returned. Returns: The ``register`` the qubit measurement result will be stored in. """ backend = active_backend() try: qubits = list(qubits) except TypeError: qubits = [qubits] if registers is None: registers = [chans.MemorySlot(qubit) for qubit in qubits] else: try: registers = list(registers) except TypeError: registers = [registers] measure_sched = macros.measure( qubits=qubits, backend=backend, qubit_mem_slots={qubit: register.index for qubit, register in zip(qubits, registers)}, ) # note this is not a subroutine. # just a macro to automate combination of stimulus and acquisition. # prepare unique reference name based on qubit and memory slot index. qubits_repr = "&".join(map(str, qubits)) mslots_repr = "&".join((str(r.index) for r in registers)) _active_builder().call_subroutine(measure_sched, name=f"measure_{qubits_repr}..{mslots_repr}") if len(qubits) == 1: return registers[0] else: return registers def measure_all() -> List[chans.MemorySlot]: r"""Measure all qubits within the currently active builder context. A simple macro function to measure all of the qubits in the device at the same time. This is useful for handling device ``meas_map`` and single measurement constraints. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: # Measure all qubits and return associated registers. regs = pulse.measure_all() .. note:: Requires the active builder context to have a backend set. Returns: The ``register``\s the qubit measurement results will be stored in. """ backend = active_backend() qubits = range(num_qubits()) registers = [chans.MemorySlot(qubit) for qubit in qubits] measure_sched = macros.measure( qubits=qubits, backend=backend, qubit_mem_slots={qubit: qubit for qubit in qubits}, ) # note this is not a subroutine. # just a macro to automate combination of stimulus and acquisition. _active_builder().call_subroutine(measure_sched, name="measure_all") return registers def delay_qubits(duration: int, *qubits: Union[int, Iterable[int]]): r"""Insert delays on all of the :class:`channels.Channel`\s that correspond to the input ``qubits`` at the same time. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q backend = FakeOpenPulse3Q() with pulse.build(backend) as pulse_prog: # Delay for 100 cycles on qubits 0, 1 and 2. regs = pulse.delay_qubits(100, 0, 1, 2) .. note:: Requires the active builder context to have a backend set. Args: duration: Duration to delay for. qubits: Physical qubits to delay on. Delays will be inserted based on the channels returned by :func:`pulse.qubit_channels`. """ qubit_chans = set(itertools.chain.from_iterable(qubit_channels(qubit) for qubit in qubits)) with align_left(): for chan in qubit_chans: delay(duration, chan) # Gate instructions def call_gate(gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True): """Call a gate and lazily schedule it to its corresponding pulse instruction. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.pulse import builder from qiskit.circuit.library import standard_gates as gates from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: builder.call_gate(gates.CXGate(), (0, 1)) We can see the role of the transpiler in scheduling gates by optimizing away two consecutive CNOT gates: .. code-block:: with pulse.build(backend) as pulse_prog: with pulse.transpiler_settings(optimization_level=3): builder.call_gate(gates.CXGate(), (0, 1)) builder.call_gate(gates.CXGate(), (0, 1)) assert pulse_prog == pulse.Schedule() .. note:: If multiple gates are called in a row they may be optimized by the transpiler, depending on the :func:`pulse.active_transpiler_settings``. .. note:: Requires the active builder context to have a backend set. Args: gate: Circuit gate instance to call. qubits: Qubits to call gate on. lazy: If ``false`` the gate will be compiled immediately, otherwise it will be added onto a lazily evaluated quantum circuit to be compiled when the builder is forced to by a circuit assumption being broken, such as the inclusion of a pulse instruction or new alignment context. """ _active_builder().call_gate(gate, qubits, lazy=lazy) def cx(control: int, target: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.CXGate` on the input physical qubits. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.cx(0, 1) """ call_gate(gates.CXGate(), (control, target)) def u1(theta: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U1Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u1(math.pi, 1) """ call_gate(gates.U1Gate(theta), qubit) def u2(phi: float, lam: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U2Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u2(0, math.pi, 1) """ call_gate(gates.U2Gate(phi, lam), qubit) def u3(theta: float, phi: float, lam: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U3Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u3(math.pi, 0, math.pi, 1) """ call_gate(gates.U3Gate(theta, phi, lam), qubit) def x(qubit: int): """Call a :class:`~qiskit.circuit.library.standard_gates.XGate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.x(0) """ call_gate(gates.XGate(), qubit)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=unused-import """ A convenient way to track reusable subschedules by name and qubit. This can be used for scheduling circuits with custom definitions, for instance:: inst_map = InstructionScheduleMap() inst_map.add('new_inst', 0, qubit_0_new_inst_schedule) sched = schedule(quantum_circuit, backend, inst_map) An instance of this class is instantiated by Pulse-enabled backends and populated with defaults (if available):: inst_map = backend.defaults().instruction_schedule_map """ from __future__ import annotations import functools import warnings from collections import defaultdict from collections.abc import Iterable, Callable from qiskit import circuit from qiskit.circuit.parameterexpression import ParameterExpression from qiskit.pulse.calibration_entries import ( CalibrationEntry, ScheduleDef, CallableDef, # for backward compatibility PulseQobjDef, CalibrationPublisher, ) from qiskit.pulse.exceptions import PulseError from qiskit.pulse.schedule import Schedule, ScheduleBlock class InstructionScheduleMap: """Mapping from :py:class:`~qiskit.circuit.QuantumCircuit` :py:class:`qiskit.circuit.Instruction` names and qubits to :py:class:`~qiskit.pulse.Schedule` s. In particular, the mapping is formatted as type:: Dict[str, Dict[Tuple[int], Schedule]] where the first key is the name of a circuit instruction (e.g. ``'u1'``, ``'measure'``), the second key is a tuple of qubit indices, and the final value is a Schedule implementing the requested instruction. These can usually be seen as gate calibrations. """ def __init__(self): """Initialize a circuit instruction to schedule mapper instance.""" # The processed and reformatted circuit instruction definitions # Do not use lambda function for nested defaultdict, i.e. lambda: defaultdict(CalibrationEntry). # This crashes qiskit parallel. Note that parallel framework passes args as # pickled object, however lambda function cannot be pickled. self._map: dict[str | circuit.instruction.Instruction, dict[tuple, CalibrationEntry]] = ( defaultdict(functools.partial(defaultdict, CalibrationEntry)) ) # A backwards mapping from qubit to supported instructions self._qubit_instructions: dict[tuple[int, ...], set] = defaultdict(set) def has_custom_gate(self) -> bool: """Return ``True`` if the map has user provided instruction.""" for qubit_inst in self._map.values(): for entry in qubit_inst.values(): if entry.user_provided: return True return False @property def instructions(self) -> list[str]: """Return all instructions which have definitions. By default, these are typically the basis gates along with other instructions such as measure and reset. Returns: The names of all the circuit instructions which have Schedule definitions in this. """ return list(self._map.keys()) def qubits_with_instruction( self, instruction: str | circuit.instruction.Instruction ) -> list[int | tuple[int, ...]]: """Return a list of the qubits for which the given instruction is defined. Single qubit instructions return a flat list, and multiqubit instructions return a list of ordered tuples. Args: instruction: The name of the circuit instruction. Returns: Qubit indices which have the given instruction defined. This is a list of tuples if the instruction has an arity greater than 1, or a flat list of ints otherwise. Raises: PulseError: If the instruction is not found. """ instruction = _get_instruction_string(instruction) if instruction not in self._map: return [] return [ qubits[0] if len(qubits) == 1 else qubits for qubits in sorted(self._map[instruction].keys()) ] def qubit_instructions(self, qubits: int | Iterable[int]) -> list[str]: """Return a list of the instruction names that are defined by the backend for the given qubit or qubits. Args: qubits: A qubit index, or a list or tuple of indices. Returns: All the instructions which are defined on the qubits. For 1 qubit, all the 1Q instructions defined. For multiple qubits, all the instructions which apply to that whole set of qubits (e.g. ``qubits=[0, 1]`` may return ``['cx']``). """ if _to_tuple(qubits) in self._qubit_instructions: return list(self._qubit_instructions[_to_tuple(qubits)]) return [] def has( self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int] ) -> bool: """Is the instruction defined for the given qubits? Args: instruction: The instruction for which to look. qubits: The specific qubits for the instruction. Returns: True iff the instruction is defined. """ instruction = _get_instruction_string(instruction) return instruction in self._map and _to_tuple(qubits) in self._map[instruction] def assert_has( self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int] ) -> None: """Error if the given instruction is not defined. Args: instruction: The instruction for which to look. qubits: The specific qubits for the instruction. Raises: PulseError: If the instruction is not defined on the qubits. """ instruction = _get_instruction_string(instruction) if not self.has(instruction, _to_tuple(qubits)): if instruction in self._map: raise PulseError( "Operation '{inst}' exists, but is only defined for qubits " "{qubits}.".format( inst=instruction, qubits=self.qubits_with_instruction(instruction) ) ) raise PulseError(f"Operation '{instruction}' is not defined for this system.") def get( self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int], *params: complex | ParameterExpression, **kwparams: complex | ParameterExpression, ) -> Schedule | ScheduleBlock: """Return the defined :py:class:`~qiskit.pulse.Schedule` or :py:class:`~qiskit.pulse.ScheduleBlock` for the given instruction on the given qubits. If all keys are not specified this method returns schedule with unbound parameters. Args: instruction: Name of the instruction or the instruction itself. qubits: The qubits for the instruction. *params: Command parameters for generating the output schedule. **kwparams: Keyworded command parameters for generating the schedule. Returns: The Schedule defined for the input. """ return self._get_calibration_entry(instruction, qubits).get_schedule(*params, **kwparams) def _get_calibration_entry( self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int], ) -> CalibrationEntry: """Return the :class:`.CalibrationEntry` without generating schedule. When calibration entry is un-parsed Pulse Qobj, this returns calibration without parsing it. :meth:`CalibrationEntry.get_schedule` method must be manually called with assigned parameters to get corresponding pulse schedule. This method is expected be directly used internally by the V2 backend converter for faster loading of the backend calibrations. Args: instruction: Name of the instruction or the instruction itself. qubits: The qubits for the instruction. Returns: The calibration entry. """ instruction = _get_instruction_string(instruction) self.assert_has(instruction, qubits) return self._map[instruction][_to_tuple(qubits)] def add( self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int], schedule: Schedule | ScheduleBlock | Callable[..., Schedule | ScheduleBlock], arguments: list[str] | None = None, ) -> None: """Add a new known instruction for the given qubits and its mapping to a pulse schedule. Args: instruction: The name of the instruction to add. qubits: The qubits which the instruction applies to. schedule: The Schedule that implements the given instruction. arguments: List of parameter names to create a parameter-bound schedule from the associated gate instruction. If :py:meth:`get` is called with arguments rather than keyword arguments, this parameter list is used to map the input arguments to parameter objects stored in the target schedule. Raises: PulseError: If the qubits are provided as an empty iterable. """ instruction = _get_instruction_string(instruction) # validation of target qubit qubits = _to_tuple(qubits) if not qubits: raise PulseError(f"Cannot add definition {instruction} with no target qubits.") # generate signature if isinstance(schedule, (Schedule, ScheduleBlock)): entry: CalibrationEntry = ScheduleDef(arguments) elif callable(schedule): if arguments: warnings.warn( "Arguments are overruled by the callback function signature. " "Input `arguments` are ignored.", UserWarning, ) entry = CallableDef() else: raise PulseError( "Supplied schedule must be one of the Schedule, ScheduleBlock or a " "callable that outputs a schedule." ) entry.define(schedule, user_provided=True) self._add(instruction, qubits, entry) def _add( self, instruction_name: str, qubits: tuple[int, ...], entry: CalibrationEntry, ): """A method to resister calibration entry. .. note:: This is internal fast-path function, and caller must ensure the entry is properly formatted. This function may be used by other programs that load backend calibrations to create Qiskit representation of it. Args: instruction_name: Name of instruction. qubits: List of qubits that this calibration is applied. entry: Calibration entry to register. :meta public: """ self._map[instruction_name][qubits] = entry self._qubit_instructions[qubits].add(instruction_name) def remove( self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int] ) -> None: """Remove the given instruction from the listing of instructions defined in self. Args: instruction: The name of the instruction to add. qubits: The qubits which the instruction applies to. """ instruction = _get_instruction_string(instruction) qubits = _to_tuple(qubits) self.assert_has(instruction, qubits) del self._map[instruction][qubits] if not self._map[instruction]: del self._map[instruction] self._qubit_instructions[qubits].remove(instruction) if not self._qubit_instructions[qubits]: del self._qubit_instructions[qubits] def pop( self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int], *params: complex | ParameterExpression, **kwparams: complex | ParameterExpression, ) -> Schedule | ScheduleBlock: """Remove and return the defined schedule for the given instruction on the given qubits. Args: instruction: Name of the instruction. qubits: The qubits for the instruction. *params: Command parameters for generating the output schedule. **kwparams: Keyworded command parameters for generating the schedule. Returns: The Schedule defined for the input. """ instruction = _get_instruction_string(instruction) schedule = self.get(instruction, qubits, *params, **kwparams) self.remove(instruction, qubits) return schedule def get_parameters( self, instruction: str | circuit.instruction.Instruction, qubits: int | Iterable[int] ) -> tuple[str, ...]: """Return the list of parameters taken by the given instruction on the given qubits. Args: instruction: Name of the instruction. qubits: The qubits for the instruction. Returns: The names of the parameters required by the instruction. """ instruction = _get_instruction_string(instruction) self.assert_has(instruction, qubits) signature = self._map[instruction][_to_tuple(qubits)].get_signature() return tuple(signature.parameters.keys()) def __str__(self): single_q_insts = "1Q instructions:\n" multi_q_insts = "Multi qubit instructions:\n" for qubits, insts in self._qubit_instructions.items(): if len(qubits) == 1: single_q_insts += f" q{qubits[0]}: {insts}\n" else: multi_q_insts += f" {qubits}: {insts}\n" instructions = single_q_insts + multi_q_insts return f"<{self.__class__.__name__}({instructions})>" def __eq__(self, other): if not isinstance(other, InstructionScheduleMap): return False for inst in self.instructions: for qinds in self.qubits_with_instruction(inst): try: if self._map[inst][_to_tuple(qinds)] != other._map[inst][_to_tuple(qinds)]: return False except KeyError: return False return True def _to_tuple(values: int | Iterable[int]) -> tuple[int, ...]: """Return the input as a tuple. Args: values: An integer, or iterable of integers. Returns: The input values as a sorted tuple. """ try: return tuple(values) except TypeError: return (values,) def _get_instruction_string(inst: str | circuit.instruction.Instruction) -> str: if isinstance(inst, str): return inst else: try: return inst.name except AttributeError as ex: raise PulseError( 'Input "inst" has no attribute "name". This should be a circuit "Instruction".' ) from ex
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=cyclic-import """ ========= Schedules ========= .. currentmodule:: qiskit.pulse Schedules are Pulse programs. They describe instruction sequences for the control hardware. The Schedule is one of the most fundamental objects to this pulse-level programming module. A ``Schedule`` is a representation of a *program* in Pulse. Each schedule tracks the time of each instruction occuring in parallel over multiple signal *channels*. .. autosummary:: :toctree: ../stubs/ Schedule ScheduleBlock """ import abc import copy import functools import itertools import multiprocessing as mp import re import sys import warnings from typing import List, Tuple, Iterable, Union, Dict, Callable, Set, Optional, Any import numpy as np import rustworkx as rx from qiskit.circuit.parameter import Parameter from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType from qiskit.pulse.channels import Channel from qiskit.pulse.exceptions import PulseError, UnassignedReferenceError from qiskit.pulse.instructions import Instruction, Reference from qiskit.pulse.utils import instruction_duration_validation from qiskit.pulse.reference_manager import ReferenceManager from qiskit.utils.multiprocessing import is_main_process Interval = Tuple[int, int] """An interval type is a tuple of a start time (inclusive) and an end time (exclusive).""" TimeSlots = Dict[Channel, List[Interval]] """List of timeslots occupied by instructions for each channel.""" class Schedule: """A quantum program *schedule* with exact time constraints for its instructions, operating over all input signal *channels* and supporting special syntaxes for building. Pulse program representation for the original Qiskit Pulse model [1]. Instructions are not allowed to overlap in time on the same channel. This overlap constraint is immediately evaluated when a new instruction is added to the ``Schedule`` object. It is necessary to specify the absolute start time and duration for each instruction so as to deterministically fix its execution time. The ``Schedule`` program supports some syntax sugar for easier programming. - Appending an instruction to the end of a channel .. code-block:: python sched = Schedule() sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) - Appending an instruction shifted in time by a given amount .. code-block:: python sched = Schedule() sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) << 30 - Merge two schedules .. code-block:: python sched1 = Schedule() sched1 += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) sched2 = Schedule() sched2 += Play(Gaussian(160, 0.1, 40), DriveChannel(1)) sched2 = sched1 | sched2 A :obj:`.PulseError` is immediately raised when the overlap constraint is violated. In the schedule representation, we cannot parametrize the duration of instructions. Thus we need to create a new schedule object for each duration. To parametrize an instruction's duration, the :class:`~qiskit.pulse.ScheduleBlock` representation may be used instead. References: [1]: https://arxiv.org/abs/2004.06755 """ # Prefix to use for auto naming. prefix = "sched" # Counter to count instance number. instances_counter = itertools.count() def __init__( self, *schedules: Union["ScheduleComponent", Tuple[int, "ScheduleComponent"]], name: Optional[str] = None, metadata: Optional[dict] = None, ): """Create an empty schedule. Args: *schedules: Child Schedules of this parent Schedule. May either be passed as the list of schedules, or a list of ``(start_time, schedule)`` pairs. name: Name of this schedule. Defaults to an autogenerated string if not provided. metadata: Arbitrary key value metadata to associate with the schedule. This gets stored as free-form data in a dict in the :attr:`~qiskit.pulse.Schedule.metadata` attribute. It will not be directly used in the schedule. Raises: TypeError: if metadata is not a dict. """ from qiskit.pulse.parameter_manager import ParameterManager if name is None: name = self.prefix + str(next(self.instances_counter)) if sys.platform != "win32" and not is_main_process(): name += f"-{mp.current_process().pid}" self._name = name self._parameter_manager = ParameterManager() if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} self._duration = 0 # These attributes are populated by ``_mutable_insert`` self._timeslots = {} self._children = [] for sched_pair in schedules: try: time, sched = sched_pair except TypeError: # recreate as sequence starting at 0. time, sched = 0, sched_pair self._mutable_insert(time, sched) @classmethod def initialize_from(cls, other_program: Any, name: Optional[str] = None) -> "Schedule": """Create new schedule object with metadata of another schedule object. Args: other_program: Qiskit program that provides metadata to new object. name: Name of new schedule. Name of ``schedule`` is used by default. Returns: New schedule object with name and metadata. Raises: PulseError: When `other_program` does not provide necessary information. """ try: name = name or other_program.name if other_program.metadata: metadata = other_program.metadata.copy() else: metadata = None return cls(name=name, metadata=metadata) except AttributeError as ex: raise PulseError( f"{cls.__name__} cannot be initialized from the program data " f"{other_program.__class__.__name__}." ) from ex @property def name(self) -> str: """Name of this Schedule""" return self._name @property def metadata(self) -> Dict[str, Any]: """The user provided metadata associated with the schedule. User provided ``dict`` of metadata for the schedule. The metadata contents do not affect the semantics of the program but are used to influence the execution of the schedule. It is expected to be passed between all transforms of the schedule and that providers will associate any schedule metadata with the results it returns from the execution of that schedule. """ return self._metadata @metadata.setter def metadata(self, metadata): """Update the schedule metadata""" if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @property def timeslots(self) -> TimeSlots: """Time keeping attribute.""" return self._timeslots @property def duration(self) -> int: """Duration of this schedule.""" return self._duration @property def start_time(self) -> int: """Starting time of this schedule.""" return self.ch_start_time(*self.channels) @property def stop_time(self) -> int: """Stopping time of this schedule.""" return self.duration @property def channels(self) -> Tuple[Channel]: """Returns channels that this schedule uses.""" return tuple(self._timeslots.keys()) @property def children(self) -> Tuple[Tuple[int, "ScheduleComponent"], ...]: """Return the child schedule components of this ``Schedule`` in the order they were added to the schedule. Notes: Nested schedules are returned as-is. If you want to collect only instructions, use py:meth:`~Schedule.instructions` instead. Returns: A tuple, where each element is a two-tuple containing the initial scheduled time of each ``NamedValue`` and the component itself. """ return tuple(self._children) @property def instructions(self) -> Tuple[Tuple[int, Instruction]]: """Get the time-ordered instructions from self.""" def key(time_inst_pair): inst = time_inst_pair[1] return time_inst_pair[0], inst.duration, sorted(chan.name for chan in inst.channels) return tuple(sorted(self._instructions(), key=key)) @property def parameters(self) -> Set: """Parameters which determine the schedule behavior.""" return self._parameter_manager.parameters def ch_duration(self, *channels: Channel) -> int: """Return the time of the end of the last instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ return self.ch_stop_time(*channels) def ch_start_time(self, *channels: Channel) -> int: """Return the time of the start of the first instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ try: chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots) return min(intervals[0][0] for intervals in chan_intervals) except ValueError: # If there are no instructions over channels return 0 def ch_stop_time(self, *channels: Channel) -> int: """Return maximum start time over supplied channels. Args: *channels: Channels within ``self`` to include. """ try: chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots) return max(intervals[-1][1] for intervals in chan_intervals) except ValueError: # If there are no instructions over channels return 0 def _instructions(self, time: int = 0): """Iterable for flattening Schedule tree. Args: time: Shifted time due to parent. Yields: Iterable[Tuple[int, Instruction]]: Tuple containing the time each :class:`~qiskit.pulse.Instruction` starts at and the flattened :class:`~qiskit.pulse.Instruction` s. """ for insert_time, child_sched in self.children: yield from child_sched._instructions(time + insert_time) def shift(self, time: int, name: Optional[str] = None, inplace: bool = False) -> "Schedule": """Return a schedule shifted forward by ``time``. Args: time: Time to shift by. name: Name of the new schedule. Defaults to the name of self. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ if inplace: return self._mutable_shift(time) return self._immutable_shift(time, name=name) def _immutable_shift(self, time: int, name: Optional[str] = None) -> "Schedule": """Return a new schedule shifted forward by `time`. Args: time: Time to shift by name: Name of the new schedule if call was mutable. Defaults to name of self """ shift_sched = Schedule.initialize_from(self, name) shift_sched.insert(time, self, inplace=True) return shift_sched def _mutable_shift(self, time: int) -> "Schedule": """Return this schedule shifted forward by `time`. Args: time: Time to shift by Raises: PulseError: if ``time`` is not an integer. """ if not isinstance(time, int): raise PulseError("Schedule start time must be an integer.") timeslots = {} for chan, ch_timeslots in self._timeslots.items(): timeslots[chan] = [(ts[0] + time, ts[1] + time) for ts in ch_timeslots] _check_nonnegative_timeslot(timeslots) self._duration = self._duration + time self._timeslots = timeslots self._children = [(orig_time + time, child) for orig_time, child in self.children] return self def insert( self, start_time: int, schedule: "ScheduleComponent", name: Optional[str] = None, inplace: bool = False, ) -> "Schedule": """Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``. Args: start_time: Time to insert the schedule. schedule: Schedule to insert. name: Name of the new schedule. Defaults to the name of self. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ if inplace: return self._mutable_insert(start_time, schedule) return self._immutable_insert(start_time, schedule, name=name) def _mutable_insert(self, start_time: int, schedule: "ScheduleComponent") -> "Schedule": """Mutably insert `schedule` into `self` at `start_time`. Args: start_time: Time to insert the second schedule. schedule: Schedule to mutably insert. """ self._add_timeslots(start_time, schedule) self._children.append((start_time, schedule)) self._parameter_manager.update_parameter_table(schedule) return self def _immutable_insert( self, start_time: int, schedule: "ScheduleComponent", name: Optional[str] = None, ) -> "Schedule": """Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``. Args: start_time: Time to insert the schedule. schedule: Schedule to insert. name: Name of the new ``Schedule``. Defaults to name of ``self``. """ new_sched = Schedule.initialize_from(self, name) new_sched._mutable_insert(0, self) new_sched._mutable_insert(start_time, schedule) return new_sched def append( self, schedule: "ScheduleComponent", name: Optional[str] = None, inplace: bool = False ) -> "Schedule": r"""Return a new schedule with ``schedule`` inserted at the maximum time over all channels shared between ``self`` and ``schedule``. .. math:: t = \textrm{max}(\texttt{x.stop_time} |\texttt{x} \in \texttt{self.channels} \cap \texttt{schedule.channels}) Args: schedule: Schedule to be appended. name: Name of the new ``Schedule``. Defaults to name of ``self``. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ common_channels = set(self.channels) & set(schedule.channels) time = self.ch_stop_time(*common_channels) return self.insert(time, schedule, name=name, inplace=inplace) def filter( self, *filter_funcs: Callable, channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, time_ranges: Optional[Iterable[Tuple[int, int]]] = None, intervals: Optional[Iterable[Interval]] = None, check_subroutine: bool = True, ) -> "Schedule": """Return a new ``Schedule`` with only the instructions from this ``Schedule`` which pass though the provided filters; i.e. an instruction will be retained iff every function in ``filter_funcs`` returns ``True``, the instruction occurs on a channel type contained in ``channels``, the instruction type is contained in ``instruction_types``, and the period over which the instruction operates is *fully* contained in one specified in ``time_ranges`` or ``intervals``. If no arguments are provided, ``self`` is returned. Args: filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction]) tuple and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. time_ranges: For example, ``[(0, 5), (6, 10)]``. intervals: For example, ``[(0, 5), (6, 10)]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types, time_ranges, intervals) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=False, recurse_subroutines=check_subroutine ) def exclude( self, *filter_funcs: Callable, channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, time_ranges: Optional[Iterable[Tuple[int, int]]] = None, intervals: Optional[Iterable[Interval]] = None, check_subroutine: bool = True, ) -> "Schedule": """Return a ``Schedule`` with only the instructions from this Schedule *failing* at least one of the provided filters. This method is the complement of py:meth:`~self.filter`, so that:: self.filter(args) | self.exclude(args) == self Args: filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction]) tuple and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. time_ranges: For example, ``[(0, 5), (6, 10)]``. intervals: For example, ``[(0, 5), (6, 10)]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types, time_ranges, intervals) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=True, recurse_subroutines=check_subroutine ) def _add_timeslots(self, time: int, schedule: "ScheduleComponent") -> None: """Update all time tracking within this schedule based on the given schedule. Args: time: The time to insert the schedule into self. schedule: The schedule to insert into self. Raises: PulseError: If timeslots overlap or an invalid start time is provided. """ if not np.issubdtype(type(time), np.integer): raise PulseError("Schedule start time must be an integer.") other_timeslots = _get_timeslots(schedule) self._duration = max(self._duration, time + schedule.duration) for channel in schedule.channels: if channel not in self._timeslots: if time == 0: self._timeslots[channel] = copy.copy(other_timeslots[channel]) else: self._timeslots[channel] = [ (i[0] + time, i[1] + time) for i in other_timeslots[channel] ] continue for idx, interval in enumerate(other_timeslots[channel]): if interval[0] + time >= self._timeslots[channel][-1][1]: # Can append the remaining intervals self._timeslots[channel].extend( [(i[0] + time, i[1] + time) for i in other_timeslots[channel][idx:]] ) break try: interval = (interval[0] + time, interval[1] + time) index = _find_insertion_index(self._timeslots[channel], interval) self._timeslots[channel].insert(index, interval) except PulseError as ex: raise PulseError( "Schedule(name='{new}') cannot be inserted into Schedule(name='{old}') at " "time {time} because its instruction on channel {ch} scheduled from time " "{t0} to {tf} overlaps with an existing instruction." "".format( new=schedule.name or "", old=self.name or "", time=time, ch=channel, t0=interval[0], tf=interval[1], ) ) from ex _check_nonnegative_timeslot(self._timeslots) def _remove_timeslots(self, time: int, schedule: "ScheduleComponent"): """Delete the timeslots if present for the respective schedule component. Args: time: The time to remove the timeslots for the ``schedule`` component. schedule: The schedule to insert into self. Raises: PulseError: If timeslots overlap or an invalid start time is provided. """ if not isinstance(time, int): raise PulseError("Schedule start time must be an integer.") for channel in schedule.channels: if channel not in self._timeslots: raise PulseError(f"The channel {channel} is not present in the schedule") channel_timeslots = self._timeslots[channel] other_timeslots = _get_timeslots(schedule) for interval in other_timeslots[channel]: if channel_timeslots: interval = (interval[0] + time, interval[1] + time) index = _interval_index(channel_timeslots, interval) if channel_timeslots[index] == interval: channel_timeslots.pop(index) continue raise PulseError( "Cannot find interval ({t0}, {tf}) to remove from " "channel {ch} in Schedule(name='{name}').".format( ch=channel, t0=interval[0], tf=interval[1], name=schedule.name ) ) if not channel_timeslots: self._timeslots.pop(channel) def _replace_timeslots(self, time: int, old: "ScheduleComponent", new: "ScheduleComponent"): """Replace the timeslots of ``old`` if present with the timeslots of ``new``. Args: time: The time to remove the timeslots for the ``schedule`` component. old: Instruction to replace. new: Instruction to replace with. """ self._remove_timeslots(time, old) self._add_timeslots(time, new) def _renew_timeslots(self): """Regenerate timeslots based on current instructions.""" self._timeslots.clear() for t0, inst in self.instructions: self._add_timeslots(t0, inst) def replace( self, old: "ScheduleComponent", new: "ScheduleComponent", inplace: bool = False, ) -> "Schedule": """Return a ``Schedule`` with the ``old`` instruction replaced with a ``new`` instruction. The replacement matching is based on an instruction equality check. .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) sched = pulse.Schedule() old = pulse.Play(pulse.Constant(100, 1.0), d0) new = pulse.Play(pulse.Constant(100, 0.1), d0) sched += old sched = sched.replace(old, new) assert sched == pulse.Schedule(new) Only matches at the top-level of the schedule tree. If you wish to perform this replacement over all instructions in the schedule tree. Flatten the schedule prior to running:: .. code-block:: sched = pulse.Schedule() sched += pulse.Schedule(old) sched = sched.flatten() sched = sched.replace(old, new) assert sched == pulse.Schedule(new) Args: old: Instruction to replace. new: Instruction to replace with. inplace: Replace instruction by mutably modifying this ``Schedule``. Returns: The modified schedule with ``old`` replaced by ``new``. Raises: PulseError: If the ``Schedule`` after replacements will has a timing overlap. """ from qiskit.pulse.parameter_manager import ParameterManager new_children = [] new_parameters = ParameterManager() for time, child in self.children: if child == old: new_children.append((time, new)) new_parameters.update_parameter_table(new) else: new_children.append((time, child)) new_parameters.update_parameter_table(child) if inplace: self._children = new_children self._parameter_manager = new_parameters self._renew_timeslots() return self else: try: new_sched = Schedule.initialize_from(self) for time, inst in new_children: new_sched.insert(time, inst, inplace=True) return new_sched except PulseError as err: raise PulseError( f"Replacement of {old} with {new} results in overlapping instructions." ) from err def is_parameterized(self) -> bool: """Return True iff the instruction is parameterized.""" return self._parameter_manager.is_parameterized() def assign_parameters( self, value_dict: Dict[ParameterExpression, ParameterValueType], inplace: bool = True ) -> "Schedule": """Assign the parameters in this schedule according to the input. Args: value_dict: A mapping from Parameters to either numeric values or another Parameter expression. inplace: Set ``True`` to override this instance with new parameter. Returns: Schedule with updated parameters. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_parameters(value_dict, inplace=True) return self._parameter_manager.assign_parameters(pulse_program=self, value_dict=value_dict) def get_parameters(self, parameter_name: str) -> List[Parameter]: """Get parameter object bound to this schedule by string name. Because different ``Parameter`` objects can have the same name, this method returns a list of ``Parameter`` s for the provided name. Args: parameter_name: Name of parameter. Returns: Parameter objects that have corresponding name. """ return self._parameter_manager.get_parameters(parameter_name) def __len__(self) -> int: """Return number of instructions in the schedule.""" return len(self.instructions) def __add__(self, other: "ScheduleComponent") -> "Schedule": """Return a new schedule with ``other`` inserted within ``self`` at ``start_time``.""" return self.append(other) def __or__(self, other: "ScheduleComponent") -> "Schedule": """Return a new schedule which is the union of `self` and `other`.""" return self.insert(0, other) def __lshift__(self, time: int) -> "Schedule": """Return a new schedule which is shifted forward by ``time``.""" return self.shift(time) def __eq__(self, other: "ScheduleComponent") -> bool: """Test if two Schedule are equal. Equality is checked by verifying there is an equal instruction at every time in ``other`` for every instruction in this ``Schedule``. .. warning:: This does not check for logical equivalency. Ie., ```python >>> Delay(10, DriveChannel(0)) + Delay(10, DriveChannel(0)) == Delay(20, DriveChannel(0)) False ``` """ # 0. type check, we consider Instruction is a subtype of schedule if not isinstance(other, (type(self), Instruction)): return False # 1. channel check if set(self.channels) != set(other.channels): return False # 2. size check if len(self.instructions) != len(other.instructions): return False # 3. instruction check return all( self_inst == other_inst for self_inst, other_inst in zip(self.instructions, other.instructions) ) def __repr__(self) -> str: name = format(self._name) if self._name else "" instructions = ", ".join([repr(instr) for instr in self.instructions[:50]]) if len(self.instructions) > 25: instructions += ", ..." return f'{self.__class__.__name__}({instructions}, name="{name}")' def _require_schedule_conversion(function: Callable) -> Callable: """A method decorator to convert schedule block to pulse schedule. This conversation is performed for backward compatibility only if all durations are assigned. """ @functools.wraps(function) def wrapper(self, *args, **kwargs): from qiskit.pulse.transforms import block_to_schedule return function(block_to_schedule(self), *args, **kwargs) return wrapper class ScheduleBlock: """Time-ordered sequence of instructions with alignment context. :class:`.ScheduleBlock` supports lazy scheduling of context instructions, i.e. their timeslots is always generated at runtime. This indicates we can parametrize instruction durations as well as other parameters. In contrast to :class:`.Schedule` being somewhat static, :class:`.ScheduleBlock` is a dynamic representation of a pulse program. .. rubric:: Pulse Builder The Qiskit pulse builder is a domain specific language that is developed on top of the schedule block. Use of the builder syntax will improve the workflow of pulse programming. See :ref:`pulse_builder` for a user guide. .. rubric:: Alignment contexts A schedule block is always relatively scheduled. Instead of taking individual instructions with absolute execution time ``t0``, the schedule block defines a context of scheduling and instructions under the same context are scheduled in the same manner (alignment). Several contexts are available in :ref:`pulse_alignments`. A schedule block is instantiated with one of these alignment contexts. The default context is :class:`AlignLeft`, for which all instructions are left-justified, in other words, meaning they use as-soon-as-possible scheduling. If you need an absolute-time interval in between instructions, you can explicitly insert :class:`~qiskit.pulse.instructions.Delay` instructions. .. rubric:: Nested blocks A schedule block can contain other nested blocks with different alignment contexts. This enables advanced scheduling, where a subset of instructions is locally scheduled in a different manner. Note that a :class:`.Schedule` instance cannot be directly added to a schedule block. To add a :class:`.Schedule` instance, wrap it in a :class:`.Call` instruction. This is implicitly performed when a schedule is added through the :ref:`pulse_builder`. .. rubric:: Unsupported operations Because the schedule block representation lacks timeslots, it cannot perform particular :class:`.Schedule` operations such as :meth:`insert` or :meth:`shift` that require instruction start time ``t0``. In addition, :meth:`exclude` and :meth:`filter` methods are not supported because these operations may identify the target instruction with ``t0``. Except for these operations, :class:`.ScheduleBlock` provides full compatibility with :class:`.Schedule`. .. rubric:: Subroutine The timeslots-free representation offers much greater flexibility for writing pulse programs. Because :class:`.ScheduleBlock` only cares about the ordering of the child blocks we can add an undefined pulse sequence as a subroutine of the main program. If your program contains the same sequence multiple times, this representation may reduce the memory footprint required by the program construction. Such a subroutine is realized by the special compiler directive :class:`~qiskit.pulse.instructions.Reference` that is defined by a unique set of reference key strings to the subroutine. The (executable) subroutine is separately stored in the main program. Appended reference directives are resolved when the main program is executed. Subroutines must be assigned through :meth:`assign_references` before execution. .. rubric:: Program Scoping When you call a subroutine from another subroutine, or append a schedule block to another schedule block, the management of references and parameters can be a hard task. Schedule block offers a convenient feature to help with this by automatically scoping the parameters and subroutines. .. code-block:: from qiskit import pulse from qiskit.circuit.parameter import Parameter amp1 = Parameter("amp") with pulse.build() as sched1: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) print(sched1.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp),) The :meth:`~ScheduleBlock.scoped_parameters` method returns all :class:`~.Parameter` objects defined in the schedule block. The parameter name is updated to reflect its scope information, i.e. where it is defined. The outer scope is called "root". Since the "amp" parameter is directly used in the current builder context, it is prefixed with "root". Note that the :class:`Parameter` object returned by :meth:`~ScheduleBlock.scoped_parameters` preserves the hidden `UUID`_ key, and thus the scoped name doesn't break references to the original :class:`Parameter`. You may want to call this program from another program. In this example, the program is called with the reference key "grand_child". You can call a subroutine without specifying a substantial program (like ``sched1`` above which we will assign later). .. code-block:: amp2 = Parameter("amp") with pulse.build() as sched2: with pulse.align_right(): pulse.reference("grand_child") pulse.play(pulse.Constant(200, amp2), pulse.DriveChannel(0)) print(sched2.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp),) This only returns "root::amp" because the "grand_child" reference is unknown. Now you assign the actual pulse program to this reference. .. code-block:: sched2.assign_references({("grand_child", ): sched1}) print(sched2.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp), Parameter(root::grand_child::amp)) Now you get two parameters "root::amp" and "root::grand_child::amp". The second parameter name indicates it is defined within the referred program "grand_child". The program calling the "grand_child" has a reference program description which is accessed through :attr:`ScheduleBlock.references`. .. code-block:: print(sched2.references) .. parsed-literal:: ReferenceManager: - ('grand_child',): ScheduleBlock(Play(Constant(duration=100, amp=amp,... Finally, you may want to call this program from another program. Here we try a different approach to define subroutine. Namely, we call a subroutine from the root program with the actual program ``sched2``. .. code-block:: amp3 = Parameter("amp") with pulse.build() as main: pulse.play(pulse.Constant(300, amp3), pulse.DriveChannel(0)) pulse.call(sched2, name="child") print(main.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp), Parameter(root::child::amp), Parameter(root::child::grand_child::amp)) This implicitly creates a reference named "child" within the root program and assigns ``sched2`` to it. You get three parameters "root::amp", "root::child::amp", and "root::child::grand_child::amp". As you can see, each parameter name reflects the layer of calls from the root program. If you know the scope of a parameter, you can directly get the parameter object using :meth:`ScheduleBlock.search_parameters` as follows. .. code-block:: main.search_parameters("root::child::grand_child::amp") You can use a regular expression to specify the scope. The following returns the parameters defined within the scope of "ground_child" regardless of its parent scope. This is sometimes convenient if you want to extract parameters from a deeply nested program. .. code-block:: main.search_parameters("\\S::grand_child::amp") Note that the root program is only aware of its direct references. .. code-block:: print(main.references) .. parsed-literal:: ReferenceManager: - ('child',): ScheduleBlock(ScheduleBlock(ScheduleBlock(Play(Con... As you can see the main program cannot directly assign a subroutine to the "grand_child" because this subroutine is not called within the root program, i.e. it is indirectly called by "child". However, the returned :class:`.ReferenceManager` is a dict-like object, and you can still reach to "grand_child" via the "child" program with the following chained dict access. .. code-block:: main.references[("child", )].references[("grand_child", )] Note that :attr:`ScheduleBlock.parameters` and :meth:`ScheduleBlock.scoped_parameters()` still collect all parameters also from the subroutine once it's assigned. .. _UUID: https://docs.python.org/3/library/uuid.html#module-uuid """ __slots__ = ( "_parent", "_name", "_reference_manager", "_parameter_manager", "_alignment_context", "_blocks", "_metadata", ) # Prefix to use for auto naming. prefix = "block" # Counter to count instance number. instances_counter = itertools.count() def __init__( self, name: Optional[str] = None, metadata: Optional[dict] = None, alignment_context=None ): """Create an empty schedule block. Args: name: Name of this schedule. Defaults to an autogenerated string if not provided. metadata: Arbitrary key value metadata to associate with the schedule. This gets stored as free-form data in a dict in the :attr:`~qiskit.pulse.ScheduleBlock.metadata` attribute. It will not be directly used in the schedule. alignment_context (AlignmentKind): ``AlignmentKind`` instance that manages scheduling of instructions in this block. Raises: TypeError: if metadata is not a dict. """ from qiskit.pulse.parameter_manager import ParameterManager from qiskit.pulse.transforms import AlignLeft if name is None: name = self.prefix + str(next(self.instances_counter)) if sys.platform != "win32" and not is_main_process(): name += f"-{mp.current_process().pid}" # This points to the parent schedule object in the current scope. # Note that schedule block can be nested without referencing, e.g. .append(child_block), # and parent=None indicates the root program of the current scope. # The nested schedule block objects should not have _reference_manager and # should refer to the one of the root program. # This also means referenced program should be assigned to the root program, not to child. self._parent = None self._name = name self._parameter_manager = ParameterManager() self._reference_manager = ReferenceManager() self._alignment_context = alignment_context or AlignLeft() self._blocks = [] # get parameters from context self._parameter_manager.update_parameter_table(self._alignment_context) if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @classmethod def initialize_from(cls, other_program: Any, name: Optional[str] = None) -> "ScheduleBlock": """Create new schedule object with metadata of another schedule object. Args: other_program: Qiskit program that provides metadata to new object. name: Name of new schedule. Name of ``block`` is used by default. Returns: New block object with name and metadata. Raises: PulseError: When ``other_program`` does not provide necessary information. """ try: name = name or other_program.name if other_program.metadata: metadata = other_program.metadata.copy() else: metadata = None try: alignment_context = other_program.alignment_context except AttributeError: alignment_context = None return cls(name=name, metadata=metadata, alignment_context=alignment_context) except AttributeError as ex: raise PulseError( f"{cls.__name__} cannot be initialized from the program data " f"{other_program.__class__.__name__}." ) from ex @property def name(self) -> str: """Return name of this schedule""" return self._name @property def metadata(self) -> Dict[str, Any]: """The user provided metadata associated with the schedule. User provided ``dict`` of metadata for the schedule. The metadata contents do not affect the semantics of the program but are used to influence the execution of the schedule. It is expected to be passed between all transforms of the schedule and that providers will associate any schedule metadata with the results it returns from the execution of that schedule. """ return self._metadata @metadata.setter def metadata(self, metadata): """Update the schedule metadata""" if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @property def alignment_context(self): """Return alignment instance that allocates block component to generate schedule.""" return self._alignment_context def is_schedulable(self) -> bool: """Return ``True`` if all durations are assigned.""" # check context assignment for context_param in self._alignment_context._context_params: if isinstance(context_param, ParameterExpression): return False # check duration assignment for elm in self.blocks: if isinstance(elm, ScheduleBlock): if not elm.is_schedulable(): return False else: try: if not isinstance(elm.duration, int): return False except UnassignedReferenceError: return False return True @property @_require_schedule_conversion def duration(self) -> int: """Duration of this schedule block.""" return self.duration @property def channels(self) -> Tuple[Channel]: """Returns channels that this schedule block uses.""" chans = set() for elm in self.blocks: if isinstance(elm, Reference): raise UnassignedReferenceError( f"This schedule contains unassigned reference {elm.ref_keys} " "and channels are ambiguous. Please assign the subroutine first." ) chans = chans | set(elm.channels) return tuple(chans) @property @_require_schedule_conversion def instructions(self) -> Tuple[Tuple[int, Instruction]]: """Get the time-ordered instructions from self.""" return self.instructions @property def blocks(self) -> Tuple["BlockComponent", ...]: """Get the block elements added to self. .. note:: The sequence of elements is returned in order of addition. Because the first element is schedule first, e.g. FIFO, the returned sequence is roughly time-ordered. However, in the parallel alignment context, especially in the as-late-as-possible scheduling, or :class:`.AlignRight` context, the actual timing of when the instructions are issued is unknown until the :class:`.ScheduleBlock` is scheduled and converted into a :class:`.Schedule`. """ blocks = [] for elm in self._blocks: if isinstance(elm, Reference): elm = self.references.get(elm.ref_keys, None) or elm blocks.append(elm) return tuple(blocks) @property def parameters(self) -> Set[Parameter]: """Return unassigned parameters with raw names.""" # Need new object not to mutate parameter_manager.parameters out_params = set() out_params |= self._parameter_manager.parameters for subroutine in self.references.values(): if subroutine is None: continue out_params |= subroutine.parameters return out_params def scoped_parameters(self) -> Tuple[Parameter]: """Return unassigned parameters with scoped names. .. note:: If a parameter is defined within a nested scope, it is prefixed with all parent-scope names with the delimiter string, which is "::". If a reference key of the scope consists of multiple key strings, it will be represented by a single string joined with ",". For example, "root::xgate,q0::amp" for the parameter "amp" defined in the reference specified by the key strings ("xgate", "q0"). """ return tuple( sorted( _collect_scoped_parameters(self, current_scope="root").values(), key=lambda p: p.name, ) ) @property def references(self) -> ReferenceManager: """Return a reference manager of the current scope.""" if self._parent is not None: return self._parent.references return self._reference_manager @_require_schedule_conversion def ch_duration(self, *channels: Channel) -> int: """Return the time of the end of the last instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ return self.ch_duration(*channels) def append( self, block: "BlockComponent", name: Optional[str] = None, inplace: bool = True ) -> "ScheduleBlock": """Return a new schedule block with ``block`` appended to the context block. The execution time is automatically assigned when the block is converted into schedule. Args: block: ScheduleBlock to be appended. name: Name of the new ``Schedule``. Defaults to name of ``self``. inplace: Perform operation inplace on this schedule. Otherwise, return a new ``Schedule``. Returns: Schedule block with appended schedule. Raises: PulseError: When invalid schedule type is specified. """ if not isinstance(block, (ScheduleBlock, Instruction)): raise PulseError( f"Appended `schedule` {block.__class__.__name__} is invalid type. " "Only `Instruction` and `ScheduleBlock` can be accepted." ) if not inplace: schedule = copy.deepcopy(self) schedule._name = name or self.name schedule.append(block, inplace=True) return schedule if isinstance(block, Reference) and block.ref_keys not in self.references: self.references[block.ref_keys] = None elif isinstance(block, ScheduleBlock): block = copy.deepcopy(block) # Expose subroutines to the current main scope. # Note that this 'block' is not called. # The block is just directly appended to the current scope. if block.is_referenced(): if block._parent is not None: # This is an edge case: # If this is not a parent, block.references points to the parent's reference # where subroutine not referred within the 'block' may exist. # Move only references existing in the 'block'. # See 'test.python.pulse.test_reference.TestReference.test_appending_child_block' for ref in _get_references(block._blocks): self.references[ref.ref_keys] = block.references[ref.ref_keys] else: # Avoid using dict.update and explicitly call __set_item__ for validation. # Reference manager of appended block is cleared because of data reduction. for ref_keys, ref in block._reference_manager.items(): self.references[ref_keys] = ref block._reference_manager.clear() # Now switch the parent because block is appended to self. block._parent = self self._blocks.append(block) self._parameter_manager.update_parameter_table(block) return self def filter( self, *filter_funcs: List[Callable], channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, check_subroutine: bool = True, ): """Return a new ``ScheduleBlock`` with only the instructions from this ``ScheduleBlock`` which pass though the provided filters; i.e. an instruction will be retained if every function in ``filter_funcs`` returns ``True``, the instruction occurs on a channel type contained in ``channels``, and the instruction type is contained in ``instruction_types``. .. warning:: Because ``ScheduleBlock`` is not aware of the execution time of the context instructions, filtering out some instructions may change the execution time of the remaining instructions. If no arguments are provided, ``self`` is returned. Args: filter_funcs: A list of Callables which take a ``Instruction`` and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. check_subroutine: Set `True` to individually filter instructions inside a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. Returns: ``ScheduleBlock`` consisting of instructions that matches with filtering condition. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=False, recurse_subroutines=check_subroutine ) def exclude( self, *filter_funcs: List[Callable], channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, check_subroutine: bool = True, ): """Return a new ``ScheduleBlock`` with only the instructions from this ``ScheduleBlock`` *failing* at least one of the provided filters. This method is the complement of py:meth:`~self.filter`, so that:: self.filter(args) + self.exclude(args) == self in terms of instructions included. .. warning:: Because ``ScheduleBlock`` is not aware of the execution time of the context instructions, excluding some instructions may change the execution time of the remaining instructions. Args: filter_funcs: A list of Callables which take a ``Instruction`` and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. Returns: ``ScheduleBlock`` consisting of instructions that do not match with at least one of filtering conditions. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=True, recurse_subroutines=check_subroutine ) def replace( self, old: "BlockComponent", new: "BlockComponent", inplace: bool = True, ) -> "ScheduleBlock": """Return a ``ScheduleBlock`` with the ``old`` component replaced with a ``new`` component. Args: old: Schedule block component to replace. new: Schedule block component to replace with. inplace: Replace instruction by mutably modifying this ``ScheduleBlock``. Returns: The modified schedule block with ``old`` replaced by ``new``. """ if not inplace: schedule = copy.deepcopy(self) return schedule.replace(old, new, inplace=True) if old not in self._blocks: # Avoid unnecessary update of reference and parameter manager return self # Temporarily copies references all_references = ReferenceManager() if isinstance(new, ScheduleBlock): new = copy.deepcopy(new) all_references.update(new.references) new._reference_manager.clear() new._parent = self for ref_key, subroutine in self.references.items(): if ref_key in all_references: warnings.warn( f"Reference {ref_key} conflicts with substituted program {new.name}. " "Existing reference has been replaced with new reference.", UserWarning, ) continue all_references[ref_key] = subroutine # Regenerate parameter table by regenerating elements. # Note that removal of parameters in old is not sufficient, # because corresponding parameters might be also used in another block element. self._parameter_manager.clear() self._parameter_manager.update_parameter_table(self._alignment_context) new_elms = [] for elm in self._blocks: if elm == old: elm = new self._parameter_manager.update_parameter_table(elm) new_elms.append(elm) self._blocks = new_elms # Regenerate reference table # Note that reference is attached to the outer schedule if nested. # Thus, this investigates all references within the scope. self.references.clear() root = self while root._parent is not None: root = root._parent for ref in _get_references(root._blocks): self.references[ref.ref_keys] = all_references[ref.ref_keys] return self def is_parameterized(self) -> bool: """Return True iff the instruction is parameterized.""" return any(self.parameters) def is_referenced(self) -> bool: """Return True iff the current schedule block contains reference to subroutine.""" return len(self.references) > 0 def assign_parameters( self, value_dict: Dict[ParameterExpression, ParameterValueType], inplace: bool = True, ) -> "ScheduleBlock": """Assign the parameters in this schedule according to the input. Args: value_dict: A mapping from Parameters to either numeric values or another Parameter expression. inplace: Set ``True`` to override this instance with new parameter. Returns: Schedule with updated parameters. Raises: PulseError: When the block is nested into another block. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_parameters(value_dict, inplace=True) # Update parameters in the current scope self._parameter_manager.assign_parameters(pulse_program=self, value_dict=value_dict) for subroutine in self._reference_manager.values(): # Also assigning parameters to the references associated with self. # Note that references are always stored in the root program. # So calling assign_parameters from nested block doesn't update references. if subroutine is None: continue subroutine.assign_parameters(value_dict=value_dict, inplace=True) return self def assign_references( self, subroutine_dict: Dict[Union[str, Tuple[str, ...]], "ScheduleBlock"], inplace: bool = True, ) -> "ScheduleBlock": """Assign schedules to references. It is only capable of assigning a schedule block to immediate references which are directly referred within the current scope. Let's see following example: .. code-block:: python from qiskit import pulse with pulse.build() as subroutine: pulse.delay(10, pulse.DriveChannel(0)) with pulse.build() as sub_prog: pulse.reference("A") with pulse.build() as main_prog: pulse.reference("B") In above example, the ``main_prog`` can refer to the subroutine "root::B" and the reference of "B" to program "A", i.e., "B::A", is not defined in the root namespace. This prevents breaking the reference "root::B::A" by the assignment of "root::B". For example, if a user could indirectly assign "root::B::A" from the root program, one can later assign another program to "root::B" that doesn't contain "A" within it. In this situation, a reference "root::B::A" would still live in the reference manager of the root. However, the subroutine "root::B::A" would no longer be used in the actual pulse program. To assign subroutine "A" to ``nested_prog`` as a nested subprogram of ``main_prog``, you must first assign "A" of the ``sub_prog``, and then assign the ``sub_prog`` to the ``main_prog``. .. code-block:: python sub_prog.assign_references({("A", ): nested_prog}, inplace=True) main_prog.assign_references({("B", ): sub_prog}, inplace=True) Alternatively, you can also write .. code-block:: python main_prog.assign_references({("B", ): sub_prog}, inplace=True) main_prog.references[("B", )].assign_references({"A": nested_prog}, inplace=True) Here :attr:`.references` returns a dict-like object, and you can mutably update the nested reference of the particular subroutine. .. note:: Assigned programs are deep-copied to prevent an unexpected update. Args: subroutine_dict: A mapping from reference key to schedule block of the subroutine. inplace: Set ``True`` to override this instance with new subroutine. Returns: Schedule block with assigned subroutine. Raises: PulseError: When reference key is not defined in the current scope. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_references(subroutine_dict, inplace=True) for key, subroutine in subroutine_dict.items(): if key not in self.references: unassigned_keys = ", ".join(map(repr, self.references.unassigned())) raise PulseError( f"Reference instruction with {key} doesn't exist " f"in the current scope: {unassigned_keys}" ) self.references[key] = copy.deepcopy(subroutine) return self def get_parameters(self, parameter_name: str) -> List[Parameter]: """Get parameter object bound to this schedule by string name. Note that we can define different parameter objects with the same name, because these different objects are identified by their unique uuid. For example, .. code-block:: python from qiskit import pulse, circuit amp1 = circuit.Parameter("amp") amp2 = circuit.Parameter("amp") with pulse.build() as sub_prog: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(sub_prog, name="sub") pulse.play(pulse.Constant(100, amp2), pulse.DriveChannel(0)) main_prog.get_parameters("amp") This returns a list of two parameters ``amp1`` and ``amp2``. Args: parameter_name: Name of parameter. Returns: Parameter objects that have corresponding name. """ matched = [p for p in self.parameters if p.name == parameter_name] return matched def search_parameters(self, parameter_regex: str) -> List[Parameter]: """Search parameter with regular expression. This method looks for the scope-aware parameters. For example, .. code-block:: python from qiskit import pulse, circuit amp1 = circuit.Parameter("amp") amp2 = circuit.Parameter("amp") with pulse.build() as sub_prog: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(sub_prog, name="sub") pulse.play(pulse.Constant(100, amp2), pulse.DriveChannel(0)) main_prog.search_parameters("root::sub::amp") This finds ``amp1`` with scoped name "root::sub::amp". Args: parameter_regex: Regular expression for scoped parameter name. Returns: Parameter objects that have corresponding name. """ pattern = re.compile(parameter_regex) return sorted( _collect_scoped_parameters(self, current_scope="root", filter_regex=pattern).values(), key=lambda p: p.name, ) def __len__(self) -> int: """Return number of instructions in the schedule.""" return len(self.blocks) def __eq__(self, other: "ScheduleBlock") -> bool: """Test if two ScheduleBlocks are equal. Equality is checked by verifying there is an equal instruction at every time in ``other`` for every instruction in this ``ScheduleBlock``. This check is performed by converting the instruction representation into directed acyclic graph, in which execution order of every instruction is evaluated correctly across all channels. Also ``self`` and ``other`` should have the same alignment context. .. warning:: This does not check for logical equivalency. Ie., ```python >>> Delay(10, DriveChannel(0)) + Delay(10, DriveChannel(0)) == Delay(20, DriveChannel(0)) False ``` """ # 0. type check if not isinstance(other, type(self)): return False # 1. transformation check if self.alignment_context != other.alignment_context: return False # 2. size check if len(self) != len(other): return False # 3. instruction check with alignment from qiskit.pulse.transforms.dag import block_to_dag as dag if not rx.is_isomorphic_node_match(dag(self), dag(other), lambda x, y: x == y): return False return True def __repr__(self) -> str: name = format(self._name) if self._name else "" blocks = ", ".join([repr(instr) for instr in self.blocks[:50]]) if len(self.blocks) > 25: blocks += ", ..." return '{}({}, name="{}", transform={})'.format( self.__class__.__name__, blocks, name, repr(self.alignment_context) ) def __add__(self, other: "BlockComponent") -> "ScheduleBlock": """Return a new schedule with ``other`` inserted within ``self`` at ``start_time``.""" return self.append(other) def _common_method(*classes): """A function decorator to attach the function to specified classes as a method. .. note:: For developer: A method attached through this decorator may hurt readability of the codebase, because the method may not be detected by a code editor. Thus, this decorator should be used to a limited extent, i.e. huge helper method. By using this decorator wisely, we can reduce code maintenance overhead without losing readability of the codebase. """ def decorator(method): @functools.wraps(method) def wrapper(*args, **kwargs): return method(*args, **kwargs) for cls in classes: setattr(cls, method.__name__, wrapper) return method return decorator @_common_method(Schedule, ScheduleBlock) def draw( self, style: Optional[Dict[str, Any]] = None, backend=None, # importing backend causes cyclic import time_range: Optional[Tuple[int, int]] = None, time_unit: str = "dt", disable_channels: Optional[List[Channel]] = None, show_snapshot: bool = True, show_framechange: bool = True, show_waveform_info: bool = True, show_barrier: bool = True, plotter: str = "mpl2d", axis: Optional[Any] = None, ): """Plot the schedule. Args: style: Stylesheet options. This can be dictionary or preset stylesheet classes. See :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXStandard`, :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXSimple`, and :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXDebugging` for details of preset stylesheets. backend (Optional[BaseBackend]): Backend object to play the input pulse program. If provided, the plotter may use to make the visualization hardware aware. time_range: Set horizontal axis limit. Tuple `(tmin, tmax)`. time_unit: The unit of specified time range either `dt` or `ns`. The unit of `ns` is available only when `backend` object is provided. disable_channels: A control property to show specific pulse channel. Pulse channel instances provided as a list are not shown in the output image. show_snapshot: Show snapshot instructions. show_framechange: Show frame change instructions. The frame change represents instructions that modulate phase or frequency of pulse channels. show_waveform_info: Show additional information about waveforms such as their name. show_barrier: Show barrier lines. plotter: Name of plotter API to generate an output image. One of following APIs should be specified:: mpl2d: Matplotlib API for 2D image generation. Matplotlib API to generate 2D image. Charts are placed along y axis with vertical offset. This API takes matplotlib.axes.Axes as ``axis`` input. ``axis`` and ``style`` kwargs may depend on the plotter. axis: Arbitrary object passed to the plotter. If this object is provided, the plotters use a given ``axis`` instead of internally initializing a figure object. This object format depends on the plotter. See plotter argument for details. Returns: Visualization output data. The returned data type depends on the ``plotter``. If matplotlib family is specified, this will be a ``matplotlib.pyplot.Figure`` data. """ # pylint: disable=cyclic-import from qiskit.visualization import pulse_drawer return pulse_drawer( program=self, style=style, backend=backend, time_range=time_range, time_unit=time_unit, disable_channels=disable_channels, show_snapshot=show_snapshot, show_framechange=show_framechange, show_waveform_info=show_waveform_info, show_barrier=show_barrier, plotter=plotter, axis=axis, ) def _interval_index(intervals: List[Interval], interval: Interval) -> int: """Find the index of an interval. Args: intervals: A sorted list of non-overlapping Intervals. interval: The interval for which the index into intervals will be found. Returns: The index of the interval. Raises: PulseError: If the interval does not exist. """ index = _locate_interval_index(intervals, interval) found_interval = intervals[index] if found_interval != interval: raise PulseError(f"The interval: {interval} does not exist in intervals: {intervals}") return index def _locate_interval_index(intervals: List[Interval], interval: Interval, index: int = 0) -> int: """Using binary search on start times, find an interval. Args: intervals: A sorted list of non-overlapping Intervals. interval: The interval for which the index into intervals will be found. index: A running tally of the index, for recursion. The user should not pass a value. Returns: The index into intervals that new_interval would be inserted to maintain a sorted list of intervals. """ if not intervals or len(intervals) == 1: return index mid_idx = len(intervals) // 2 mid = intervals[mid_idx] if interval[1] <= mid[0] and (interval != mid): return _locate_interval_index(intervals[:mid_idx], interval, index=index) else: return _locate_interval_index(intervals[mid_idx:], interval, index=index + mid_idx) def _find_insertion_index(intervals: List[Interval], new_interval: Interval) -> int: """Using binary search on start times, return the index into `intervals` where the new interval belongs, or raise an error if the new interval overlaps with any existing ones. Args: intervals: A sorted list of non-overlapping Intervals. new_interval: The interval for which the index into intervals will be found. Returns: The index into intervals that new_interval should be inserted to maintain a sorted list of intervals. Raises: PulseError: If new_interval overlaps with the given intervals. """ index = _locate_interval_index(intervals, new_interval) if index < len(intervals): if _overlaps(intervals[index], new_interval): raise PulseError("New interval overlaps with existing.") return index if new_interval[1] <= intervals[index][0] else index + 1 return index def _overlaps(first: Interval, second: Interval) -> bool: """Return True iff first and second overlap. Note: first.stop may equal second.start, since Interval stop times are exclusive. """ if first[0] == second[0] == second[1]: # They fail to overlap if one of the intervals has duration 0 return False if first[0] > second[0]: first, second = second, first return second[0] < first[1] def _check_nonnegative_timeslot(timeslots: TimeSlots): """Test that a channel has no negative timeslots. Raises: PulseError: If a channel timeslot is negative. """ for chan, chan_timeslots in timeslots.items(): if chan_timeslots: if chan_timeslots[0][0] < 0: raise PulseError(f"An instruction on {chan} has a negative starting time.") def _get_timeslots(schedule: "ScheduleComponent") -> TimeSlots: """Generate timeslots from given schedule component. Args: schedule: Input schedule component. Raises: PulseError: When invalid schedule type is specified. """ if isinstance(schedule, Instruction): duration = schedule.duration instruction_duration_validation(duration) timeslots = {channel: [(0, duration)] for channel in schedule.channels} elif isinstance(schedule, Schedule): timeslots = schedule.timeslots else: raise PulseError(f"Invalid schedule type {type(schedule)} is specified.") return timeslots def _get_references(block_elms: List["BlockComponent"]) -> Set[Reference]: """Recursively get reference instructions in the current scope. Args: block_elms: List of schedule block elements to investigate. Returns: A set of unique reference instructions. """ references = set() for elm in block_elms: if isinstance(elm, ScheduleBlock): references |= _get_references(elm._blocks) elif isinstance(elm, Reference): references.add(elm) return references def _collect_scoped_parameters( schedule: ScheduleBlock, current_scope: str, filter_regex: Optional[re.Pattern] = None, ) -> Dict[Tuple[str, int], Parameter]: """A helper function to collect parameters from all references in scope-aware fashion. Parameter object is renamed with attached scope information but its UUID is remained. This means object is treated identically on the assignment logic. This function returns a dictionary of all parameters existing in the target program including its reference, which is keyed on the unique identifier consisting of scoped parameter name and parameter object UUID. This logic prevents parameter clash in the different scope. For example, when two parameter objects with the same UUID exist in different references, both of them appear in the output dictionary, even though they are technically the same object. This feature is particularly convenient to search parameter object with associated scope. Args: schedule: Schedule to get parameters. current_scope: Name of scope where schedule exist. filter_regex: Optional. Compiled regex to sort parameter by name. Returns: A dictionary of scoped parameter objects. """ parameters_out = {} for param in schedule._parameter_manager.parameters: new_name = f"{current_scope}{Reference.scope_delimiter}{param.name}" if filter_regex and not re.search(filter_regex, new_name): continue scoped_param = Parameter.__new__(Parameter, new_name, uuid=getattr(param, "_uuid")) scoped_param.__init__(new_name) unique_key = new_name, hash(param) parameters_out[unique_key] = scoped_param for sub_namespace, subroutine in schedule.references.items(): if subroutine is None: continue composite_key = Reference.key_delimiter.join(sub_namespace) full_path = f"{current_scope}{Reference.scope_delimiter}{composite_key}" sub_parameters = _collect_scoped_parameters( subroutine, current_scope=full_path, filter_regex=filter_regex ) parameters_out.update(sub_parameters) return parameters_out # These type aliases are defined at the bottom of the file, because as of 2022-01-18 they are # imported into other parts of Terra. Previously, the aliases were at the top of the file and used # forwards references within themselves. This was fine within the same file, but causes scoping # issues when the aliases are imported into different scopes, in which the `ForwardRef` instances # would no longer resolve. Instead, we only use forward references in the annotations of _this_ # file to reference the aliases, which are guaranteed to resolve in scope, so the aliases can all be # concrete. ScheduleComponent = Union[Schedule, Instruction] """An element that composes a pulse schedule.""" BlockComponent = Union[ScheduleBlock, Instruction] """An element that composes a pulse schedule block."""
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Basic rescheduling functions which take schedule or instructions and return new schedules.""" import warnings from collections import defaultdict from typing import List, Optional, Iterable, Union, Type import numpy as np from qiskit.pulse import channels as chans, exceptions, instructions from qiskit.pulse.channels import ClassicalIOChannel from qiskit.pulse.exceptions import PulseError from qiskit.pulse.exceptions import UnassignedDurationError from qiskit.pulse.instruction_schedule_map import InstructionScheduleMap from qiskit.pulse.instructions import directives from qiskit.pulse.schedule import Schedule, ScheduleBlock, ScheduleComponent def block_to_schedule(block: ScheduleBlock) -> Schedule: """Convert ``ScheduleBlock`` to ``Schedule``. Args: block: A ``ScheduleBlock`` to convert. Returns: Scheduled pulse program. Raises: UnassignedDurationError: When any instruction duration is not assigned. PulseError: When the alignment context duration is shorter than the schedule duration. .. note:: This transform may insert barriers in between contexts. """ if not block.is_schedulable(): raise UnassignedDurationError( "All instruction durations should be assigned before creating `Schedule`." "Please check `.parameters` to find unassigned parameter objects." ) schedule = Schedule.initialize_from(block) for op_data in block.blocks: if isinstance(op_data, ScheduleBlock): context_schedule = block_to_schedule(op_data) if hasattr(op_data.alignment_context, "duration"): # context may have local scope duration, e.g. EquispacedAlignment for 1000 dt post_buffer = op_data.alignment_context.duration - context_schedule.duration if post_buffer < 0: raise PulseError( f"ScheduleBlock {op_data.name} has longer duration than " "the specified context duration " f"{context_schedule.duration} > {op_data.duration}." ) else: post_buffer = 0 schedule.append(context_schedule, inplace=True) # prevent interruption by following instructions. # padding with delay instructions is no longer necessary, thanks to alignment context. if post_buffer > 0: context_boundary = instructions.RelativeBarrier(*op_data.channels) schedule.append(context_boundary.shift(post_buffer), inplace=True) else: schedule.append(op_data, inplace=True) # transform with defined policy return block.alignment_context.align(schedule) def compress_pulses(schedules: List[Schedule]) -> List[Schedule]: """Optimization pass to replace identical pulses. Args: schedules: Schedules to compress. Returns: Compressed schedules. """ existing_pulses = [] new_schedules = [] for schedule in schedules: new_schedule = Schedule.initialize_from(schedule) for time, inst in schedule.instructions: if isinstance(inst, instructions.Play): if inst.pulse in existing_pulses: idx = existing_pulses.index(inst.pulse) identical_pulse = existing_pulses[idx] new_schedule.insert( time, instructions.Play(identical_pulse, inst.channel, inst.name), inplace=True, ) else: existing_pulses.append(inst.pulse) new_schedule.insert(time, inst, inplace=True) else: new_schedule.insert(time, inst, inplace=True) new_schedules.append(new_schedule) return new_schedules def flatten(program: Schedule) -> Schedule: """Flatten (inline) any called nodes into a Schedule tree with no nested children. Args: program: Pulse program to remove nested structure. Returns: Flatten pulse program. Raises: PulseError: When invalid data format is given. """ if isinstance(program, Schedule): flat_sched = Schedule.initialize_from(program) for time, inst in program.instructions: flat_sched.insert(time, inst, inplace=True) return flat_sched else: raise PulseError(f"Invalid input program {program.__class__.__name__} is specified.") def inline_subroutines(program: Union[Schedule, ScheduleBlock]) -> Union[Schedule, ScheduleBlock]: """Recursively remove call instructions and inline the respective subroutine instructions. Assigned parameter values, which are stored in the parameter table, are also applied. The subroutine is copied before the parameter assignment to avoid mutation problem. Args: program: A program which may contain the subroutine, i.e. ``Call`` instruction. Returns: A schedule without subroutine. Raises: PulseError: When input program is not valid data format. """ if isinstance(program, Schedule): return _inline_schedule(program) elif isinstance(program, ScheduleBlock): return _inline_block(program) else: raise PulseError(f"Invalid program {program.__class__.__name__} is specified.") def _inline_schedule(schedule: Schedule) -> Schedule: """A helper function to inline subroutine of schedule. .. note:: If subroutine is ``ScheduleBlock`` it is converted into Schedule to get ``t0``. """ ret_schedule = Schedule.initialize_from(schedule) for t0, inst in schedule.children: # note that schedule.instructions unintentionally flatten the nested schedule. # this should be performed by another transformer node. if isinstance(inst, instructions.Call): # bind parameter subroutine = inst.assigned_subroutine() # convert into schedule if block is given if isinstance(subroutine, ScheduleBlock): subroutine = block_to_schedule(subroutine) # recursively inline the program inline_schedule = _inline_schedule(subroutine) ret_schedule.insert(t0, inline_schedule, inplace=True) elif isinstance(inst, Schedule): # recursively inline the program inline_schedule = _inline_schedule(inst) ret_schedule.insert(t0, inline_schedule, inplace=True) else: ret_schedule.insert(t0, inst, inplace=True) return ret_schedule def _inline_block(block: ScheduleBlock) -> ScheduleBlock: """A helper function to inline subroutine of schedule block. .. note:: If subroutine is ``Schedule`` the function raises an error. """ ret_block = ScheduleBlock.initialize_from(block) for inst in block.blocks: if isinstance(inst, instructions.Call): # bind parameter subroutine = inst.assigned_subroutine() if isinstance(subroutine, Schedule): raise PulseError( f"A subroutine {subroutine.name} is a pulse Schedule. " "This program cannot be inserted into ScheduleBlock because " "t0 associated with instruction will be lost." ) # recursively inline the program inline_block = _inline_block(subroutine) ret_block.append(inline_block, inplace=True) elif isinstance(inst, ScheduleBlock): # recursively inline the program inline_block = _inline_block(inst) ret_block.append(inline_block, inplace=True) else: ret_block.append(inst, inplace=True) return ret_block def remove_directives(schedule: Schedule) -> Schedule: """Remove directives. Args: schedule: A schedule to remove compiler directives. Returns: A schedule without directives. """ return schedule.exclude(instruction_types=[directives.Directive]) def remove_trivial_barriers(schedule: Schedule) -> Schedule: """Remove trivial barriers with 0 or 1 channels. Args: schedule: A schedule to remove trivial barriers. Returns: schedule: A schedule without trivial barriers """ def filter_func(inst): return isinstance(inst[1], directives.RelativeBarrier) and len(inst[1].channels) < 2 return schedule.exclude(filter_func) def align_measures( schedules: Iterable[ScheduleComponent], inst_map: Optional[InstructionScheduleMap] = None, cal_gate: str = "u3", max_calibration_duration: Optional[int] = None, align_time: Optional[int] = None, align_all: Optional[bool] = True, ) -> List[Schedule]: """Return new schedules where measurements occur at the same physical time. This transformation will align the first :class:`.Acquire` on every channel to occur at the same time. Minimum measurement wait time (to allow for calibration pulses) is enforced and may be set with ``max_calibration_duration``. By default only instructions containing a :class:`.AcquireChannel` or :class:`.MeasureChannel` will be shifted. If you wish to keep the relative timing of all instructions in the schedule set ``align_all=True``. This method assumes that ``MeasureChannel(i)`` and ``AcquireChannel(i)`` correspond to the same qubit and the acquire/play instructions should be shifted together on these channels. .. code-block:: from qiskit import pulse from qiskit.pulse import transforms d0 = pulse.DriveChannel(0) m0 = pulse.MeasureChannel(0) a0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) sched = pulse.Schedule() sched.append(pulse.Play(pulse.Constant(10, 0.5), d0), inplace=True) sched.append(pulse.Play(pulse.Constant(10, 1.), m0).shift(sched.duration), inplace=True) sched.append(pulse.Acquire(20, a0, mem0).shift(sched.duration), inplace=True) sched_shifted = sched << 20 aligned_sched, aligned_sched_shifted = transforms.align_measures([sched, sched_shifted]) assert aligned_sched == aligned_sched_shifted If it is desired to only shift acquisition and measurement stimulus instructions set the flag ``align_all=False``: .. code-block:: aligned_sched, aligned_sched_shifted = transforms.align_measures( [sched, sched_shifted], align_all=False, ) assert aligned_sched != aligned_sched_shifted Args: schedules: Collection of schedules to be aligned together inst_map: Mapping of circuit operations to pulse schedules cal_gate: The name of the gate to inspect for the calibration time max_calibration_duration: If provided, inst_map and cal_gate will be ignored align_time: If provided, this will be used as final align time. align_all: Shift all instructions in the schedule such that they maintain their relative alignment with the shifted acquisition instruction. If ``False`` only the acquisition and measurement pulse instructions will be shifted. Returns: The input list of schedules transformed to have their measurements aligned. Raises: PulseError: If the provided alignment time is negative. """ def get_first_acquire_times(schedules): """Return a list of first acquire times for each schedule.""" acquire_times = [] for schedule in schedules: visited_channels = set() qubit_first_acquire_times = defaultdict(lambda: None) for time, inst in schedule.instructions: if isinstance(inst, instructions.Acquire) and inst.channel not in visited_channels: visited_channels.add(inst.channel) qubit_first_acquire_times[inst.channel.index] = time acquire_times.append(qubit_first_acquire_times) return acquire_times def get_max_calibration_duration(inst_map, cal_gate): """Return the time needed to allow for readout discrimination calibration pulses.""" # TODO (qiskit-terra #5472): fix behavior of this. max_calibration_duration = 0 for qubits in inst_map.qubits_with_instruction(cal_gate): cmd = inst_map.get(cal_gate, qubits, np.pi, 0, np.pi) max_calibration_duration = max(cmd.duration, max_calibration_duration) return max_calibration_duration if align_time is not None and align_time < 0: raise exceptions.PulseError("Align time cannot be negative.") first_acquire_times = get_first_acquire_times(schedules) # Extract the maximum acquire in every schedule across all acquires in the schedule. # If there are no acquires in the schedule default to 0. max_acquire_times = [max(0, *times.values()) for times in first_acquire_times] if align_time is None: if max_calibration_duration is None: if inst_map: max_calibration_duration = get_max_calibration_duration(inst_map, cal_gate) else: max_calibration_duration = 0 align_time = max(max_calibration_duration, *max_acquire_times) # Shift acquires according to the new scheduled time new_schedules = [] for sched_idx, schedule in enumerate(schedules): new_schedule = Schedule.initialize_from(schedule) stop_time = schedule.stop_time if align_all: if first_acquire_times[sched_idx]: shift = align_time - max_acquire_times[sched_idx] else: shift = align_time - stop_time else: shift = 0 for time, inst in schedule.instructions: measurement_channels = { chan.index for chan in inst.channels if isinstance(chan, (chans.MeasureChannel, chans.AcquireChannel)) } if measurement_channels: sched_first_acquire_times = first_acquire_times[sched_idx] max_start_time = max( sched_first_acquire_times[chan] for chan in measurement_channels if chan in sched_first_acquire_times ) shift = align_time - max_start_time if shift < 0: warnings.warn( "The provided alignment time is scheduling an acquire instruction " "earlier than it was scheduled for in the original Schedule. " "This may result in an instruction being scheduled before t=0 and " "an error being raised." ) new_schedule.insert(time + shift, inst, inplace=True) new_schedules.append(new_schedule) return new_schedules def add_implicit_acquires(schedule: ScheduleComponent, meas_map: List[List[int]]) -> Schedule: """Return a new schedule with implicit acquires from the measurement mapping replaced by explicit ones. .. warning:: Since new acquires are being added, Memory Slots will be set to match the qubit index. This may overwrite your specification. Args: schedule: Schedule to be aligned. meas_map: List of lists of qubits that are measured together. Returns: A ``Schedule`` with the additional acquisition instructions. """ new_schedule = Schedule.initialize_from(schedule) acquire_map = {} for time, inst in schedule.instructions: if isinstance(inst, instructions.Acquire): if inst.mem_slot and inst.mem_slot.index != inst.channel.index: warnings.warn( "One of your acquires was mapped to a memory slot which didn't match" " the qubit index. I'm relabeling them to match." ) # Get the label of all qubits that are measured with the qubit(s) in this instruction all_qubits = [] for sublist in meas_map: if inst.channel.index in sublist: all_qubits.extend(sublist) # Replace the old acquire instruction by a new one explicitly acquiring all qubits in # the measurement group. for i in all_qubits: explicit_inst = instructions.Acquire( inst.duration, chans.AcquireChannel(i), mem_slot=chans.MemorySlot(i), kernel=inst.kernel, discriminator=inst.discriminator, ) if time not in acquire_map: new_schedule.insert(time, explicit_inst, inplace=True) acquire_map = {time: {i}} elif i not in acquire_map[time]: new_schedule.insert(time, explicit_inst, inplace=True) acquire_map[time].add(i) else: new_schedule.insert(time, inst, inplace=True) return new_schedule def pad( schedule: Schedule, channels: Optional[Iterable[chans.Channel]] = None, until: Optional[int] = None, inplace: bool = False, pad_with: Optional[Type[instructions.Instruction]] = None, ) -> Schedule: """Pad the input Schedule with ``Delay``s on all unoccupied timeslots until ``schedule.duration`` or ``until`` if not ``None``. Args: schedule: Schedule to pad. channels: Channels to pad. Defaults to all channels in ``schedule`` if not provided. If the supplied channel is not a member of ``schedule`` it will be added. until: Time to pad until. Defaults to ``schedule.duration`` if not provided. inplace: Pad this schedule by mutating rather than returning a new schedule. pad_with: Pulse ``Instruction`` subclass to be used for padding. Default to :class:`~qiskit.pulse.instructions.Delay` instruction. Returns: The padded schedule. Raises: PulseError: When non pulse instruction is set to `pad_with`. """ until = until or schedule.duration channels = channels or schedule.channels if pad_with: if issubclass(pad_with, instructions.Instruction): pad_cls = pad_with else: raise PulseError( f"'{pad_with.__class__.__name__}' is not valid pulse instruction to pad with." ) else: pad_cls = instructions.Delay for channel in channels: if isinstance(channel, ClassicalIOChannel): continue if channel not in schedule.channels: schedule = schedule.insert(0, instructions.Delay(until, channel), inplace=inplace) continue prev_time = 0 timeslots = iter(schedule.timeslots[channel]) to_pad = [] while prev_time < until: try: t0, t1 = next(timeslots) except StopIteration: to_pad.append((prev_time, until - prev_time)) break if prev_time < t0: to_pad.append((prev_time, min(t0, until) - prev_time)) prev_time = t1 for t0, duration in to_pad: schedule = schedule.insert(t0, pad_cls(duration, channel), inplace=inplace) return schedule
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """ `SATInterface` class. """ import os import json from typing import List, Tuple, Union, Optional, Dict, Any from sys import stdout from datetime import datetime from hashlib import sha256 from qiskit import transpile, QuantumCircuit, qpy from qiskit.result.counts import Counts from qiskit.visualization.circuit.text import TextDrawing from qiskit.providers.backend import Backend from qiskit.transpiler.passes import RemoveBarriers from IPython import display from matplotlib.figure import Figure from sat_circuits_engine.util import timer_dec, timestamp, flatten_circuit from sat_circuits_engine.util.settings import DATA_PATH, TRANSPILE_KWARGS from sat_circuits_engine.circuit import GroverConstraintsOperator, SATCircuit from sat_circuits_engine.constraints_parse import ParsedConstraints from sat_circuits_engine.interface.circuit_decomposition import decompose_operator from sat_circuits_engine.interface.counts_visualization import plot_histogram from sat_circuits_engine.interface.translator import ConstraintsTranslator from sat_circuits_engine.classical_processing import ( find_iterations_unknown, calc_iterations, ClassicalVerifier, ) from sat_circuits_engine.interface.interactive_inputs import ( interactive_operator_inputs, interactive_solutions_num_input, interactive_run_input, interactive_backend_input, interactive_shots_input, ) # Local globlas for visualization of charts and diagrams IFRAME_WIDTH = "100%" IFRAME_HEIGHT = "700" class SATInterface: """ An interface for building, running and mining data from n-SAT problems quantum circuits. There are 2 options to use this class: (1) Using an interactive interface (intuitive but somewhat limited) - for this just initiate a bare instance of this class: `SATInterface()`. (2) Using the API defined by this class, that includes the following methods: * The following descriptions are partial, for full annotations see the methods' docstrings. - `__init__`: an instance of `SATInterface must be initiated with exactly 1 combination: (a) (high_level_constraints_string + high_level_vars) - for constraints in a high-level format. (b) (num_input_qubits + constraints_string) - for constraints in a low-level foramt. * For formats annotations see `constriants_format.ipynb` in the main directory. - `obtain_grover_operator`: obtains the suitable grover operator for the constraints. - `save_display_grover_operator`: saves and displays data generated by the `obtain_grover_operator` method. - `obtain_overall_circuit`: obtains the suitable overall SAT circuit. - `save_display_overall_circuit: saves and displays data generated by the `obtain_overall_circuit` method. - `run_overall_circuit`: executes the overall SAT circuit. - `save_display_results`: saves and displays data generated by the `run_overall_circuit` method. It is very recommended to go through `demos.ipynb` that demonstrates the various optional uses of this class, in addition to reading `constraints_format.ipynb`, which is a must for using this package properly. Both notebooks are in ther main directory. """ def __init__( self, num_input_qubits: Optional[int] = None, constraints_string: Optional[str] = None, high_level_constraints_string: Optional[str] = None, high_level_vars: Optional[Dict[str, int]] = None, name: Optional[str] = None, save_data: Optional[bool] = True, ) -> None: """ Accepts the combination of paramters: (high_level_constraints_string + high_level_vars) or (num_input_qubits + constraints_string). Exactly one combination is accepted. In other cases either an iteractive user interface will be called to take user's inputs, or an exception will be raised due to misuse of the API. Args: num_input_qubits (Optional[int] = None): number of input qubits. constraints_string (Optional[str] = None): a string of constraints in a low-level format. high_level_constraints_string (Optional[str] = None): a string of constraints in a high-level format. high_level_vars (Optional[Dict[str, int]] = None): a dictionary that configures the high-level variables - keys are names and values are bits-lengths. name (Optional[str] = None): a name for this object, if None than the generic name "SAT" is given automatically. save_data (Optional[bool] = True): if True, saves all data and metadata generated by this class to a unique data folder (by using the `save_XXX` methods of this class). Raises: SyntaxError - if a forbidden combination of arguments has been provided. """ if name is None: name = "SAT" self.name = name # Creating a directory for data to be saved if save_data: self.time_created = timestamp(datetime.now()) self.dir_path = f"{DATA_PATH}{self.time_created}_{self.name}/" os.mkdir(self.dir_path) print(f"Data will be saved into '{self.dir_path}'.") # Initial metadata, more to be added by this class' `save_XXX` methods self.metadata = { "name": self.name, "datetime": self.time_created, "num_input_qubits": num_input_qubits, "constraints_string": constraints_string, "high_level_constraints_string": high_level_constraints_string, "high_level_vars": high_level_vars, } self.update_metadata() # Identifying user's platform, for visualization purposes self.identify_platform() # In the case of low-level constraints format, that is the default value self.high_to_low_map = None # Case A - interactive interface if (num_input_qubits is None or constraints_string is None) and ( high_level_constraints_string is None or high_level_vars is None ): self.interactive_interface() # Case B - API else: self.high_level_constraints_string = high_level_constraints_string self.high_level_vars = high_level_vars # Case B.1 - high-level format constraints inputs if num_input_qubits is None or constraints_string is None: self.num_input_qubits = sum(self.high_level_vars.values()) self.high_to_low_map, self.constraints_string = ConstraintsTranslator( self.high_level_constraints_string, self.high_level_vars ).translate() # Case B.2 - low-level format constraints inputs elif num_input_qubits is not None and constraints_string is not None: self.num_input_qubits = num_input_qubits self.constraints_string = constraints_string # Misuse else: raise SyntaxError( "SATInterface accepts the combination of paramters:" "(high_level_constraints_string + high_level_vars) or " "(num_input_qubits + constraints_string). " "Exactly one combination is accepted, not both." ) self.parsed_constraints = ParsedConstraints( self.constraints_string, self.high_level_constraints_string ) def update_metadata(self, update_metadata: Optional[Dict[str, Any]] = None) -> None: """ Updates the metadata file (in the unique data folder of a given `SATInterface` instance). Args: update_metadata (Optional[Dict[str, Any]] = None): - If None - just dumps `self.metadata` into the metadata JSON file. - If defined - updates the `self.metadata` attribute and then dumps it. """ if update_metadata is not None: self.metadata.update(update_metadata) with open(f"{self.dir_path}metadata.json", "w") as metadata_file: json.dump(self.metadata, metadata_file, indent=4) def identify_platform(self) -> None: """ Identifies user's platform. Writes True to `self.jupyter` for Jupyter notebook, False for terminal. """ # If True then the platform is a terminal/command line/shell if stdout.isatty(): self.jupyter = False # If False, we assume the platform is a Jupyter notebook else: self.jupyter = True def output_to_platform( self, *, title: str, output_terminal: Union[TextDrawing, str], output_jupyter: Union[Figure, str], display_both_on_jupyter: Optional[bool] = False, ) -> None: """ Displays output to user's platform. Args: title (str): a title for the output. output_terminal (Union[TextDrawing, str]): text to print for a terminal platform. output_jupyter: (Union[Figure, str]): objects to display for a Jupyter notebook platform. can handle `Figure` matplotlib objects or strings of paths to IFrame displayable file, e.g PDF files. display_both_on_jupyter (Optional[bool] = False): if True, displays both `output_terminal` and `output_jupyter` in a Jupyter notebook platform. Raises: TypeError - in the case of misusing the `output_jupyter` argument. """ print() print(title) if self.jupyter: if isinstance(output_jupyter, str): display.display(display.IFrame(output_jupyter, width=IFRAME_WIDTH, height=IFRAME_HEIGHT)) elif isinstance(output_jupyter, Figure): display.display(output_jupyter) else: raise TypeError("output_jupyter must be an str (path to image file) or a Figure object.") if display_both_on_jupyter: print(output_terminal) else: print(output_terminal) def interactive_interface(self) -> None: """ An interactive CLI that allows exploiting most (but not all) of the package's features. Uses functions of the form `interactive_XXX_inputs` from the `interactive_inputs.py` module. Divided into 3 main stages: 1. Obtaining Grover's operator for the SAT problem. 2. Obtaining the overall SAT cirucit. 3. Executing the circuit and parsing the results. The interface is built in a modular manner such that a user can halt at any stage. The defualt settings for the interactive user intreface are: 1. `name = "SAT"`. 2. `save_data = True`. 3. `display = True`. 4. `transpile_kwargs = {'basis_gates': ['u', 'cx'], 'optimization_level': 3}`. 5. Backends are limited to those defined in the global-constant-like function `BACKENDS`: - Those are the local `aer_simulator` and the remote `ibmq_qasm_simulator` for now. Due to these default settings the interactive CLI is somewhat restrictive, for full flexibility a user should use the API and not the CLI. """ # Handling operator part operator_inputs = interactive_operator_inputs() self.num_input_qubits = operator_inputs["num_input_qubits"] self.high_to_low_map = operator_inputs["high_to_low_map"] self.constraints_string = operator_inputs["constraints_string"] self.high_level_constraints_string = operator_inputs["high_level_constraints_string"] self.high_level_vars = operator_inputs["high_level_vars"] self.parsed_constraints = ParsedConstraints( self.constraints_string, self.high_level_constraints_string ) self.update_metadata( { "num_input_qubits": self.num_input_qubits, "constraints_string": self.constraints_string, "high_level_constraints_string": self.high_level_constraints_string, "high_level_vars": self.high_level_vars, } ) obtain_grover_operator_output = self.obtain_grover_operator() self.save_display_grover_operator(obtain_grover_operator_output) # Handling overall circuit part solutions_num = interactive_solutions_num_input() if solutions_num is not None: backend = None if solutions_num == -1: backend = interactive_backend_input() overall_circuit_data = self.obtain_overall_sat_circuit( obtain_grover_operator_output["operator"], solutions_num, backend ) self.save_display_overall_circuit(overall_circuit_data) # Handling circuit execution part if interactive_run_input(): if backend is None: backend = interactive_backend_input() shots = interactive_shots_input() counts_parsed = self.run_overall_sat_circuit( overall_circuit_data["circuit"], backend, shots ) self.save_display_results(counts_parsed) print() print(f"Done saving data into '{self.dir_path}'.") def obtain_grover_operator( self, transpile_kwargs: Optional[Dict[str, Any]] = None ) -> Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]: """ Obtains the suitable `GroverConstraintsOperator` object for the constraints, decomposes it using the `circuit_decomposition.py` module and transpiles it according to `transpile_kwargs`. Args: transpile_kwargs (Optional[Dict[str, Any]]): kwargs for Qiskit's transpile function. The defualt is set to the global constant `TRANSPILE_KWARGS`. Returns: (Dict[str, Union[GroverConstraintsOperator, QuantumCircuit, Dict[str, List[int]]]]): - 'operator' (GroverConstraintsOperator):the high-level blocks operator. - 'decomposed_operator' (QuantumCircuit): decomposed to building-blocks operator. * For annotations regarding the decomposition method see the `circuit_decomposition` module. - 'transpiled_operator' (QuantumCircuit): the transpiled operator. *** The high-level operator and the decomposed operator are generated with barriers between constraints as default for visualizations purposes. The barriers are stripped off before transpiling so the the transpiled operator object contains no barriers. *** - 'high_level_to_bit_indexes_map' (Optional[Dict[str, List[int]]] = None): A map of high-level variables with their allocated bit-indexes in the input register. """ print() print( "The system synthesizes and transpiles a Grover's " "operator for the given constraints. Please wait.." ) if transpile_kwargs is None: transpile_kwargs = TRANSPILE_KWARGS self.transpile_kwargs = transpile_kwargs operator = GroverConstraintsOperator( self.parsed_constraints, self.num_input_qubits, insert_barriers=True ) decomposed_operator = decompose_operator(operator) no_baerriers_operator = RemoveBarriers()(operator) transpiled_operator = transpile(no_baerriers_operator, **transpile_kwargs) print("Done.") return { "operator": operator, "decomposed_operator": decomposed_operator, "transpiled_operator": transpiled_operator, "high_level_to_bit_indexes_map": self.high_to_low_map, } def save_display_grover_operator( self, obtain_grover_operator_output: Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]], display: Optional[bool] = True, ) -> None: """ Handles saving and displaying data generated by the `self.obtain_grover_operator` method. Args: obtain_grover_operator_output(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]): the dictionary returned upon calling the `self.obtain_grover_operator` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ # Creating a directory to save operator's data operator_dir_path = f"{self.dir_path}grover_operator/" os.mkdir(operator_dir_path) # Titles for displaying objects, by order of `obtain_grover_operator_output` titles = [ "The operator diagram - high level blocks:", "The operator diagram - decomposed:", f"The transpiled operator diagram saved into '{operator_dir_path}'.\n" f"It's not presented here due to its complexity.\n" f"Please note that barriers appear in the high-level diagrams above only for convenient\n" f"visual separation between constraints.\n" f"Before transpilation all barriers are removed to avoid redundant inefficiencies.", ] for index, (op_name, op_obj) in enumerate(obtain_grover_operator_output.items()): # Generic path and name for files to be saved files_path = f"{operator_dir_path}{op_name}" # Generating a circuit diagrams figure figure_path = f"{files_path}.pdf" op_obj.draw("mpl", filename=figure_path, fold=-1) # Generating a QPY serialization file for the circuit object qpy_file_path = f"{files_path}.qpy" with open(qpy_file_path, "wb") as qpy_file: qpy.dump(op_obj, qpy_file) # Original high-level operator and decomposed operator if index < 2 and display: # Displaying to user self.output_to_platform( title=titles[index], output_terminal=op_obj.draw("text"), output_jupyter=figure_path ) # Transpiled operator elif index == 2: # Output to user, not including the circuit diagram print() print(titles[index]) print() print(f"The transpilation kwargs are: {self.transpile_kwargs}.") transpiled_operator_depth = op_obj.depth() transpiled_operator_gates_count = op_obj.count_ops() print(f"Transpiled operator depth: {transpiled_operator_depth}.") print(f"Transpiled operator gates count: {transpiled_operator_gates_count}.") print(f"Total number of qubits: {op_obj.num_qubits}.") # Generating QASM 2.0 file only for the (flattened = no registers) tranpsiled operator qasm_file_path = f"{files_path}.qasm" flatten_circuit(op_obj).qasm(filename=qasm_file_path) # Index 3 is 'high_level_to_bit_indexes_map' so it's time to break from the loop break # Mapping from high-level variables to bit-indexes will be displayed as well mapping = obtain_grover_operator_output["high_level_to_bit_indexes_map"] if mapping: print() print(f"The high-level variables mapping to bit-indexes:\n{mapping}") print() print( f"Saved into '{operator_dir_path}':\n", " Circuit diagrams for all levels.\n", " QPY serialization exports for all levels.\n", " QASM 2.0 export only for the transpiled level.", ) with open(f"{operator_dir_path}operator.qpy", "rb") as qpy_file: operator_qpy_sha256 = sha256(qpy_file.read()).hexdigest() self.update_metadata( { "high_level_to_bit_indexes_map": self.high_to_low_map, "transpile_kwargs": self.transpile_kwargs, "transpiled_operator_depth": transpiled_operator_depth, "transpiled_operator_gates_count": transpiled_operator_gates_count, "operator_qpy_sha256": operator_qpy_sha256, } ) def obtain_overall_sat_circuit( self, grover_operator: GroverConstraintsOperator, solutions_num: int, backend: Optional[Backend] = None, ) -> Dict[str, SATCircuit]: """ Obtains the suitable `SATCircuit` object (= the overall SAT circuit) for the SAT problem. Args: grover_operator (GroverConstraintsOperator): Grover's operator for the SAT problem. solutions_num (int): number of solutions for the SAT problem. In the case the number of solutions is unknown, specific negative values are accepted: * '-1' - for launching a classical iterative stochastic process that finds an adequate number of iterations - by calling the `find_iterations_unknown` function (see its docstrings for more information). * '-2' - for generating a dynamic circuit that iterates over Grover's iterator until a solution is obtained, using weak measurements. TODO - this feature isn't ready yet. backend (Optional[Backend] = None): in the case of a '-1' value given to `solutions_num`, a backend object to execute the depicted iterative prcess upon should be provided. Returns: (Dict[str, SATCircuit]): - 'circuit' key for the overall SAT circuit. - 'concise_circuit' key for the overall SAT circuit, with only 1 iteration over Grover's iterator (operator + diffuser). Useful for visualization purposes. *** The concise circuit is generated with barriers between segments as default for visualizations purposes. In the actual circuit there no barriers. *** """ # -1 = Unknown number of solutions - iterative stochastic process print() if solutions_num == -1: assert backend is not None, "Need to specify a backend if `solutions_num == -1`." print("Please wait while the system checks various solutions..") circuit, iterations = find_iterations_unknown( self.num_input_qubits, grover_operator, self.parsed_constraints, precision=10, backend=backend, ) print() print(f"An adequate number of iterations found = {iterations}.") # -2 = Unknown number of solutions - implement a dynamic circuit # TODO this feature isn't fully implemented yet elif solutions_num == -2: print("The system builds a dynamic circuit..") circuit = SATCircuit(self.num_input_qubits, grover_operator, iterations=None) circuit.add_input_reg_measurement() iterations = None # Known number of solutions else: print("The system builds the overall circuit..") iterations = calc_iterations(self.num_input_qubits, solutions_num) print(f"\nFor {solutions_num} solutions, {iterations} iterations needed.") circuit = SATCircuit( self.num_input_qubits, grover_operator, iterations, insert_barriers=False ) circuit.add_input_reg_measurement() self.iterations = iterations # Obtaining a SATCircuit object with one iteration for concise representation concise_circuit = SATCircuit( self.num_input_qubits, grover_operator, iterations=1, insert_barriers=True ) concise_circuit.add_input_reg_measurement() return {"circuit": circuit, "concise_circuit": concise_circuit} def save_display_overall_circuit( self, obtain_overall_sat_circuit_output: Dict[str, SATCircuit], display: Optional[bool] = True ) -> None: """ Handles saving and displaying data generated by the `self.obtain_overall_sat_circuit` method. Args: obtain_overall_sat_circuit_output(Dict[str, SATCircuit]): the dictionary returned upon calling the `self.obtain_overall_sat_circuit` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ circuit = obtain_overall_sat_circuit_output["circuit"] concise_circuit = obtain_overall_sat_circuit_output["concise_circuit"] # Creating a directory to save overall circuit's data overall_circuit_dir_path = f"{self.dir_path}overall_circuit/" os.mkdir(overall_circuit_dir_path) # Generating a figure of the overall SAT circuit with just 1 iteration (i.e "concise") concise_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_1_iteration.pdf" concise_circuit.draw("mpl", filename=concise_circuit_fig_path, fold=-1) # Displaying the concise circuit to user if display: if self.iterations: self.output_to_platform( title=( f"The high level circuit contains {self.iterations}" f" iterations of the following form:" ), output_terminal=concise_circuit.draw("text"), output_jupyter=concise_circuit_fig_path, ) # Dynamic circuit case - TODO NOT FULLY IMPLEMENTED YET else: dynamic_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_dynamic.pdf" circuit.draw("mpl", filename=dynamic_circuit_fig_path, fold=-1) self.output_to_platform( title="The dynamic circuit diagram:", output_terminal=circuit.draw("text"), output_jupyter=dynamic_circuit_fig_path, ) if self.iterations: transpiled_overall_circuit = transpile(flatten_circuit(circuit), **self.transpile_kwargs) print() print(f"The transpilation kwargs are: {self.transpile_kwargs}.") transpiled_overall_circuit_depth = transpiled_overall_circuit.depth() transpiled_overall_circuit_gates_count = transpiled_overall_circuit.count_ops() print(f"Transpiled overall-circuit depth: {transpiled_overall_circuit_depth}.") print(f"Transpiled overall-circuit gates count: {transpiled_overall_circuit_gates_count}.") print(f"Total number of qubits: {transpiled_overall_circuit.num_qubits}.") print() print("Exporting the full overall SAT circuit object..") export_files_path = f"{overall_circuit_dir_path}overall_circuit" with open(f"{export_files_path}.qpy", "wb") as qpy_file: qpy.dump(circuit, qpy_file) if self.iterations: transpiled_overall_circuit.qasm(filename=f"{export_files_path}.qasm") print() print( f"Saved into '{overall_circuit_dir_path}':\n", " A concised (1 iteration) circuit diagram of the high-level overall SAT circuit.\n", " QPY serialization export for the full overall SAT circuit object.", ) if self.iterations: print(" QASM 2.0 export for the transpiled full overall SAT circuit object.") metadata_update = { "num_total_qubits": circuit.num_qubits, "num_iterations": circuit.iterations, } if self.iterations: metadata_update["transpiled_overall_circuit_depth"] = (transpiled_overall_circuit_depth,) metadata_update[ "transpiled_overall_circuit_gates_count" ] = transpiled_overall_circuit_gates_count self.update_metadata(metadata_update) @timer_dec("Circuit simulation execution time = ") def run_overall_sat_circuit( self, circuit: QuantumCircuit, backend: Backend, shots: int ) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]: """ Executes a `circuit` on `backend` transpiled w.r.t backend, `shots` times. Args: circuit (QuantumCircuit): `QuantumCircuit` object or child-object (a.k.a `SATCircuit`) to execute. backend (Backend): backend to execute `circuit` upon. shots (int): number of execution shots. Returns: (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): dict object returned by `self.parse_counts` - see this method's docstrings for annotations. """ # Defines also instance attributes to use in other methods self.backend = backend self.shots = shots print() print(f"The system is running the circuit {shots} times on {backend}, please wait..") print("This process might take a while.") job = backend.run(transpile(circuit, backend), shots=shots) counts = job.result().get_counts() print("Done.") parsed_counts = self.parse_counts(counts) return parsed_counts def parse_counts( self, counts: Counts ) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]: """ Parses a `Counts` object into several desired datas (see 'Returns' section). Args: counts (Counts): the `Counts` object to parse. Returns: (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): 'counts' (Counts) - the original `Counts` object. 'counts_sorted' (List[Tuple[Union[str, int]]]) - results sorted in a descending order. 'distilled_solutions' (List[str]): list of solutions (bitstrings). 'high_level_vars_values' (List[Dict[str, int]]): list of solutions (each solution is a dictionary with variable-names as keys and their integer values as values). """ # Sorting results in an a descending order counts_sorted = sorted(counts.items(), key=lambda x: x[1], reverse=True) # Generating a set of distilled verified-only solutions verifier = ClassicalVerifier(self.parsed_constraints) distilled_solutions = set() for count_item in counts_sorted: if not verifier.verify(count_item[0]): break distilled_solutions.add(count_item[0]) # In the case of high-level format in use, translating `distilled_solutions` into integer values high_level_vars_values = None if self.high_level_constraints_string and self.high_level_vars: # Container for dictionaries with variables integer values high_level_vars_values = [] for solution in distilled_solutions: # Keys are variable-names and values are their integer values solution_vars = {} for var, bits_bundle in self.high_to_low_map.items(): reversed_solution = solution[::-1] var_bitstring = "" for bit_index in bits_bundle: var_bitstring += reversed_solution[bit_index] # Translating to integer value solution_vars[var] = int(var_bitstring, 2) high_level_vars_values.append(solution_vars) return { "counts": counts, "counts_sorted": counts_sorted, "distilled_solutions": distilled_solutions, "high_level_vars_values": high_level_vars_values, } def save_display_results( self, run_overall_sat_circuit_output: Dict[ str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]] ], display: Optional[bool] = True, ) -> None: """ Handles saving and displaying data generated by the `self.run_overall_sat_circuit` method. Args: run_overall_sat_circuit_output (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): the dictionary returned upon calling the `self.run_overall_sat_circuit` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ counts = run_overall_sat_circuit_output["counts"] counts_sorted = run_overall_sat_circuit_output["counts_sorted"] distilled_solutions = run_overall_sat_circuit_output["distilled_solutions"] high_level_vars_values = run_overall_sat_circuit_output["high_level_vars_values"] # Creating a directory to save results data results_dir_path = f"{self.dir_path}results/" os.mkdir(results_dir_path) # Defining custom dimensions for the custom `plot_histogram` of this package histogram_fig_width = max((len(counts) * self.num_input_qubits * (10 / 72)), 7) histogram_fig_height = 5 histogram_figsize = (histogram_fig_width, histogram_fig_height) histogram_path = f"{results_dir_path}histogram.pdf" plot_histogram(counts, figsize=histogram_figsize, sort="value_desc", filename=histogram_path) if display: # Basic output text output_text = ( f"All counts:\n{counts_sorted}\n" f"\nDistilled solutions ({len(distilled_solutions)} total):\n" f"{distilled_solutions}" ) # Additional outputs for a high-level constraints format if high_level_vars_values: # Mapping from high-level variables to bit-indexes will be displayed as well output_text += ( f"\n\nThe high-level variables mapping to bit-indexes:" f"\n{self.high_to_low_map}" ) # Actual integer solutions will be displayed as well additional_text = "" for solution_index, solution in enumerate(high_level_vars_values): additional_text += f"Solution {solution_index + 1}: " for var_index, (var, value) in enumerate(solution.items()): additional_text += f"{var} = {value}" if var_index != len(solution) - 1: additional_text += ", " else: additional_text += "\n" output_text += f"\n\nHigh-level format solutions: \n{additional_text}" self.output_to_platform( title=f"The results for {self.shots} shots are:", output_terminal=output_text, output_jupyter=histogram_path, display_both_on_jupyter=True, ) results_dict = { "high_level_to_bit_indexes_map": self.high_to_low_map, "solutions": list(distilled_solutions), "high_level_solutions": high_level_vars_values, "counts": counts_sorted, } with open(f"{results_dir_path}results.json", "w") as results_file: json.dump(results_dict, results_file, indent=4) self.update_metadata( { "num_solutions": len(distilled_solutions), "backend": str(self.backend), "shots": self.shots, } )
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-train/qiskit__qiskit
swe-train
from qiskit import * from oracle_generation import generate_oracle get_bin = lambda x, n: format(x, 'b').zfill(n) def gen_circuits(min,max,size): circuits = [] secrets = [] ORACLE_SIZE = size for i in range(min,max+1): cur_str = get_bin(i,ORACLE_SIZE-1) (circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str) circuits.append(circuit) secrets.append(secret) return (circuits, secrets)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A collection of discrete probability metrics.""" from __future__ import annotations import numpy as np def hellinger_distance(dist_p: dict, dist_q: dict) -> float: """Computes the Hellinger distance between two counts distributions. Parameters: dist_p (dict): First dict of counts. dist_q (dict): Second dict of counts. Returns: float: Distance References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ """ p_sum = sum(dist_p.values()) q_sum = sum(dist_q.values()) p_normed = {} for key, val in dist_p.items(): p_normed[key] = val / p_sum q_normed = {} for key, val in dist_q.items(): q_normed[key] = val / q_sum total = 0 for key, val in p_normed.items(): if key in q_normed: total += (np.sqrt(val) - np.sqrt(q_normed[key])) ** 2 del q_normed[key] else: total += val total += sum(q_normed.values()) dist = np.sqrt(total) / np.sqrt(2) return dist def hellinger_fidelity(dist_p: dict, dist_q: dict) -> float: """Computes the Hellinger fidelity between two counts distributions. The fidelity is defined as :math:`\\left(1-H^{2}\\right)^{2}` where H is the Hellinger distance. This value is bounded in the range [0, 1]. This is equivalent to the standard classical fidelity :math:`F(Q,P)=\\left(\\sum_{i}\\sqrt{p_{i}q_{i}}\\right)^{2}` that in turn is equal to the quantum state fidelity for diagonal density matrices. Parameters: dist_p (dict): First dict of counts. dist_q (dict): Second dict of counts. Returns: float: Fidelity Example: .. code-block:: from qiskit import QuantumCircuit, execute, BasicAer from qiskit.quantum_info.analysis import hellinger_fidelity qc = 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') res1 = execute(qc, sim).result() res2 = execute(qc, sim).result() hellinger_fidelity(res1.get_counts(), res2.get_counts()) References: `Quantum Fidelity @ wikipedia <https://en.wikipedia.org/wiki/Fidelity_of_quantum_states>`_ `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ """ dist = hellinger_distance(dist_p, dist_q) return (1 - dist**2) ** 2
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import copy import itertools from functools import reduce import logging import json from operator import iadd as op_iadd, isub as op_isub import sys import numpy as np from scipy import sparse as scisparse from scipy import linalg as scila from qiskit import ClassicalRegister, QuantumCircuit from qiskit.quantum_info import Pauli from qiskit.qasm import pi from qiskit.assembler.run_config import RunConfig from qiskit.tools import parallel_map from qiskit.tools.events import TextProgressBar from qiskit.aqua import AquaError, aqua_globals from qiskit.aqua.utils import PauliGraph, compile_and_run_circuits, find_regs_by_name from qiskit.aqua.utils.backend_utils import is_statevector_backend logger = logging.getLogger(__name__) class Operator(object): """ Operators relevant for quantum applications Note: For grouped paulis representation, all operations will always convert it to paulis and then convert it back. (It might be a performance issue.) """ def __init__(self, paulis=None, grouped_paulis=None, matrix=None, coloring="largest-degree"): """ Args: paulis ([[float, Pauli]]): each list contains a coefficient (real number) and a corresponding Pauli class object. grouped_paulis ([[[float, Pauli]]]): each list of list contains a grouped paulis. matrix (numpy.ndarray or scipy.sparse.csr_matrix) : a 2-D sparse matrix represents operator (using CSR format internally) coloring (bool): method to group paulis. """ self._paulis = paulis self._coloring = coloring self._grouped_paulis = grouped_paulis if matrix is not None: matrix = matrix if scisparse.issparse(matrix) else scisparse.csr_matrix(matrix) matrix = matrix if scisparse.isspmatrix_csr(matrix) else matrix.to_csr(copy=True) self._matrix = matrix self._to_dia_matrix(mode="matrix") # use for fast lookup whether or not the paulis is existed. self._simplify_paulis() self._summarize_circuits = False def _extend_or_combine(self, rhs, mode, operation=op_iadd): """ Add two operators either extend (in-place) or combine (copy) them. The addition performs optimized combiniation of two operators. If `rhs` has identical basis, the coefficient are combined rather than appended. Args: rhs (Operator): to-be-combined operator mode (str): in-place or not. Returns: Operator: the operator. """ if mode == 'inplace': lhs = self elif mode == 'non-inplace': lhs = copy.deepcopy(self) if lhs._paulis is not None and rhs._paulis is not None: for pauli in rhs._paulis: pauli_label = pauli[1].to_label() idx = lhs._paulis_table.get(pauli_label, None) if idx is not None: lhs._paulis[idx][0] = operation(lhs._paulis[idx][0], pauli[0]) else: lhs._paulis_table[pauli_label] = len(lhs._paulis) new_pauli = copy.deepcopy(pauli) new_pauli[0] = operation(0.0, pauli[0]) lhs._paulis.append(new_pauli) elif lhs._grouped_paulis is not None and rhs._grouped_paulis is not None: lhs._grouped_paulis_to_paulis() rhs._grouped_paulis_to_paulis() lhs = operation(lhs, rhs) lhs._paulis_to_grouped_paulis() elif lhs._matrix is not None and rhs._matrix is not None: lhs._matrix = operation(lhs._matrix, rhs._matrix) lhs._to_dia_matrix(mode='matrix') else: raise TypeError("the representations of two Operators should be the same. ({}, {})".format( lhs.representations, rhs.representations)) return lhs def __add__(self, rhs): """Overload + operation""" return self._extend_or_combine(rhs, 'non-inplace', op_iadd) def __iadd__(self, rhs): """Overload += operation""" return self._extend_or_combine(rhs, 'inplace', op_iadd) def __sub__(self, rhs): """Overload - operation""" return self._extend_or_combine(rhs, 'non-inplace', op_isub) def __isub__(self, rhs): """Overload -= operation""" return self._extend_or_combine(rhs, 'inplace', op_isub) def __neg__(self): """Overload unary - """ ret = copy.deepcopy(self) ret.scaling_coeff(-1.0) return ret def __eq__(self, rhs): """Overload == operation""" if self._matrix is not None and rhs._matrix is not None: return np.all(self._matrix == rhs._matrix) if self._paulis is not None and rhs._paulis is not None: if len(self._paulis) != len(rhs._paulis): return False for coeff, pauli in self._paulis: found_pauli = False rhs_coeff = 0.0 for coeff2, pauli2 in rhs._paulis: if pauli == pauli2: found_pauli = True rhs_coeff = coeff2 break if not found_pauli and rhs_coeff != 0.0: # since we might have 0 weights of paulis. return False if coeff != rhs_coeff: return False return True if self._grouped_paulis is not None and rhs._grouped_paulis is not None: self._grouped_paulis_to_paulis() rhs._grouped_paulis_to_paulis() return self.__eq__(rhs) def __ne__(self, rhs): """ != """ return not self.__eq__(rhs) def __str__(self): """Overload str()""" curr_repr = "" length = "" group = None if self._paulis is not None: curr_repr = 'paulis' length = len(self._paulis) elif self._grouped_paulis is not None: curr_repr = 'grouped_paulis' group = len(self._grouped_paulis) length = sum([len(gp) - 1 for gp in self._grouped_paulis]) elif self._matrix is not None: curr_repr = 'matrix' length = "{}x{}".format(2 ** self.num_qubits, 2 ** self.num_qubits) ret = "Representation: {}, qubits: {}, size: {}{}".format( curr_repr, self.num_qubits, length, "" if group is None else " (number of groups: {})".format(group)) return ret def copy(self): """Get a copy of self.""" return copy.deepcopy(self) def chop(self, threshold=1e-15): """ Eliminate the real and imagine part of coeff in each pauli by `threshold`. If pauli's coeff is less then `threshold` in both real and imagine parts, the pauli is removed. To align the internal representations, all available representations are chopped. The chopped result is stored back to original property. Note: if coeff is real-only, the imag part is skipped. Args: threshold (float): threshold chops the paulis """ def chop_real_imag(coeff, threshold): temp_real = coeff.real if np.absolute(coeff.real) >= threshold else 0.0 temp_imag = coeff.imag if np.absolute(coeff.imag) >= threshold else 0.0 if temp_real == 0.0 and temp_imag == 0.0: return 0.0 else: new_coeff = temp_real + 1j * temp_imag return new_coeff if self._paulis is not None: for i in range(len(self._paulis)): self._paulis[i][0] = chop_real_imag(self._paulis[i][0], threshold) paulis = [x for x in self._paulis if x[0] != 0.0] self._paulis = paulis self._paulis_table = {pauli[1].to_label(): i for i, pauli in enumerate(self._paulis)} if self._dia_matrix is not None: self._to_dia_matrix('paulis') elif self._grouped_paulis is not None: grouped_paulis = [] for group_idx in range(1, len(self._grouped_paulis)): for pauli_idx in range(len(self._grouped_paulis[group_idx])): self._grouped_paulis[group_idx][pauli_idx][0] = chop_real_imag( self._grouped_paulis[group_idx][pauli_idx][0], threshold) paulis = [x for x in self._grouped_paulis[group_idx] if x[0] != 0.0] grouped_paulis.append(paulis) self._grouped_paulis = grouped_paulis if self._dia_matrix is not None: self._to_dia_matrix('grouped_paulis') elif self._matrix is not None: rows, cols = self._matrix.nonzero() for row, col in zip(rows, cols): self._matrix[row, col] = chop_real_imag(self._matrix[row, col], threshold) self._matrix.eliminate_zeros() if self._dia_matrix is not None: self._to_dia_matrix('matrix') def _simplify_paulis(self): """ Merge the paulis (grouped_paulis) whose bases are identical but the pauli with zero coefficient would not be removed. Usually used in construction. """ if self._paulis is not None: new_paulis = [] new_paulis_table = {} for curr_paulis in self._paulis: pauli_label = curr_paulis[1].to_label() new_idx = new_paulis_table.get(pauli_label, None) if new_idx is not None: new_paulis[new_idx][0] += curr_paulis[0] else: new_paulis_table[pauli_label] = len(new_paulis) new_paulis.append(curr_paulis) self._paulis = new_paulis self._paulis_table = new_paulis_table elif self._grouped_paulis is not None: self._grouped_paulis_to_paulis() self._simplify_paulis() self._paulis_to_grouped_paulis() def __mul__(self, rhs): """ Overload * operation. Only support two Operators have the same representation mode. Returns: Operator: the multipled Operator. Raises: TypeError, if two Operators do not have the same representations. """ if self._paulis is not None and rhs._paulis is not None: ret_pauli = Operator(paulis=[]) for existed_pauli in self._paulis: for pauli in rhs._paulis: basis, sign = Pauli.sgn_prod(existed_pauli[1], pauli[1]) coeff = existed_pauli[0] * pauli[0] * sign if abs(coeff) > 1e-15: pauli_term = [coeff, basis] ret_pauli += Operator(paulis=[pauli_term]) return ret_pauli elif self._grouped_paulis is not None and rhs._grouped_paulis is not None: self._grouped_paulis_to_paulis() rhs._grouped_paulis_to_paulis() mul_pauli = self * rhs mul_pauli._paulis_to_grouped_paulis() ret_grouped_pauli = Operator(paulis=mul_pauli._paulis, grouped_paulis=mul_pauli._grouped_paulis) return ret_grouped_pauli elif self._matrix is not None and rhs._matrix is not None: ret_matrix = self._matrix.dot(rhs._matrix) return Operator(matrix=ret_matrix) else: raise TypeError("the representations of two Operators should be the same. ({}, {})".format( self.representations, rhs.representations)) @property def coloring(self): """Getter of method of grouping paulis""" return self._coloring @coloring.setter def coloring(self, new_coloring): """Setter of method of grouping paulis""" self._coloring = new_coloring @property def aer_paulis(self): if getattr(self, '_aer_paulis', None) is None: self.to_paulis() aer_paulis = [] for coeff, p in self._paulis: new_coeff = [coeff.real, coeff.imag] new_p = p.to_label() aer_paulis.append([new_coeff, new_p]) self._aer_paulis = aer_paulis return self._aer_paulis def _to_dia_matrix(self, mode): """ Convert the reprenetations into diagonal matrix if possible and then store it back. For paulis, if all paulis are Z or I (identity), convert to dia_matrix. Args: mode (str): "matrix", "paulis" or "grouped_paulis". """ if mode not in ['matrix', 'paulis', 'grouped_paulis']: raise ValueError( 'Mode should be one of "matrix", "paulis", "grouped_paulis"') if mode == 'matrix' and self._matrix is not None: dia_matrix = self._matrix.diagonal() if not scisparse.csr_matrix(dia_matrix).nnz == self._matrix.nnz: dia_matrix = None self._dia_matrix = dia_matrix elif mode == 'paulis' and self._paulis is not None: if self._paulis == []: self._dia_matrix = None else: valid_dia_matrix_flag = True dia_matrix = 0.0 for idx in range(len(self._paulis)): coeff, pauli = self._paulis[idx][0], self._paulis[idx][1] if not (np.all(np.logical_not(pauli.x))): valid_dia_matrix_flag = False break dia_matrix += coeff * pauli.to_spmatrix().diagonal() self._dia_matrix = dia_matrix.copy() if valid_dia_matrix_flag else None elif mode == 'grouped_paulis' and self._grouped_paulis is not None: self._grouped_paulis_to_paulis() self._to_dia_matrix(mode='paulis') self._paulis_to_grouped_paulis() else: self._dia_matrix = None @property def paulis(self): """Getter of Pauli list.""" return self._paulis @property def grouped_paulis(self): """Getter of grouped Pauli list.""" return self._grouped_paulis @property def matrix(self): """Getter of matrix; if matrix is diagonal, diagonal matrix is returned instead.""" return self._dia_matrix if self._dia_matrix is not None else self._matrix def enable_summarize_circuits(self): self._summarize_circuits = True def disable_summarize_circuits(self): self._summarize_circuits = False @property def representations(self): """ Return the available representations in the Operator. Returns: list: available representations ([str]) """ ret = [] if self._paulis is not None: ret.append("paulis") if self._grouped_paulis is not None: ret.append("grouped_paulis") if self._matrix is not None: ret.append("matrix") return ret @property def num_qubits(self): """ number of qubits required for the operator. Returns: int: number of qubits """ if self._paulis is not None: if self._paulis != []: return len(self._paulis[0][1]) else: return 0 elif self._grouped_paulis is not None and self._grouped_paulis != []: return len(self._grouped_paulis[0][0][1]) else: return int(np.log2(self._matrix.shape[0])) @staticmethod def load_from_file(file_name, before_04=False): """ Load paulis in a file to construct an Operator. Args: file_name (str): path to the file, which contains a list of Paulis and coefficients. before_04 (bool): support the format < 0.4. Returns: Operator class: the loaded operator. """ with open(file_name, 'r') as file: return Operator.load_from_dict(json.load(file), before_04=before_04) def save_to_file(self, file_name): """ Save operator to a file in pauli representation. Args: file_name (str): path to the file """ with open(file_name, 'w') as f: json.dump(self.save_to_dict(), f) @staticmethod def load_from_dict(dictionary, before_04=False): """ Load paulis in a dict to construct an Operator, \ the dict must be represented as follows: label and coeff (real and imag). \ E.g.: \ {'paulis': \ [ \ {'label': 'IIII', \ 'coeff': {'real': -0.33562957575267038, 'imag': 0.0}}, \ {'label': 'ZIII', \ 'coeff': {'real': 0.28220597164664896, 'imag': 0.0}}, \ ... \ ] \ } \ Args: dictionary (dict): dictionary, which contains a list of Paulis and coefficients. before_04 (bool): support the format < 0.4. Returns: Operator: the loaded operator. """ if 'paulis' not in dictionary: raise AquaError('Dictionary missing "paulis" key') paulis = [] for op in dictionary['paulis']: if 'label' not in op: raise AquaError('Dictionary missing "label" key') pauli_label = op['label'] if 'coeff' not in op: raise AquaError('Dictionary missing "coeff" key') pauli_coeff = op['coeff'] if 'real' not in pauli_coeff: raise AquaError('Dictionary missing "real" key') coeff = pauli_coeff['real'] if 'imag' in pauli_coeff: coeff = complex(pauli_coeff['real'], pauli_coeff['imag']) pauli_label = pauli_label[::-1] if before_04 else pauli_label paulis.append([coeff, Pauli.from_label(pauli_label)]) return Operator(paulis=paulis) def save_to_dict(self): """ Save operator to a dict in pauli representation. Returns: dict: a dictionary contains an operator with pauli representation. """ self._check_representation("paulis") ret_dict = {"paulis": []} for pauli in self._paulis: op = {"label": pauli[1].to_label()} if isinstance(pauli[0], complex): op["coeff"] = {"real": np.real(pauli[0]), "imag": np.imag(pauli[0]) } else: op["coeff"] = {"real": pauli[0]} ret_dict["paulis"].append(op) return ret_dict def print_operators(self, print_format='paulis'): """ Print out the paulis in the selected representation. Args: print_format (str): "paulis", "grouped_paulis", "matrix" Returns: str: a formated operator. Raises: ValueError: if `print_format` is not supported. """ ret = "" if print_format == 'paulis': self._check_representation("paulis") for pauli in self._paulis: ret = ''.join([ret, "{}\t{}\n".format(pauli[1].to_label(), pauli[0])]) if ret == "": ret = ''.join([ret, "Pauli list is empty."]) elif print_format == 'grouped_paulis': self._check_representation("grouped_paulis") for i in range(len(self._grouped_paulis)): ret = ''.join([ret, 'Post Rotations of TPB set {} '.format(i)]) ret = ''.join([ret, ': {} '.format(self._grouped_paulis[i][0][1].to_label())]) ret = ''.join([ret, '\n']) for j in range(1, len(self._grouped_paulis[i])): ret = ''.join([ret, '{} '.format(self._grouped_paulis[i][j][1].to_label())]) ret = ''.join([ret, '{}\n'.format(self._grouped_paulis[i][j][0])]) ret = ''.join([ret, '\n']) if ret == "": ret = ''.join([ret, "Grouped pauli list is empty."]) elif print_format == 'matrix': self._check_representation("matrix") ret = str(self._matrix.toarray()) else: raise ValueError('Mode should be one of "matrix", "paulis", "grouped_paulis"') return ret def construct_evaluation_circuit(self, operator_mode, input_circuit, backend, use_simulator_operator_mode=False): """ Construct the circuits for evaluation. Args: operator_mode (str): representation of operator, including paulis, grouped_paulis and matrix input_circuit (QuantumCircuit): the quantum circuit. backend (BaseBackend): backend selection for quantum machine. use_simulator_operator_mode (bool): if aer_provider is used, we can do faster evaluation for pauli mode on statevector simualtion Returns: [QuantumCircuit]: the circuits for evaluation. """ if is_statevector_backend(backend): if operator_mode == 'matrix': circuits = [input_circuit] else: self._check_representation("paulis") if use_simulator_operator_mode: circuits = [input_circuit] else: n_qubits = self.num_qubits q = find_regs_by_name(input_circuit, 'q') circuits = [input_circuit] for idx, pauli in enumerate(self._paulis): circuit = QuantumCircuit() + input_circuit if np.all(np.logical_not(pauli[1].z)) and np.all(np.logical_not(pauli[1].x)): # all I continue for qubit_idx in range(n_qubits): if not pauli[1].z[qubit_idx] and pauli[1].x[qubit_idx]: circuit.u3(np.pi, 0.0, np.pi, q[qubit_idx]) # x elif pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]: circuit.u1(np.pi, q[qubit_idx]) # z elif pauli[1].z[qubit_idx] and pauli[1].x[qubit_idx]: circuit.u3(np.pi, np.pi/2, np.pi/2, q[qubit_idx]) # y circuits.append(circuit) else: if operator_mode == 'matrix': raise AquaError("matrix mode can not be used with non-statevector simulator.") n_qubits = self.num_qubits circuits = [] base_circuit = QuantumCircuit() + input_circuit c = find_regs_by_name(base_circuit, 'c', qreg=False) if c is None: c = ClassicalRegister(n_qubits, name='c') base_circuit.add_register(c) if operator_mode == "paulis": self._check_representation("paulis") for idx, pauli in enumerate(self._paulis): circuit = QuantumCircuit() + base_circuit q = find_regs_by_name(circuit, 'q') c = find_regs_by_name(circuit, 'c', qreg=False) for qubit_idx in range(n_qubits): if pauli[1].x[qubit_idx]: if pauli[1].z[qubit_idx]: # Measure Y circuit.u1(-np.pi/2, q[qubit_idx]) # sdg circuit.u2(0.0, np.pi, q[qubit_idx]) # h else: # Measure X circuit.u2(0.0, np.pi, q[qubit_idx]) # h circuit.barrier(q) circuit.measure(q, c) circuits.append(circuit) else: self._check_representation("grouped_paulis") for idx, tpb_set in enumerate(self._grouped_paulis): circuit = QuantumCircuit() + base_circuit q = find_regs_by_name(circuit, 'q') c = find_regs_by_name(circuit, 'c', qreg=False) for qubit_idx in range(n_qubits): if tpb_set[0][1].x[qubit_idx]: if tpb_set[0][1].z[qubit_idx]: # Measure Y circuit.u1(-np.pi/2, q[qubit_idx]) # sdg circuit.u2(0.0, np.pi, q[qubit_idx]) # h else: # Measure X circuit.u2(0.0, np.pi, q[qubit_idx]) # h circuit.barrier(q) circuit.measure(q, c) circuits.append(circuit) return circuits def evaluate_with_result(self, operator_mode, circuits, backend, result, use_simulator_operator_mode=False): """ Use the executed result with operator to get the evaluated value. Args: operator_mode (str): representation of operator, including paulis, grouped_paulis and matrix circuits (list of qiskit.QuantumCircuit): the quantum circuits. backend (str): backend selection for quantum machine. result (qiskit.Result): the result from the backend. use_simulator_operator_mode (bool): if aer_provider is used, we can do faster evaluation for pauli mode on statevector simualtion Returns: float: the mean value float: the standard deviation """ avg, std_dev, variance = 0.0, 0.0, 0.0 if is_statevector_backend(backend): if operator_mode == "matrix": self._check_representation("matrix") if self._dia_matrix is None: self._to_dia_matrix(mode='matrix') quantum_state = np.asarray(result.get_statevector(circuits[0])) if self._dia_matrix is not None: avg = np.sum(self._dia_matrix * np.absolute(quantum_state) ** 2) else: avg = np.vdot(quantum_state, self._matrix.dot(quantum_state)) else: self._check_representation("paulis") if use_simulator_operator_mode: temp = result.data(circuits[0])['snapshots']['expectation_value']['test'][0]['value'] avg = temp[0] + 1j * temp[1] else: quantum_state = np.asarray(result.get_statevector(circuits[0])) circuit_idx = 1 for idx, pauli in enumerate(self._paulis): if np.all(np.logical_not(pauli[1].z)) and np.all(np.logical_not(pauli[1].x)): avg += pauli[0] else: quantum_state_i = np.asarray(result.get_statevector(circuits[circuit_idx])) avg += pauli[0] * (np.vdot(quantum_state, quantum_state_i)) circuit_idx += 1 else: if logger.isEnabledFor(logging.DEBUG): logger.debug("Computing the expectation from measurement results:") TextProgressBar(sys.stderr) num_shots = sum(list(result.get_counts(circuits[0]).values())) if operator_mode == "paulis": self._check_representation("paulis") results = parallel_map(Operator._routine_paulis_with_shots, [(pauli, result.get_counts(circuits[idx])) for idx, pauli in enumerate(self._paulis)], num_processes=aqua_globals.num_processes) for result in results: avg += result[0] variance += result[1] else: self._check_representation("grouped_paulis") results = parallel_map(Operator._routine_grouped_paulis_with_shots, [(tpb_set, result.get_counts(circuits[tpb_idx])) for tpb_idx, tpb_set in enumerate(self._grouped_paulis)], num_processes=aqua_globals.num_processes) for result in results: avg += result[0] variance += result[1] std_dev = np.sqrt(variance / num_shots) return avg, std_dev @staticmethod def _routine_grouped_paulis_with_shots(args): tpb_set, measured_results = args avg_paulis = [] avg = 0.0 variance = 0.0 for pauli_idx, pauli in enumerate(tpb_set): if pauli_idx == 0: continue observable = Operator._measure_pauli_z(measured_results, pauli[1]) avg_paulis.append(observable) avg += pauli[0] * observable # Compute the covariance matrix elements of tpb_set # and add up to the total standard deviation # tpb_set = grouped_paulis, tensor product basis set for pauli_1_idx, pauli_1 in enumerate(tpb_set): for pauli_2_idx, pauli_2 in enumerate(tpb_set): if pauli_1_idx == 0 or pauli_2_idx == 0: continue variance += pauli_1[0] * pauli_2[0] * \ Operator._covariance(measured_results, pauli_1[1], pauli_2[1], avg_paulis[pauli_1_idx-1], avg_paulis[pauli_2_idx-1]) return avg, variance @staticmethod def _routine_paulis_with_shots(args): pauli, measured_results = args curr_result = Operator._measure_pauli_z(measured_results, pauli[1]) avg = pauli[0] * curr_result variance = (pauli[0] ** 2) * Operator._covariance(measured_results, pauli[1], pauli[1], curr_result, curr_result) return avg, variance def _eval_directly(self, quantum_state): self._check_representation("matrix") if self._dia_matrix is None: self._to_dia_matrix(mode='matrix') if self._dia_matrix is not None: avg = np.sum(self._dia_matrix * np.absolute(quantum_state) ** 2) else: avg = np.vdot(quantum_state, self._matrix.dot(quantum_state)) return avg def eval(self, operator_mode, input_circuit, backend, backend_config=None, compile_config=None, run_config=None, qjob_config=None, noise_config=None): """ Supporting three ways to evaluate the given circuits with the operator. 1. If `input_circuit` is a numpy.ndarray, it will directly perform inner product with the operator. 2. If `backend` is a statevector simulator, use quantum backend to get statevector \ and then evaluate with the operator. 3. Other cases: it use with quanutm backend (simulator or real quantum machine), \ to obtain the mean and standard deviation of measured results. Args: operator_mode (str): representation of operator, including paulis, grouped_paulis and matrix input_circuit (QuantumCircuit or numpy.ndarray): the quantum circuit. backend (BaseBackend): backend selection for quantum machine. backend_config (dict): configuration for backend compile_config (dict): configuration for compilation run_config (RunConfig): configuration for running a circuit qjob_config (dict): the setting to retrieve results from quantum backend, including timeout and wait. noise_config (dict) the setting of noise model for the qasm simulator in the Aer provider. Returns: float, float: mean and standard deviation of avg """ backend_config = backend_config or {} compile_config = compile_config or {} if run_config is not None: if isinstance(run_config, dict): run_config = RunConfig(**run_config) else: run_config = RunConfig() qjob_config = qjob_config or {} noise_config = noise_config or {} if isinstance(input_circuit, np.ndarray): avg = self._eval_directly(input_circuit) std_dev = 0.0 else: if is_statevector_backend(backend): run_config.shots = 1 circuits = self.construct_evaluation_circuit(operator_mode, input_circuit, backend) result = compile_and_run_circuits(circuits, backend=backend, backend_config=backend_config, compile_config=compile_config, run_config=run_config, qjob_config=qjob_config, noise_config=noise_config, show_circuit_summary=self._summarize_circuits) avg, std_dev = self.evaluate_with_result(operator_mode, circuits, backend, result) return avg, std_dev def to_paulis(self): self._check_representation('paulis') def to_grouped_paulis(self): self._check_representation('grouped_paulis') def to_matrix(self): self._check_representation('matrix') def convert(self, input_format, output_format, force=False): """ A wrapper for conversion among all representations. Note that, if the output target is already there, it will skip the conversion. The result is stored back into its property directly. Args: input_format (str): case-insensitive input format, should be one of "paulis", "grouped_paulis", "matrix" output_format (str): case-insensitive output format, should be one of "paulis", "grouped_paulis", "matrix" force (bool): convert to targeted format regardless its present. Raises: ValueError: if the unsupported output_format is specified. """ input_format = input_format.lower() output_format = output_format.lower() if input_format not in ["paulis", "grouped_paulis", "matrix"]: raise ValueError( "Input format {} is not supported".format(input_format)) if output_format not in ["paulis", "grouped_paulis", "matrix"]: raise ValueError( "Output format {} is not supported".format(output_format)) if output_format == "paulis" and (self._paulis is None or force): if input_format == "matrix": self._matrix_to_paulis() elif input_format == "grouped_paulis": self._grouped_paulis_to_paulis() elif output_format == "grouped_paulis" and (self._grouped_paulis is None or force): if self._grouped_paulis == []: return if input_format == "paulis": self._paulis_to_grouped_paulis() elif input_format == "matrix": self._matrix_to_grouped_paulis() elif output_format == "matrix" and (self._matrix is None or force): if input_format == "paulis": self._paulis_to_matrix() elif input_format == "grouped_paulis": self._grouped_paulis_to_matrix() def _grouped_paulis_to_paulis(self): """ Convert grouped paulis to paulis, and save it in internal property directly. Note: Ideally, all paulis in grouped_paulis should be unique. No need to check whether it is existed. """ if self._grouped_paulis == []: return paulis = [] for group in self._grouped_paulis: for idx in range(1, len(group)): # the first one is the header. paulis.append(group[idx]) self._paulis = paulis self._matrix = None self._grouped_paulis = None def _matrix_to_paulis(self): """ Convert matrix to paulis, and save it in internal property directly. Note: Conversion from Paulis to matrix: H = sum_i alpha_i * Pauli_i Conversion from matrix to Paulis: alpha_i = coeff * Trace(H.Pauli_i) (dot product of trace) where coeff = 2^(- # of qubits), # of qubit = log2(dim of matrix) """ if self._matrix.nnz == 0: return num_qubits = self.num_qubits coeff = 2 ** (-num_qubits) paulis = [] # generate all possible paulis basis for basis in itertools.product('IXYZ', repeat=num_qubits): pauli_i = Pauli.from_label(''.join(basis)) trace_value = np.sum(self._matrix.dot(pauli_i.to_spmatrix()).diagonal()) alpha_i = trace_value * coeff if alpha_i != 0.0: paulis.append([alpha_i, pauli_i]) self._paulis = paulis self._matrix = None self._grouped_paulis = None def _paulis_to_grouped_paulis(self): """ Convert paulis to grouped_paulis, and save it in internal property directly. Groups a list of [coeff,Pauli] into tensor product basis (tpb) sets """ if self._paulis == []: return if self._coloring is not None: self._grouped_paulis = PauliGraph(self._paulis, mode=self._coloring).grouped_paulis else: temp_paulis = copy.deepcopy(self._paulis) n = self.num_qubits grouped_paulis = [] sorted_paulis = [] def check_pauli_in_list(target, pauli_list): ret = False for pauli in pauli_list: if target[1] == pauli[1]: ret = True break return ret for i in range(len(temp_paulis)): p_1 = temp_paulis[i] if not check_pauli_in_list(p_1, sorted_paulis): paulis_temp = [] # pauli_list_temp.extend(p_1) # this is going to signal the total # post-rotations of the set (set master) paulis_temp.append(p_1) paulis_temp.append(copy.deepcopy(p_1)) paulis_temp[0][0] = 0.0 # zero coeff for HEADER for j in range(i+1, len(temp_paulis)): p_2 = temp_paulis[j] if not check_pauli_in_list(p_2, sorted_paulis) and p_1[1] != p_2[1]: j = 0 for i in range(n): # p_2 is identity, p_1 is identity, p_1 and p_2 has same basis if not ((not p_2[1].z[i] and not p_2[1].x[i]) or (not p_1[1].z[i] and not p_1[1].x[i]) or (p_2[1].z[i] == p_1[1].z[i] and p_2[1].x[i] == p_1[1].x[i])): break else: # update master, if p_2 is not identity if p_2[1].z[i] or p_2[1].x[i]: paulis_temp[0][1].update_z(p_2[1].z[i], i) paulis_temp[0][1].update_x(p_2[1].x[i], i) j += 1 if j == n: paulis_temp.append(p_2) sorted_paulis.append(p_2) grouped_paulis.append(paulis_temp) self._grouped_paulis = grouped_paulis self._matrix = None self._paulis = None def _matrix_to_grouped_paulis(self): """ Convert matrix to grouped_paulis, and save it in internal property directly. """ if self._matrix.nnz == 0: return self._matrix_to_paulis() self._paulis_to_grouped_paulis() self._matrix = None self._paulis = None def _paulis_to_matrix(self): """ Convert paulis to matrix, and save it in internal property directly. If all paulis are Z or I (identity), convert to dia_matrix. """ if self._paulis == []: return p = self._paulis[0] hamiltonian = p[0] * p[1].to_spmatrix() for idx in range(1, len(self._paulis)): p = self._paulis[idx] hamiltonian += p[0] * p[1].to_spmatrix() self._matrix = hamiltonian self._to_dia_matrix(mode='matrix') self._paulis = None self._grouped_paulis = None def _grouped_paulis_to_matrix(self): """ Convert grouped_paulis to matrix, and save it in internal property directly. If all paulis are Z or I (identity), convert to dia_matrix. """ if self._grouped_paulis == []: return p = self._grouped_paulis[0][1] hamiltonian = p[0] * p[1].to_spmatrix() for idx in range(2, len(self._grouped_paulis[0])): p = self._grouped_paulis[0][idx] hamiltonian += p[0] * p[1].to_spmatrix() for group_idx in range(1, len(self._grouped_paulis)): group = self._grouped_paulis[group_idx] for idx in range(1, len(group)): p = group[idx] hamiltonian += p[0] * p[1].to_spmatrix() self._matrix = hamiltonian self._to_dia_matrix(mode='matrix') self._paulis = None self._grouped_paulis = None @staticmethod def _measure_pauli_z(data, pauli): """ Appropriate post-rotations on the state are assumed. Args: data (dict): a dictionary of the form data = {'00000': 10} ({str: int}) pauli (Pauli): a Pauli object Returns: float: Expected value of paulis given data """ observable = 0.0 num_shots = sum(data.values()) p_z_or_x = np.logical_or(pauli.z, pauli.x) for key, value in data.items(): bitstr = np.asarray(list(key))[::-1].astype(np.bool) sign = -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p_z_or_x)) else 1.0 observable += sign * value observable /= num_shots return observable @staticmethod def _covariance(data, pauli_1, pauli_2, avg_1, avg_2): """ Compute the covariance matrix element between two Paulis, given the measurement outcome. Appropriate post-rotations on the state are assumed. Args: data (dict): a dictionary of the form data = {'00000': 10} ({str:int}) pauli_1 (Pauli): a Pauli class member pauli_2 (Pauli): a Pauli class member avg_1 (float): expectation value of pauli_1 on `data` avg_2 (float): expectation value of pauli_2 on `data` Returns: float: the element of the covariance matrix between two Paulis """ cov = 0.0 num_shots = sum(data.values()) if num_shots == 1: return cov p1_z_or_x = np.logical_or(pauli_1.z, pauli_1.x) p2_z_or_x = np.logical_or(pauli_2.z, pauli_2.x) for key, value in data.items(): bitstr = np.asarray(list(key))[::-1].astype(np.bool) sign_1 = -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p1_z_or_x)) else 1.0 sign_2 = -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p2_z_or_x)) else 1.0 cov += (sign_1 - avg_1) * (sign_2 - avg_2) * value cov /= (num_shots - 1) return cov def two_qubit_reduced_operator(self, m, threshold=10**-13): """ Eliminates the central and last qubit in a list of Pauli that has diagonal operators (Z,I) at those positions Chemistry specific method: It can be used to taper two qubits in parity and binary-tree mapped fermionic Hamiltonians when the spin orbitals are ordered in two spin sectors, (block spin order) according to the number of particles in the system. Args: m (int): number of fermionic particles threshold (float): threshold for Pauli simplification Returns: Operator: a new operator whose qubit number is reduced by 2. """ if self._paulis is None or self._paulis == []: return self operator_out = Operator(paulis=[]) par_1 = 1 if m % 2 == 0 else -1 par_2 = 1 if m % 4 == 0 else -1 n = self.num_qubits last_idx = n - 1 mid_idx = n // 2 - 1 for pauli_term in self._paulis: # loop over Pauli terms coeff_out = pauli_term[0] # Z operator encountered at qubit n/2-1 if pauli_term[1].z[mid_idx] and not pauli_term[1].x[mid_idx]: coeff_out = par_2 * coeff_out # Z operator encountered at qubit n-1 if pauli_term[1].z[last_idx] and not pauli_term[1].x[last_idx]: coeff_out = par_1 * coeff_out # TODO: can change to delete z_temp = [] x_temp = [] for j in range(n - 1): if j != mid_idx: z_temp.append(pauli_term[1].z[j]) x_temp.append(pauli_term[1].x[j]) pauli_term_out = [coeff_out, Pauli(np.asarray(z_temp), np.asarray(x_temp))] if np.absolute(coeff_out) > threshold: operator_out += Operator(paulis=[pauli_term_out]) operator_out.chop(threshold=threshold) return operator_out def get_flat_pauli_list(self): """ Get the flat list of paulis Returns: list: The list of pauli terms """ if self._paulis is not None: return [] + self._paulis else: if self._grouped_paulis is not None: return [pauli for group in self._grouped_paulis for pauli in group[1:]] elif self._matrix is not None: self._check_representation('paulis') return [] + self._paulis @staticmethod def construct_evolution_circuit(slice_pauli_list, evo_time, num_time_slices, state_registers, ancillary_registers=None, ctl_idx=0, unitary_power=None, use_basis_gates=True, shallow_slicing=False): """ Construct the evolution circuit according to the supplied specification. Args: slice_pauli_list (list): The list of pauli terms corresponding to a single time slice to be evolved evo_time (int): The evolution time num_time_slices (int): The number of time slices for the expansion state_registers (QuantumRegister): The Qiskit QuantumRegister corresponding to the qubits of the system ancillary_registers (QuantumRegister): The optional Qiskit QuantumRegister corresponding to the control qubits for the state_registers of the system ctl_idx (int): The index of the qubit of the control ancillary_registers to use unitary_power (int): The power to which the unitary operator is to be raised use_basis_gates (bool): boolean flag for indicating only using basis gates when building circuit. shallow_slicing (bool): boolean flag for indicating using shallow qc.data reference repetition for slicing Returns: QuantumCircuit: The Qiskit QuantumCircuit corresponding to specified evolution. """ if state_registers is None: raise ValueError('Quantum state registers are required.') qc_slice = QuantumCircuit(state_registers) if ancillary_registers is not None: qc_slice.add_register(ancillary_registers) # for each pauli [IXYZ]+, record the list of qubit pairs needing CX's cnot_qubit_pairs = [None] * len(slice_pauli_list) # for each pauli [IXYZ]+, record the highest index of the nontrivial pauli gate (X,Y, or Z) top_XYZ_pauli_indices = [-1] * len(slice_pauli_list) for pauli_idx, pauli in enumerate(reversed(slice_pauli_list)): n_qubits = pauli[1].numberofqubits # changes bases if necessary nontrivial_pauli_indices = [] for qubit_idx in range(n_qubits): # pauli I if not pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]: continue if cnot_qubit_pairs[pauli_idx] is None: nontrivial_pauli_indices.append(qubit_idx) if pauli[1].x[qubit_idx]: # pauli X if not pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.u2(0.0, pi, state_registers[qubit_idx]) else: qc_slice.h(state_registers[qubit_idx]) # pauli Y elif pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.u3(pi / 2, -pi / 2, pi / 2, state_registers[qubit_idx]) else: qc_slice.rx(pi / 2, state_registers[qubit_idx]) # pauli Z elif pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]: pass else: raise ValueError('Unrecognized pauli: {}'.format(pauli[1])) if len(nontrivial_pauli_indices) > 0: top_XYZ_pauli_indices[pauli_idx] = nontrivial_pauli_indices[-1] # insert lhs cnot gates if cnot_qubit_pairs[pauli_idx] is None: cnot_qubit_pairs[pauli_idx] = list(zip( sorted(nontrivial_pauli_indices)[:-1], sorted(nontrivial_pauli_indices)[1:] )) for pair in cnot_qubit_pairs[pauli_idx]: qc_slice.cx(state_registers[pair[0]], state_registers[pair[1]]) # insert Rz gate if top_XYZ_pauli_indices[pauli_idx] >= 0: if ancillary_registers is None: lam = (2.0 * pauli[0] * evo_time / num_time_slices).real if use_basis_gates: qc_slice.u1(lam, state_registers[top_XYZ_pauli_indices[pauli_idx]]) else: qc_slice.rz(lam, state_registers[top_XYZ_pauli_indices[pauli_idx]]) else: unitary_power = (2 ** ctl_idx) if unitary_power is None else unitary_power lam = (2.0 * pauli[0] * evo_time / num_time_slices * unitary_power).real if use_basis_gates: qc_slice.u1(lam / 2, state_registers[top_XYZ_pauli_indices[pauli_idx]]) qc_slice.cx(ancillary_registers[ctl_idx], state_registers[top_XYZ_pauli_indices[pauli_idx]]) qc_slice.u1(-lam / 2, state_registers[top_XYZ_pauli_indices[pauli_idx]]) qc_slice.cx(ancillary_registers[ctl_idx], state_registers[top_XYZ_pauli_indices[pauli_idx]]) else: qc_slice.crz(lam, ancillary_registers[ctl_idx], state_registers[top_XYZ_pauli_indices[pauli_idx]]) # insert rhs cnot gates for pair in reversed(cnot_qubit_pairs[pauli_idx]): qc_slice.cx(state_registers[pair[0]], state_registers[pair[1]]) # revert bases if necessary for qubit_idx in range(n_qubits): if pauli[1].x[qubit_idx]: # pauli X if not pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.u2(0.0, pi, state_registers[qubit_idx]) else: qc_slice.h(state_registers[qubit_idx]) # pauli Y elif pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.u3(-pi / 2, -pi / 2, pi / 2, state_registers[qubit_idx]) else: qc_slice.rx(-pi / 2, state_registers[qubit_idx]) # repeat the slice if shallow_slicing: logger.info('Under shallow slicing mode, the qc.data reference is repeated shallowly. ' 'Thus, changing gates of one slice of the output circuit might affect other slices.') qc_slice.data *= num_time_slices qc = qc_slice else: qc = QuantumCircuit() for _ in range(num_time_slices): qc += qc_slice return qc @staticmethod def _suzuki_expansion_slice_matrix(pauli_list, lam, expansion_order): """ Compute the matrix for a single slice of the suzuki expansion following the paper https://arxiv.org/pdf/quant-ph/0508139.pdf Args: pauli_list (list): The operator's complete list of pauli terms for the suzuki expansion lam (complex): The parameter lambda as defined in said paper expansion_order (int): The order for the suzuki expansion Returns: numpy array: The matrix representation corresponding to the specified suzuki expansion """ if expansion_order == 1: left = reduce( lambda x, y: x @ y, [scila.expm(lam / 2 * c * p.to_spmatrix().tocsc()) for c, p in pauli_list] ) right = reduce( lambda x, y: x @ y, [scila.expm(lam / 2 * c * p.to_spmatrix().tocsc()) for c, p in reversed(pauli_list)] ) return left @ right else: pk = (4 - 4 ** (1 / (2 * expansion_order - 1))) ** -1 side_base = Operator._suzuki_expansion_slice_matrix( pauli_list, lam * pk, expansion_order - 1 ) side = side_base @ side_base middle = Operator._suzuki_expansion_slice_matrix( pauli_list, lam * (1 - 4 * pk), expansion_order - 1 ) return side @ middle @ side @staticmethod def _suzuki_expansion_slice_pauli_list(pauli_list, lam_coef, expansion_order): """ Similar to _suzuki_expansion_slice_matrix, with the difference that this method computes the list of pauli terms for a single slice of the suzuki expansion, which can then be fed to construct_evolution_circuit to build the QuantumCircuit. """ if expansion_order == 1: half = [[lam_coef / 2 * c, p] for c, p in pauli_list] return half + list(reversed(half)) else: pk = (4 - 4 ** (1 / (2 * expansion_order - 1))) ** -1 side_base = Operator._suzuki_expansion_slice_pauli_list( pauli_list, lam_coef * pk, expansion_order - 1 ) side = side_base * 2 middle = Operator._suzuki_expansion_slice_pauli_list( pauli_list, lam_coef * (1 - 4 * pk), expansion_order - 1 ) return side + middle + side def evolve( self, state_in=None, evo_time=0, evo_mode=None, num_time_slices=0, quantum_registers=None, expansion_mode='trotter', expansion_order=1 ): """ Carry out the eoh evolution for the operator under supplied specifications. Args: state_in: The initial state for the evolution evo_time (int): The evolution time evo_mode (str): The mode under which the evolution is carried out. Currently only support 'matrix' or 'circuit' num_time_slices (int): The number of time slices for the expansion quantum_registers (QuantumRegister): The QuantumRegister to build the QuantumCircuit off of expansion_mode (str): The mode under which the expansion is to be done. Currently support 'trotter', which follows the expansion as discussed in http://science.sciencemag.org/content/273/5278/1073, and 'suzuki', which corresponds to the discussion in https://arxiv.org/pdf/quant-ph/0508139.pdf expansion_order (int): The order for suzuki expansion Returns: Depending on the evo_mode specified, either return the matrix vector multiplication result or the constructed QuantumCircuit. """ if num_time_slices < 0 or not isinstance(num_time_slices, int): raise ValueError('Number of time slices should be a non-negative integer.') if not (expansion_mode == 'trotter' or expansion_mode == 'suzuki'): raise NotImplementedError('Expansion mode {} not supported.'.format(expansion_mode)) pauli_list = self.get_flat_pauli_list() if evo_mode == 'matrix': self._check_representation("matrix") if num_time_slices == 0: return scila.expm(-1.j * evo_time * self._matrix.tocsc()) @ state_in else: if len(pauli_list) == 1: approx_matrix_slice = scila.expm( -1.j * evo_time / num_time_slices * pauli_list[0][0] * pauli_list[0][1].to_spmatrix().tocsc() ) else: if expansion_mode == 'trotter': approx_matrix_slice = reduce( lambda x, y: x @ y, [ scila.expm(-1.j * evo_time / num_time_slices * c * p.to_spmatrix().tocsc()) for c, p in pauli_list ] ) # suzuki expansion elif expansion_mode == 'suzuki': approx_matrix_slice = Operator._suzuki_expansion_slice_matrix( pauli_list, -1.j * evo_time / num_time_slices, expansion_order ) else: raise ValueError('Unrecognized expansion mode {}.'.format(expansion_mode)) return reduce(lambda x, y: x @ y, [approx_matrix_slice] * num_time_slices) @ state_in elif evo_mode == 'circuit': if num_time_slices == 0: raise ValueError('Number of time slices should be a positive integer for {} mode.'.format(evo_mode)) else: if quantum_registers is None: raise ValueError('Quantum registers are needed for circuit construction.') if len(pauli_list) == 1: slice_pauli_list = pauli_list else: if expansion_mode == 'trotter': slice_pauli_list = pauli_list # suzuki expansion else: slice_pauli_list = Operator._suzuki_expansion_slice_pauli_list( pauli_list, 1, expansion_order ) return self.construct_evolution_circuit( slice_pauli_list, evo_time, num_time_slices, quantum_registers ) else: raise ValueError('Evolution mode should be either "matrix" or "circuit".') def is_empty(self): """ Check Operator is empty or not. Returns: bool: is empty? """ if self._matrix is None and self._dia_matrix is None \ and (self._paulis == [] or self._paulis is None) \ and (self._grouped_paulis == [] or self._grouped_paulis is None): return True else: return False def _check_representation(self, targeted_representation): """ Check the targeted representation is existed or not, if not, find available representations and then convert to the targeted one. Args: targeted_representation (str): should be one of paulis, grouped_paulis and matrix Raises: ValueError: if the `targeted_representation` is not recognized. """ if targeted_representation == 'paulis': if self._paulis is None: if self._matrix is not None: self._matrix_to_paulis() elif self._grouped_paulis is not None: self._grouped_paulis_to_paulis() else: raise AquaError( "at least having one of the three operator representations.") elif targeted_representation == 'grouped_paulis': if self._grouped_paulis is None: if self._paulis is not None: self._paulis_to_grouped_paulis() elif self._matrix is not None: self._matrix_to_grouped_paulis() else: raise AquaError( "at least having one of the three operator representations.") elif targeted_representation == 'matrix': if self._matrix is None: if self._paulis is not None: self._paulis_to_matrix() elif self._grouped_paulis is not None: self._grouped_paulis_to_matrix() else: raise AquaError( "at least having one of the three operator representations.") else: raise ValueError( '"targeted_representation" should be one of "paulis", "grouped_paulis" and "matrix".' ) @staticmethod def row_echelon_F2(matrix_in): """ Computes the row Echelon form of a binary matrix on the binary finite field Args: matrix_in (numpy.ndarray): binary matrix Returns: numpy.ndarray : matrix_in in Echelon row form """ size = matrix_in.shape for i in range(size[0]): pivot_index = 0 for j in range(size[1]): if matrix_in[i, j] == 1: pivot_index = j break for k in range(size[0]): if k != i and matrix_in[k, pivot_index] == 1: matrix_in[k, :] = np.mod(matrix_in[k, :] + matrix_in[i, :], 2) matrix_out_temp = copy.deepcopy(matrix_in) indices = [] matrix_out = np.zeros(size) for i in range(size[0] - 1): if np.array_equal(matrix_out_temp[i, :], np.zeros(size[1])): indices.append(i) for row in np.sort(indices)[::-1]: matrix_out_temp = np.delete(matrix_out_temp, (row), axis=0) matrix_out[0:size[0] - len(indices), :] = matrix_out_temp matrix_out = matrix_out.astype(int) return matrix_out @staticmethod def kernel_F2(matrix_in): """ Computes the kernel of a binary matrix on the binary finite field Args: matrix_in (numpy.ndarray): binary matrix Returns: [numpy.ndarray]: the list of kernel vectors """ size = matrix_in.shape kernel = [] matrix_in_id = np.vstack((matrix_in, np.identity(size[1]))) matrix_in_id_ech = (Operator.row_echelon_F2(matrix_in_id.transpose())).transpose() for col in range(size[1]): if (np.array_equal(matrix_in_id_ech[0:size[0], col], np.zeros(size[0])) and not np.array_equal(matrix_in_id_ech[size[0]:, col], np.zeros(size[1]))): kernel.append(matrix_in_id_ech[size[0]:, col]) return kernel def find_Z2_symmetries(self): """ Finds Z2 Pauli-type symmetries of an Operator Returns: [Pauli]: the list of Pauli objects representing the Z2 symmetries [Pauli]: the list of single - qubit Pauli objects to construct the Cliffors operators [Operators]: the list of Clifford unitaries to block diagonalize Operator [int]: the list of support of the single-qubit Pauli objects used to build the clifford operators """ Pauli_symmetries = [] sq_paulis = [] cliffords = [] sq_list = [] stacked_paulis = [] if self.is_empty(): logger.info("Operator is empty.") return [], [], [], [] self._check_representation("paulis") for pauli in self._paulis: stacked_paulis.append(np.concatenate((pauli[1].x, pauli[1].z), axis=0).astype(np.int)) stacked_matrix = np.array(np.stack(stacked_paulis)) symmetries = Operator.kernel_F2(stacked_matrix) if len(symmetries) == 0: logger.info("No symmetry is found.") return [], [], [], [] stacked_symmetries = np.stack(symmetries) symm_shape = stacked_symmetries.shape for row in range(symm_shape[0]): Pauli_symmetries.append(Pauli(stacked_symmetries[row, : symm_shape[1] // 2], stacked_symmetries[row, symm_shape[1] // 2:])) stacked_symm_del = np.delete(stacked_symmetries, (row), axis=0) for col in range(symm_shape[1] // 2): # case symmetries other than one at (row) have Z or I on col qubit Z_or_I = True for symm_idx in range(symm_shape[0] - 1): if not (stacked_symm_del[symm_idx, col] == 0 and stacked_symm_del[symm_idx, col + symm_shape[1] // 2] in (0, 1)): Z_or_I = False if Z_or_I: if ((stacked_symmetries[row, col] == 1 and stacked_symmetries[row, col + symm_shape[1] // 2] == 0) or (stacked_symmetries[row, col] == 1 and stacked_symmetries[row, col + symm_shape[1] // 2] == 1)): sq_paulis.append(Pauli(np.zeros(symm_shape[1] // 2), np.zeros(symm_shape[1] // 2))) sq_paulis[row].z[col] = False sq_paulis[row].x[col] = True sq_list.append(col) break # case symmetries other than one at (row) have X or I on col qubit X_or_I = True for symm_idx in range(symm_shape[0] - 1): if not (stacked_symm_del[symm_idx, col] in (0, 1) and stacked_symm_del[symm_idx, col + symm_shape[1] // 2] == 0): X_or_I = False if X_or_I: if ((stacked_symmetries[row, col] == 0 and stacked_symmetries[row, col + symm_shape[1] // 2] == 1) or (stacked_symmetries[row, col] == 1 and stacked_symmetries[row, col + symm_shape[1] // 2] == 1)): sq_paulis.append(Pauli(np.zeros(symm_shape[1] // 2), np.zeros(symm_shape[1] // 2))) sq_paulis[row].z[col] = True sq_paulis[row].x[col] = False sq_list.append(col) break # case symmetries other than one at (row) have Y or I on col qubit Y_or_I = True for symm_idx in range(symm_shape[0] - 1): if not ((stacked_symm_del[symm_idx, col] == 1 and stacked_symm_del[symm_idx, col + symm_shape[1] // 2] == 1) or (stacked_symm_del[symm_idx, col] == 0 and stacked_symm_del[symm_idx, col + symm_shape[1] // 2] == 0)): Y_or_I = False if Y_or_I: if ((stacked_symmetries[row, col] == 0 and stacked_symmetries[row, col + symm_shape[1] // 2] == 1) or (stacked_symmetries[row, col] == 1 and stacked_symmetries[row, col + symm_shape[1] // 2] == 0)): sq_paulis.append(Pauli(np.zeros(symm_shape[1] // 2), np.zeros(symm_shape[1] // 2))) sq_paulis[row].z[col] = True sq_paulis[row].x[col] = True sq_list.append(col) break for symm_idx, Pauli_symm in enumerate(Pauli_symmetries): cliffords.append(Operator([[1 / np.sqrt(2), Pauli_symm], [1 / np.sqrt(2), sq_paulis[symm_idx]]])) return Pauli_symmetries, sq_paulis, cliffords, sq_list @staticmethod def qubit_tapering(operator, cliffords, sq_list, tapering_values): """ Builds an Operator which has a number of qubits tapered off, based on a block-diagonal Operator built using a list of cliffords. The block-diagonal subspace is an input parameter, set through the list tapering_values, which takes values +/- 1. Args: operator (Operator): the target operator to be tapered cliffords ([Operator]): list of unitary Clifford transformation sq_list ([int]): position of the single-qubit operators that anticommute with the cliffords tapering_values ([int]): array of +/- 1 used to select the subspace. Length has to be equal to the length of cliffords and sq_list Returns: Operator : the tapered operator, or empty operator if the `operator` is empty. """ if len(cliffords) == 0 or len(sq_list) == 0 or len(tapering_values) == 0: logger.warning("Cliffords, single qubit list and tapering values cannot be empty.\n" "Return the original operator instead.") return operator if len(cliffords) != len(sq_list): logger.warning("Number of Clifford unitaries has to be the same as length of single" "qubit list and tapering values.\n" "Return the original operator instead.") return operator if len(sq_list) != len(tapering_values): logger.warning("Number of Clifford unitaries has to be the same as length of single" "qubit list and tapering values.\n" "Return the original operator instead.") return operator if operator.is_empty(): logger.warning("The operator is empty, return the empty operator directly.") return operator operator.to_paulis() for clifford in cliffords: operator = clifford * operator * clifford operator_out = Operator(paulis=[]) for pauli_term in operator.paulis: coeff_out = pauli_term[0] for idx, qubit_idx in enumerate(sq_list): if not (not pauli_term[1].z[qubit_idx] and not pauli_term[1].x[qubit_idx]): coeff_out = tapering_values[idx] * coeff_out z_temp = np.delete(pauli_term[1].z.copy(), np.asarray(sq_list)) x_temp = np.delete(pauli_term[1].x.copy(), np.asarray(sq_list)) pauli_term_out = [coeff_out, Pauli(z_temp, x_temp)] operator_out += Operator(paulis=[pauli_term_out]) operator_out.zeros_coeff_elimination() return operator_out def zeros_coeff_elimination(self): """ Elinminate paulis or grouped paulis whose coefficients are zeros. The difference from `_simplify_paulis` method is that, this method will not remove duplicated paulis. """ if self._paulis is not None: new_paulis = [pauli for pauli in self._paulis if pauli[0] != 0] self._paulis = new_paulis self._paulis_table = {pauli[1].to_label(): i for i, pauli in enumerate(self._paulis)} elif self._grouped_paulis is not None: self._grouped_paulis_to_paulis() self.zeros_coeff_elimination() self._paulis_to_grouped_paulis() self._paulis = None def scaling_coeff(self, scaling_factor): """ Constant scale the coefficient in an operator. Note that: the behavior of scaling in paulis (grouped_paulis) might be different from matrix Args: scaling_factor (float): the sacling factor """ if self._paulis is not None: for idx in range(len(self._paulis)): self._paulis[idx] = [self._paulis[idx][0] * scaling_factor, self._paulis[idx][1]] elif self._grouped_paulis is not None: self._grouped_paulis_to_paulis() self._scale_paulis(scaling_factor) self._paulis_to_grouped_paulis() elif self._matrix is not None: self._matrix *= scaling_factor if self._dia_matrix is not None: self._dia_matrix *= scaling_factor
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Chi-matrix representation of a Quantum Channel. """ from __future__ import annotations import copy as _copy import math import numpy as np from qiskit import _numpy_compat from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.instruction import Instruction from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel from qiskit.quantum_info.operators.channel.choi import Choi from qiskit.quantum_info.operators.channel.superop import SuperOp from qiskit.quantum_info.operators.channel.transformations import _to_chi from qiskit.quantum_info.operators.mixins import generate_apidocs from qiskit.quantum_info.operators.base_operator import BaseOperator class Chi(QuantumChannel): r"""Pauli basis Chi-matrix representation of a quantum channel. The Chi-matrix representation of an :math:`n`-qubit quantum channel :math:`\mathcal{E}` is a matrix :math:`\chi` such that the evolution of a :class:`~qiskit.quantum_info.DensityMatrix` :math:`\rho` is given by .. math:: \mathcal{E}(ρ) = \frac{1}{2^n} \sum_{i, j} \chi_{i,j} P_i ρ P_j where :math:`[P_0, P_1, ..., P_{4^{n}-1}]` is the :math:`n`-qubit Pauli basis in lexicographic order. It is related to the :class:`Choi` representation by a change of basis of the Choi-matrix into the Pauli basis. The :math:`\frac{1}{2^n}` in the definition above is a normalization factor that arises from scaling the Pauli basis to make it orthonormal. See reference [1] for further details. References: 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). `arXiv:1111.6950 [quant-ph] <https://arxiv.org/abs/1111.6950>`_ """ def __init__( self, data: QuantumCircuit | Instruction | BaseOperator | np.ndarray, input_dims: int | tuple | None = None, output_dims: int | tuple | None = None, ): """Initialize a quantum channel Chi-matrix operator. Args: data (QuantumCircuit or Instruction or BaseOperator or matrix): data to initialize superoperator. input_dims (tuple): the input subsystem dimensions. [Default: None] output_dims (tuple): the output subsystem dimensions. [Default: None] Raises: QiskitError: if input data is not an N-qubit channel or cannot be initialized as a Chi-matrix. Additional Information: If the input or output dimensions are None, they will be automatically determined from the input data. The Chi matrix representation is only valid for N-qubit channels. """ # If the input is a raw list or matrix we assume that it is # already a Chi matrix. if isinstance(data, (list, np.ndarray)): # Initialize from raw numpy or list matrix. chi_mat = np.asarray(data, dtype=complex) # Determine input and output dimensions dim_l, dim_r = chi_mat.shape if dim_l != dim_r: raise QiskitError("Invalid Chi-matrix input.") if input_dims: input_dim = np.prod(input_dims) if output_dims: output_dim = np.prod(input_dims) if output_dims is None and input_dims is None: output_dim = int(math.sqrt(dim_l)) input_dim = dim_l // output_dim elif input_dims is None: input_dim = dim_l // output_dim elif output_dims is None: output_dim = dim_l // input_dim # Check dimensions if input_dim * output_dim != dim_l: raise QiskitError("Invalid shape for Chi-matrix input.") else: # Otherwise we initialize by conversion from another Qiskit # object into the QuantumChannel. if isinstance(data, (QuantumCircuit, Instruction)): # If the input is a Terra QuantumCircuit or Instruction we # convert it to a SuperOp data = SuperOp._init_instruction(data) else: # We use the QuantumChannel init transform to initialize # other objects into a QuantumChannel or Operator object. data = self._init_transformer(data) input_dim, output_dim = data.dim # Now that the input is an operator we convert it to a Chi object rep = getattr(data, "_channel_rep", "Operator") chi_mat = _to_chi(rep, data._data, input_dim, output_dim) if input_dims is None: input_dims = data.input_dims() if output_dims is None: output_dims = data.output_dims() # Check input is N-qubit channel num_qubits = int(math.log2(input_dim)) if 2**num_qubits != input_dim or input_dim != output_dim: raise QiskitError("Input is not an n-qubit Chi matrix.") super().__init__(chi_mat, num_qubits=num_qubits) def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): dtype = self.data.dtype return np.array(self.data, dtype=dtype, copy=copy) @property def _bipartite_shape(self): """Return the shape for bipartite matrix""" return (self._input_dim, self._output_dim, self._input_dim, self._output_dim) def _evolve(self, state, qargs=None): return SuperOp(self)._evolve(state, qargs) # --------------------------------------------------------------------- # BaseOperator methods # --------------------------------------------------------------------- def conjugate(self): # Since conjugation is basis dependent we transform # to the Choi representation to compute the # conjugate channel return Chi(Choi(self).conjugate()) def transpose(self): return Chi(Choi(self).transpose()) def adjoint(self): return Chi(Choi(self).adjoint()) def compose(self, other: Chi, qargs: list | None = None, front: bool = False) -> Chi: if qargs is None: qargs = getattr(other, "qargs", None) if qargs is not None: return Chi(SuperOp(self).compose(other, qargs=qargs, front=front)) # If no qargs we compose via Choi representation to avoid an additional # representation conversion to SuperOp and then convert back to Chi return Chi(Choi(self).compose(other, front=front)) def tensor(self, other: Chi) -> Chi: if not isinstance(other, Chi): other = Chi(other) return self._tensor(self, other) def expand(self, other: Chi) -> Chi: if not isinstance(other, Chi): other = Chi(other) return self._tensor(other, self) @classmethod def _tensor(cls, a, b): ret = _copy.copy(a) ret._op_shape = a._op_shape.tensor(b._op_shape) ret._data = np.kron(a._data, b.data) return ret # Update docstrings for API docs generate_apidocs(Chi)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Choi-matrix representation of a Quantum Channel. """ from __future__ import annotations import copy as _copy import math import numpy as np from qiskit import _numpy_compat from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.instruction import Instruction from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel from qiskit.quantum_info.operators.op_shape import OpShape from qiskit.quantum_info.operators.channel.superop import SuperOp from qiskit.quantum_info.operators.channel.transformations import _to_choi from qiskit.quantum_info.operators.channel.transformations import _bipartite_tensor from qiskit.quantum_info.operators.mixins import generate_apidocs from qiskit.quantum_info.operators.base_operator import BaseOperator class Choi(QuantumChannel): r"""Choi-matrix representation of a Quantum Channel. The Choi-matrix representation of a quantum channel :math:`\mathcal{E}` is a matrix .. math:: \Lambda = \sum_{i,j} |i\rangle\!\langle j|\otimes \mathcal{E}\left(|i\rangle\!\langle j|\right) Evolution of a :class:`~qiskit.quantum_info.DensityMatrix` :math:`\rho` with respect to the Choi-matrix is given by .. math:: \mathcal{E}(\rho) = \mbox{Tr}_{1}\left[\Lambda (\rho^T \otimes \mathbb{I})\right] where :math:`\mbox{Tr}_1` is the :func:`partial_trace` over subsystem 1. See reference [1] for further details. References: 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). `arXiv:1111.6950 [quant-ph] <https://arxiv.org/abs/1111.6950>`_ """ def __init__( self, data: QuantumCircuit | Instruction | BaseOperator | np.ndarray, input_dims: int | tuple | None = None, output_dims: int | tuple | None = None, ): """Initialize a quantum channel Choi matrix operator. Args: data (QuantumCircuit or Instruction or BaseOperator or matrix): data to initialize superoperator. input_dims (tuple): the input subsystem dimensions. [Default: None] output_dims (tuple): the output subsystem dimensions. [Default: None] Raises: QiskitError: if input data cannot be initialized as a Choi matrix. Additional Information: If the input or output dimensions are None, they will be automatically determined from the input data. If the input data is a Numpy array of shape (4**N, 4**N) qubit systems will be used. If the input operator is not an N-qubit operator, it will assign a single subsystem with dimension specified by the shape of the input. """ # If the input is a raw list or matrix we assume that it is # already a Choi matrix. if isinstance(data, (list, np.ndarray)): # Initialize from raw numpy or list matrix. choi_mat = np.asarray(data, dtype=complex) # Determine input and output dimensions dim_l, dim_r = choi_mat.shape if dim_l != dim_r: raise QiskitError("Invalid Choi-matrix input.") if input_dims: input_dim = np.prod(input_dims) if output_dims: output_dim = np.prod(output_dims) if output_dims is None and input_dims is None: output_dim = int(math.sqrt(dim_l)) input_dim = dim_l // output_dim elif input_dims is None: input_dim = dim_l // output_dim elif output_dims is None: output_dim = dim_l // input_dim # Check dimensions if input_dim * output_dim != dim_l: raise QiskitError("Invalid shape for input Choi-matrix.") op_shape = OpShape.auto( dims_l=output_dims, dims_r=input_dims, shape=(output_dim, input_dim) ) else: # Otherwise we initialize by conversion from another Qiskit # object into the QuantumChannel. if isinstance(data, (QuantumCircuit, Instruction)): # If the input is a Terra QuantumCircuit or Instruction we # convert it to a SuperOp data = SuperOp._init_instruction(data) else: # We use the QuantumChannel init transform to initialize # other objects into a QuantumChannel or Operator object. data = self._init_transformer(data) op_shape = data._op_shape output_dim, input_dim = op_shape.shape # Now that the input is an operator we convert it to a Choi object rep = getattr(data, "_channel_rep", "Operator") choi_mat = _to_choi(rep, data._data, input_dim, output_dim) super().__init__(choi_mat, op_shape=op_shape) def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): dtype = self.data.dtype if dtype is None else dtype return np.array(self.data, dtype=dtype, copy=copy) @property def _bipartite_shape(self): """Return the shape for bipartite matrix""" return (self._input_dim, self._output_dim, self._input_dim, self._output_dim) def _evolve(self, state, qargs=None): return SuperOp(self)._evolve(state, qargs) # --------------------------------------------------------------------- # BaseOperator methods # --------------------------------------------------------------------- def conjugate(self): ret = _copy.copy(self) ret._data = np.conj(self._data) return ret def transpose(self): ret = _copy.copy(self) ret._op_shape = self._op_shape.transpose() # Make bipartite matrix d_in, d_out = self.dim data = np.reshape(self._data, (d_in, d_out, d_in, d_out)) # Swap input and output indices on bipartite matrix data = np.transpose(data, (1, 0, 3, 2)) ret._data = np.reshape(data, (d_in * d_out, d_in * d_out)) return ret def compose(self, other: Choi, qargs: list | None = None, front: bool = False) -> Choi: if qargs is None: qargs = getattr(other, "qargs", None) if qargs is not None: return Choi(SuperOp(self).compose(other, qargs=qargs, front=front)) if not isinstance(other, Choi): other = Choi(other) new_shape = self._op_shape.compose(other._op_shape, qargs, front) output_dim, input_dim = new_shape.shape if front: first = np.reshape(other._data, other._bipartite_shape) second = np.reshape(self._data, self._bipartite_shape) else: first = np.reshape(self._data, self._bipartite_shape) second = np.reshape(other._data, other._bipartite_shape) # Contract Choi matrices for composition data = np.reshape( np.einsum("iAjB,AkBl->ikjl", first, second), (input_dim * output_dim, input_dim * output_dim), ) ret = Choi(data) ret._op_shape = new_shape return ret def tensor(self, other: Choi) -> Choi: if not isinstance(other, Choi): other = Choi(other) return self._tensor(self, other) def expand(self, other: Choi) -> Choi: if not isinstance(other, Choi): other = Choi(other) return self._tensor(other, self) @classmethod def _tensor(cls, a, b): ret = _copy.copy(a) ret._op_shape = a._op_shape.tensor(b._op_shape) ret._data = _bipartite_tensor( a._data, b.data, shape1=a._bipartite_shape, shape2=b._bipartite_shape ) return ret # Update docstrings for API docs generate_apidocs(Choi)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Kraus representation of a Quantum Channel. """ from __future__ import annotations import copy import math from numbers import Number import numpy as np from qiskit import circuit from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.instruction import Instruction from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.predicates import is_identity_matrix from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel from qiskit.quantum_info.operators.op_shape import OpShape from qiskit.quantum_info.operators.channel.choi import Choi from qiskit.quantum_info.operators.channel.superop import SuperOp from qiskit.quantum_info.operators.channel.transformations import _to_kraus from qiskit.quantum_info.operators.mixins import generate_apidocs from qiskit.quantum_info.operators.base_operator import BaseOperator class Kraus(QuantumChannel): r"""Kraus representation of a quantum channel. For a quantum channel :math:`\mathcal{E}`, the Kraus representation is given by a set of matrices :math:`[A_0,...,A_{K-1}]` such that the evolution of a :class:`~qiskit.quantum_info.DensityMatrix` :math:`\rho` is given by .. math:: \mathcal{E}(\rho) = \sum_{i=0}^{K-1} A_i \rho A_i^\dagger A general operator map :math:`\mathcal{G}` can also be written using the generalized Kraus representation which is given by two sets of matrices :math:`[A_0,...,A_{K-1}]`, :math:`[B_0,...,A_{B-1}]` such that .. math:: \mathcal{G}(\rho) = \sum_{i=0}^{K-1} A_i \rho B_i^\dagger See reference [1] for further details. References: 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). `arXiv:1111.6950 [quant-ph] <https://arxiv.org/abs/1111.6950>`_ """ def __init__( self, data: QuantumCircuit | circuit.instruction.Instruction | BaseOperator | np.ndarray, input_dims: tuple | None = None, output_dims: tuple | None = None, ): """Initialize a quantum channel Kraus operator. Args: data: data to initialize superoperator. input_dims: the input subsystem dimensions. output_dims: the output subsystem dimensions. Raises: QiskitError: if input data cannot be initialized as a list of Kraus matrices. Additional Information: If the input or output dimensions are None, they will be automatically determined from the input data. If the input data is a list of Numpy arrays of shape :math:`(2^N,\\,2^N)` qubit systems will be used. If the input does not correspond to an N-qubit channel, it will assign a single subsystem with dimension specified by the shape of the input. """ # If the input is a list or tuple we assume it is a list of Kraus # matrices, if it is a numpy array we assume that it is a single Kraus # operator # TODO properly handle array construction from ragged data (like tuple(np.ndarray, None)) # and document these accepted input cases. See also Qiskit/qiskit-terra#9307. if isinstance(data, (list, tuple, np.ndarray)): # Check if it is a single unitary matrix A for channel: # E(rho) = A * rho * A^\dagger if _is_matrix(data): # Convert single Kraus op to general Kraus pair kraus = ([np.asarray(data, dtype=complex)], None) shape = kraus[0][0].shape # Check if single Kraus set [A_i] for channel: # E(rho) = sum_i A_i * rho * A_i^dagger elif isinstance(data, list) and len(data) > 0: # Get dimensions from first Kraus op kraus = [np.asarray(data[0], dtype=complex)] shape = kraus[0].shape # Iterate over remaining ops and check they are same shape for i in data[1:]: op = np.asarray(i, dtype=complex) if op.shape != shape: raise QiskitError("Kraus operators are different dimensions.") kraus.append(op) # Convert single Kraus set to general Kraus pair kraus = (kraus, None) # Check if generalized Kraus set ([A_i], [B_i]) for channel: # E(rho) = sum_i A_i * rho * B_i^dagger elif isinstance(data, tuple) and len(data) == 2 and len(data[0]) > 0: kraus_left = [np.asarray(data[0][0], dtype=complex)] shape = kraus_left[0].shape for i in data[0][1:]: op = np.asarray(i, dtype=complex) if op.shape != shape: raise QiskitError("Kraus operators are different dimensions.") kraus_left.append(op) if data[1] is None: kraus = (kraus_left, None) else: kraus_right = [] for i in data[1]: op = np.asarray(i, dtype=complex) if op.shape != shape: raise QiskitError("Kraus operators are different dimensions.") kraus_right.append(op) kraus = (kraus_left, kraus_right) else: raise QiskitError("Invalid input for Kraus channel.") op_shape = OpShape.auto(dims_l=output_dims, dims_r=input_dims, shape=kraus[0][0].shape) else: # Otherwise we initialize by conversion from another Qiskit # object into the QuantumChannel. if isinstance(data, (QuantumCircuit, Instruction)): # If the input is a Terra QuantumCircuit or Instruction we # convert it to a SuperOp data = SuperOp._init_instruction(data) else: # We use the QuantumChannel init transform to initialize # other objects into a QuantumChannel or Operator object. data = self._init_transformer(data) op_shape = data._op_shape output_dim, input_dim = op_shape.shape # Now that the input is an operator we convert it to a Kraus rep = getattr(data, "_channel_rep", "Operator") kraus = _to_kraus(rep, data._data, input_dim, output_dim) # Initialize either single or general Kraus if kraus[1] is None or np.allclose(kraus[0], kraus[1]): # Standard Kraus map data = (kraus[0], None) else: # General (non-CPTP) Kraus map data = kraus super().__init__(data, op_shape=op_shape) @property def data(self): """Return list of Kraus matrices for channel.""" if self._data[1] is None: # If only a single Kraus set, don't return the tuple # Just the fist set return self._data[0] else: # Otherwise return the tuple of both kraus sets return self._data def is_cptp(self, atol=None, rtol=None): """Return True if completely-positive trace-preserving.""" if self._data[1] is not None: return False if atol is None: atol = self.atol if rtol is None: rtol = self.rtol accum = 0j for op in self._data[0]: accum += np.dot(np.transpose(np.conj(op)), op) return is_identity_matrix(accum, rtol=rtol, atol=atol) def _evolve(self, state, qargs=None): return SuperOp(self)._evolve(state, qargs) # --------------------------------------------------------------------- # BaseOperator methods # --------------------------------------------------------------------- def conjugate(self): ret = copy.copy(self) kraus_l, kraus_r = self._data kraus_l = [np.conj(k) for k in kraus_l] if kraus_r is not None: kraus_r = [k.conj() for k in kraus_r] ret._data = (kraus_l, kraus_r) return ret def transpose(self): ret = copy.copy(self) ret._op_shape = self._op_shape.transpose() kraus_l, kraus_r = self._data kraus_l = [np.transpose(k) for k in kraus_l] if kraus_r is not None: kraus_r = [np.transpose(k) for k in kraus_r] ret._data = (kraus_l, kraus_r) return ret def adjoint(self): ret = copy.copy(self) ret._op_shape = self._op_shape.transpose() kraus_l, kraus_r = self._data kraus_l = [np.conj(np.transpose(k)) for k in kraus_l] if kraus_r is not None: kraus_r = [np.conj(np.transpose(k)) for k in kraus_r] ret._data = (kraus_l, kraus_r) return ret def compose(self, other: Kraus, qargs: list | None = None, front: bool = False) -> Kraus: if qargs is None: qargs = getattr(other, "qargs", None) if qargs is not None: return Kraus(SuperOp(self).compose(other, qargs=qargs, front=front)) if not isinstance(other, Kraus): other = Kraus(other) new_shape = self._op_shape.compose(other._op_shape, qargs, front) input_dims = new_shape.dims_r() output_dims = new_shape.dims_l() if front: ka_l, ka_r = self._data kb_l, kb_r = other._data else: ka_l, ka_r = other._data kb_l, kb_r = self._data kab_l = [np.dot(a, b) for a in ka_l for b in kb_l] if ka_r is None and kb_r is None: kab_r = None elif ka_r is None: kab_r = [np.dot(a, b) for a in ka_l for b in kb_r] elif kb_r is None: kab_r = [np.dot(a, b) for a in ka_r for b in kb_l] else: kab_r = [np.dot(a, b) for a in ka_r for b in kb_r] ret = Kraus((kab_l, kab_r), input_dims, output_dims) ret._op_shape = new_shape return ret def tensor(self, other: Kraus) -> Kraus: if not isinstance(other, Kraus): other = Kraus(other) return self._tensor(self, other) def expand(self, other: Kraus) -> Kraus: if not isinstance(other, Kraus): other = Kraus(other) return self._tensor(other, self) @classmethod def _tensor(cls, a, b): ret = copy.copy(a) ret._op_shape = a._op_shape.tensor(b._op_shape) # Get tensor matrix ka_l, ka_r = a._data kb_l, kb_r = b._data kab_l = [np.kron(ka, kb) for ka in ka_l for kb in kb_l] if ka_r is None and kb_r is None: kab_r = None else: if ka_r is None: ka_r = ka_l if kb_r is None: kb_r = kb_l kab_r = [np.kron(a, b) for a in ka_r for b in kb_r] ret._data = (kab_l, kab_r) return ret def __add__(self, other): qargs = getattr(other, "qargs", None) if not isinstance(other, QuantumChannel): other = Choi(other) return self._add(other, qargs=qargs) def __sub__(self, other): qargs = getattr(other, "qargs", None) if not isinstance(other, QuantumChannel): other = Choi(other) return self._add(-other, qargs=qargs) def _add(self, other, qargs=None): # Since we cannot directly add two channels in the Kraus # representation we try and use the other channels method # or convert to the Choi representation return Kraus(Choi(self)._add(other, qargs=qargs)) def _multiply(self, other): if not isinstance(other, Number): raise QiskitError("other is not a number") ret = copy.copy(self) # If the number is complex we need to convert to general # kraus channel so we multiply via Choi representation if isinstance(other, complex) or other < 0: # Convert to Choi-matrix ret._data = Kraus(Choi(self)._multiply(other))._data return ret # If the number is real we can update the Kraus operators # directly val = math.sqrt(other) kraus_r = None kraus_l = [val * k for k in self._data[0]] if self._data[1] is not None: kraus_r = [val * k for k in self._data[1]] ret._data = (kraus_l, kraus_r) return ret def _is_matrix(data): # return True if data is a 2-d array/tuple/list if not isinstance(data, np.ndarray): data = np.array(data, dtype=object) return data.ndim == 2 # Update docstrings for API docs generate_apidocs(Kraus)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Pauli Transfer Matrix (PTM) representation of a Quantum Channel. """ from __future__ import annotations import copy as _copy import math import numpy as np from qiskit import _numpy_compat from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.instruction import Instruction from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel from qiskit.quantum_info.operators.channel.superop import SuperOp from qiskit.quantum_info.operators.channel.transformations import _to_ptm from qiskit.quantum_info.operators.mixins import generate_apidocs from qiskit.quantum_info.operators.base_operator import BaseOperator class PTM(QuantumChannel): r"""Pauli Transfer Matrix (PTM) representation of a Quantum Channel. The PTM representation of an :math:`n`-qubit quantum channel :math:`\mathcal{E}` is an :math:`n`-qubit :class:`SuperOp` :math:`R` defined with respect to vectorization in the Pauli basis instead of column-vectorization. The elements of the PTM :math:`R` are given by .. math:: R_{i,j} = \frac{1}{2^n} \mbox{Tr}\left[P_i \mathcal{E}(P_j) \right] where :math:`[P_0, P_1, ..., P_{4^{n}-1}]` is the :math:`n`-qubit Pauli basis in lexicographic order. Evolution of a :class:`~qiskit.quantum_info.DensityMatrix` :math:`\rho` with respect to the PTM is given by .. math:: |\mathcal{E}(\rho)\rangle\!\rangle_P = S_P |\rho\rangle\!\rangle_P where :math:`|A\rangle\!\rangle_P` denotes vectorization in the Pauli basis :math:`\langle i | A\rangle\!\rangle_P = \sqrt{\frac{1}{2^n}} \mbox{Tr}[P_i A]`. See reference [1] for further details. References: 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). `arXiv:1111.6950 [quant-ph] <https://arxiv.org/abs/1111.6950>`_ """ def __init__( self, data: QuantumCircuit | Instruction | BaseOperator | np.ndarray, input_dims: int | tuple | None = None, output_dims: int | tuple | None = None, ): """Initialize a PTM quantum channel operator. Args: data (QuantumCircuit or Instruction or BaseOperator or matrix): data to initialize superoperator. input_dims (tuple): the input subsystem dimensions. [Default: None] output_dims (tuple): the output subsystem dimensions. [Default: None] Raises: QiskitError: if input data is not an N-qubit channel or cannot be initialized as a PTM. Additional Information: If the input or output dimensions are None, they will be automatically determined from the input data. The PTM representation is only valid for N-qubit channels. """ # If the input is a raw list or matrix we assume that it is # already a Chi matrix. if isinstance(data, (list, np.ndarray)): # Should we force this to be real? ptm = np.asarray(data, dtype=complex) # Determine input and output dimensions dout, din = ptm.shape if input_dims: input_dim = np.prod(input_dims) else: input_dim = int(math.sqrt(din)) if output_dims: output_dim = np.prod(input_dims) else: output_dim = int(math.sqrt(dout)) if output_dim**2 != dout or input_dim**2 != din or input_dim != output_dim: raise QiskitError("Invalid shape for PTM matrix.") else: # Otherwise we initialize by conversion from another Qiskit # object into the QuantumChannel. if isinstance(data, (QuantumCircuit, Instruction)): # If the input is a Terra QuantumCircuit or Instruction we # convert it to a SuperOp data = SuperOp._init_instruction(data) else: # We use the QuantumChannel init transform to initialize # other objects into a QuantumChannel or Operator object. data = self._init_transformer(data) input_dim, output_dim = data.dim # Now that the input is an operator we convert it to a PTM object rep = getattr(data, "_channel_rep", "Operator") ptm = _to_ptm(rep, data._data, input_dim, output_dim) if input_dims is None: input_dims = data.input_dims() if output_dims is None: output_dims = data.output_dims() # Check input is N-qubit channel num_qubits = int(math.log2(input_dim)) if 2**num_qubits != input_dim or input_dim != output_dim: raise QiskitError("Input is not an n-qubit Pauli transfer matrix.") super().__init__(ptm, num_qubits=num_qubits) def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): dtype = self.data.dtype if dtype is None else dtype return np.array(self.data, dtype=dtype, copy=copy) @property def _bipartite_shape(self): """Return the shape for bipartite matrix""" return (self._output_dim, self._output_dim, self._input_dim, self._input_dim) def _evolve(self, state, qargs=None): return SuperOp(self)._evolve(state, qargs) # --------------------------------------------------------------------- # BaseOperator methods # --------------------------------------------------------------------- def conjugate(self): # Since conjugation is basis dependent we transform # to the SuperOp representation to compute the # conjugate channel return PTM(SuperOp(self).conjugate()) def transpose(self): return PTM(SuperOp(self).transpose()) def adjoint(self): return PTM(SuperOp(self).adjoint()) def compose(self, other: PTM, qargs: list | None = None, front: bool = False) -> PTM: if qargs is None: qargs = getattr(other, "qargs", None) if qargs is not None: return PTM(SuperOp(self).compose(other, qargs=qargs, front=front)) # Convert other to PTM if not isinstance(other, PTM): other = PTM(other) new_shape = self._op_shape.compose(other._op_shape, qargs, front) input_dims = new_shape.dims_r() output_dims = new_shape.dims_l() if front: data = np.dot(self._data, other.data) else: data = np.dot(other.data, self._data) ret = PTM(data, input_dims, output_dims) ret._op_shape = new_shape return ret def tensor(self, other: PTM) -> PTM: if not isinstance(other, PTM): other = PTM(other) return self._tensor(self, other) def expand(self, other: PTM) -> PTM: if not isinstance(other, PTM): other = PTM(other) return self._tensor(other, self) @classmethod def _tensor(cls, a, b): ret = _copy.copy(a) ret._op_shape = a._op_shape.tensor(b._op_shape) ret._data = np.kron(a._data, b.data) return ret # Update docstrings for API docs generate_apidocs(PTM)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Superoperator representation of a Quantum Channel.""" from __future__ import annotations import copy as _copy import math from typing import TYPE_CHECKING import numpy as np from qiskit import _numpy_compat from qiskit.circuit.instruction import Instruction from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel from qiskit.quantum_info.operators.channel.transformations import _bipartite_tensor, _to_superop from qiskit.quantum_info.operators.mixins import generate_apidocs from qiskit.quantum_info.operators.op_shape import OpShape from qiskit.quantum_info.operators.operator import Operator if TYPE_CHECKING: from qiskit.quantum_info.states.densitymatrix import DensityMatrix from qiskit.quantum_info.states.statevector import Statevector class SuperOp(QuantumChannel): r"""Superoperator representation of a quantum channel. The Superoperator representation of a quantum channel :math:`\mathcal{E}` is a matrix :math:`S` such that the evolution of a :class:`~qiskit.quantum_info.DensityMatrix` :math:`\rho` is given by .. math:: |\mathcal{E}(\rho)\rangle\!\rangle = S |\rho\rangle\!\rangle where the double-ket notation :math:`|A\rangle\!\rangle` denotes a vector formed by stacking the columns of the matrix :math:`A` *(column-vectorization)*. See reference [1] for further details. References: 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). `arXiv:1111.6950 [quant-ph] <https://arxiv.org/abs/1111.6950>`_ """ def __init__( self, data: QuantumCircuit | Instruction | BaseOperator | np.ndarray, input_dims: tuple | None = None, output_dims: tuple | None = None, ): """Initialize a quantum channel Superoperator operator. Args: data (QuantumCircuit or Instruction or BaseOperator or matrix): data to initialize superoperator. input_dims (tuple): the input subsystem dimensions. [Default: None] output_dims (tuple): the output subsystem dimensions. [Default: None] Raises: QiskitError: if input data cannot be initialized as a superoperator. Additional Information: If the input or output dimensions are None, they will be automatically determined from the input data. If the input data is a Numpy array of shape (4**N, 4**N) qubit systems will be used. If the input operator is not an N-qubit operator, it will assign a single subsystem with dimension specified by the shape of the input. """ # If the input is a raw list or matrix we assume that it is # already a superoperator. if isinstance(data, (list, np.ndarray)): # We initialize directly from superoperator matrix super_mat = np.asarray(data, dtype=complex) # Determine total input and output dimensions dout, din = super_mat.shape input_dim = int(math.sqrt(din)) output_dim = int(math.sqrt(dout)) if output_dim**2 != dout or input_dim**2 != din: raise QiskitError("Invalid shape for SuperOp matrix.") op_shape = OpShape.auto( dims_l=output_dims, dims_r=input_dims, shape=(output_dim, input_dim) ) else: # Otherwise we initialize by conversion from another Qiskit # object into the QuantumChannel. if isinstance(data, (QuantumCircuit, Instruction)): # If the input is a Terra QuantumCircuit or Instruction we # perform a simulation to construct the circuit superoperator. # This will only work if the circuit or instruction can be # defined in terms of instructions which have no classical # register components. The instructions can be gates, reset, # or Kraus instructions. Any conditional gates or measure # will cause an exception to be raised. data = self._init_instruction(data) else: # We use the QuantumChannel init transform to initialize # other objects into a QuantumChannel or Operator object. data = self._init_transformer(data) # Now that the input is an operator we convert it to a # SuperOp object op_shape = data._op_shape input_dim, output_dim = data.dim rep = getattr(data, "_channel_rep", "Operator") super_mat = _to_superop(rep, data._data, input_dim, output_dim) # Initialize QuantumChannel super().__init__(super_mat, op_shape=op_shape) def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): dtype = self.data.dtype if dtype is None else dtype return np.array(self.data, dtype=dtype, copy=copy) @property def _tensor_shape(self): """Return the tensor shape of the superoperator matrix""" return 2 * tuple(reversed(self._op_shape.dims_l())) + 2 * tuple( reversed(self._op_shape.dims_r()) ) @property def _bipartite_shape(self): """Return the shape for bipartite matrix""" return (self._output_dim, self._output_dim, self._input_dim, self._input_dim) # --------------------------------------------------------------------- # BaseOperator methods # --------------------------------------------------------------------- def conjugate(self): ret = _copy.copy(self) ret._data = np.conj(self._data) return ret def transpose(self): ret = _copy.copy(self) ret._data = np.transpose(self._data) ret._op_shape = self._op_shape.transpose() return ret def adjoint(self): ret = _copy.copy(self) ret._data = np.conj(np.transpose(self._data)) ret._op_shape = self._op_shape.transpose() return ret def tensor(self, other: SuperOp) -> SuperOp: if not isinstance(other, SuperOp): other = SuperOp(other) return self._tensor(self, other) def expand(self, other: SuperOp) -> SuperOp: if not isinstance(other, SuperOp): other = SuperOp(other) return self._tensor(other, self) @classmethod def _tensor(cls, a, b): ret = _copy.copy(a) ret._op_shape = a._op_shape.tensor(b._op_shape) ret._data = _bipartite_tensor( a._data, b.data, shape1=a._bipartite_shape, shape2=b._bipartite_shape ) return ret def compose(self, other: SuperOp, qargs: list | None = None, front: bool = False) -> SuperOp: if qargs is None: qargs = getattr(other, "qargs", None) if not isinstance(other, SuperOp): other = SuperOp(other) # Validate dimensions are compatible and return the composed # operator dimensions new_shape = self._op_shape.compose(other._op_shape, qargs, front) input_dims = new_shape.dims_r() output_dims = new_shape.dims_l() # Full composition of superoperators if qargs is None: if front: data = np.dot(self._data, other.data) else: data = np.dot(other.data, self._data) ret = SuperOp(data, input_dims, output_dims) ret._op_shape = new_shape return ret # Compute tensor contraction indices from qargs num_qargs_l, num_qargs_r = self._op_shape.num_qargs if front: num_indices = num_qargs_r shift = 2 * num_qargs_l right_mul = True else: num_indices = num_qargs_l shift = 0 right_mul = False # Reshape current matrix # Note that we must reverse the subsystem dimension order as # qubit 0 corresponds to the right-most position in the tensor # product, which is the last tensor wire index. tensor = np.reshape(self.data, self._tensor_shape) mat = np.reshape(other.data, other._tensor_shape) # Add first set of indices indices = [2 * num_indices - 1 - qubit for qubit in qargs] + [ num_indices - 1 - qubit for qubit in qargs ] final_shape = [np.prod(output_dims) ** 2, np.prod(input_dims) ** 2] data = np.reshape( Operator._einsum_matmul(tensor, mat, indices, shift, right_mul), final_shape ) ret = SuperOp(data, input_dims, output_dims) ret._op_shape = new_shape return ret # --------------------------------------------------------------------- # Additional methods # --------------------------------------------------------------------- def _evolve(self, state, qargs=None): """Evolve a quantum state by the quantum channel. Args: state (DensityMatrix or Statevector): The input state. qargs (list): a list of quantum state subsystem positions to apply the quantum channel on. Returns: DensityMatrix: the output quantum state as a density matrix. Raises: QiskitError: if the quantum channel dimension does not match the specified quantum state subsystem dimensions. """ # Prevent cyclic imports by importing DensityMatrix here # pylint: disable=cyclic-import from qiskit.quantum_info.states.densitymatrix import DensityMatrix if not isinstance(state, DensityMatrix): state = DensityMatrix(state) if qargs is None: # Evolution on full matrix if state._op_shape.shape[0] != self._op_shape.shape[1]: raise QiskitError( "Operator input dimension is not equal to density matrix dimension." ) # We reshape in column-major vectorization (Fortran order in Numpy) # since that is how the SuperOp is defined vec = np.ravel(state.data, order="F") mat = np.reshape( np.dot(self.data, vec), (self._output_dim, self._output_dim), order="F" ) return DensityMatrix(mat, dims=self.output_dims()) # Otherwise we are applying an operator only to subsystems # Check dimensions of subsystems match the operator if state.dims(qargs) != self.input_dims(): raise QiskitError( "Operator input dimensions are not equal to statevector subsystem dimensions." ) # Reshape statevector and operator tensor = np.reshape(state.data, state._op_shape.tensor_shape) mat = np.reshape(self.data, self._tensor_shape) # Construct list of tensor indices of statevector to be contracted num_indices = len(state.dims()) indices = [num_indices - 1 - qubit for qubit in qargs] + [ 2 * num_indices - 1 - qubit for qubit in qargs ] tensor = Operator._einsum_matmul(tensor, mat, indices) # Replace evolved dimensions new_dims = list(state.dims()) output_dims = self.output_dims() for i, qubit in enumerate(qargs): new_dims[qubit] = output_dims[i] new_dim = np.prod(new_dims) # reshape tensor to density matrix tensor = np.reshape(tensor, (new_dim, new_dim)) return DensityMatrix(tensor, dims=new_dims) @classmethod def _init_instruction(cls, instruction): """Convert a QuantumCircuit or Instruction to a SuperOp.""" # Convert circuit to an instruction if isinstance(instruction, QuantumCircuit): instruction = instruction.to_instruction() # Initialize an identity superoperator of the correct size # of the circuit op = SuperOp(np.eye(4**instruction.num_qubits)) op._append_instruction(instruction) return op @classmethod def _instruction_to_superop(cls, obj): """Return superop for instruction if defined or None otherwise.""" if not isinstance(obj, Instruction): raise QiskitError("Input is not an instruction.") chan = None if obj.name == "reset": # For superoperator evolution we can simulate a reset as # a non-unitary superoperator matrix chan = SuperOp(np.array([[1, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])) if obj.name == "kraus": kraus = obj.params dim = len(kraus[0]) chan = SuperOp(_to_superop("Kraus", (kraus, None), dim, dim)) elif hasattr(obj, "to_matrix"): # If instruction is a gate first we see if it has a # `to_matrix` definition and if so use that. try: kraus = [obj.to_matrix()] dim = len(kraus[0]) chan = SuperOp(_to_superop("Kraus", (kraus, None), dim, dim)) except QiskitError: pass return chan def _append_instruction(self, obj, qargs=None): """Update the current Operator by apply an instruction.""" from qiskit.circuit.barrier import Barrier chan = self._instruction_to_superop(obj) if chan is not None: # Perform the composition and inplace update the current state # of the operator op = self.compose(chan, qargs=qargs) self._data = op.data elif isinstance(obj, Barrier): return else: # If the instruction doesn't have a matrix defined we use its # circuit decomposition definition if it exists, otherwise we # cannot compose this gate and raise an error. if obj.definition is None: raise QiskitError(f"Cannot apply Instruction: {obj.name}") if not isinstance(obj.definition, QuantumCircuit): raise QiskitError( "{} instruction definition is {}; " "expected QuantumCircuit".format(obj.name, type(obj.definition)) ) qubit_indices = {bit: idx for idx, bit in enumerate(obj.definition.qubits)} for instruction in obj.definition.data: if instruction.clbits: raise QiskitError( "Cannot apply instruction with classical bits:" f" {instruction.operation.name}" ) # Get the integer position of the flat register if qargs is None: new_qargs = [qubit_indices[tup] for tup in instruction.qubits] else: new_qargs = [qargs[qubit_indices[tup]] for tup in instruction.qubits] self._append_instruction(instruction.operation, qargs=new_qargs) # Update docstrings for API docs generate_apidocs(SuperOp)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ CNOTDihedral operator class. """ from __future__ import annotations import itertools import numpy as np from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic.pauli import Pauli from qiskit.quantum_info.operators.scalar_op import ScalarOp from qiskit.quantum_info.operators.mixins import generate_apidocs, AdjointMixin from qiskit.circuit import QuantumCircuit, Instruction from .dihedral_circuits import _append_circuit from .polynomial import SpecialPolynomial class CNOTDihedral(BaseOperator, AdjointMixin): """An N-qubit operator from the CNOT-Dihedral group. The CNOT-Dihedral group is generated by the quantum gates, :class:`~qiskit.circuit.library.CXGate`, :class:`~qiskit.circuit.library.TGate`, and :class:`~qiskit.circuit.library.XGate`. **Representation** An :math:`N`-qubit CNOT-Dihedral operator is stored as an affine function and a phase polynomial, based on the convention in references [1, 2]. The affine function consists of an :math:`N \\times N` invertible binary matrix, and an :math:`N` binary vector. The phase polynomial is a polynomial of degree at most 3, in :math:`N` variables, whose coefficients are in the ring Z_8 with 8 elements. .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import CNOTDihedral circ = QuantumCircuit(3) circ.cx(0, 1) circ.x(2) circ.t(1) circ.t(1) circ.t(1) elem = CNOTDihedral(circ) # Print the CNOTDihedral element print(elem) .. parsed-literal:: phase polynomial = 0 + 3*x_0 + 3*x_1 + 2*x_0*x_1 affine function = (x_0,x_0 + x_1,x_2 + 1) **Circuit Conversion** CNOTDihedral operators can be initialized from circuits containing *only* the following gates: :class:`~qiskit.circuit.library.IGate`, :class:`~qiskit.circuit.library.XGate`, :class:`~qiskit.circuit.library.YGate`, :class:`~qiskit.circuit.library.ZGate`, :class:`~qiskit.circuit.library.TGate`, :class:`~qiskit.circuit.library.TdgGate` :class:`~qiskit.circuit.library.SGate`, :class:`~qiskit.circuit.library.SdgGate`, :class:`~qiskit.circuit.library.CXGate`, :class:`~qiskit.circuit.library.CZGate`, :class:`~qiskit.circuit.library.CSGate`, :class:`~qiskit.circuit.library.CSdgGate`, :class:`~qiskit.circuit.library.SwapGate`, :class:`~qiskit.circuit.library.CCZGate`. They can be converted back into a :class:`~qiskit.circuit.QuantumCircuit`, or :class:`~qiskit.circuit.Gate` object using the :meth:`~CNOTDihedral.to_circuit` or :meth:`~CNOTDihderal.to_instruction` methods respectively. Note that this decomposition is not necessarily optimal in terms of number of gates if the number of qubits is more than two. CNOTDihedral operators can also be converted to :class:`~qiskit.quantum_info.Operator` objects using the :meth:`to_operator` method. This is done via decomposing to a circuit, and then simulating the circuit as a unitary operator. References: 1. Shelly Garion and Andrew W. Cross, *Synthesis of CNOT-Dihedral circuits with optimal number of two qubit gates*, `Quantum 4(369), 2020 <https://quantum-journal.org/papers/q-2020-12-07-369/>`_ 2. Andrew W. Cross, Easwar Magesan, Lev S. Bishop, John A. Smolin and Jay M. Gambetta, *Scalable randomised benchmarking of non-Clifford gates*, npj Quantum Inf 2, 16012 (2016). """ def __init__( self, data: CNOTDihedral | QuantumCircuit | Instruction | None = None, num_qubits: int | None = None, validate: bool = True, ): """Initialize a CNOTDihedral operator object. Args: data (CNOTDihedral or QuantumCircuit or ~qiskit.circuit.Instruction): Optional, operator to initialize. num_qubits (int): Optional, initialize an empty CNOTDihedral operator. validate (bool): if True, validates the CNOTDihedral element. Raises: QiskitError: if the type is invalid. QiskitError: if validate=True and the CNOTDihedral element is invalid. """ if num_qubits: # initialize n-qubit identity self._num_qubits = num_qubits # phase polynomial self.poly = SpecialPolynomial(self._num_qubits) # n x n invertible matrix over Z_2 self.linear = np.eye(self._num_qubits, dtype=np.int8) # binary shift, n coefficients in Z_2 self.shift = np.zeros(self._num_qubits, dtype=np.int8) # Initialize from another CNOTDihedral by sharing the underlying # poly, linear and shift elif isinstance(data, CNOTDihedral): self.linear = data.linear self.shift = data.shift self.poly = data.poly # Initialize from ScalarOp as N-qubit identity discarding any global phase elif isinstance(data, ScalarOp): if not data.is_unitary() or set(data._input_dims) != {2} or data.num_qubits is None: raise QiskitError("Can only initialize from N-qubit identity ScalarOp.") self._num_qubits = data.num_qubits # phase polynomial self.poly = SpecialPolynomial(self._num_qubits) # n x n invertible matrix over Z_2 self.linear = np.eye(self._num_qubits, dtype=np.int8) # binary shift, n coefficients in Z_2 self.shift = np.zeros(self._num_qubits, dtype=np.int8) # Initialize from a QuantumCircuit or Instruction object elif isinstance(data, (QuantumCircuit, Instruction)): self._num_qubits = data.num_qubits elem = self._from_circuit(data) self.poly = elem.poly self.linear = elem.linear self.shift = elem.shift elif isinstance(data, Pauli): self._num_qubits = data.num_qubits elem = self._from_circuit(data.to_instruction()) self.poly = elem.poly self.linear = elem.linear self.shift = elem.shift else: raise QiskitError("Invalid input type for CNOTDihedral class.") # Initialize BaseOperator super().__init__(num_qubits=self._num_qubits) # Validate the CNOTDihedral element if validate and not self._is_valid(): raise QiskitError("Invalid CNOTDihedral element.") @property def name(self): """Unique string identifier for operation type.""" return "cnotdihedral" @property def num_clbits(self): """Number of classical bits.""" return 0 def _z2matmul(self, left, right): """Compute product of two n x n z2 matrices.""" prod = np.mod(np.dot(left, right), 2) return prod def _z2matvecmul(self, mat, vec): """Compute mat*vec of n x n z2 matrix and vector.""" prod = np.mod(np.dot(mat, vec), 2) return prod def _dot(self, other): """Left multiplication self * other.""" if self.num_qubits != other.num_qubits: raise QiskitError("Multiplication on different number of qubits.") result = CNOTDihedral(num_qubits=self.num_qubits) result.shift = [ (x[0] + x[1]) % 2 for x in zip(self._z2matvecmul(self.linear, other.shift), self.shift) ] result.linear = self._z2matmul(self.linear, other.linear) # Compute x' = B1*x + c1 using the p_j identity new_vars = [] for i in range(self.num_qubits): support = np.arange(self.num_qubits)[np.nonzero(other.linear[i])] poly = SpecialPolynomial(self.num_qubits) poly.set_pj(support) if other.shift[i] == 1: poly = -1 * poly poly.weight_0 = (poly.weight_0 + 1) % 8 new_vars.append(poly) # p' = p1 + p2(x') result.poly = other.poly + self.poly.evaluate(new_vars) return result def _compose(self, other): """Right multiplication other * self.""" if self.num_qubits != other.num_qubits: raise QiskitError("Multiplication on different number of qubits.") result = CNOTDihedral(num_qubits=self.num_qubits) result.shift = [ (x[0] + x[1]) % 2 for x in zip(self._z2matvecmul(other.linear, self.shift), other.shift) ] result.linear = self._z2matmul(other.linear, self.linear) # Compute x' = B1*x + c1 using the p_j identity new_vars = [] for i in range(self.num_qubits): support = np.arange(other.num_qubits)[np.nonzero(self.linear[i])] poly = SpecialPolynomial(self.num_qubits) poly.set_pj(support) if self.shift[i] == 1: poly = -1 * poly poly.weight_0 = (poly.weight_0 + 1) % 8 new_vars.append(poly) # p' = p1 + p2(x') result.poly = self.poly + other.poly.evaluate(new_vars) return result def __eq__(self, other): """Test equality.""" return ( isinstance(other, CNOTDihedral) and self.poly == other.poly and (self.linear == other.linear).all() and (self.shift == other.shift).all() ) def _append_cx(self, i, j): """Apply a CX gate to this element. Left multiply the element by CX(i, j). """ if not 0 <= i < self.num_qubits or not 0 <= j < self.num_qubits: raise QiskitError("CX qubits are out of bounds.") self.linear[j] = (self.linear[i] + self.linear[j]) % 2 self.shift[j] = (self.shift[i] + self.shift[j]) % 2 def _append_phase(self, k, i): """Apply an k-th power of T to this element. Left multiply the element by T_i^k. """ if not 0 <= i < self.num_qubits: raise QiskitError("phase qubit out of bounds.") # If the kth bit is flipped, conjugate this gate if self.shift[i] == 1: k = (7 * k) % 8 # Take all subsets \alpha of the support of row i # of weight up to 3 and add k*(-2)**(|\alpha| - 1) mod 8 # to the corresponding term. support = np.arange(self.num_qubits)[np.nonzero(self.linear[i])] subsets_2 = itertools.combinations(support, 2) subsets_3 = itertools.combinations(support, 3) for j in support: value = self.poly.get_term([j]) self.poly.set_term([j], (value + k) % 8) for j in subsets_2: value = self.poly.get_term(list(j)) self.poly.set_term(list(j), (value + -2 * k) % 8) for j in subsets_3: value = self.poly.get_term(list(j)) self.poly.set_term(list(j), (value + 4 * k) % 8) def _append_x(self, i): """Apply X to this element. Left multiply the element by X(i). """ if not 0 <= i < self.num_qubits: raise QiskitError("X qubit out of bounds.") self.shift[i] = (self.shift[i] + 1) % 2 def __str__(self): """Return formatted string representation.""" out = "phase polynomial = \n" out += str(self.poly) out += "\naffine function = \n" out += " (" for row in range(self.num_qubits): wrote = False for col in range(self.num_qubits): if self.linear[row][col] != 0: if wrote: out += " + x_" + str(col) else: out += "x_" + str(col) wrote = True if self.shift[row] != 0: out += " + 1" if row != self.num_qubits - 1: out += "," out += ")\n" return out def to_circuit(self): """Return a QuantumCircuit implementing the CNOT-Dihedral element. Return: QuantumCircuit: a circuit implementation of the CNOTDihedral object. References: 1. Shelly Garion and Andrew W. Cross, *Synthesis of CNOT-Dihedral circuits with optimal number of two qubit gates*, `Quantum 4(369), 2020 <https://quantum-journal.org/papers/q-2020-12-07-369/>`_ 2. Andrew W. Cross, Easwar Magesan, Lev S. Bishop, John A. Smolin and Jay M. Gambetta, *Scalable randomised benchmarking of non-Clifford gates*, npj Quantum Inf 2, 16012 (2016). """ from qiskit.synthesis.cnotdihedral import synth_cnotdihedral_full return synth_cnotdihedral_full(self) def to_instruction(self): """Return a Gate instruction implementing the CNOTDihedral object.""" return self.to_circuit().to_gate() def _from_circuit(self, circuit): """Initialize from a QuantumCircuit or Instruction. Args: circuit (QuantumCircuit or ~qiskit.circuit.Instruction): instruction to initialize. Returns: CNOTDihedral: the CNOTDihedral object for the circuit. Raises: QiskitError: if the input instruction is not CNOTDihedral or contains classical register instruction. """ if not isinstance(circuit, (QuantumCircuit, Instruction)): raise QiskitError("Input must be a QuantumCircuit or Instruction") # Initialize an identity CNOTDihedral object elem = CNOTDihedral(num_qubits=self._num_qubits) _append_circuit(elem, circuit) return elem def __array__(self, dtype=None): if dtype: return np.asarray(self.to_matrix(), dtype=dtype) return self.to_matrix() def to_matrix(self): """Convert operator to Numpy matrix.""" return self.to_operator().data def to_operator(self) -> Operator: """Convert to an Operator object.""" return Operator(self.to_instruction()) def compose( self, other: CNOTDihedral, qargs: list | None = None, front: bool = False ) -> CNOTDihedral: if qargs is not None: raise NotImplementedError("compose method does not support qargs.") if self.num_qubits != other.num_qubits: raise QiskitError("Incompatible dimension for composition") if front: other = self._dot(other) else: other = self._compose(other) other.poly.weight_0 = 0 # set global phase return other def _tensor(self, other, reverse=False): """Returns the tensor product operator.""" if not isinstance(other, CNOTDihedral): raise QiskitError("Tensored element is not a CNOTDihderal object.") if reverse: elem0 = self elem1 = other else: elem0 = other elem1 = self result = CNOTDihedral(num_qubits=elem0.num_qubits + elem1.num_qubits) linear = np.block( [ [elem0.linear, np.zeros((elem0.num_qubits, elem1.num_qubits), dtype=np.int8)], [np.zeros((elem1.num_qubits, elem0.num_qubits), dtype=np.int8), elem1.linear], ] ) result.linear = linear shift = np.block([elem0.shift, elem1.shift]) result.shift = shift for i in range(elem0.num_qubits): value = elem0.poly.get_term([i]) result.poly.set_term([i], value) for j in range(i): value = elem0.poly.get_term([j, i]) result.poly.set_term([j, i], value) for k in range(j): value = elem0.poly.get_term([k, j, i]) result.poly.set_term([k, j, i], value) for i in range(elem1.num_qubits): value = elem1.poly.get_term([i]) result.poly.set_term([i + elem0.num_qubits], value) for j in range(i): value = elem1.poly.get_term([j, i]) result.poly.set_term([j + elem0.num_qubits, i + elem0.num_qubits], value) for k in range(j): value = elem1.poly.get_term([k, j, i]) result.poly.set_term( [k + elem0.num_qubits, j + elem0.num_qubits, i + elem0.num_qubits], value ) return result def tensor(self, other: CNOTDihedral) -> CNOTDihedral: return self._tensor(other, reverse=True) def expand(self, other: CNOTDihedral) -> CNOTDihedral: return self._tensor(other, reverse=False) def adjoint(self): circ = self.to_instruction() result = self._from_circuit(circ.inverse()) return result def conjugate(self): circ = self.to_instruction() new_circ = QuantumCircuit(self.num_qubits) bit_indices = {bit: index for index, bit in enumerate(circ.definition.qubits)} for instruction in circ.definition: new_qubits = [bit_indices[tup] for tup in instruction.qubits] if instruction.operation.name == "p": params = 2 * np.pi - instruction.operation.params[0] instruction.operation.params[0] = params new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "t": instruction.operation.name = "tdg" new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "tdg": instruction.operation.name = "t" new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "s": instruction.operation.name = "sdg" new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "sdg": instruction.operation.name = "s" new_circ.append(instruction.operation, new_qubits) else: new_circ.append(instruction.operation, new_qubits) result = self._from_circuit(new_circ) return result def transpose(self): circ = self.to_instruction() result = self._from_circuit(circ.reverse_ops()) return result def _is_valid(self): """Return True if input is a CNOTDihedral element.""" if ( self.poly.weight_0 != 0 or len(self.poly.weight_1) != self.num_qubits or len(self.poly.weight_2) != int(self.num_qubits * (self.num_qubits - 1) / 2) or len(self.poly.weight_3) != int(self.num_qubits * (self.num_qubits - 1) * (self.num_qubits - 2) / 6) ): return False if ( (self.linear).shape != (self.num_qubits, self.num_qubits) or len(self.shift) != self.num_qubits or not np.allclose((np.linalg.det(self.linear) % 2), 1) ): return False if ( not (set(self.poly.weight_1.flatten())).issubset({0, 1, 2, 3, 4, 5, 6, 7}) or not (set(self.poly.weight_2.flatten())).issubset({0, 2, 4, 6}) or not (set(self.poly.weight_3.flatten())).issubset({0, 4}) ): return False if not (set(self.shift.flatten())).issubset({0, 1}) or not ( set(self.linear.flatten()) ).issubset({0, 1}): return False return True # Update docstrings for API docs generate_apidocs(CNOTDihedral)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017--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. """ Clifford operator class. """ from __future__ import annotations import functools import itertools import re from typing import Literal import numpy as np from qiskit.circuit import Instruction, QuantumCircuit from qiskit.circuit.library.standard_gates import HGate, IGate, SGate, XGate, YGate, ZGate from qiskit.circuit.operation import Operation from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.quantum_info.operators.mixins import AdjointMixin, generate_apidocs from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.scalar_op import ScalarOp from qiskit.quantum_info.operators.symplectic.base_pauli import _count_y from qiskit.utils.deprecation import deprecate_func from qiskit.synthesis.linear import calc_inverse_matrix from .base_pauli import BasePauli from .clifford_circuits import _append_circuit, _append_operation from .stabilizer_table import StabilizerTable class Clifford(BaseOperator, AdjointMixin, Operation): """An N-qubit unitary operator from the Clifford group. **Representation** An *N*-qubit Clifford operator is stored as a length *2N × (2N+1)* boolean tableau using the convention from reference [1]. * Rows 0 to *N-1* are the *destabilizer* group generators * Rows *N* to *2N-1* are the *stabilizer* group generators. The internal boolean tableau for the Clifford can be accessed using the :attr:`tableau` attribute. The destabilizer or stabilizer rows can each be accessed as a length-N Stabilizer table using :attr:`destab` and :attr:`stab` attributes. A more easily human readable representation of the Clifford operator can be obtained by calling the :meth:`to_dict` method. This representation is also used if a Clifford object is printed as in the following example .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import Clifford # Bell state generation circuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) cliff = Clifford(qc) # Print the Clifford print(cliff) # Print the Clifford destabilizer rows print(cliff.to_labels(mode="D")) # Print the Clifford stabilizer rows print(cliff.to_labels(mode="S")) .. parsed-literal:: Clifford: Stabilizer = ['+XX', '+ZZ'], Destabilizer = ['+IZ', '+XI'] ['+IZ', '+XI'] ['+XX', '+ZZ'] **Circuit Conversion** Clifford operators can be initialized from circuits containing *only* the following Clifford gates: :class:`~qiskit.circuit.library.IGate`, :class:`~qiskit.circuit.library.XGate`, :class:`~qiskit.circuit.library.YGate`, :class:`~qiskit.circuit.library.ZGate`, :class:`~qiskit.circuit.library.HGate`, :class:`~qiskit.circuit.library.SGate`, :class:`~qiskit.circuit.library.SdgGate`, :class:`~qiskit.circuit.library.SXGate`, :class:`~qiskit.circuit.library.SXdgGate`, :class:`~qiskit.circuit.library.CXGate`, :class:`~qiskit.circuit.library.CZGate`, :class:`~qiskit.circuit.library.CYGate`, :class:`~qiskit.circuit.library.DXGate`, :class:`~qiskit.circuit.library.SwapGate`, :class:`~qiskit.circuit.library.iSwapGate`, :class:`~qiskit.circuit.library.ECRGate`, :class:`~qiskit.circuit.library.LinearFunction`, :class:`~qiskit.circuit.library.PermutationGate`. They can be converted back into a :class:`~qiskit.circuit.QuantumCircuit`, or :class:`~qiskit.circuit.Gate` object using the :meth:`~Clifford.to_circuit` or :meth:`~Clifford.to_instruction` methods respectively. Note that this decomposition is not necessarily optimal in terms of number of gates. .. note:: A minimally generating set of gates for Clifford circuits is the :class:`~qiskit.circuit.library.HGate` and :class:`~qiskit.circuit.library.SGate` gate and *either* the :class:`~qiskit.circuit.library.CXGate` or :class:`~qiskit.circuit.library.CZGate` two-qubit gate. Clifford operators can also be converted to :class:`~qiskit.quantum_info.Operator` objects using the :meth:`to_operator` method. This is done via decomposing to a circuit, and then simulating the circuit as a unitary operator. References: 1. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). `arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_ """ _COMPOSE_PHASE_LOOKUP = None _COMPOSE_1Q_LOOKUP = None def __array__(self, dtype=None): if dtype: return np.asarray(self.to_matrix(), dtype=dtype) return self.to_matrix() def __init__(self, data, validate=True, copy=True): """Initialize an operator object.""" # pylint: disable=cyclic-import from qiskit.circuit.library import LinearFunction, PermutationGate # Initialize from another Clifford if isinstance(data, Clifford): num_qubits = data.num_qubits self.tableau = data.tableau.copy() if copy else data.tableau # Initialize from ScalarOp as N-qubit identity discarding any global phase elif isinstance(data, ScalarOp): if not data.num_qubits or not data.is_unitary(): raise QiskitError("Can only initialize from N-qubit identity ScalarOp.") num_qubits = data.num_qubits self.tableau = np.fromfunction( lambda i, j: i == j, (2 * num_qubits, 2 * num_qubits + 1) ).astype(bool) # Initialize from LinearFunction elif isinstance(data, LinearFunction): num_qubits = len(data.linear) self.tableau = self.from_linear_function(data) # Initialize from PermutationGate elif isinstance(data, PermutationGate): num_qubits = len(data.pattern) self.tableau = self.from_permutation(data) # Initialize from a QuantumCircuit or Instruction object elif isinstance(data, (QuantumCircuit, Instruction)): num_qubits = data.num_qubits self.tableau = Clifford.from_circuit(data).tableau # DEPRECATED: data is StabilizerTable elif isinstance(data, StabilizerTable): self.tableau = self._stack_table_phase(data.array, data.phase) num_qubits = data.num_qubits # Initialize StabilizerTable directly from the data else: if isinstance(data, (list, np.ndarray)) and np.asarray(data, dtype=bool).ndim == 2: data = np.array(data, dtype=bool, copy=copy) if data.shape[0] == data.shape[1]: self.tableau = self._stack_table_phase( data, np.zeros(data.shape[0], dtype=bool) ) num_qubits = data.shape[0] // 2 elif data.shape[0] + 1 == data.shape[1]: self.tableau = data num_qubits = data.shape[0] // 2 else: raise QiskitError("") else: n_paulis = len(data) symp = self._from_label(data[0]) num_qubits = len(symp) // 2 tableau = np.zeros((n_paulis, len(symp)), dtype=bool) tableau[0] = symp for i in range(1, n_paulis): tableau[i] = self._from_label(data[i]) self.tableau = tableau # Validate table is a symplectic matrix if validate and not Clifford._is_symplectic(self.symplectic_matrix): raise QiskitError( "Invalid Clifford. Input StabilizerTable is not a valid symplectic matrix." ) # Initialize BaseOperator super().__init__(num_qubits=num_qubits) @property def name(self): """Unique string identifier for operation type.""" return "clifford" @property def num_clbits(self): """Number of classical bits.""" return 0 def __repr__(self): return f"Clifford({repr(self.tableau)})" def __str__(self): return ( f'Clifford: Stabilizer = {self.to_labels(mode="S")}, ' f'Destabilizer = {self.to_labels(mode="D")}' ) def __eq__(self, other): """Check if two Clifford tables are equal""" return super().__eq__(other) and (self.tableau == other.tableau).all() def copy(self): return type(self)(self, validate=False, copy=True) # --------------------------------------------------------------------- # Attributes # --------------------------------------------------------------------- # pylint: disable=bad-docstring-quotes @deprecate_func( since="0.24.0", additional_msg="Instead, index or iterate through the Clifford.tableau attribute.", ) def __getitem__(self, key): """Return a stabilizer Pauli row""" return self.table.__getitem__(key) @deprecate_func(since="0.24.0", additional_msg="Use Clifford.tableau property instead.") def __setitem__(self, key, value): """Set a stabilizer Pauli row""" self.tableau.__setitem__(key, self._stack_table_phase(value.array, value.phase)) @property @deprecate_func( since="0.24.0", additional_msg="Use Clifford.stab and Clifford.destab properties instead.", is_property=True, ) def table(self): """Return StabilizerTable""" return StabilizerTable(self.symplectic_matrix, phase=self.phase) @table.setter @deprecate_func( since="0.24.0", additional_msg="Use Clifford.stab and Clifford.destab properties instead.", is_property=True, ) def table(self, value): """Set the stabilizer table""" # Note this setter cannot change the size of the Clifford # It can only replace the contents of the StabilizerTable with # another StabilizerTable of the same size. if not isinstance(value, StabilizerTable): value = StabilizerTable(value) self.symplectic_matrix = value._table._array self.phase = value._table._phase @property @deprecate_func( since="0.24.0", additional_msg="Use Clifford.stab properties instead.", is_property=True, ) def stabilizer(self): """Return the stabilizer block of the StabilizerTable.""" array = self.tableau[self.num_qubits : 2 * self.num_qubits, :-1] phase = self.tableau[self.num_qubits : 2 * self.num_qubits, -1].reshape(self.num_qubits) return StabilizerTable(array, phase) @stabilizer.setter @deprecate_func( since="0.24.0", additional_msg="Use Clifford.stab properties instead.", is_property=True, ) def stabilizer(self, value): """Set the value of stabilizer block of the StabilizerTable""" if not isinstance(value, StabilizerTable): value = StabilizerTable(value) self.tableau[self.num_qubits : 2 * self.num_qubits, :-1] = value.array @property @deprecate_func( since="0.24.0", additional_msg="Use Clifford.destab properties instead.", is_property=True, ) def destabilizer(self): """Return the destabilizer block of the StabilizerTable.""" array = self.tableau[0 : self.num_qubits, :-1] phase = self.tableau[0 : self.num_qubits, -1].reshape(self.num_qubits) return StabilizerTable(array, phase) @destabilizer.setter @deprecate_func( since="0.24.0", additional_msg="Use Clifford.destab properties instead.", is_property=True, ) def destabilizer(self, value): """Set the value of destabilizer block of the StabilizerTable""" if not isinstance(value, StabilizerTable): value = StabilizerTable(value) self.tableau[: self.num_qubits, :-1] = value.array @property def symplectic_matrix(self): """Return boolean symplectic matrix.""" return self.tableau[:, :-1] @symplectic_matrix.setter def symplectic_matrix(self, value): self.tableau[:, :-1] = value @property def phase(self): """Return phase with boolean representation.""" return self.tableau[:, -1] @phase.setter def phase(self, value): self.tableau[:, -1] = value @property def x(self): """The x array for the symplectic representation.""" return self.tableau[:, 0 : self.num_qubits] @x.setter def x(self, value): self.tableau[:, 0 : self.num_qubits] = value @property def z(self): """The z array for the symplectic representation.""" return self.tableau[:, self.num_qubits : 2 * self.num_qubits] @z.setter def z(self, value): self.tableau[:, self.num_qubits : 2 * self.num_qubits] = value @property def destab(self): """The destabilizer array for the symplectic representation.""" return self.tableau[: self.num_qubits, :] @destab.setter def destab(self, value): self.tableau[: self.num_qubits, :] = value @property def destab_x(self): """The destabilizer x array for the symplectic representation.""" return self.tableau[: self.num_qubits, : self.num_qubits] @destab_x.setter def destab_x(self, value): self.tableau[: self.num_qubits, : self.num_qubits] = value @property def destab_z(self): """The destabilizer z array for the symplectic representation.""" return self.tableau[: self.num_qubits, self.num_qubits : 2 * self.num_qubits] @destab_z.setter def destab_z(self, value): self.tableau[: self.num_qubits, self.num_qubits : 2 * self.num_qubits] = value @property def destab_phase(self): """Return phase of destabilizer with boolean representation.""" return self.tableau[: self.num_qubits, -1] @destab_phase.setter def destab_phase(self, value): self.tableau[: self.num_qubits, -1] = value @property def stab(self): """The stabilizer array for the symplectic representation.""" return self.tableau[self.num_qubits :, :] @stab.setter def stab(self, value): self.tableau[self.num_qubits :, :] = value @property def stab_x(self): """The stabilizer x array for the symplectic representation.""" return self.tableau[self.num_qubits :, : self.num_qubits] @stab_x.setter def stab_x(self, value): self.tableau[self.num_qubits :, : self.num_qubits] = value @property def stab_z(self): """The stabilizer array for the symplectic representation.""" return self.tableau[self.num_qubits :, self.num_qubits : 2 * self.num_qubits] @stab_z.setter def stab_z(self, value): self.tableau[self.num_qubits :, self.num_qubits : 2 * self.num_qubits] = value @property def stab_phase(self): """Return phase of stabilizer with boolean representation.""" return self.tableau[self.num_qubits :, -1] @stab_phase.setter def stab_phase(self, value): self.tableau[self.num_qubits :, -1] = value # --------------------------------------------------------------------- # Utility Operator methods # --------------------------------------------------------------------- def is_unitary(self): """Return True if the Clifford table is valid.""" # A valid Clifford is always unitary, so this function is really # checking that the underlying Stabilizer table array is a valid # Clifford array. return Clifford._is_symplectic(self.symplectic_matrix) # --------------------------------------------------------------------- # BaseOperator Abstract Methods # --------------------------------------------------------------------- def conjugate(self): return Clifford._conjugate_transpose(self, "C") def adjoint(self): return Clifford._conjugate_transpose(self, "A") def transpose(self): return Clifford._conjugate_transpose(self, "T") def tensor(self, other: Clifford) -> Clifford: if not isinstance(other, Clifford): other = Clifford(other) return self._tensor(self, other) def expand(self, other: Clifford) -> Clifford: if not isinstance(other, Clifford): other = Clifford(other) return self._tensor(other, self) @classmethod def _tensor(cls, a, b): n = a.num_qubits + b.num_qubits tableau = np.zeros((2 * n, 2 * n + 1), dtype=bool) clifford = cls(tableau, validate=False) clifford.destab_x[: b.num_qubits, : b.num_qubits] = b.destab_x clifford.destab_x[b.num_qubits :, b.num_qubits :] = a.destab_x clifford.destab_z[: b.num_qubits, : b.num_qubits] = b.destab_z clifford.destab_z[b.num_qubits :, b.num_qubits :] = a.destab_z clifford.stab_x[: b.num_qubits, : b.num_qubits] = b.stab_x clifford.stab_x[b.num_qubits :, b.num_qubits :] = a.stab_x clifford.stab_z[: b.num_qubits, : b.num_qubits] = b.stab_z clifford.stab_z[b.num_qubits :, b.num_qubits :] = a.stab_z clifford.phase[: b.num_qubits] = b.destab_phase clifford.phase[b.num_qubits : n] = a.destab_phase clifford.phase[n : n + b.num_qubits] = b.stab_phase clifford.phase[n + b.num_qubits :] = a.stab_phase return clifford def compose( self, other: Clifford | QuantumCircuit | Instruction, qargs: list | None = None, front: bool = False, ) -> Clifford: if qargs is None: qargs = getattr(other, "qargs", None) # If other is a QuantumCircuit we can more efficiently compose # using the _append_circuit method to update each gate recursively # to the current Clifford, rather than converting to a Clifford first # and then doing the composition of tables. if not front: if isinstance(other, QuantumCircuit): return _append_circuit(self.copy(), other, qargs=qargs) if isinstance(other, Instruction): return _append_operation(self.copy(), other, qargs=qargs) if not isinstance(other, Clifford): # Not copying is safe since we're going to drop our only reference to `other` at the end # of the function. other = Clifford(other, copy=False) # Validate compose dimensions self._op_shape.compose(other._op_shape, qargs, front) # Pad other with identities if composing on subsystem other = self._pad_with_identity(other, qargs) left, right = (self, other) if front else (other, self) if self.num_qubits == 1: return self._compose_1q(left, right) return self._compose_general(left, right) @classmethod def _compose_general(cls, first, second): # Correcting for phase due to Pauli multiplication. Start with factors of -i from XZ = -iY # on individual qubits, and then handle multiplication between each qubitwise pair. ifacts = np.sum(second.x & second.z, axis=1, dtype=int) x1, z1 = first.x.astype(np.uint8), first.z.astype(np.uint8) lookup = cls._compose_lookup() # The loop is over 2*n_qubits entries, and the entire loop is cubic in the number of qubits. for k, row2 in enumerate(second.symplectic_matrix): x1_select = x1[row2] z1_select = z1[row2] x1_accum = np.logical_xor.accumulate(x1_select, axis=0).astype(np.uint8) z1_accum = np.logical_xor.accumulate(z1_select, axis=0).astype(np.uint8) indexer = (x1_select[1:], z1_select[1:], x1_accum[:-1], z1_accum[:-1]) ifacts[k] += np.sum(lookup[indexer]) p = np.mod(ifacts, 4) // 2 phase = ( (np.matmul(second.symplectic_matrix, first.phase, dtype=int) + second.phase + p) % 2 ).astype(bool) data = cls._stack_table_phase( (np.matmul(second.symplectic_matrix, first.symplectic_matrix, dtype=int) % 2).astype( bool ), phase, ) return Clifford(data, validate=False, copy=False) @classmethod def _compose_1q(cls, first, second): # 1-qubit composition can be done with a simple lookup table; there are 24 elements in the # 1q Clifford group, so 576 possible combinations, which is small enough to look up. if cls._COMPOSE_1Q_LOOKUP is None: # The valid tables for 1q Cliffords. tables_1q = np.array( [ [[False, True], [True, False]], [[False, True], [True, True]], [[True, False], [False, True]], [[True, False], [True, True]], [[True, True], [False, True]], [[True, True], [True, False]], ] ) phases_1q = np.array([[False, False], [False, True], [True, False], [True, True]]) # Build the lookup table. cliffords = [ cls(cls._stack_table_phase(table, phase), validate=False, copy=False) for table, phase in itertools.product(tables_1q, phases_1q) ] cls._COMPOSE_1Q_LOOKUP = { (cls._hash(left), cls._hash(right)): cls._compose_general(left, right) for left, right in itertools.product(cliffords, repeat=2) } return cls._COMPOSE_1Q_LOOKUP[cls._hash(first), cls._hash(second)].copy() @classmethod def _compose_lookup( cls, ): if cls._COMPOSE_PHASE_LOOKUP is None: # A lookup table for calculating phases. The indices are # current_x, current_z, running_x_count, running_z_count # where all counts taken modulo 2. lookup = np.zeros((2, 2, 2, 2), dtype=int) lookup[0, 1, 1, 0] = lookup[1, 0, 1, 1] = lookup[1, 1, 0, 1] = -1 lookup[0, 1, 1, 1] = lookup[1, 0, 0, 1] = lookup[1, 1, 1, 0] = 1 lookup.setflags(write=False) cls._COMPOSE_PHASE_LOOKUP = lookup return cls._COMPOSE_PHASE_LOOKUP # --------------------------------------------------------------------- # Representation conversions # --------------------------------------------------------------------- def to_dict(self): """Return dictionary representation of Clifford object.""" return { "stabilizer": self.to_labels(mode="S"), "destabilizer": self.to_labels(mode="D"), } @classmethod def from_dict(cls, obj): """Load a Clifford from a dictionary""" labels = obj.get("destabilizer") + obj.get("stabilizer") n_paulis = len(labels) symp = cls._from_label(labels[0]) tableau = np.zeros((n_paulis, len(symp)), dtype=bool) tableau[0] = symp for i in range(1, n_paulis): tableau[i] = cls._from_label(labels[i]) return cls(tableau) def to_matrix(self): """Convert operator to Numpy matrix.""" return self.to_operator().data @classmethod def from_matrix(cls, matrix: np.ndarray) -> Clifford: """Create a Clifford from a unitary matrix. Note that this function takes exponentially long time w.r.t. the number of qubits. Args: matrix (np.array): A unitary matrix representing a Clifford to be converted. Returns: Clifford: the Clifford object for the unitary matrix. Raises: QiskitError: if the input is not a Clifford matrix. """ tableau = cls._unitary_matrix_to_tableau(matrix) if tableau is None: raise QiskitError("Non-Clifford matrix is not convertible") return cls(tableau) @classmethod def from_linear_function(cls, linear_function): """Create a Clifford from a Linear Function. If the linear function is represented by a nxn binary invertible matrix A, then the corresponding Clifford has symplectic matrix [[A^t, 0], [0, A^{-1}]]. Args: linear_function (LinearFunction): A linear function to be converted. Returns: Clifford: the Clifford object for this linear function. """ mat = linear_function.linear mat_t = np.transpose(mat) mat_i = calc_inverse_matrix(mat) dim = len(mat) zero = np.zeros((dim, dim), dtype=int) symplectic_mat = np.block([[mat_t, zero], [zero, mat_i]]) phase = np.zeros(2 * dim, dtype=int) tableau = cls._stack_table_phase(symplectic_mat, phase) return tableau @classmethod def from_permutation(cls, permutation_gate): """Create a Clifford from a PermutationGate. Args: permutation_gate (PermutationGate): A permutation to be converted. Returns: Clifford: the Clifford object for this permutation. """ pat = permutation_gate.pattern dim = len(pat) symplectic_mat = np.zeros((2 * dim, 2 * dim), dtype=int) for i, j in enumerate(pat): symplectic_mat[j, i] = True symplectic_mat[j + dim, i + dim] = True phase = np.zeros(2 * dim, dtype=bool) tableau = cls._stack_table_phase(symplectic_mat, phase) return tableau def to_operator(self) -> Operator: """Convert to an Operator object.""" return Operator(self.to_instruction()) @classmethod def from_operator(cls, operator: Operator) -> Clifford: """Create a Clifford from a operator. Note that this function takes exponentially long time w.r.t. the number of qubits. Args: operator (Operator): An operator representing a Clifford to be converted. Returns: Clifford: the Clifford object for the operator. Raises: QiskitError: if the input is not a Clifford operator. """ tableau = cls._unitary_matrix_to_tableau(operator.to_matrix()) if tableau is None: raise QiskitError("Non-Clifford operator is not convertible") return cls(tableau) def to_circuit(self): """Return a QuantumCircuit implementing the Clifford. For N <= 3 qubits this is based on optimal CX cost decomposition from reference [1]. For N > 3 qubits this is done using the general non-optimal compilation routine from reference [2]. Return: QuantumCircuit: a circuit implementation of the Clifford. References: 1. S. Bravyi, D. Maslov, *Hadamard-free circuits expose the structure of the Clifford group*, `arXiv:2003.09412 [quant-ph] <https://arxiv.org/abs/2003.09412>`_ 2. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). `arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_ """ from qiskit.synthesis.clifford import synth_clifford_full return synth_clifford_full(self) def to_instruction(self): """Return a Gate instruction implementing the Clifford.""" return self.to_circuit().to_gate() @staticmethod def from_circuit(circuit: QuantumCircuit | Instruction) -> Clifford: """Initialize from a QuantumCircuit or Instruction. Args: circuit (QuantumCircuit or ~qiskit.circuit.Instruction): instruction to initialize. Returns: Clifford: the Clifford object for the instruction. Raises: QiskitError: if the input instruction is non-Clifford or contains classical register instruction. """ if not isinstance(circuit, (QuantumCircuit, Instruction)): raise QiskitError("Input must be a QuantumCircuit or Instruction") # Initialize an identity Clifford clifford = Clifford(np.eye(2 * circuit.num_qubits), validate=False) if isinstance(circuit, QuantumCircuit): clifford = _append_circuit(clifford, circuit) else: clifford = _append_operation(clifford, circuit) return clifford @staticmethod def from_label(label: str) -> Clifford: """Return a tensor product of single-qubit Clifford gates. Args: label (string): single-qubit operator string. Returns: Clifford: The N-qubit Clifford operator. Raises: QiskitError: if the label contains invalid characters. Additional Information: The labels correspond to the single-qubit Cliffords are * - Label - Stabilizer - Destabilizer * - ``"I"`` - +Z - +X * - ``"X"`` - -Z - +X * - ``"Y"`` - -Z - -X * - ``"Z"`` - +Z - -X * - ``"H"`` - +X - +Z * - ``"S"`` - +Z - +Y """ # Check label is valid label_gates = { "I": IGate(), "X": XGate(), "Y": YGate(), "Z": ZGate(), "H": HGate(), "S": SGate(), } if re.match(r"^[IXYZHS\-+]+$", label) is None: raise QiskitError("Label contains invalid characters.") # Initialize an identity matrix and apply each gate num_qubits = len(label) op = Clifford(np.eye(2 * num_qubits, dtype=bool)) for qubit, char in enumerate(reversed(label)): op = _append_operation(op, label_gates[char], qargs=[qubit]) return op def to_labels(self, array: bool = False, mode: Literal["S", "D", "B"] = "B"): r"""Convert a Clifford to a list Pauli (de)stabilizer string labels. For large Clifford converting using the ``array=True`` kwarg will be more efficient since it allocates memory for the full Numpy array of labels in advance. .. list-table:: Stabilizer Representations :header-rows: 1 * - Label - Phase - Symplectic - Matrix - Pauli * - ``"+I"`` - 0 - :math:`[0, 0]` - :math:`\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}` - :math:`I` * - ``"-I"`` - 1 - :math:`[0, 0]` - :math:`\begin{bmatrix} -1 & 0 \\ 0 & -1 \end{bmatrix}` - :math:`-I` * - ``"X"`` - 0 - :math:`[1, 0]` - :math:`\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}` - :math:`X` * - ``"-X"`` - 1 - :math:`[1, 0]` - :math:`\begin{bmatrix} 0 & -1 \\ -1 & 0 \end{bmatrix}` - :math:`-X` * - ``"Y"`` - 0 - :math:`[1, 1]` - :math:`\begin{bmatrix} 0 & 1 \\ -1 & 0 \end{bmatrix}` - :math:`iY` * - ``"-Y"`` - 1 - :math:`[1, 1]` - :math:`\begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix}` - :math:`-iY` * - ``"Z"`` - 0 - :math:`[0, 1]` - :math:`\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}` - :math:`Z` * - ``"-Z"`` - 1 - :math:`[0, 1]` - :math:`\begin{bmatrix} -1 & 0 \\ 0 & 1 \end{bmatrix}` - :math:`-Z` Args: array (bool): return a Numpy array if True, otherwise return a list (Default: False). mode (Literal["S", "D", "B"]): return both stabilizer and destabilizer if "B", return only stabilizer if "S" and return only destabilizer if "D". Returns: list or array: The rows of the StabilizerTable in label form. Raises: QiskitError: if stabilizer and destabilizer are both False. """ if mode not in ("S", "B", "D"): raise QiskitError("mode must be B, S, or D.") size = 2 * self.num_qubits if mode == "B" else self.num_qubits offset = self.num_qubits if mode == "S" else 0 ret = np.zeros(size, dtype=f"<U{1 + self.num_qubits}") for i in range(size): z = self.tableau[i + offset, self.num_qubits : 2 * self.num_qubits] x = self.tableau[i + offset, 0 : self.num_qubits] phase = int(self.tableau[i + offset, -1]) * 2 label = BasePauli._to_label(z, x, phase, group_phase=True) if label[0] != "-": label = "+" + label ret[i] = label if array: return ret return ret.tolist() # --------------------------------------------------------------------- # Internal helper functions # --------------------------------------------------------------------- def _hash(self): """Produce a hashable value that is unique for each different Clifford. This should only be used internally when the classes being hashed are under our control, because classes of this type are mutable.""" return np.packbits(self.tableau).tobytes() @staticmethod def _is_symplectic(mat): """Return True if input is symplectic matrix.""" # Condition is # table.T * [[0, 1], [1, 0]] * table = [[0, 1], [1, 0]] # where we are block matrix multiplying using symplectic product dim = len(mat) // 2 if mat.shape != (2 * dim, 2 * dim): return False one = np.eye(dim, dtype=int) zero = np.zeros((dim, dim), dtype=int) seye = np.block([[zero, one], [one, zero]]) arr = mat.astype(int) return np.array_equal(np.mod(arr.T.dot(seye).dot(arr), 2), seye) @staticmethod def _conjugate_transpose(clifford, method): """Return the adjoint, conjugate, or transpose of the Clifford. Args: clifford (Clifford): a clifford object. method (str): what function to apply 'A', 'C', or 'T'. Returns: Clifford: the modified clifford. """ ret = clifford.copy() if method in ["A", "T"]: # Apply inverse # Update table tmp = ret.destab_x.copy() ret.destab_x = ret.stab_z.T ret.destab_z = ret.destab_z.T ret.stab_x = ret.stab_x.T ret.stab_z = tmp.T # Update phase ret.phase ^= clifford.dot(ret).phase if method in ["C", "T"]: # Apply conjugate ret.phase ^= np.mod(_count_y(ret.x, ret.z), 2).astype(bool) return ret def _pad_with_identity(self, clifford, qargs): """Pad Clifford with identities on other subsystems.""" if qargs is None: return clifford padded = Clifford(np.eye(2 * self.num_qubits, dtype=bool), validate=False, copy=False) inds = list(qargs) + [self.num_qubits + i for i in qargs] # Pad Pauli array for i, pos in enumerate(qargs): padded.tableau[inds, pos] = clifford.tableau[:, i] padded.tableau[inds, self.num_qubits + pos] = clifford.tableau[ :, clifford.num_qubits + i ] # Pad phase padded.phase[inds] = clifford.phase return padded @staticmethod def _stack_table_phase(table, phase): return np.hstack((table, phase.reshape(len(phase), 1))) @staticmethod def _from_label(label): phase = False if label[0] in ("-", "+"): phase = label[0] == "-" label = label[1:] num_qubits = len(label) symp = np.zeros(2 * num_qubits + 1, dtype=bool) xs = symp[0:num_qubits] zs = symp[num_qubits : 2 * num_qubits] for i, char in enumerate(label): if char not in ["I", "X", "Y", "Z"]: raise QiskitError( f"Pauli string contains invalid character: {char} not in ['I', 'X', 'Y', 'Z']." ) if char in ("X", "Y"): xs[num_qubits - 1 - i] = True if char in ("Z", "Y"): zs[num_qubits - 1 - i] = True symp[-1] = phase return symp @staticmethod def _pauli_matrix_to_row(mat, num_qubits): """Generate a binary vector (a row of tableau representation) from a Pauli matrix. Return None if the non-Pauli matrix is supplied.""" # pylint: disable=too-many-return-statements def find_one_index(x, decimals=6): indices = np.where(np.round(np.abs(x), decimals) == 1) return indices[0][0] if len(indices[0]) == 1 else None def bitvector(n, num_bits): return np.array([int(digit) for digit in format(n, f"0{num_bits}b")], dtype=bool)[::-1] # compute x-bits xint = find_one_index(mat[0, :]) if xint is None: return None xbits = bitvector(xint, num_qubits) # extract non-zero elements from matrix (rounded to 1, -1, 1j or -1j) entries = np.empty(len(mat), dtype=complex) for i, row in enumerate(mat): index = find_one_index(row) if index is None: return None expected = xint ^ i if index != expected: return None entries[i] = np.round(mat[i, index]) # compute z-bits zbits = np.empty(num_qubits, dtype=bool) for k in range(num_qubits): sign = np.round(entries[2**k] / entries[0]) if sign == 1: zbits[k] = False elif sign == -1: zbits[k] = True else: return None # compute phase phase = None num_y = sum(xbits & zbits) positive_phase = (-1j) ** num_y if entries[0] == positive_phase: phase = False elif entries[0] == -1 * positive_phase: phase = True if phase is None: return None # validate all non-zero elements coef = ((-1) ** phase) * positive_phase ivec, zvec = np.ones(2), np.array([1, -1]) expected = coef * functools.reduce(np.kron, [zvec if z else ivec for z in zbits[::-1]]) if not np.allclose(entries, expected): return None return np.hstack([xbits, zbits, phase]) @staticmethod def _unitary_matrix_to_tableau(matrix): # pylint: disable=invalid-name num_qubits = int(np.log2(len(matrix))) stab = np.empty((num_qubits, 2 * num_qubits + 1), dtype=bool) for i in range(num_qubits): label = "I" * (num_qubits - i - 1) + "X" + "I" * i Xi = Operator.from_label(label).to_matrix() target = matrix @ Xi @ np.conj(matrix).T row = Clifford._pauli_matrix_to_row(target, num_qubits) if row is None: return None stab[i] = row destab = np.empty((num_qubits, 2 * num_qubits + 1), dtype=bool) for i in range(num_qubits): label = "I" * (num_qubits - i - 1) + "Z" + "I" * i Zi = Operator.from_label(label).to_matrix() target = matrix @ Zi @ np.conj(matrix).T row = Clifford._pauli_matrix_to_row(target, num_qubits) if row is None: return None destab[i] = row tableau = np.vstack([stab, destab]) return tableau # Update docstrings for API docs generate_apidocs(Clifford)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ DensityMatrix quantum state class. """ from __future__ import annotations import copy as _copy from numbers import Number import numpy as np from qiskit import _numpy_compat from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.instruction import Instruction from qiskit.exceptions import QiskitError from qiskit.quantum_info.states.quantum_state import QuantumState from qiskit.quantum_info.operators.mixins.tolerances import TolerancesMixin from qiskit.quantum_info.operators.op_shape import OpShape from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic import Pauli, SparsePauliOp from qiskit.quantum_info.operators.scalar_op import ScalarOp from qiskit.quantum_info.operators.predicates import is_hermitian_matrix from qiskit.quantum_info.operators.predicates import is_positive_semidefinite_matrix from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel from qiskit.quantum_info.operators.channel.superop import SuperOp from qiskit._accelerate.pauli_expval import density_expval_pauli_no_x, density_expval_pauli_with_x from qiskit.quantum_info.states.statevector import Statevector class DensityMatrix(QuantumState, TolerancesMixin): """DensityMatrix class""" def __init__( self, data: np.ndarray | list | QuantumCircuit | Instruction | QuantumState, dims: int | tuple | list | None = None, ): """Initialize a density matrix object. Args: data (np.ndarray or list or matrix_like or QuantumCircuit or qiskit.circuit.Instruction): A statevector, quantum instruction or an object with a ``to_operator`` or ``to_matrix`` method from which the density matrix can be constructed. If a vector the density matrix is constructed as the projector of that vector. If a quantum instruction, the density matrix is constructed by assuming all qubits are initialized in the zero state. dims (int or tuple or list): Optional. The subsystem dimension of the state (See additional information). Raises: QiskitError: if input data is not valid. Additional Information: The ``dims`` kwarg can be None, an integer, or an iterable of integers. * ``Iterable`` -- the subsystem dimensions are the values in the list with the total number of subsystems given by the length of the list. * ``Int`` or ``None`` -- the leading dimension of the input matrix specifies the total dimension of the density matrix. If it is a power of two the state will be initialized as an N-qubit state. If it is not a power of two the state will have a single d-dimensional subsystem. """ if isinstance(data, (list, np.ndarray)): # Finally we check if the input is a raw matrix in either a # python list or numpy array format. self._data = np.asarray(data, dtype=complex) elif isinstance(data, (QuantumCircuit, Instruction)): # If the data is a circuit or an instruction use the classmethod # to construct the DensityMatrix object self._data = DensityMatrix.from_instruction(data)._data elif hasattr(data, "to_operator"): # If the data object has a 'to_operator' attribute this is given # higher preference than the 'to_matrix' method for initializing # an Operator object. op = data.to_operator() self._data = op.data if dims is None: dims = op.output_dims() elif hasattr(data, "to_matrix"): # If no 'to_operator' attribute exists we next look for a # 'to_matrix' attribute to a matrix that will be cast into # a complex numpy matrix. self._data = np.asarray(data.to_matrix(), dtype=complex) else: raise QiskitError("Invalid input data format for DensityMatrix") # Convert statevector into a density matrix ndim = self._data.ndim shape = self._data.shape if ndim == 2 and shape[0] == shape[1]: pass # We good elif ndim == 1: self._data = np.outer(self._data, np.conj(self._data)) elif ndim == 2 and shape[1] == 1: self._data = np.reshape(self._data, shape[0]) else: raise QiskitError("Invalid DensityMatrix input: not a square matrix.") super().__init__(op_shape=OpShape.auto(shape=self._data.shape, dims_l=dims, dims_r=dims)) def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): dtype = self.data.dtype if dtype is None else dtype return np.array(self.data, dtype=dtype, copy=copy) def __eq__(self, other): return super().__eq__(other) and np.allclose( self._data, other._data, rtol=self.rtol, atol=self.atol ) def __repr__(self): prefix = "DensityMatrix(" pad = len(prefix) * " " return "{}{},\n{}dims={})".format( prefix, np.array2string(self._data, separator=", ", prefix=prefix), pad, self._op_shape.dims_l(), ) @property def settings(self): """Return settings.""" return {"data": self.data, "dims": self._op_shape.dims_l()} def draw(self, output: str | None = None, **drawer_args): """Return a visualization of the Statevector. **repr**: ASCII TextMatrix of the state's ``__repr__``. **text**: ASCII TextMatrix that can be printed in the console. **latex**: An IPython Latex object for displaying in Jupyter Notebooks. **latex_source**: Raw, uncompiled ASCII source to generate array using LaTeX. **qsphere**: Matplotlib figure, rendering of density matrix using `plot_state_qsphere()`. **hinton**: Matplotlib figure, rendering of density matrix using `plot_state_hinton()`. **bloch**: Matplotlib figure, rendering of density matrix using `plot_bloch_multivector()`. Args: output (str): Select the output method to use for drawing the state. Valid choices are `repr`, `text`, `latex`, `latex_source`, `qsphere`, `hinton`, or `bloch`. Default is `repr`. Default can be changed by adding the line ``state_drawer = <default>`` to ``~/.qiskit/settings.conf`` under ``[default]``. drawer_args: Arguments to be passed directly to the relevant drawing function or constructor (`TextMatrix()`, `array_to_latex()`, `plot_state_qsphere()`, `plot_state_hinton()` or `plot_bloch_multivector()`). See the relevant function under `qiskit.visualization` for that function's documentation. Returns: :class:`matplotlib.Figure` or :class:`str` or :class:`TextMatrix` or :class:`IPython.display.Latex`: Drawing of the Statevector. Raises: ValueError: when an invalid output method is selected. """ # pylint: disable=cyclic-import from qiskit.visualization.state_visualization import state_drawer return state_drawer(self, output=output, **drawer_args) def _ipython_display_(self): out = self.draw() if isinstance(out, str): print(out) else: from IPython.display import display display(out) @property def data(self): """Return data.""" return self._data def is_valid(self, atol=None, rtol=None): """Return True if trace 1 and positive semidefinite.""" if atol is None: atol = self.atol if rtol is None: rtol = self.rtol # Check trace == 1 if not np.allclose(self.trace(), 1, rtol=rtol, atol=atol): return False # Check Hermitian if not is_hermitian_matrix(self.data, rtol=rtol, atol=atol): return False # Check positive semidefinite return is_positive_semidefinite_matrix(self.data, rtol=rtol, atol=atol) def to_operator(self) -> Operator: """Convert to Operator""" dims = self.dims() return Operator(self.data, input_dims=dims, output_dims=dims) def conjugate(self): """Return the conjugate of the density matrix.""" return DensityMatrix(np.conj(self.data), dims=self.dims()) def trace(self): """Return the trace of the density matrix.""" return np.trace(self.data) def purity(self): """Return the purity of the quantum state.""" # For a valid statevector the purity is always 1, however if we simply # have an arbitrary vector (not correctly normalized) then the # purity is equivalent to the trace squared: # P(|psi>) = Tr[|psi><psi|psi><psi|] = |<psi|psi>|^2 return np.trace(np.dot(self.data, self.data)) def tensor(self, other: DensityMatrix) -> DensityMatrix: """Return the tensor product state self ⊗ other. Args: other (DensityMatrix): a quantum state object. Returns: DensityMatrix: the tensor product operator self ⊗ other. Raises: QiskitError: if other is not a quantum state. """ if not isinstance(other, DensityMatrix): other = DensityMatrix(other) ret = _copy.copy(self) ret._data = np.kron(self._data, other._data) ret._op_shape = self._op_shape.tensor(other._op_shape) return ret def expand(self, other: DensityMatrix) -> DensityMatrix: """Return the tensor product state other ⊗ self. Args: other (DensityMatrix): a quantum state object. Returns: DensityMatrix: the tensor product state other ⊗ self. Raises: QiskitError: if other is not a quantum state. """ if not isinstance(other, DensityMatrix): other = DensityMatrix(other) ret = _copy.copy(self) ret._data = np.kron(other._data, self._data) ret._op_shape = self._op_shape.expand(other._op_shape) return ret def _add(self, other): """Return the linear combination self + other. Args: other (DensityMatrix): a quantum state object. Returns: DensityMatrix: the linear combination self + other. Raises: QiskitError: if other is not a quantum state, or has incompatible dimensions. """ if not isinstance(other, DensityMatrix): other = DensityMatrix(other) self._op_shape._validate_add(other._op_shape) ret = _copy.copy(self) ret._data = self.data + other.data return ret def _multiply(self, other): """Return the scalar multiplied state other * self. Args: other (complex): a complex number. Returns: DensityMatrix: the scalar multiplied state other * self. Raises: QiskitError: if other is not a valid complex number. """ if not isinstance(other, Number): raise QiskitError("other is not a number") ret = _copy.copy(self) ret._data = other * self.data return ret def evolve( self, other: Operator | QuantumChannel | Instruction | QuantumCircuit, qargs: list[int] | None = None, ) -> DensityMatrix: """Evolve a quantum state by an operator. Args: other (Operator or QuantumChannel or Instruction or Circuit): The operator to evolve by. qargs (list): a list of QuantumState subsystem positions to apply the operator on. Returns: DensityMatrix: the output density matrix. Raises: QiskitError: if the operator dimension does not match the specified QuantumState subsystem dimensions. """ if qargs is None: qargs = getattr(other, "qargs", None) # Evolution by a circuit or instruction if isinstance(other, (QuantumCircuit, Instruction)): return self._evolve_instruction(other, qargs=qargs) # Evolution by a QuantumChannel # Currently the class that has `to_quantumchannel` is QuantumError of Qiskit Aer, so we can't # use QuantumError as a type hint. if hasattr(other, "to_quantumchannel"): return other.to_quantumchannel()._evolve(self, qargs=qargs) if isinstance(other, QuantumChannel): return other._evolve(self, qargs=qargs) # Unitary evolution by an Operator if not isinstance(other, Operator): dims = self.dims(qargs=qargs) other = Operator(other, input_dims=dims, output_dims=dims) return self._evolve_operator(other, qargs=qargs) def reverse_qargs(self) -> DensityMatrix: r"""Return a DensityMatrix with reversed subsystem ordering. For a tensor product state this is equivalent to reversing the order of tensor product subsystems. For a density matrix :math:`\rho = \rho_{n-1} \otimes ... \otimes \rho_0` the returned state will be :math:`\rho_0 \otimes ... \otimes \rho_{n-1}`. Returns: DensityMatrix: the state with reversed subsystem order. """ ret = _copy.copy(self) axes = tuple(range(self._op_shape._num_qargs_l - 1, -1, -1)) axes = axes + tuple(len(axes) + i for i in axes) ret._data = np.reshape( np.transpose(np.reshape(self.data, self._op_shape.tensor_shape), axes), self._op_shape.shape, ) ret._op_shape = self._op_shape.reverse() return ret def _expectation_value_pauli(self, pauli, qargs=None): """Compute the expectation value of a Pauli. Args: pauli (Pauli): a Pauli operator to evaluate expval of. qargs (None or list): subsystems to apply operator on. Returns: complex: the expectation value. """ n_pauli = len(pauli) if qargs is None: qubits = np.arange(n_pauli) else: qubits = np.array(qargs) x_mask = np.dot(1 << qubits, pauli.x) z_mask = np.dot(1 << qubits, pauli.z) pauli_phase = (-1j) ** pauli.phase if pauli.phase else 1 if x_mask + z_mask == 0: return pauli_phase * self.trace() data = np.ravel(self.data, order="F") if x_mask == 0: return pauli_phase * density_expval_pauli_no_x(data, self.num_qubits, z_mask) x_max = qubits[pauli.x][-1] y_phase = (-1j) ** pauli._count_y() y_phase = y_phase[0] return pauli_phase * density_expval_pauli_with_x( data, self.num_qubits, z_mask, x_mask, y_phase, x_max ) def expectation_value(self, oper: Operator, qargs: None | list[int] = None) -> complex: """Compute the expectation value of an operator. Args: oper (Operator): an operator to evaluate expval. qargs (None or list): subsystems to apply the operator on. Returns: complex: the expectation value. """ if isinstance(oper, Pauli): return self._expectation_value_pauli(oper, qargs) if isinstance(oper, SparsePauliOp): return sum( coeff * self._expectation_value_pauli(Pauli((z, x)), qargs) for z, x, coeff in zip(oper.paulis.z, oper.paulis.x, oper.coeffs) ) if not isinstance(oper, Operator): oper = Operator(oper) return np.trace(Operator(self).dot(oper, qargs=qargs).data) def probabilities( self, qargs: None | list[int] = None, decimals: None | int = None ) -> np.ndarray: """Return the subsystem measurement probability vector. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. Args: qargs (None or list): subsystems to return probabilities for, if None return for all subsystems (Default: None). decimals (None or int): the number of decimal places to round values. If None no rounding is done (Default: None). Returns: np.array: The Numpy vector array of probabilities. Examples: Consider a 2-qubit product state :math:`\\rho=\\rho_1\\otimes\\rho_0` with :math:`\\rho_1=|+\\rangle\\!\\langle+|`, :math:`\\rho_0=|0\\rangle\\!\\langle0|`. .. code-block:: from qiskit.quantum_info import DensityMatrix rho = DensityMatrix.from_label('+0') # Probabilities for measuring both qubits probs = rho.probabilities() print('probs: {}'.format(probs)) # Probabilities for measuring only qubit-0 probs_qubit_0 = rho.probabilities([0]) print('Qubit-0 probs: {}'.format(probs_qubit_0)) # Probabilities for measuring only qubit-1 probs_qubit_1 = rho.probabilities([1]) print('Qubit-1 probs: {}'.format(probs_qubit_1)) .. parsed-literal:: probs: [0.5 0. 0.5 0. ] Qubit-0 probs: [1. 0.] Qubit-1 probs: [0.5 0.5] We can also permute the order of qubits in the ``qargs`` list to change the qubit position in the probabilities output .. code-block:: from qiskit.quantum_info import DensityMatrix rho = DensityMatrix.from_label('+0') # Probabilities for measuring both qubits probs = rho.probabilities([0, 1]) print('probs: {}'.format(probs)) # Probabilities for measuring both qubits # but swapping qubits 0 and 1 in output probs_swapped = rho.probabilities([1, 0]) print('Swapped probs: {}'.format(probs_swapped)) .. parsed-literal:: probs: [0.5 0. 0.5 0. ] Swapped probs: [0.5 0.5 0. 0. ] """ probs = self._subsystem_probabilities( np.abs(self.data.diagonal()), self._op_shape.dims_l(), qargs=qargs ) # to account for roundoff errors, we clip probs = np.clip(probs, a_min=0, a_max=1) if decimals is not None: probs = probs.round(decimals=decimals) return probs def reset(self, qargs: list[int] | None = None) -> DensityMatrix: """Reset state or subsystems to the 0-state. Args: qargs (list or None): subsystems to reset, if None all subsystems will be reset to their 0-state (Default: None). Returns: DensityMatrix: the reset state. Additional Information: If all subsystems are reset this will return the ground state on all subsystems. If only a some subsystems are reset this function will perform evolution by the reset :class:`~qiskit.quantum_info.SuperOp` of the reset subsystems. """ if qargs is None: # Resetting all qubits does not require sampling or RNG ret = _copy.copy(self) state = np.zeros(self._op_shape.shape, dtype=complex) state[0, 0] = 1 ret._data = state return ret # Reset by evolving by reset SuperOp dims = self.dims(qargs) reset_superop = SuperOp(ScalarOp(dims, coeff=0)) reset_superop.data[0] = Operator(ScalarOp(dims)).data.ravel() return self.evolve(reset_superop, qargs=qargs) @classmethod def from_label(cls, label: str) -> DensityMatrix: r"""Return a tensor product of Pauli X,Y,Z eigenstates. .. list-table:: Single-qubit state labels :header-rows: 1 * - Label - Statevector * - ``"0"`` - :math:`\begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix}` * - ``"1"`` - :math:`\begin{pmatrix} 0 & 0 \\ 0 & 1 \end{pmatrix}` * - ``"+"`` - :math:`\frac{1}{2}\begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix}` * - ``"-"`` - :math:`\frac{1}{2}\begin{pmatrix} 1 & -1 \\ -1 & 1 \end{pmatrix}` * - ``"r"`` - :math:`\frac{1}{2}\begin{pmatrix} 1 & -i \\ i & 1 \end{pmatrix}` * - ``"l"`` - :math:`\frac{1}{2}\begin{pmatrix} 1 & i \\ -i & 1 \end{pmatrix}` Args: label (string): a eigenstate string ket label (see table for allowed values). Returns: DensityMatrix: The N-qubit basis state density matrix. Raises: QiskitError: if the label contains invalid characters, or the length of the label is larger than an explicitly specified num_qubits. """ return DensityMatrix(Statevector.from_label(label)) @staticmethod def from_int(i: int, dims: int | tuple | list) -> DensityMatrix: """Return a computational basis state density matrix. Args: i (int): the basis state element. dims (int or tuple or list): The subsystem dimensions of the statevector (See additional information). Returns: DensityMatrix: The computational basis state :math:`|i\\rangle\\!\\langle i|`. Additional Information: The ``dims`` kwarg can be an integer or an iterable of integers. * ``Iterable`` -- the subsystem dimensions are the values in the list with the total number of subsystems given by the length of the list. * ``Int`` -- the integer specifies the total dimension of the state. If it is a power of two the state will be initialized as an N-qubit state. If it is not a power of two the state will have a single d-dimensional subsystem. """ size = np.prod(dims) state = np.zeros((size, size), dtype=complex) state[i, i] = 1.0 return DensityMatrix(state, dims=dims) @classmethod def from_instruction(cls, instruction: Instruction | QuantumCircuit) -> DensityMatrix: """Return the output density matrix of an instruction. The statevector is initialized in the state :math:`|{0,\\ldots,0}\\rangle` of the same number of qubits as the input instruction or circuit, evolved by the input instruction, and the output statevector returned. Args: instruction (qiskit.circuit.Instruction or QuantumCircuit): instruction or circuit Returns: DensityMatrix: the final density matrix. Raises: QiskitError: if the instruction contains invalid instructions for density matrix simulation. """ # Convert circuit to an instruction if isinstance(instruction, QuantumCircuit): instruction = instruction.to_instruction() # Initialize an the statevector in the all |0> state num_qubits = instruction.num_qubits init = np.zeros((2**num_qubits, 2**num_qubits), dtype=complex) init[0, 0] = 1 vec = DensityMatrix(init, dims=num_qubits * (2,)) vec._append_instruction(instruction) return vec def to_dict(self, decimals: None | int = None) -> dict: r"""Convert the density matrix to dictionary form. This dictionary representation uses a Ket-like notation where the dictionary keys are qudit strings for the subsystem basis vectors. If any subsystem has a dimension greater than 10 comma delimiters are inserted between integers so that subsystems can be distinguished. Args: decimals (None or int): the number of decimal places to round values. If None no rounding is done (Default: None). Returns: dict: the dictionary form of the DensityMatrix. Examples: The ket-form of a 2-qubit density matrix :math:`rho = |-\rangle\!\langle -|\otimes |0\rangle\!\langle 0|` .. code-block:: from qiskit.quantum_info import DensityMatrix rho = DensityMatrix.from_label('-0') print(rho.to_dict()) .. parsed-literal:: { '00|00': (0.4999999999999999+0j), '10|00': (-0.4999999999999999-0j), '00|10': (-0.4999999999999999+0j), '10|10': (0.4999999999999999+0j) } For non-qubit subsystems the integer range can go from 0 to 9. For example in a qutrit system .. code-block:: import numpy as np from qiskit.quantum_info import DensityMatrix mat = np.zeros((9, 9)) mat[0, 0] = 0.25 mat[3, 3] = 0.25 mat[6, 6] = 0.25 mat[-1, -1] = 0.25 rho = DensityMatrix(mat, dims=(3, 3)) print(rho.to_dict()) .. parsed-literal:: {'00|00': (0.25+0j), '10|10': (0.25+0j), '20|20': (0.25+0j), '22|22': (0.25+0j)} For large subsystem dimensions delimiters are required. The following example is for a 20-dimensional system consisting of a qubit and 10-dimensional qudit. .. code-block:: import numpy as np from qiskit.quantum_info import DensityMatrix mat = np.zeros((2 * 10, 2 * 10)) mat[0, 0] = 0.5 mat[-1, -1] = 0.5 rho = DensityMatrix(mat, dims=(2, 10)) print(rho.to_dict()) .. parsed-literal:: {'00|00': (0.5+0j), '91|91': (0.5+0j)} """ return self._matrix_to_dict( self.data, self._op_shape.dims_l(), decimals=decimals, string_labels=True ) def _evolve_operator(self, other, qargs=None): """Evolve density matrix by an operator""" # Get shape of output density matrix new_shape = self._op_shape.compose(other._op_shape, qargs=qargs) new_shape._dims_r = new_shape._dims_l new_shape._num_qargs_r = new_shape._num_qargs_l ret = _copy.copy(self) if qargs is None: # Evolution on full matrix op_mat = other.data ret._data = np.dot(op_mat, self.data).dot(op_mat.T.conj()) ret._op_shape = new_shape return ret # Reshape statevector and operator tensor = np.reshape(self.data, self._op_shape.tensor_shape) # Construct list of tensor indices of statevector to be contracted num_indices = len(self.dims()) indices = [num_indices - 1 - qubit for qubit in qargs] # Left multiple by mat mat = np.reshape(other.data, other._op_shape.tensor_shape) tensor = Operator._einsum_matmul(tensor, mat, indices) # Right multiply by mat ** dagger adj = other.adjoint() mat_adj = np.reshape(adj.data, adj._op_shape.tensor_shape) tensor = Operator._einsum_matmul(tensor, mat_adj, indices, num_indices, True) # Replace evolved dimensions ret._data = np.reshape(tensor, new_shape.shape) ret._op_shape = new_shape return ret def _append_instruction(self, other, qargs=None): """Update the current Statevector by applying an instruction.""" from qiskit.circuit.reset import Reset from qiskit.circuit.barrier import Barrier # Try evolving by a matrix operator (unitary-like evolution) mat = Operator._instruction_to_matrix(other) if mat is not None: self._data = self._evolve_operator(Operator(mat), qargs=qargs).data return # Special instruction types if isinstance(other, Reset): self._data = self.reset(qargs)._data return if isinstance(other, Barrier): return # Otherwise try evolving by a Superoperator chan = SuperOp._instruction_to_superop(other) if chan is not None: # Evolve current state by the superoperator self._data = chan._evolve(self, qargs=qargs).data return # If the instruction doesn't have a matrix defined we use its # circuit decomposition definition if it exists, otherwise we # cannot compose this gate and raise an error. if other.definition is None: raise QiskitError(f"Cannot apply Instruction: {other.name}") if not isinstance(other.definition, QuantumCircuit): raise QiskitError( "{} instruction definition is {}; expected QuantumCircuit".format( other.name, type(other.definition) ) ) qubit_indices = {bit: idx for idx, bit in enumerate(other.definition.qubits)} for instruction in other.definition: if instruction.clbits: raise QiskitError( f"Cannot apply instruction with classical bits: {instruction.operation.name}" ) # Get the integer position of the flat register if qargs is None: new_qargs = [qubit_indices[tup] for tup in instruction.qubits] else: new_qargs = [qargs[qubit_indices[tup]] for tup in instruction.qubits] self._append_instruction(instruction.operation, qargs=new_qargs) def _evolve_instruction(self, obj, qargs=None): """Return a new statevector by applying an instruction.""" if isinstance(obj, QuantumCircuit): obj = obj.to_instruction() vec = _copy.copy(self) vec._append_instruction(obj, qargs=qargs) return vec def to_statevector(self, atol: float | None = None, rtol: float | None = None) -> Statevector: """Return a statevector from a pure density matrix. Args: atol (float): Absolute tolerance for checking operation validity. rtol (float): Relative tolerance for checking operation validity. Returns: Statevector: The pure density matrix's corresponding statevector. Corresponds to the eigenvector of the only non-zero eigenvalue. Raises: QiskitError: if the state is not pure. """ if atol is None: atol = self.atol if rtol is None: rtol = self.rtol if not is_hermitian_matrix(self._data, atol=atol, rtol=rtol): raise QiskitError("Not a valid density matrix (non-hermitian).") evals, evecs = np.linalg.eig(self._data) nonzero_evals = evals[abs(evals) > atol] if len(nonzero_evals) != 1 or not np.isclose(nonzero_evals[0], 1, atol=atol, rtol=rtol): raise QiskitError("Density matrix is not a pure state") psi = evecs[:, np.argmax(evals)] # eigenvectors returned in columns. return Statevector(psi) def partial_transpose(self, qargs: list[int]) -> DensityMatrix: """Return partially transposed density matrix. Args: qargs (list): The subsystems to be transposed. Returns: DensityMatrix: The partially transposed density matrix. """ arr = self._data.reshape(self._op_shape.tensor_shape) qargs = len(self._op_shape.dims_l()) - 1 - np.array(qargs) n = len(self.dims()) lst = list(range(2 * n)) for i in qargs: lst[i], lst[i + n] = lst[i + n], lst[i] rho = np.transpose(arr, lst) rho = np.reshape(rho, self._op_shape.shape) return DensityMatrix(rho, dims=self.dims())
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Stabilizer state class. """ from __future__ import annotations import numpy as np from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.op_shape import OpShape from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic import Clifford, Pauli, PauliList from qiskit.quantum_info.operators.symplectic.clifford_circuits import _append_x from qiskit.quantum_info.states.quantum_state import QuantumState from qiskit.circuit import QuantumCircuit, Instruction class StabilizerState(QuantumState): """StabilizerState class. Stabilizer simulator using the convention from reference [1]. Based on the internal class :class:`~qiskit.quantum_info.Clifford`. .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import StabilizerState, Pauli # Bell state generation circuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) stab = StabilizerState(qc) # Print the StabilizerState print(stab) # Calculate the StabilizerState measurement probabilities dictionary print (stab.probabilities_dict()) # Calculate expectation value of the StabilizerState print (stab.expectation_value(Pauli('ZZ'))) .. parsed-literal:: StabilizerState(StabilizerTable: ['+XX', '+ZZ']) {'00': 0.5, '11': 0.5} 1 References: 1. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). `arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_ """ def __init__( self, data: StabilizerState | Clifford | Pauli | QuantumCircuit | Instruction, validate: bool = True, ): """Initialize a StabilizerState object. Args: data (StabilizerState or Clifford or Pauli or QuantumCircuit or qiskit.circuit.Instruction): Data from which the stabilizer state can be constructed. validate (boolean): validate that the stabilizer state data is a valid Clifford. """ # Initialize from another StabilizerState if isinstance(data, StabilizerState): self._data = data._data # Initialize from a Pauli elif isinstance(data, Pauli): self._data = Clifford(data.to_instruction()) # Initialize from a Clifford, QuantumCircuit or Instruction else: self._data = Clifford(data, validate) # Initialize super().__init__(op_shape=OpShape.auto(num_qubits_r=self._data.num_qubits, num_qubits_l=0)) def __eq__(self, other): return (self._data.stab == other._data.stab).all() def __repr__(self): return f"StabilizerState({self._data.stabilizer})" @property def clifford(self): """Return StabilizerState Clifford data""" return self._data def is_valid(self, atol=None, rtol=None): """Return True if a valid StabilizerState.""" return self._data.is_unitary() def _add(self, other): raise NotImplementedError(f"{type(self)} does not support addition") def _multiply(self, other): raise NotImplementedError(f"{type(self)} does not support scalar multiplication") def trace(self) -> float: """Return the trace of the stabilizer state as a density matrix, which equals to 1, since it is always a pure state. Returns: float: the trace (should equal 1). Raises: QiskitError: if input is not a StabilizerState. """ if not self.is_valid(): raise QiskitError("StabilizerState is not a valid quantum state.") return 1.0 def purity(self) -> float: """Return the purity of the quantum state, which equals to 1, since it is always a pure state. Returns: float: the purity (should equal 1). Raises: QiskitError: if input is not a StabilizerState. """ if not self.is_valid(): raise QiskitError("StabilizerState is not a valid quantum state.") return 1.0 def to_operator(self) -> Operator: """Convert state to matrix operator class""" return Clifford(self.clifford).to_operator() def conjugate(self): """Return the conjugate of the operator.""" ret = self.copy() ret._data = ret._data.conjugate() return ret def tensor(self, other: StabilizerState) -> StabilizerState: """Return the tensor product stabilizer state self ⊗ other. Args: other (StabilizerState): a stabilizer state object. Returns: StabilizerState: the tensor product operator self ⊗ other. Raises: QiskitError: if other is not a StabilizerState. """ if not isinstance(other, StabilizerState): other = StabilizerState(other) ret = self.copy() ret._data = self.clifford.tensor(other.clifford) return ret def expand(self, other: StabilizerState) -> StabilizerState: """Return the tensor product stabilizer state other ⊗ self. Args: other (StabilizerState): a stabilizer state object. Returns: StabilizerState: the tensor product operator other ⊗ self. Raises: QiskitError: if other is not a StabilizerState. """ if not isinstance(other, StabilizerState): other = StabilizerState(other) ret = self.copy() ret._data = self.clifford.expand(other.clifford) return ret def evolve( self, other: Clifford | QuantumCircuit | Instruction, qargs: list | None = None ) -> StabilizerState: """Evolve a stabilizer state by a Clifford operator. Args: other (Clifford or QuantumCircuit or qiskit.circuit.Instruction): The Clifford operator to evolve by. qargs (list): a list of stabilizer subsystem positions to apply the operator on. Returns: StabilizerState: the output stabilizer state. Raises: QiskitError: if other is not a StabilizerState. QiskitError: if the operator dimension does not match the specified StabilizerState subsystem dimensions. """ if not isinstance(other, StabilizerState): other = StabilizerState(other) ret = self.copy() ret._data = self.clifford.compose(other.clifford, qargs=qargs) return ret def expectation_value(self, oper: Pauli, qargs: None | list = None) -> complex: """Compute the expectation value of a Pauli operator. Args: oper (Pauli): a Pauli operator to evaluate expval. qargs (None or list): subsystems to apply the operator on. Returns: complex: the expectation value (only 0 or 1 or -1 or i or -i). Raises: QiskitError: if oper is not a Pauli operator. """ if not isinstance(oper, Pauli): raise QiskitError("Operator for expectation value is not a Pauli operator.") num_qubits = self.clifford.num_qubits if qargs is None: qubits = range(num_qubits) else: qubits = qargs # Construct Pauli on num_qubits pauli = Pauli(num_qubits * "I") phase = 0 pauli_phase = (-1j) ** oper.phase if oper.phase else 1 for pos, qubit in enumerate(qubits): pauli.x[qubit] = oper.x[pos] pauli.z[qubit] = oper.z[pos] phase += pauli.x[qubit] & pauli.z[qubit] # Check if there is a stabilizer that anti-commutes with an odd number of qubits # If so the expectation value is 0 for p in range(num_qubits): num_anti = 0 num_anti += np.count_nonzero(pauli.z & self.clifford.stab_x[p]) num_anti += np.count_nonzero(pauli.x & self.clifford.stab_z[p]) if num_anti % 2 == 1: return 0 # Otherwise pauli is (-1)^a prod_j S_j^b_j for Clifford stabilizers # If pauli anti-commutes with D_j then b_j = 1. # Multiply pauli by stabilizers with anti-commuting destabilizers pauli_z = (pauli.z).copy() # Make a copy of pauli.z for p in range(num_qubits): # Check if destabilizer anti-commutes num_anti = 0 num_anti += np.count_nonzero(pauli.z & self.clifford.destab_x[p]) num_anti += np.count_nonzero(pauli.x & self.clifford.destab_z[p]) if num_anti % 2 == 0: continue # If anti-commutes multiply Pauli by stabilizer phase += 2 * self.clifford.stab_phase[p] phase += np.count_nonzero(self.clifford.stab_z[p] & self.clifford.stab_x[p]) phase += 2 * np.count_nonzero(pauli_z & self.clifford.stab_x[p]) pauli_z = pauli_z ^ self.clifford.stab_z[p] # For valid stabilizers, `phase` can only be 0 (= 1) or 2 (= -1) at this point. if phase % 4 != 0: return -pauli_phase return pauli_phase def equiv(self, other: StabilizerState) -> bool: """Return True if the two generating sets generate the same stabilizer group. Args: other (StabilizerState): another StabilizerState. Returns: bool: True if other has a generating set that generates the same StabilizerState. """ if not isinstance(other, StabilizerState): try: other = StabilizerState(other) except QiskitError: return False num_qubits = self.num_qubits if other.num_qubits != num_qubits: return False pauli_orig = PauliList.from_symplectic( self._data.stab_z, self._data.stab_x, 2 * self._data.stab_phase ) pauli_other = PauliList.from_symplectic( other._data.stab_z, other._data.stab_x, 2 * other._data.stab_phase ) # Check that each stabilizer from the original set commutes with each stabilizer # from the other set if not np.all([pauli.commutes(pauli_other) for pauli in pauli_orig]): return False # Compute the expected value of each stabilizer from the original set on the stabilizer state # determined by the other set. The two stabilizer states coincide if and only if the # expected value is +1 for each stabilizer for i in range(num_qubits): exp_val = self.expectation_value(pauli_other[i]) if exp_val != 1: return False return True def probabilities(self, qargs: None | list = None, decimals: None | int = None) -> np.ndarray: """Return the subsystem measurement probability vector. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. Args: qargs (None or list): subsystems to return probabilities for, if None return for all subsystems (Default: None). decimals (None or int): the number of decimal places to round values. If None no rounding is done (Default: None). Returns: np.array: The Numpy vector array of probabilities. """ probs_dict = self.probabilities_dict(qargs, decimals) if qargs is None: qargs = range(self.clifford.num_qubits) probs = np.zeros(2 ** len(qargs)) for key, value in probs_dict.items(): place = int(key, 2) probs[place] = value return probs def probabilities_dict(self, qargs: None | list = None, decimals: None | int = None) -> dict: """Return the subsystem measurement probability dictionary. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. This dictionary representation uses a Ket-like notation where the dictionary keys are qudit strings for the subsystem basis vectors. If any subsystem has a dimension greater than 10 comma delimiters are inserted between integers so that subsystems can be distinguished. Args: qargs (None or list): subsystems to return probabilities for, if None return for all subsystems (Default: None). decimals (None or int): the number of decimal places to round values. If None no rounding is done (Default: None). Returns: dict: The measurement probabilities in dict (ket) form. """ if qargs is None: qubits = range(self.clifford.num_qubits) else: qubits = qargs outcome = ["X"] * len(qubits) outcome_prob = 1.0 probs = {} # probabilities dictionary self._get_probablities(qubits, outcome, outcome_prob, probs) if decimals is not None: for key, value in probs.items(): probs[key] = round(value, decimals) return probs def reset(self, qargs: list | None = None) -> StabilizerState: """Reset state or subsystems to the 0-state. Args: qargs (list or None): subsystems to reset, if None all subsystems will be reset to their 0-state (Default: None). Returns: StabilizerState: the reset state. Additional Information: If all subsystems are reset this will return the ground state on all subsystems. If only some subsystems are reset this function will perform a measurement on those subsystems and evolve the subsystems so that the collapsed post-measurement states are rotated to the 0-state. The RNG seed for this sampling can be set using the :meth:`seed` method. """ # Resetting all qubits does not require sampling or RNG if qargs is None: return StabilizerState(Clifford(np.eye(2 * self.clifford.num_qubits))) randbits = self._rng.integers(2, size=len(qargs)) ret = self.copy() for bit, qubit in enumerate(qargs): # Apply measurement and get classical outcome outcome = ret._measure_and_update(qubit, randbits[bit]) # Use the outcome to apply X gate to any qubits left in the # |1> state after measure, then discard outcome. if outcome == 1: _append_x(ret.clifford, qubit) return ret def measure(self, qargs: list | None = None) -> tuple: """Measure subsystems and return outcome and post-measure state. Note that this function uses the QuantumStates internal random number generator for sampling the measurement outcome. The RNG seed can be set using the :meth:`seed` method. Args: qargs (list or None): subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). Returns: tuple: the pair ``(outcome, state)`` where ``outcome`` is the measurement outcome string label, and ``state`` is the collapsed post-measurement stabilizer state for the corresponding outcome. """ if qargs is None: qargs = range(self.clifford.num_qubits) randbits = self._rng.integers(2, size=len(qargs)) ret = self.copy() outcome = "" for bit, qubit in enumerate(qargs): outcome = str(ret._measure_and_update(qubit, randbits[bit])) + outcome return outcome, ret def sample_memory(self, shots: int, qargs: None | list = None) -> np.ndarray: """Sample a list of qubit measurement outcomes in the computational basis. Args: shots (int): number of samples to generate. qargs (None or list): subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). Returns: np.array: list of sampled counts if the order sampled. Additional Information: This function implements the measurement :meth:`measure` method. The seed for random number generator used for sampling can be set to a fixed value by using the stats :meth:`seed` method. """ memory = [] for _ in range(shots): # copy the StabilizerState since measure updates it stab = self.copy() memory.append(stab.measure(qargs)[0]) return memory # ----------------------------------------------------------------------- # Helper functions for calculating the measurement # ----------------------------------------------------------------------- def _measure_and_update(self, qubit, randbit): """Measure a single qubit and return outcome and post-measure state. Note that this function uses the QuantumStates internal random number generator for sampling the measurement outcome. The RNG seed can be set using the :meth:`seed` method. Note that stabilizer state measurements only have three probabilities: (p0, p1) = (0.5, 0.5), (1, 0), or (0, 1) The random case happens if there is a row anti-commuting with Z[qubit] """ num_qubits = self.clifford.num_qubits clifford = self.clifford stab_x = self.clifford.stab_x # Check if there exists stabilizer anticommuting with Z[qubit] # in this case the measurement outcome is random z_anticommuting = np.any(stab_x[:, qubit]) if z_anticommuting == 0: # Deterministic outcome - measuring it will not change the StabilizerState aux_pauli = Pauli(num_qubits * "I") for i in range(num_qubits): if clifford.x[i][qubit]: aux_pauli = self._rowsum_deterministic(clifford, aux_pauli, i + num_qubits) outcome = aux_pauli.phase return outcome else: # Non-deterministic outcome outcome = randbit p_qubit = np.min(np.nonzero(stab_x[:, qubit])) p_qubit += num_qubits # Updating the StabilizerState for i in range(2 * num_qubits): # the last condition is not in the AG paper but we seem to need it if (clifford.x[i][qubit]) and (i != p_qubit) and (i != (p_qubit - num_qubits)): self._rowsum_nondeterministic(clifford, i, p_qubit) clifford.destab[p_qubit - num_qubits] = clifford.stab[p_qubit - num_qubits].copy() clifford.x[p_qubit] = np.zeros(num_qubits) clifford.z[p_qubit] = np.zeros(num_qubits) clifford.z[p_qubit][qubit] = True clifford.phase[p_qubit] = outcome return outcome @staticmethod def _phase_exponent(x1, z1, x2, z2): """Exponent g of i such that Pauli(x1,z1) * Pauli(x2,z2) = i^g Pauli(x1+x2,z1+z2)""" # pylint: disable=invalid-name phase = (x2 * z1 * (1 + 2 * z2 + 2 * x1) - x1 * z2 * (1 + 2 * z1 + 2 * x2)) % 4 if phase < 0: phase += 4 # now phase in {0, 1, 3} if phase == 2: raise QiskitError("Invalid rowsum phase exponent in measurement calculation.") return phase @staticmethod def _rowsum(accum_pauli, accum_phase, row_pauli, row_phase): """Aaronson-Gottesman rowsum helper function""" newr = 2 * row_phase + 2 * accum_phase for qubit in range(row_pauli.num_qubits): newr += StabilizerState._phase_exponent( row_pauli.x[qubit], row_pauli.z[qubit], accum_pauli.x[qubit], accum_pauli.z[qubit] ) newr %= 4 if (newr != 0) & (newr != 2): raise QiskitError("Invalid rowsum in measurement calculation.") accum_phase = int(newr == 2) accum_pauli.x ^= row_pauli.x accum_pauli.z ^= row_pauli.z return accum_pauli, accum_phase @staticmethod def _rowsum_nondeterministic(clifford, accum, row): """Updating StabilizerState Clifford in the non-deterministic rowsum calculation. row and accum are rows in the StabilizerState Clifford.""" row_phase = clifford.phase[row] accum_phase = clifford.phase[accum] z = clifford.z x = clifford.x row_pauli = Pauli((z[row], x[row])) accum_pauli = Pauli((z[accum], x[accum])) accum_pauli, accum_phase = StabilizerState._rowsum( accum_pauli, accum_phase, row_pauli, row_phase ) clifford.phase[accum] = accum_phase x[accum] = accum_pauli.x z[accum] = accum_pauli.z @staticmethod def _rowsum_deterministic(clifford, aux_pauli, row): """Updating an auxilary Pauli aux_pauli in the deterministic rowsum calculation. The StabilizerState itself is not updated.""" row_phase = clifford.phase[row] accum_phase = aux_pauli.phase accum_pauli = aux_pauli row_pauli = Pauli((clifford.z[row], clifford.x[row])) accum_pauli, accum_phase = StabilizerState._rowsum( accum_pauli, accum_phase, row_pauli, row_phase ) aux_pauli = accum_pauli aux_pauli.phase = accum_phase return aux_pauli # ----------------------------------------------------------------------- # Helper functions for calculating the probabilities # ----------------------------------------------------------------------- def _get_probablities(self, qubits, outcome, outcome_prob, probs): """Recursive helper function for calculating the probabilities""" qubit_for_branching = -1 ret = self.copy() for i in range(len(qubits)): qubit = qubits[len(qubits) - i - 1] if outcome[i] == "X": is_deterministic = not any(ret.clifford.stab_x[:, qubit]) if is_deterministic: single_qubit_outcome = ret._measure_and_update(qubit, 0) if single_qubit_outcome: outcome[i] = "1" else: outcome[i] = "0" else: qubit_for_branching = i if qubit_for_branching == -1: str_outcome = "".join(outcome) probs[str_outcome] = outcome_prob return for single_qubit_outcome in range(0, 2): new_outcome = outcome.copy() if single_qubit_outcome: new_outcome[qubit_for_branching] = "1" else: new_outcome[qubit_for_branching] = "0" stab_cpy = ret.copy() stab_cpy._measure_and_update( qubits[len(qubits) - qubit_for_branching - 1], single_qubit_outcome ) stab_cpy._get_probablities(qubits, new_outcome, 0.5 * outcome_prob, probs)
https://github.com/swe-train/qiskit__qiskit
swe-train
from qiskit import * from qiskit.tools.visualization import plot_bloch_multivector import matplotlib.pyplot as plt from qiskit.visualization.gate_map import plot_coupling_map, plot_gate_map from qiskit.visualization.state_visualization import plot_bloch_vector, plot_state_city, plot_state_paulivec circuit = QuantumCircuit(1,1) circuit.x(0) simulator = Aer.get_backend('statevector_simulator') result = execute(circuit, backend = simulator).result() statevector = result.get_statevector() print(statevector) simulator2 = Aer.get_backend('unitary_simulator') result = execute(circuit, backend= simulator2).result() unitary = result.get_unitary() print(unitary)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A container class for counts from a circuit execution.""" import re from qiskit.result import postprocess from qiskit import exceptions # NOTE: A dict subclass should not overload any dunder methods like __getitem__ # this can cause unexpected behavior and issues as the cPython dict # implementation has many standard methods in C for performance and the dunder # methods are not always used as expected. For example, update() doesn't call # __setitem__ so overloading __setitem__ would not always provide the expected # result class Counts(dict): """A class to store a counts result from a circuit execution.""" bitstring_regex = re.compile(r"^[01\s]+$") def __init__(self, data, time_taken=None, creg_sizes=None, memory_slots=None): """Build a counts object Args: data (dict): The dictionary input for the counts. Where the keys represent a measured classical value and the value is an integer the number of shots with that result. The keys can be one of several formats: * A hexadecimal string of the form ``'0x4a'`` * A bit string prefixed with ``0b`` for example ``'0b1011'`` * A bit string formatted across register and memory slots. For example, ``'00 10'``. * A dit string, for example ``'02'``. Note for objects created with dit strings the ``creg_sizes`` and ``memory_slots`` kwargs don't work and :meth:`hex_outcomes` and :meth:`int_outcomes` also do not work. time_taken (float): The duration of the experiment that generated the counts in seconds. creg_sizes (list): a nested list where the inner element is a list of tuples containing both the classical register name and classical register size. For example, ``[('c_reg', 2), ('my_creg', 4)]``. memory_slots (int): The number of total ``memory_slots`` in the experiment. Raises: TypeError: If the input key type is not an ``int`` or ``str``. QiskitError: If a dit string key is input with ``creg_sizes`` and/or ``memory_slots``. """ bin_data = None data = dict(data) if not data: self.int_raw = {} self.hex_raw = {} bin_data = {} else: first_key = next(iter(data.keys())) if isinstance(first_key, int): self.int_raw = data self.hex_raw = {hex(key): value for key, value in self.int_raw.items()} elif isinstance(first_key, str): if first_key.startswith("0x"): self.hex_raw = data self.int_raw = {int(key, 0): value for key, value in self.hex_raw.items()} elif first_key.startswith("0b"): self.int_raw = {int(key, 0): value for key, value in data.items()} self.hex_raw = {hex(key): value for key, value in self.int_raw.items()} else: if not creg_sizes and not memory_slots: self.hex_raw = None self.int_raw = None bin_data = data else: hex_dict = {} int_dict = {} for bitstring, value in data.items(): if not self.bitstring_regex.search(bitstring): raise exceptions.QiskitError( "Counts objects with dit strings do not " "currently support dit string formatting parameters " "creg_sizes or memory_slots" ) int_key = self._remove_space_underscore(bitstring) int_dict[int_key] = value hex_dict[hex(int_key)] = value self.hex_raw = hex_dict self.int_raw = int_dict else: raise TypeError( "Invalid input key type %s, must be either an int " "key or string key with hexademical value or bit string" ) header = {} self.creg_sizes = creg_sizes if self.creg_sizes: header["creg_sizes"] = self.creg_sizes self.memory_slots = memory_slots if self.memory_slots: header["memory_slots"] = self.memory_slots if not bin_data: bin_data = postprocess.format_counts(self.hex_raw, header=header) super().__init__(bin_data) self.time_taken = time_taken def most_frequent(self): """Return the most frequent count Returns: str: The bit string for the most frequent result Raises: QiskitError: when there is >1 count with the same max counts, or an empty object. """ if not self: raise exceptions.QiskitError("Can not return a most frequent count on an empty object") max_value = max(self.values()) max_values_counts = [x[0] for x in self.items() if x[1] == max_value] if len(max_values_counts) != 1: raise exceptions.QiskitError( "Multiple values have the same maximum counts: %s" % ",".join(max_values_counts) ) return max_values_counts[0] def hex_outcomes(self): """Return a counts dictionary with hexadecimal string keys Returns: dict: A dictionary with the keys as hexadecimal strings instead of bitstrings Raises: QiskitError: If the Counts object contains counts for dit strings """ if self.hex_raw: return {key.lower(): value for key, value in self.hex_raw.items()} else: out_dict = {} for bitstring, value in self.items(): if not self.bitstring_regex.search(bitstring): raise exceptions.QiskitError( "Counts objects with dit strings do not " "currently support conversion to hexadecimal" ) int_key = self._remove_space_underscore(bitstring) out_dict[hex(int_key)] = value return out_dict def int_outcomes(self): """Build a counts dictionary with integer keys instead of count strings Returns: dict: A dictionary with the keys as integers instead of bitstrings Raises: QiskitError: If the Counts object contains counts for dit strings """ if self.int_raw: return self.int_raw else: out_dict = {} for bitstring, value in self.items(): if not self.bitstring_regex.search(bitstring): raise exceptions.QiskitError( "Counts objects with dit strings do not " "currently support conversion to integer" ) int_key = self._remove_space_underscore(bitstring) out_dict[int_key] = value return out_dict @staticmethod def _remove_space_underscore(bitstring): """Removes all spaces and underscores from bitstring""" return int(bitstring.replace(" ", "").replace("_", ""), 2) def shots(self): """Return the number of shots""" return sum(self.values())
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Functions to generate the basic approximations of single qubit gates for Solovay-Kitaev.""" from __future__ import annotations import warnings import collections import numpy as np import qiskit.circuit.library.standard_gates as gates from qiskit.circuit import Gate from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.utils import optionals from .gate_sequence import GateSequence Node = collections.namedtuple("Node", ("labels", "sequence", "children")) _1q_inverses = { "i": "i", "x": "x", "y": "y", "z": "z", "h": "h", "t": "tdg", "tdg": "t", "s": "sdg", "sdg": "s", } _1q_gates = { "i": gates.IGate(), "x": gates.XGate(), "y": gates.YGate(), "z": gates.ZGate(), "h": gates.HGate(), "t": gates.TGate(), "tdg": gates.TdgGate(), "s": gates.SGate(), "sdg": gates.SdgGate(), "sx": gates.SXGate(), "sxdg": gates.SXdgGate(), } def _check_candidate(candidate, existing_sequences, tol=1e-10): if optionals.HAS_SKLEARN: return _check_candidate_kdtree(candidate, existing_sequences, tol) warnings.warn( "The SolovayKitaev algorithm relies on scikit-learn's KDTree for a " "fast search over the basis approximations. Without this, we fallback onto a " "greedy search with is significantly slower. We highly suggest to install " "scikit-learn to use this feature.", category=RuntimeWarning, ) return _check_candidate_greedy(candidate, existing_sequences, tol) def _check_candidate_greedy(candidate, existing_sequences, tol=1e-10): # do a quick, string-based check if the same sequence already exists if any(candidate.name == existing.name for existing in existing_sequences): return False for existing in existing_sequences: if matrix_equal(existing.product_su2, candidate.product_su2, ignore_phase=True, atol=tol): # is the new sequence less or more efficient? return len(candidate.gates) < len(existing.gates) return True @optionals.HAS_SKLEARN.require_in_call def _check_candidate_kdtree(candidate, existing_sequences, tol=1e-10): """Check if there's a candidate implementing the same matrix up to ``tol``. This uses a k-d tree search and is much faster than the greedy, list-based search. """ from sklearn.neighbors import KDTree # do a quick, string-based check if the same sequence already exists if any(candidate.name == existing.name for existing in existing_sequences): return False points = np.array([sequence.product.flatten() for sequence in existing_sequences]) candidate = np.array([candidate.product.flatten()]) kdtree = KDTree(points) dist, _ = kdtree.query(candidate) return dist[0][0] > tol def _process_node(node: Node, basis: list[str], sequences: list[GateSequence]): inverse_last = _1q_inverses[node.labels[-1]] if node.labels else None for label in basis: if label == inverse_last: continue sequence = node.sequence.copy() sequence.append(_1q_gates[label]) if _check_candidate(sequence, sequences): sequences.append(sequence) node.children.append(Node(node.labels + (label,), sequence, [])) return node.children def generate_basic_approximations( basis_gates: list[str | Gate], depth: int, filename: str | None = None ) -> list[GateSequence]: """Generates a list of ``GateSequence``s with the gates in ``basic_gates``. Args: basis_gates: The gates from which to create the sequences of gates. depth: The maximum depth of the approximations. filename: If provided, the basic approximations are stored in this file. Returns: List of ``GateSequences`` using the gates in ``basic_gates``. Raises: ValueError: If ``basis_gates`` contains an invalid gate identifier. """ basis = [] for gate in basis_gates: if isinstance(gate, str): if gate not in _1q_gates.keys(): raise ValueError(f"Invalid gate identifier: {gate}") basis.append(gate) else: # gate is a qiskit.circuit.Gate basis.append(gate.name) tree = Node((), GateSequence(), []) cur_level = [tree] sequences = [tree.sequence] for _ in [None] * depth: next_level = [] for node in cur_level: next_level.extend(_process_node(node, basis, sequences)) cur_level = next_level if filename is not None: data = {} for sequence in sequences: gatestring = sequence.name data[gatestring] = sequence.product np.save(filename, data) return sequences
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Durations of instructions, one of transpiler configurations.""" from __future__ import annotations from typing import Optional, List, Tuple, Union, Iterable import qiskit.circuit from qiskit.circuit import Barrier, Delay from qiskit.circuit import Instruction, Qubit, ParameterExpression from qiskit.circuit.duration import duration_in_dt from qiskit.providers import Backend from qiskit.transpiler.exceptions import TranspilerError from qiskit.utils.deprecation import deprecate_arg from qiskit.utils.units import apply_prefix def _is_deprecated_qubits_argument(qubits: Union[int, list[int], Qubit, list[Qubit]]) -> bool: if isinstance(qubits, (int, Qubit)): qubits = [qubits] return isinstance(qubits[0], Qubit) class InstructionDurations: """Helper class to provide durations of instructions for scheduling. It stores durations (gate lengths) and dt to be used at the scheduling stage of transpiling. It can be constructed from ``backend`` or ``instruction_durations``, which is an argument of :func:`transpile`. The duration of an instruction depends on the instruction (given by name), the qubits, and optionally the parameters of the instruction. Note that these fields are used as keys in dictionaries that are used to retrieve the instruction durations. Therefore, users must use the exact same parameter value to retrieve an instruction duration as the value with which it was added. """ def __init__( self, instruction_durations: "InstructionDurationsType" | None = None, dt: float = None ): self.duration_by_name: dict[str, tuple[float, str]] = {} self.duration_by_name_qubits: dict[tuple[str, tuple[int, ...]], tuple[float, str]] = {} self.duration_by_name_qubits_params: dict[ tuple[str, tuple[int, ...], tuple[float, ...]], tuple[float, str] ] = {} self.dt = dt if instruction_durations: self.update(instruction_durations) def __str__(self): """Return a string representation of all stored durations.""" string = "" for k, v in self.duration_by_name.items(): string += k string += ": " string += str(v[0]) + " " + v[1] string += "\n" for k, v in self.duration_by_name_qubits.items(): string += k[0] + str(k[1]) string += ": " string += str(v[0]) + " " + v[1] string += "\n" return string @classmethod def from_backend(cls, backend: Backend): """Construct an :class:`InstructionDurations` object from the backend. Args: backend: backend from which durations (gate lengths) and dt are extracted. Returns: InstructionDurations: The InstructionDurations constructed from backend. Raises: TranspilerError: If dt and dtm is different in the backend. """ # All durations in seconds in gate_length instruction_durations = [] backend_properties = backend.properties() if hasattr(backend_properties, "_gates"): for gate, insts in backend_properties._gates.items(): for qubits, props in insts.items(): if "gate_length" in props: gate_length = props["gate_length"][0] # Throw away datetime at index 1 instruction_durations.append((gate, qubits, gate_length, "s")) for q, props in backend.properties()._qubits.items(): if "readout_length" in props: readout_length = props["readout_length"][0] # Throw away datetime at index 1 instruction_durations.append(("measure", [q], readout_length, "s")) try: dt = backend.configuration().dt except AttributeError: dt = None return InstructionDurations(instruction_durations, dt=dt) def update(self, inst_durations: "InstructionDurationsType" | None, dt: float = None): """Update self with inst_durations (inst_durations overwrite self). Args: inst_durations: Instruction durations to be merged into self (overwriting self). dt: Sampling duration in seconds of the target backend. Returns: InstructionDurations: The updated InstructionDurations. Raises: TranspilerError: If the format of instruction_durations is invalid. """ if dt: self.dt = dt if inst_durations is None: return self if isinstance(inst_durations, InstructionDurations): self.duration_by_name.update(inst_durations.duration_by_name) self.duration_by_name_qubits.update(inst_durations.duration_by_name_qubits) self.duration_by_name_qubits_params.update( inst_durations.duration_by_name_qubits_params ) else: for i, items in enumerate(inst_durations): if not isinstance(items[-1], str): items = (*items, "dt") # set default unit if len(items) == 4: # (inst_name, qubits, duration, unit) inst_durations[i] = (*items[:3], None, items[3]) else: inst_durations[i] = items # assert (inst_name, qubits, duration, parameters, unit) if len(inst_durations[i]) != 5: raise TranspilerError( "Each entry of inst_durations dictionary must be " "(inst_name, qubits, duration) or " "(inst_name, qubits, duration, unit) or" "(inst_name, qubits, duration, parameters) or" "(inst_name, qubits, duration, parameters, unit) " f"received {inst_durations[i]}." ) if inst_durations[i][2] is None: raise TranspilerError(f"None duration for {inst_durations[i]}.") for name, qubits, duration, parameters, unit in inst_durations: if isinstance(qubits, int): qubits = [qubits] if isinstance(parameters, (int, float)): parameters = [parameters] if qubits is None: self.duration_by_name[name] = duration, unit elif parameters is None: self.duration_by_name_qubits[(name, tuple(qubits))] = duration, unit else: key = (name, tuple(qubits), tuple(parameters)) self.duration_by_name_qubits_params[key] = duration, unit return self @deprecate_arg( "qubits", deprecation_description=( "Using a Qubit or List[Qubit] for the ``qubits`` argument to InstructionDurations.get()" ), additional_msg="Instead, use an integer for the qubit index.", since="0.19.0", predicate=_is_deprecated_qubits_argument, ) def get( self, inst: str | qiskit.circuit.Instruction, qubits: int | list[int] | Qubit | list[Qubit] | list[int | Qubit], unit: str = "dt", parameters: list[float] | None = None, ) -> float: """Get the duration of the instruction with the name, qubits, and parameters. Some instructions may have a parameter dependent duration. Args: inst: An instruction or its name to be queried. qubits: Qubits or its indices that the instruction acts on. unit: The unit of duration to be returned. It must be 's' or 'dt'. parameters: The value of the parameters of the desired instruction. Returns: float|int: The duration of the instruction on the qubits. Raises: TranspilerError: No duration is defined for the instruction. """ if isinstance(inst, Barrier): return 0 elif isinstance(inst, Delay): return self._convert_unit(inst.duration, inst.unit, unit) if isinstance(inst, Instruction): inst_name = inst.name else: inst_name = inst if isinstance(qubits, (int, Qubit)): qubits = [qubits] if isinstance(qubits[0], Qubit): qubits = [q.index for q in qubits] try: return self._get(inst_name, qubits, unit, parameters) except TranspilerError as ex: raise TranspilerError( f"Duration of {inst_name} on qubits {qubits} is not found." ) from ex def _get( self, name: str, qubits: list[int], to_unit: str, parameters: Iterable[float] | None = None, ) -> float: """Get the duration of the instruction with the name, qubits, and parameters.""" if name == "barrier": return 0 if parameters is not None: key = (name, tuple(qubits), tuple(parameters)) else: key = (name, tuple(qubits)) if key in self.duration_by_name_qubits_params: duration, unit = self.duration_by_name_qubits_params[key] elif key in self.duration_by_name_qubits: duration, unit = self.duration_by_name_qubits[key] elif name in self.duration_by_name: duration, unit = self.duration_by_name[name] else: raise TranspilerError(f"No value is found for key={key}") return self._convert_unit(duration, unit, to_unit) def _convert_unit(self, duration: float, from_unit: str, to_unit: str) -> float: if from_unit.endswith("s") and from_unit != "s": duration = apply_prefix(duration, from_unit) from_unit = "s" # assert both from_unit and to_unit in {'s', 'dt'} if from_unit == to_unit: return duration if self.dt is None: raise TranspilerError( f"dt is necessary to convert durations from '{from_unit}' to '{to_unit}'" ) if from_unit == "s" and to_unit == "dt": if isinstance(duration, ParameterExpression): return duration / self.dt return duration_in_dt(duration, self.dt) elif from_unit == "dt" and to_unit == "s": return duration * self.dt else: raise TranspilerError(f"Conversion from '{from_unit}' to '{to_unit}' is not supported") def units_used(self) -> set[str]: """Get the set of all units used in this instruction durations. Returns: Set of units used in this instruction durations. """ units_used = set() for _, unit in self.duration_by_name_qubits.values(): units_used.add(unit) for _, unit in self.duration_by_name.values(): units_used.add(unit) return units_used InstructionDurationsType = Union[ List[Tuple[str, Optional[Iterable[int]], float, Optional[Iterable[float]], str]], List[Tuple[str, Optional[Iterable[int]], float, Optional[Iterable[float]]]], List[Tuple[str, Optional[Iterable[int]], float, str]], List[Tuple[str, Optional[Iterable[int]], float]], InstructionDurations, ] """List of tuples representing (instruction name, qubits indices, parameters, duration)."""
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ A two-ways dict to represent a layout. Layout is the relation between virtual (qu)bits and physical (qu)bits. Virtual (qu)bits are tuples, e.g. `(QuantumRegister(3, 'qr'), 2)` or simply `qr[2]`. Physical (qu)bits are integers. """ from __future__ import annotations from typing import List from dataclasses import dataclass from qiskit import circuit from qiskit.circuit.quantumregister import Qubit, QuantumRegister from qiskit.transpiler.exceptions import LayoutError from qiskit.converters import isinstanceint class Layout: """Two-ways dict to represent a Layout.""" __slots__ = ("_regs", "_p2v", "_v2p") def __init__(self, input_dict=None): """construct a Layout from a bijective dictionary, mapping virtual qubits to physical qubits""" self._regs = [] self._p2v = {} self._v2p = {} if input_dict is not None: if not isinstance(input_dict, dict): raise LayoutError("Layout constructor takes a dict") self.from_dict(input_dict) def __repr__(self): """Representation of a Layout""" str_list = [] for key, val in self._p2v.items(): str_list.append(f"{key}: {val},") if str_list: str_list[-1] = str_list[-1][:-1] return "Layout({\n" + "\n".join(str_list) + "\n})" def from_dict(self, input_dict): """Populates a Layout from a dictionary. The dictionary must be a bijective mapping between virtual qubits (tuple) and physical qubits (int). Args: input_dict (dict): e.g.:: {(QuantumRegister(3, 'qr'), 0): 0, (QuantumRegister(3, 'qr'), 1): 1, (QuantumRegister(3, 'qr'), 2): 2} Can be written more concisely as follows: * virtual to physical:: {qr[0]: 0, qr[1]: 1, qr[2]: 2} * physical to virtual:: {0: qr[0], 1: qr[1], 2: qr[2]} """ for key, value in input_dict.items(): virtual, physical = Layout.order_based_on_type(key, value) self._p2v[physical] = virtual if virtual is None: continue self._v2p[virtual] = physical @staticmethod def order_based_on_type(value1, value2): """decides which one is physical/virtual based on the type. Returns (virtual, physical)""" if isinstanceint(value1) and isinstance(value2, (Qubit, type(None))): physical = int(value1) virtual = value2 elif isinstanceint(value2) and isinstance(value1, (Qubit, type(None))): physical = int(value2) virtual = value1 else: raise LayoutError( "The map (%s -> %s) has to be a (Bit -> integer)" " or the other way around." % (type(value1), type(value2)) ) return virtual, physical def __getitem__(self, item): if item in self._p2v: return self._p2v[item] if item in self._v2p: return self._v2p[item] raise KeyError(f"The item {item} does not exist in the Layout") def __contains__(self, item): return item in self._p2v or item in self._v2p def __setitem__(self, key, value): virtual, physical = Layout.order_based_on_type(key, value) self._set_type_checked_item(virtual, physical) def _set_type_checked_item(self, virtual, physical): old = self._v2p.pop(virtual, None) self._p2v.pop(old, None) old = self._p2v.pop(physical, None) self._v2p.pop(old, None) self._p2v[physical] = virtual if virtual is not None: self._v2p[virtual] = physical def __delitem__(self, key): if isinstance(key, int): del self._v2p[self._p2v[key]] del self._p2v[key] elif isinstance(key, Qubit): del self._p2v[self._v2p[key]] del self._v2p[key] else: raise LayoutError( "The key to remove should be of the form" " Qubit or integer) and %s was provided" % (type(key),) ) def __len__(self): return len(self._p2v) def __eq__(self, other): if isinstance(other, Layout): return self._p2v == other._p2v and self._v2p == other._v2p return False def copy(self): """Returns a copy of a Layout instance.""" layout_copy = type(self)() layout_copy._regs = self._regs.copy() layout_copy._p2v = self._p2v.copy() layout_copy._v2p = self._v2p.copy() return layout_copy def add(self, virtual_bit, physical_bit=None): """ Adds a map element between `bit` and `physical_bit`. If `physical_bit` is not defined, `bit` will be mapped to a new physical bit. Args: virtual_bit (tuple): A (qu)bit. For example, (QuantumRegister(3, 'qr'), 2). physical_bit (int): A physical bit. For example, 3. """ if physical_bit is None: if len(self._p2v) == 0: physical_bit = 0 else: max_physical = max(self._p2v) # Fill any gaps in the existing bits for physical_candidate in range(max_physical): if physical_candidate not in self._p2v: physical_bit = physical_candidate break # If there are no free bits in the allocated physical bits add new ones else: physical_bit = max_physical + 1 self[virtual_bit] = physical_bit def add_register(self, reg): """Adds at the end physical_qubits that map each bit in reg. Args: reg (Register): A (qu)bit Register. For example, QuantumRegister(3, 'qr'). """ self._regs.append(reg) for bit in reg: if bit not in self: self.add(bit) def get_registers(self): """ Returns the registers in the layout [QuantumRegister(2, 'qr0'), QuantumRegister(3, 'qr1')] Returns: Set: A set of Registers in the layout """ return set(self._regs) def get_virtual_bits(self): """ Returns the dictionary where the keys are virtual (qu)bits and the values are physical (qu)bits. """ return self._v2p def get_physical_bits(self): """ Returns the dictionary where the keys are physical (qu)bits and the values are virtual (qu)bits. """ return self._p2v def swap(self, left, right): """Swaps the map between left and right. Args: left (tuple or int): Item to swap with right. right (tuple or int): Item to swap with left. Raises: LayoutError: If left and right have not the same type. """ if type(left) is not type(right): raise LayoutError("The method swap only works with elements of the same type.") temp = self[left] self[left] = self[right] self[right] = temp def combine_into_edge_map(self, another_layout): """Combines self and another_layout into an "edge map". For example:: self another_layout resulting edge map qr_1 -> 0 0 <- q_2 qr_1 -> q_2 qr_2 -> 2 2 <- q_1 qr_2 -> q_1 qr_3 -> 3 3 <- q_0 qr_3 -> q_0 The edge map is used to compose dags via, for example, compose. Args: another_layout (Layout): The other layout to combine. Returns: dict: A "edge map". Raises: LayoutError: another_layout can be bigger than self, but not smaller. Otherwise, raises. """ edge_map = {} for virtual, physical in self._v2p.items(): if physical not in another_layout._p2v: raise LayoutError( "The wire_map_from_layouts() method does not support when the" " other layout (another_layout) is smaller." ) edge_map[virtual] = another_layout[physical] return edge_map def reorder_bits(self, bits) -> list[int]: """Given an ordered list of bits, reorder them according to this layout. The list of bits must exactly match the virtual bits in this layout. Args: bits (list[Bit]): the bits to reorder. Returns: List: ordered bits. """ order = [0] * len(bits) # the i-th bit is now sitting in position j for i, v in enumerate(bits): j = self[v] order[i] = j return order @staticmethod def generate_trivial_layout(*regs): """Creates a trivial ("one-to-one") Layout with the registers and qubits in `regs`. Args: *regs (Registers, Qubits): registers and qubits to include in the layout. Returns: Layout: A layout with all the `regs` in the given order. """ layout = Layout() for reg in regs: if isinstance(reg, QuantumRegister): layout.add_register(reg) else: layout.add(reg) return layout @staticmethod def from_intlist(int_list, *qregs): """Converts a list of integers to a Layout mapping virtual qubits (index of the list) to physical qubits (the list values). Args: int_list (list): A list of integers. *qregs (QuantumRegisters): The quantum registers to apply the layout to. Returns: Layout: The corresponding Layout object. Raises: LayoutError: Invalid input layout. """ if not all(isinstanceint(i) for i in int_list): raise LayoutError("Expected a list of ints") if len(int_list) != len(set(int_list)): raise LayoutError("Duplicate values not permitted; Layout is bijective.") num_qubits = sum(reg.size for reg in qregs) # Check if list is too short to cover all qubits if len(int_list) != num_qubits: raise LayoutError( f"Integer list length ({len(int_list)}) must equal number of qubits " f"in circuit ({num_qubits}): {int_list}." ) out = Layout() main_idx = 0 for qreg in qregs: for idx in range(qreg.size): out[qreg[idx]] = int_list[main_idx] main_idx += 1 out.add_register(qreg) if main_idx != len(int_list): for int_item in int_list[main_idx:]: out[int_item] = None return out @staticmethod def from_qubit_list(qubit_list, *qregs): """ Populates a Layout from a list containing virtual qubits, Qubit or None. Args: qubit_list (list): e.g.: [qr[0], None, qr[2], qr[3]] *qregs (QuantumRegisters): The quantum registers to apply the layout to. Returns: Layout: the corresponding Layout object Raises: LayoutError: If the elements are not Qubit or None """ out = Layout() for physical, virtual in enumerate(qubit_list): if virtual is None: continue if isinstance(virtual, Qubit): if virtual in out._v2p: raise LayoutError("Duplicate values not permitted; Layout is bijective.") out[virtual] = physical else: raise LayoutError("The list should contain elements of the Bits or NoneTypes") for qreg in qregs: out.add_register(qreg) return out def compose(self, other: Layout, qubits: List[Qubit]) -> Layout: """Compose this layout with another layout. If this layout represents a mapping from the P-qubits to the positions of the Q-qubits, and the other layout represents a mapping from the Q-qubits to the positions of the R-qubits, then the composed layout represents a mapping from the P-qubits to the positions of the R-qubits. Args: other: The existing :class:`.Layout` to compose this :class:`.Layout` with. qubits: A list of :class:`.Qubit` objects over which ``other`` is defined, used to establish the correspondence between the positions of the ``other`` qubits and the actual qubits. Returns: A new layout object the represents this layout composed with the ``other`` layout. """ other_v2p = other.get_virtual_bits() return Layout({virt: other_v2p[qubits[phys]] for virt, phys in self._v2p.items()}) def inverse(self, source_qubits: List[Qubit], target_qubits: List[Qubit]): """Finds the inverse of this layout. This is possible when the layout is a bijective mapping, however the input and the output qubits may be different (in particular, this layout may be the mapping from the extended-with-ancillas virtual qubits to physical qubits). Thus, if this layout represents a mapping from the P-qubits to the positions of the Q-qubits, the inverse layout represents a mapping from the Q-qubits to the positions of the P-qubits. Args: source_qubits: A list of :class:`.Qubit` objects representing the domain of the layout. target_qubits: A list of :class:`.Qubit` objects representing the image of the layout. Returns: A new layout object the represents the inverse of this layout. """ source_qubit_to_position = {q: p for p, q in enumerate(source_qubits)} return Layout( { target_qubits[pos_phys]: source_qubit_to_position[virt] for virt, pos_phys in self._v2p.items() } ) def to_permutation(self, qubits: List[Qubit]): """Creates a permutation corresponding to this layout. This is possible when the layout is a bijective mapping with the same source and target qubits (for instance, a "final_layout" corresponds to a permutation of the physical circuit qubits). If this layout is a mapping from qubits to their new positions, the resulting permutation describes which qubits occupy the positions 0, 1, 2, etc. after applying the permutation. For example, suppose that the list of qubits is ``[qr_0, qr_1, qr_2]``, and the layout maps ``qr_0`` to ``2``, ``qr_1`` to ``0``, and ``qr_2`` to ``1``. In terms of positions in ``qubits``, this maps ``0`` to ``2``, ``1`` to ``0`` and ``2`` to ``1``, with the corresponding permutation being ``[1, 2, 0]``. """ perm = [None] * len(qubits) for i, q in enumerate(qubits): pos = self._v2p[q] perm[pos] = i return perm @dataclass class TranspileLayout: r"""Layout attributes for the output circuit from transpiler. The :mod:`~qiskit.transpiler` is unitary-preserving up to the "initial layout" and "final layout" permutations. The initial layout permutation is caused by setting and applying the initial layout during the :ref:`layout_stage`. The final layout permutation is caused by :class:`~.SwapGate` insertion during the :ref:`routing_stage`. This class provides an interface to reason about these permutations using a variety of helper methods. During the layout stage, the transpiler can potentially remap the order of the qubits in the circuit as it fits the circuit to the target backend. For example, let the input circuit be: .. plot: :include-source: from qiskit.circuit import QuantumCircuit, QuantumRegister qr = QuantumRegister(3, name="MyReg") qc = QuantumCircuit(qr) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.draw("mpl") Suppose that during the layout stage the transpiler reorders the qubits to be: .. plot: :include-source: from qiskit import QuantumCircuit qc = QuantumCircuit(3) qc.h(2) qc.cx(2, 1) qc.cx(2, 0) qc.draw("mpl") Then the output of the :meth:`.initial_virtual_layout` method is equivalent to:: Layout({ qr[0]: 2, qr[1]: 1, qr[2]: 0, }) (it is also this attribute in the :meth:`.QuantumCircuit.draw` and :func:`.circuit_drawer` which is used to display the mapping of qubits to positions in circuit visualizations post-transpilation). Building on the above example, suppose that during the routing stage the transpiler needs to insert swap gates, and the output circuit becomes: .. plot: :include-source: from qiskit import QuantumCircuit qc = QuantumCircuit(3) qc.h(2) qc.cx(2, 1) qc.swap(0, 1) qc.cx(2, 1) qc.draw("mpl") Then the output of the :meth:`routing_permutation` method is:: [1, 0, 2] which maps positions of qubits before routing to their final positions after routing. There are three public attributes associated with the class, however these are mostly provided for backwards compatibility and represent the internal state from the transpiler. They are defined as: * :attr:`initial_layout` - This attribute is used to model the permutation caused by the :ref:`layout_stage`. It is a :class:`~.Layout` object that maps the input :class:`~.QuantumCircuit`\s :class:`~.circuit.Qubit` objects to the position in the output :class:`.QuantumCircuit.qubits` list. * :attr:`input_qubit_mapping` - This attribute is used to retain input ordering of the original :class:`~.QuantumCircuit` object. It maps the virtual :class:`~.circuit.Qubit` object from the original circuit (and :attr:`initial_layout`) to its corresponding position in :attr:`.QuantumCircuit.qubits` in the original circuit. This is needed when computing the permutation of the :class:`Operator` of the circuit (and used by :meth:`.Operator.from_circuit`). * :attr:`final_layout` - This attribute is used to model the permutation caused by the :ref:`routing_stage`. It is a :class:`~.Layout` object that maps the output circuit's qubits from :class:`.QuantumCircuit.qubits` in the output circuit to their final positions after routing. Importantly, this only represents the permutation caused by inserting :class:`~.SwapGate`\s into the :class:`~.QuantumCircuit` during the :ref:`routing_stage`. It is **not** a mapping from the original input circuit's position to the final position at the end of the transpiled circuit. If you need this, you can use the :meth:`.final_index_layout` to generate this. If :attr:`final_layout` is set to ``None``, this indicates that routing was not run, and can be considered equivalent to a trivial layout with the qubits from the output circuit's :attr:`~.QuantumCircuit.qubits` list. """ initial_layout: Layout input_qubit_mapping: dict[circuit.Qubit, int] final_layout: Layout | None = None _input_qubit_count: int | None = None _output_qubit_list: List[Qubit] | None = None def initial_virtual_layout(self, filter_ancillas: bool = False) -> Layout: """Return a :class:`.Layout` object for the initial layout. This returns a mapping of virtual :class:`~.circuit.Qubit` objects in the input circuit to the positions of the physical qubits selected during layout. This is analogous to the :attr:`.initial_layout` attribute. Args: filter_ancillas: If set to ``True`` only qubits in the input circuit will be in the returned layout. Any ancilla qubits added to the output circuit will be filtered from the returned object. Returns: A layout object mapping the input circuit's :class:`~.circuit.Qubit` objects to the positions of the selected physical qubits. """ if not filter_ancillas: return self.initial_layout return Layout( { k: v for k, v in self.initial_layout.get_virtual_bits().items() if self.input_qubit_mapping[k] < self._input_qubit_count } ) def initial_index_layout(self, filter_ancillas: bool = False) -> List[int]: """Generate an initial layout as an array of integers. Args: filter_ancillas: If set to ``True`` any ancilla qubits added to the transpiler will not be included in the output. Return: A layout array that maps a position in the array to its new position in the output circuit. """ virtual_map = self.initial_layout.get_virtual_bits() if filter_ancillas: output = [None] * self._input_qubit_count else: output = [None] * len(virtual_map) for index, (virt, phys) in enumerate(virtual_map.items()): if filter_ancillas and index >= self._input_qubit_count: break pos = self.input_qubit_mapping[virt] output[pos] = phys return output def routing_permutation(self) -> List[int]: """Generate a final layout as an array of integers. If there is no :attr:`.final_layout` attribute present then that indicates there was no output permutation caused by routing or other transpiler transforms. In this case the function will return a list of ``[0, 1, 2, .., n]``. Returns: A layout array that maps a position in the array to its new position in the output circuit. """ if self.final_layout is None: return list(range(len(self._output_qubit_list))) virtual_map = self.final_layout.get_virtual_bits() return [virtual_map[virt] for virt in self._output_qubit_list] def final_index_layout(self, filter_ancillas: bool = True) -> List[int]: """Generate the final layout as an array of integers. This method will generate an array of final positions for each qubit in the input circuit. For example, if you had an input circuit like:: qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) and the output from the transpiler was:: tqc = QuantumCircuit(3) tqc.h(2) tqc.cx(2, 1) tqc.swap(0, 1) tqc.cx(2, 1) then the :meth:`.final_index_layout` method returns:: [2, 0, 1] This can be seen as follows. Qubit 0 in the original circuit is mapped to qubit 2 in the output circuit during the layout stage, which is mapped to qubit 2 during the routing stage. Qubit 1 in the original circuit is mapped to qubit 1 in the output circuit during the layout stage, which is mapped to qubit 0 during the routing stage. Qubit 2 in the original circuit is mapped to qubit 0 in the output circuit during the layout stage, which is mapped to qubit 1 during the routing stage. The output list length will be as wide as the input circuit's number of qubits, as the output list from this method is for tracking the permutation of qubits in the original circuit caused by the transpiler. Args: filter_ancillas: If set to ``False`` any ancillas allocated in the output circuit will be included in the layout. Returns: A list of final positions for each input circuit qubit. """ if self._input_qubit_count is None: # TODO: After there is a way to differentiate the ancilla qubits added by the transpiler # don't use the ancilla name anymore.See #10817 for discussion on this. num_source_qubits = len( [ x for x in self.input_qubit_mapping if getattr(x, "_register", "").startswith("ancilla") ] ) else: num_source_qubits = self._input_qubit_count if self._output_qubit_list is None: circuit_qubits = list(self.final_layout.get_virtual_bits()) else: circuit_qubits = self._output_qubit_list pos_to_virt = {v: k for k, v in self.input_qubit_mapping.items()} qubit_indices = [] if filter_ancillas: num_qubits = num_source_qubits else: num_qubits = len(self._output_qubit_list) for index in range(num_qubits): qubit_idx = self.initial_layout[pos_to_virt[index]] if self.final_layout is not None: qubit_idx = self.final_layout[circuit_qubits[qubit_idx]] qubit_indices.append(qubit_idx) return qubit_indices def final_virtual_layout(self, filter_ancillas: bool = True) -> Layout: """Generate the final layout as a :class:`.Layout` object. This method will generate an array of final positions for each qubit in the input circuit. For example, if you had an input circuit like:: qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) and the output from the transpiler was:: tqc = QuantumCircuit(3) tqc.h(2) tqc.cx(2, 1) tqc.swap(0, 1) tqc.cx(2, 1) then the return from this function would be a layout object:: Layout({ qc.qubits[0]: 2, qc.qubits[1]: 0, qc.qubits[2]: 1, }) This can be seen as follows. Qubit 0 in the original circuit is mapped to qubit 2 in the output circuit during the layout stage, which is mapped to qubit 2 during the routing stage. Qubit 1 in the original circuit is mapped to qubit 1 in the output circuit during the layout stage, which is mapped to qubit 0 during the routing stage. Qubit 2 in the original circuit is mapped to qubit 0 in the output circuit during the layout stage, which is mapped to qubit 1 during the routing stage. The output list length will be as wide as the input circuit's number of qubits, as the output list from this method is for tracking the permutation of qubits in the original circuit caused by the transpiler. Args: filter_ancillas: If set to ``False`` any ancillas allocated in the output circuit will be included in the layout. Returns: A layout object mapping to the final positions for each qubit. """ res = self.final_index_layout(filter_ancillas=filter_ancillas) pos_to_virt = {v: k for k, v in self.input_qubit_mapping.items()} return Layout({pos_to_virt[index]: phys for index, phys in enumerate(res)})
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A swap strategy pass for blocks of commuting gates.""" from __future__ import annotations from collections import defaultdict from qiskit.circuit import Gate, QuantumCircuit, Qubit from qiskit.converters import circuit_to_dag from qiskit.dagcircuit import DAGCircuit, DAGOpNode from qiskit.transpiler import TransformationPass, Layout, TranspilerError from qiskit.transpiler.passes.routing.commuting_2q_gate_routing.swap_strategy import SwapStrategy from qiskit.transpiler.passes.routing.commuting_2q_gate_routing.commuting_2q_block import ( Commuting2qBlock, ) class Commuting2qGateRouter(TransformationPass): """A class to swap route one or more commuting gates to the coupling map. This pass routes blocks of commuting two-qubit gates encapsulated as :class:`.Commuting2qBlock` instructions. This pass will not apply to other instructions. The mapping to the coupling map is done using swap strategies, see :class:`.SwapStrategy`. The swap strategy should suit the problem and the coupling map. This transpiler pass should ideally be executed before the quantum circuit is enlarged with any idle ancilla qubits. Otherwise we may swap qubits outside of the portion of the chip we want to use. Therefore, the swap strategy and its associated coupling map do not represent physical qubits. Instead, they represent an intermediate mapping that corresponds to the physical qubits once the initial layout is applied. The example below shows how to map a four qubit :class:`.PauliEvolutionGate` to qubits 0, 1, 3, and 4 of the five qubit device with the coupling map .. parsed-literal:: 0 -- 1 -- 2 | 3 | 4 To do this we use a line swap strategy for qubits 0, 1, 3, and 4 defined it in terms of virtual qubits 0, 1, 2, and 3. .. code-block:: python from qiskit import QuantumCircuit from qiskit.opflow import PauliSumOp from qiskit.circuit.library import PauliEvolutionGate from qiskit.transpiler import Layout, CouplingMap, PassManager from qiskit.transpiler.passes import FullAncillaAllocation from qiskit.transpiler.passes import EnlargeWithAncilla from qiskit.transpiler.passes import ApplyLayout from qiskit.transpiler.passes import SetLayout from qiskit.transpiler.passes.routing.commuting_2q_gate_routing import ( SwapStrategy, FindCommutingPauliEvolutions, Commuting2qGateRouter, ) # Define the circuit on virtual qubits op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(4)) # Define the swap strategy on qubits before the initial_layout is applied. swap_strat = SwapStrategy.from_line([0, 1, 2, 3]) # Chose qubits 0, 1, 3, and 4 from the backend coupling map shown above. backend_cmap = CouplingMap(couplinglist=[(0, 1), (1, 2), (1, 3), (3, 4)]) initial_layout = Layout.from_intlist([0, 1, 3, 4], *circ.qregs) pm_pre = PassManager( [ FindCommutingPauliEvolutions(), Commuting2qGateRouter(swap_strat), SetLayout(initial_layout), FullAncillaAllocation(backend_cmap), EnlargeWithAncilla(), ApplyLayout(), ] ) # Insert swap gates, map to initial_layout and finally enlarge with ancilla. pm_pre.run(circ).draw("mpl") This pass manager relies on the ``current_layout`` which corresponds to the qubit layout as swap gates are applied. The pass will traverse all nodes in the dag. If a node should be routed using a swap strategy then it will be decomposed into sub-instructions with swap layers in between and the ``current_layout`` will be modified. Nodes that should not be routed using swap strategies will be added back to the dag taking the ``current_layout`` into account. """ def __init__( self, swap_strategy: SwapStrategy | None = None, edge_coloring: dict[tuple[int, int], int] | None = None, ) -> None: r""" Args: swap_strategy: An instance of a :class:`.SwapStrategy` that holds the swap layers that are used, and the order in which to apply them, to map the instruction to the hardware. If this field is not given if should be contained in the property set of the pass. This allows other passes to determine the most appropriate swap strategy at run-time. edge_coloring: An optional edge coloring of the coupling map (I.e. no two edges that share a node have the same color). If the edge coloring is given then the commuting gates that can be simultaneously applied given the current qubit permutation are grouped according to the edge coloring and applied according to this edge coloring. Here, a color is an int which is used as the index to define and access the groups of commuting gates that can be applied simultaneously. If the edge coloring is not given then the sets will be built-up using a greedy algorithm. The edge coloring is useful to position gates such as ``RZZGate``\s next to swap gates to exploit CX cancellations. """ super().__init__() self._swap_strategy = swap_strategy self._bit_indices: dict[Qubit, int] | None = None self._edge_coloring = edge_coloring def run(self, dag: DAGCircuit) -> DAGCircuit: """Run the pass by decomposing the nodes it applies on. Args: dag: The dag to which we will add swaps. Returns: A dag where swaps have been added for the intended gate type. Raises: TranspilerError: If the swap strategy was not given at init time and there is no swap strategy in the property set. TranspilerError: If the quantum circuit contains more than one qubit register. TranspilerError: If there are qubits that are not contained in the quantum register. """ if self._swap_strategy is None: swap_strategy = self.property_set["swap_strategy"] if swap_strategy is None: raise TranspilerError("No swap strategy given at init or in the property set.") else: swap_strategy = self._swap_strategy if len(dag.qregs) != 1: raise TranspilerError( f"{self.__class__.__name__} runs on circuits with one quantum register." ) if len(dag.qubits) != next(iter(dag.qregs.values())).size: raise TranspilerError("Circuit has qubits not contained in the qubit register.") new_dag = dag.copy_empty_like() current_layout = Layout.generate_trivial_layout(*dag.qregs.values()) # Used to keep track of nodes that do not decompose using swap strategies. accumulator = new_dag.copy_empty_like() for node in dag.topological_op_nodes(): if isinstance(node.op, Commuting2qBlock): # Check that the swap strategy creates enough connectivity for the node. self._check_edges(dag, node, swap_strategy) # Compose any accumulated non-swap strategy gates to the dag accumulator = self._compose_non_swap_nodes(accumulator, current_layout, new_dag) # Decompose the swap-strategy node and add to the dag. new_dag.compose(self.swap_decompose(dag, node, current_layout, swap_strategy)) else: accumulator.apply_operation_back(node.op, node.qargs, node.cargs) self._compose_non_swap_nodes(accumulator, current_layout, new_dag) return new_dag def _compose_non_swap_nodes( self, accumulator: DAGCircuit, layout: Layout, new_dag: DAGCircuit ) -> DAGCircuit: """Add all the non-swap strategy nodes that we have accumulated up to now. This method also resets the node accumulator to an empty dag. Args: layout: The current layout that keeps track of the swaps. new_dag: The new dag that we are building up. accumulator: A DAG to keep track of nodes that do not decompose using swap strategies. Returns: A new accumulator with the same registers as ``new_dag``. """ # Add all the non-swap strategy nodes that we have accumulated up to now. order = layout.reorder_bits(new_dag.qubits) order_bits: list[int | None] = [None] * len(layout) for idx, val in enumerate(order): order_bits[val] = idx new_dag.compose(accumulator, qubits=order_bits) # Re-initialize the node accumulator return new_dag.copy_empty_like() def _position_in_cmap(self, dag: DAGCircuit, j: int, k: int, layout: Layout) -> tuple[int, ...]: """A helper function to track the movement of virtual qubits through the swaps. Args: j: The index of decision variable j (i.e. virtual qubit). k: The index of decision variable k (i.e. virtual qubit). layout: The current layout that takes into account previous swap gates. Returns: The position in the coupling map of the virtual qubits j and k as a tuple. """ bit0 = dag.find_bit(layout.get_physical_bits()[j]).index bit1 = dag.find_bit(layout.get_physical_bits()[k]).index return bit0, bit1 def _build_sub_layers( self, current_layer: dict[tuple[int, int], Gate] ) -> list[dict[tuple[int, int], Gate]]: """A helper method to build-up sets of gates to simultaneously apply. This is done with an edge coloring if the ``edge_coloring`` init argument was given or with a greedy algorithm if not. With an edge coloring all gates on edges with the same color will be applied simultaneously. These sublayers are applied in the order of their color, which is an int, in increasing color order. Args: current_layer: All gates in the current layer can be applied given the qubit ordering of the current layout. However, not all gates in the current layer can be applied simultaneously. This function creates sub-layers by building up sub-layers of gates. All gates in a sub-layer can simultaneously be applied given the coupling map and current qubit configuration. Returns: A list of gate dicts that can be applied. The gates a position 0 are applied first. A gate dict has the qubit tuple as key and the gate to apply as value. """ if self._edge_coloring is not None: return self._edge_coloring_build_sub_layers(current_layer) else: return self._greedy_build_sub_layers(current_layer) def _edge_coloring_build_sub_layers( self, current_layer: dict[tuple[int, int], Gate] ) -> list[dict[tuple[int, int], Gate]]: """The edge coloring method of building sub-layers of commuting gates.""" sub_layers: list[dict[tuple[int, int], Gate]] = [ {} for _ in set(self._edge_coloring.values()) ] for edge, gate in current_layer.items(): color = self._edge_coloring[edge] sub_layers[color][edge] = gate return sub_layers @staticmethod def _greedy_build_sub_layers( current_layer: dict[tuple[int, int], Gate] ) -> list[dict[tuple[int, int], Gate]]: """The greedy method of building sub-layers of commuting gates.""" sub_layers = [] while len(current_layer) > 0: current_sub_layer, remaining_gates = {}, {} blocked_vertices: set[tuple] = set() for edge, evo_gate in current_layer.items(): if blocked_vertices.isdisjoint(edge): current_sub_layer[edge] = evo_gate # A vertex becomes blocked once a gate is applied to it. blocked_vertices = blocked_vertices.union(edge) else: remaining_gates[edge] = evo_gate current_layer = remaining_gates sub_layers.append(current_sub_layer) return sub_layers def swap_decompose( self, dag: DAGCircuit, node: DAGOpNode, current_layout: Layout, swap_strategy: SwapStrategy ) -> DAGCircuit: """Take an instance of :class:`.Commuting2qBlock` and map it to the coupling map. The mapping is done with the swap strategy. Args: dag: The dag which contains the :class:`.Commuting2qBlock` we route. node: A node whose operation is a :class:`.Commuting2qBlock`. current_layout: The layout before the swaps are applied. This function will modify the layout so that subsequent gates can be properly composed on the dag. swap_strategy: The swap strategy used to decompose the node. Returns: A dag that is compatible with the coupling map where swap gates have been added to map the gates in the :class:`.Commuting2qBlock` to the hardware. """ trivial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) gate_layers = self._make_op_layers(dag, node.op, current_layout, swap_strategy) # Iterate over and apply gate layers max_distance = max(gate_layers.keys()) circuit_with_swap = QuantumCircuit(len(dag.qubits)) for i in range(max_distance + 1): # Get current layer and replace the problem indices j,k by the corresponding # positions in the coupling map. The current layer corresponds # to all the gates that can be applied at the ith swap layer. current_layer = {} for (j, k), local_gate in gate_layers.get(i, {}).items(): current_layer[self._position_in_cmap(dag, j, k, current_layout)] = local_gate # Not all gates that are applied at the ith swap layer can be applied at the same # time. We therefore greedily build sub-layers. sub_layers = self._build_sub_layers(current_layer) # Apply sub-layers for sublayer in sub_layers: for edge, local_gate in sublayer.items(): circuit_with_swap.append(local_gate, edge) # Apply SWAP gates if i < max_distance: for swap in swap_strategy.swap_layer(i): (j, k) = [trivial_layout.get_physical_bits()[vertex] for vertex in swap] circuit_with_swap.swap(j, k) current_layout.swap(j, k) return circuit_to_dag(circuit_with_swap) def _make_op_layers( self, dag: DAGCircuit, op: Commuting2qBlock, layout: Layout, swap_strategy: SwapStrategy ) -> dict[int, dict[tuple, Gate]]: """Creates layers of two-qubit gates based on the distance in the swap strategy.""" gate_layers: dict[int, dict[tuple, Gate]] = defaultdict(dict) for node in op.node_block: edge = (dag.find_bit(node.qargs[0]).index, dag.find_bit(node.qargs[1]).index) bit0 = layout.get_virtual_bits()[dag.qubits[edge[0]]] bit1 = layout.get_virtual_bits()[dag.qubits[edge[1]]] distance = swap_strategy.distance_matrix[bit0, bit1] gate_layers[distance][edge] = node.op return gate_layers def _check_edges(self, dag: DAGCircuit, node: DAGOpNode, swap_strategy: SwapStrategy): """Check if the swap strategy can create the required connectivity. Args: node: The dag node for which to check if the swap strategy provides enough connectivity. swap_strategy: The swap strategy that is being used. Raises: TranspilerError: If there is an edge that the swap strategy cannot accommodate and if the pass has been configured to raise on such issues. """ required_edges = set() for sub_node in node.op: edge = (dag.find_bit(sub_node.qargs[0]).index, dag.find_bit(sub_node.qargs[1]).index) required_edges.add(edge) # Check that the swap strategy supports all required edges if not required_edges.issubset(swap_strategy.possible_edges): raise TranspilerError( f"{swap_strategy} cannot implement all edges in {required_edges}." )
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2024. # # 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. """Dynamical Decoupling insertion pass.""" import itertools import numpy as np from qiskit.circuit import Gate, Delay, Reset from qiskit.circuit.library.standard_gates import IGate, UGate, U3Gate from qiskit.dagcircuit import DAGOpNode, DAGInNode from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.synthesis.one_qubit import OneQubitEulerDecomposer from qiskit.transpiler import InstructionDurations from qiskit.transpiler.passes.optimization import Optimize1qGates from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.exceptions import TranspilerError from qiskit.utils.deprecation import deprecate_func class DynamicalDecoupling(TransformationPass): """Dynamical decoupling insertion pass. This pass works on a scheduled, physical circuit. It scans the circuit for idle periods of time (i.e. those containing delay instructions) and inserts a DD sequence of gates in those spots. These gates amount to the identity, so do not alter the logical action of the circuit, but have the effect of mitigating decoherence in those idle periods. As a special case, the pass allows a length-1 sequence (e.g. [XGate()]). In this case the DD insertion happens only when the gate inverse can be absorbed into a neighboring gate in the circuit (so we would still be replacing Delay with something that is equivalent to the identity). This can be used, for instance, as a Hahn echo. This pass ensures that the inserted sequence preserves the circuit exactly (including global phase). .. plot:: :include-source: import numpy as np from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import XGate from qiskit.transpiler import PassManager, InstructionDurations from qiskit.transpiler.passes import ALAPSchedule, DynamicalDecoupling from qiskit.visualization import timeline_drawer # Because the legacy passes do not propagate the scheduling information correctly, it is # necessary to run a no-op "re-schedule" before the output circuits can be drawn. def draw(circuit): from qiskit import transpile scheduled = transpile( circuit, optimization_level=0, instruction_durations=InstructionDurations(), scheduling_method="alap", ) return timeline_drawer(scheduled) circ = QuantumCircuit(4) circ.h(0) circ.cx(0, 1) circ.cx(1, 2) circ.cx(2, 3) circ.measure_all() durations = InstructionDurations( [("h", 0, 50), ("cx", [0, 1], 700), ("reset", None, 10), ("cx", [1, 2], 200), ("cx", [2, 3], 300), ("x", None, 50), ("measure", None, 1000)] ) # balanced X-X sequence on all qubits dd_sequence = [XGate(), XGate()] pm = PassManager([ALAPSchedule(durations), DynamicalDecoupling(durations, dd_sequence)]) circ_dd = pm.run(circ) draw(circ_dd) # Uhrig sequence on qubit 0 n = 8 dd_sequence = [XGate()] * n def uhrig_pulse_location(k): return np.sin(np.pi * (k + 1) / (2 * n + 2)) ** 2 spacing = [] for k in range(n): spacing.append(uhrig_pulse_location(k) - sum(spacing)) spacing.append(1 - sum(spacing)) pm = PassManager( [ ALAPSchedule(durations), DynamicalDecoupling(durations, dd_sequence, qubits=[0], spacing=spacing), ] ) circ_dd = pm.run(circ) draw(circ_dd) """ @deprecate_func( additional_msg=( "Instead, use :class:`~.PadDynamicalDecoupling`, which performs the same " "function but requires scheduling and alignment analysis passes to run prior to it." ), since="1.1.0", ) def __init__( self, durations, dd_sequence, qubits=None, spacing=None, skip_reset_qubits=True, target=None ): """Dynamical decoupling initializer. Args: durations (InstructionDurations): Durations of instructions to be used in scheduling. dd_sequence (list[Gate]): sequence of gates to apply in idle spots. qubits (list[int]): physical qubits on which to apply DD. If None, all qubits will undergo DD (when possible). spacing (list[float]): a list of spacings between the DD gates. The available slack will be divided according to this. The list length must be one more than the length of dd_sequence, and the elements must sum to 1. If None, a balanced spacing will be used [d/2, d, d, ..., d, d, d/2]. skip_reset_qubits (bool): if True, does not insert DD on idle periods that immediately follow initialized/reset qubits (as qubits in the ground state are less susceptile to decoherence). target (Target): The :class:`~.Target` representing the target backend, if both ``durations`` and this are specified then this argument will take precedence and ``durations`` will be ignored. """ super().__init__() self._durations = durations self._dd_sequence = dd_sequence self._qubits = qubits self._spacing = spacing self._skip_reset_qubits = skip_reset_qubits self._target = target if target is not None: self._durations = target.durations() for gate in dd_sequence: if gate.name not in target.operation_names: raise TranspilerError( f"{gate.name} in dd_sequence is not supported in the target" ) def run(self, dag): """Run the DynamicalDecoupling pass on dag. Args: dag (DAGCircuit): a scheduled DAG. Returns: DAGCircuit: equivalent circuit with delays interrupted by DD, where possible. Raises: TranspilerError: if the circuit is not mapped on physical qubits. """ if len(dag.qregs) != 1 or dag.qregs.get("q", None) is None: raise TranspilerError("DD runs on physical circuits only.") if dag.duration is None: raise TranspilerError("DD runs after circuit is scheduled.") durations = self._update_inst_durations(dag) num_pulses = len(self._dd_sequence) sequence_gphase = 0 if num_pulses != 1: if num_pulses % 2 != 0: raise TranspilerError("DD sequence must contain an even number of gates (or 1).") noop = np.eye(2) for gate in self._dd_sequence: noop = noop.dot(gate.to_matrix()) if not matrix_equal(noop, IGate().to_matrix(), ignore_phase=True): raise TranspilerError("The DD sequence does not make an identity operation.") sequence_gphase = np.angle(noop[0][0]) if self._qubits is None: self._qubits = set(range(dag.num_qubits())) else: self._qubits = set(self._qubits) if self._spacing: if sum(self._spacing) != 1 or any(a < 0 for a in self._spacing): raise TranspilerError( "The spacings must be given in terms of fractions " "of the slack period and sum to 1." ) else: # default to balanced spacing mid = 1 / num_pulses end = mid / 2 self._spacing = [end] + [mid] * (num_pulses - 1) + [end] for qarg in list(self._qubits): for gate in self._dd_sequence: if not self.__gate_supported(gate, qarg): self._qubits.discard(qarg) break index_sequence_duration_map = {} for physical_qubit in self._qubits: dd_sequence_duration = 0 for index, gate in enumerate(self._dd_sequence): gate = gate.to_mutable() self._dd_sequence[index] = gate gate.duration = durations.get(gate, physical_qubit) dd_sequence_duration += gate.duration index_sequence_duration_map[physical_qubit] = dd_sequence_duration new_dag = dag.copy_empty_like() for nd in dag.topological_op_nodes(): if not isinstance(nd.op, Delay): new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs, check=False) continue dag_qubit = nd.qargs[0] physical_qubit = dag.find_bit(dag_qubit).index if physical_qubit not in self._qubits: # skip unwanted qubits new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs, check=False) continue pred = next(dag.predecessors(nd)) succ = next(dag.successors(nd)) if self._skip_reset_qubits: # discount initial delays if isinstance(pred, DAGInNode) or isinstance(pred.op, Reset): new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs, check=False) continue dd_sequence_duration = index_sequence_duration_map[physical_qubit] slack = nd.op.duration - dd_sequence_duration if slack <= 0: # dd doesn't fit new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs, check=False) continue if num_pulses == 1: # special case of using a single gate for DD u_inv = self._dd_sequence[0].inverse().to_matrix() theta, phi, lam, phase = OneQubitEulerDecomposer().angles_and_phase(u_inv) # absorb the inverse into the successor (from left in circuit) if isinstance(succ, DAGOpNode) and isinstance(succ.op, (UGate, U3Gate)): theta_r, phi_r, lam_r = succ.op.params succ.op.params = Optimize1qGates.compose_u3( theta_r, phi_r, lam_r, theta, phi, lam ) sequence_gphase += phase # absorb the inverse into the predecessor (from right in circuit) elif isinstance(pred, DAGOpNode) and isinstance(pred.op, (UGate, U3Gate)): theta_l, phi_l, lam_l = pred.op.params pred.op.params = Optimize1qGates.compose_u3( theta, phi, lam, theta_l, phi_l, lam_l ) sequence_gphase += phase # don't do anything if there's no single-qubit gate to absorb the inverse else: new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs, check=False) continue # insert the actual DD sequence taus = [int(slack * a) for a in self._spacing] unused_slack = slack - sum(taus) # unused, due to rounding to int multiples of dt middle_index = int((len(taus) - 1) / 2) # arbitrary: redistribute to middle taus[middle_index] += unused_slack # now we add up to original delay duration for tau, gate in itertools.zip_longest(taus, self._dd_sequence): if tau > 0: new_dag.apply_operation_back(Delay(tau), [dag_qubit], check=False) if gate is not None: new_dag.apply_operation_back(gate, [dag_qubit], check=False) new_dag.global_phase = new_dag.global_phase + sequence_gphase return new_dag def _update_inst_durations(self, dag): """Update instruction durations with circuit information. If the dag contains gate calibrations and no instruction durations were provided through the target or as a standalone input, the circuit calibration durations will be used. The priority order for instruction durations is: target > standalone > circuit. """ circ_durations = InstructionDurations() if dag.calibrations: cal_durations = [] for gate, gate_cals in dag.calibrations.items(): for (qubits, parameters), schedule in gate_cals.items(): cal_durations.append((gate, qubits, parameters, schedule.duration)) circ_durations.update(cal_durations, circ_durations.dt) if self._durations is not None: circ_durations.update(self._durations, getattr(self._durations, "dt", None)) return circ_durations def __gate_supported(self, gate: Gate, qarg: int) -> bool: """A gate is supported on the qubit (qarg) or not.""" if self._target is None or self._target.instruction_supported(gate.name, qargs=(qarg,)): return True return False
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Filter ops from a circuit""" from typing import Callable from qiskit.dagcircuit import DAGCircuit, DAGOpNode from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.passes.utils import control_flow class FilterOpNodes(TransformationPass): """Remove all operations that match a filter function This transformation pass is used to remove any operations that matches a the provided filter function. Args: predicate: A given callable that will be passed the :class:`.DAGOpNode` for each node in the :class:`.DAGCircuit`. If the callable returns ``True`` the :class:`.DAGOpNode` is retained in the circuit and if it returns ``False`` it is removed from the circuit. Example: Filter out operations that are labelled ``"foo"`` .. plot:: :include-source: from qiskit import QuantumCircuit from qiskit.transpiler.passes import FilterOpNodes circuit = QuantumCircuit(1) circuit.x(0, label='foo') circuit.barrier() circuit.h(0) circuit = FilterOpNodes( lambda node: getattr(node.op, "label") != "foo" )(circuit) circuit.draw('mpl') """ def __init__(self, predicate: Callable[[DAGOpNode], bool]): super().__init__() self.predicate = predicate @control_flow.trivial_recurse def run(self, dag: DAGCircuit) -> DAGCircuit: """Run the RemoveBarriers pass on `dag`.""" for node in dag.op_nodes(): if not self.predicate(node): dag.remove_op_node(node) return dag
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Remove all barriers in a circuit""" from qiskit.dagcircuit import DAGCircuit from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.passes.utils import control_flow class RemoveBarriers(TransformationPass): """Return a circuit with any barrier removed. This transformation is not semantics preserving. Example: .. plot:: :include-source: from qiskit import QuantumCircuit from qiskit.transpiler.passes import RemoveBarriers circuit = QuantumCircuit(1) circuit.x(0) circuit.barrier() circuit.h(0) circuit = RemoveBarriers()(circuit) circuit.draw('mpl') """ @control_flow.trivial_recurse def run(self, dag: DAGCircuit) -> DAGCircuit: """Run the RemoveBarriers pass on `dag`.""" dag.remove_all_ops_named("barrier") return dag
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names # of its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ############################################################################### """ Routines for running Python functions in parallel using process pools from the multiprocessing library. """ import os from concurrent.futures import ProcessPoolExecutor import sys from qiskit.exceptions import QiskitError from qiskit.utils.multiprocessing import local_hardware_info from qiskit.tools.events.pubsub import Publisher from qiskit import user_config def get_platform_parallel_default(): """ Returns the default parallelism flag value for the current platform. Returns: parallel_default: The default parallelism flag value for the current platform. """ # Default False on Windows if sys.platform == "win32": parallel_default = False # On macOS default false on Python >=3.8 elif sys.platform == "darwin": parallel_default = False # On linux (and other OSes) default to True else: parallel_default = True return parallel_default CONFIG = user_config.get_config() if os.getenv("QISKIT_PARALLEL", None) is not None: PARALLEL_DEFAULT = os.getenv("QISKIT_PARALLEL", None).lower() == "true" else: PARALLEL_DEFAULT = get_platform_parallel_default() # Set parallel flag if os.getenv("QISKIT_IN_PARALLEL") is None: os.environ["QISKIT_IN_PARALLEL"] = "FALSE" if os.getenv("QISKIT_NUM_PROCS") is not None: CPU_COUNT = int(os.getenv("QISKIT_NUM_PROCS")) else: CPU_COUNT = CONFIG.get("num_process", local_hardware_info()["cpus"]) def _task_wrapper(param): (task, value, task_args, task_kwargs) = param return task(value, *task_args, **task_kwargs) def parallel_map( # pylint: disable=dangerous-default-value task, values, task_args=(), task_kwargs={}, num_processes=CPU_COUNT ): """ Parallel execution of a mapping of `values` to the function `task`. This is functionally equivalent to:: result = [task(value, *task_args, **task_kwargs) for value in values] On Windows this function defaults to a serial implementation to avoid the overhead from spawning processes in Windows. Args: task (func): Function that is to be called for each value in ``values``. values (array_like): List or array of values for which the ``task`` function is to be evaluated. task_args (list): Optional additional arguments to the ``task`` function. task_kwargs (dict): Optional additional keyword argument to the ``task`` function. num_processes (int): Number of processes to spawn. Returns: result: The result list contains the value of ``task(value, *task_args, **task_kwargs)`` for each value in ``values``. Raises: QiskitError: If user interrupts via keyboard. Events: terra.parallel.start: The collection of parallel tasks are about to start. terra.parallel.update: One of the parallel task has finished. terra.parallel.finish: All the parallel tasks have finished. Examples: .. code-block:: python import time from qiskit.tools.parallel import parallel_map def func(_): time.sleep(0.1) return 0 parallel_map(func, list(range(10))); """ if len(values) == 0: return [] if len(values) == 1: return [task(values[0], *task_args, **task_kwargs)] Publisher().publish("terra.parallel.start", len(values)) nfinished = [0] def _callback(_): nfinished[0] += 1 Publisher().publish("terra.parallel.done", nfinished[0]) # Run in parallel if not Win and not in parallel already if ( num_processes > 1 and os.getenv("QISKIT_IN_PARALLEL") == "FALSE" and CONFIG.get("parallel_enabled", PARALLEL_DEFAULT) ): os.environ["QISKIT_IN_PARALLEL"] = "TRUE" try: results = [] with ProcessPoolExecutor(max_workers=num_processes) as executor: param = ((task, value, task_args, task_kwargs) for value in values) future = executor.map(_task_wrapper, param) results = list(future) Publisher().publish("terra.parallel.done", len(results)) except (KeyboardInterrupt, Exception) as error: if isinstance(error, KeyboardInterrupt): Publisher().publish("terra.parallel.finish") os.environ["QISKIT_IN_PARALLEL"] = "FALSE" raise QiskitError("Keyboard interrupt in parallel_map.") from error # Otherwise just reset parallel flag and error os.environ["QISKIT_IN_PARALLEL"] = "FALSE" raise error Publisher().publish("terra.parallel.finish") os.environ["QISKIT_IN_PARALLEL"] = "FALSE" return results # Cannot do parallel on Windows , if another parallel_map is running in parallel, # or len(values) == 1. results = [] for _, value in enumerate(values): result = task(value, *task_args, **task_kwargs) results.append(result) _callback(0) Publisher().publish("terra.parallel.finish") return results
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """ Visualization function for DAG circuit representation. """ from rustworkx.visualization import graphviz_draw from qiskit.dagcircuit.dagnode import DAGOpNode, DAGInNode, DAGOutNode from qiskit.circuit import Qubit from qiskit.utils import optionals as _optionals from qiskit.exceptions import InvalidFileError from .exceptions import VisualizationError @_optionals.HAS_GRAPHVIZ.require_in_call def dag_drawer(dag, scale=0.7, filename=None, style="color"): """Plot the directed acyclic graph (dag) to represent operation dependencies in a quantum circuit. This function calls the :func:`~rustworkx.visualization.graphviz_draw` function from the ``rustworkx`` package to draw the DAG. Args: dag (DAGCircuit): The dag to draw. scale (float): scaling factor filename (str): file path to save image to (format inferred from name) style (str): 'plain': B&W graph 'color' (default): color input/output/op nodes Returns: PIL.Image: if in Jupyter notebook and not saving to file, otherwise None. Raises: VisualizationError: when style is not recognized. InvalidFileError: when filename provided is not valid Example: .. plot:: :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.visualization import dag_drawer q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) dag_drawer(dag) """ # NOTE: use type str checking to avoid potential cyclical import # the two tradeoffs ere that it will not handle subclasses and it is # slower (which doesn't matter for a visualization function) type_str = str(type(dag)) if "DAGDependency" in type_str: graph_attrs = {"dpi": str(100 * scale)} def node_attr_func(node): if style == "plain": return {} if style == "color": n = {} n["label"] = str(node.node_id) + ": " + str(node.name) if node.name == "measure": n["color"] = "blue" n["style"] = "filled" n["fillcolor"] = "lightblue" if node.name == "barrier": n["color"] = "black" n["style"] = "filled" n["fillcolor"] = "green" if getattr(node.op, "_directive", False): n["color"] = "black" n["style"] = "filled" n["fillcolor"] = "red" if getattr(node.op, "condition", None): n["label"] = str(node.node_id) + ": " + str(node.name) + " (conditional)" n["color"] = "black" n["style"] = "filled" n["fillcolor"] = "lightgreen" return n else: raise VisualizationError("Unrecognized style %s for the dag_drawer." % style) edge_attr_func = None else: register_bit_labels = { bit: f"{reg.name}[{idx}]" for reg in list(dag.qregs.values()) + list(dag.cregs.values()) for (idx, bit) in enumerate(reg) } graph_attrs = {"dpi": str(100 * scale)} def node_attr_func(node): if style == "plain": return {} if style == "color": n = {} if isinstance(node, DAGOpNode): n["label"] = node.name n["color"] = "blue" n["style"] = "filled" n["fillcolor"] = "lightblue" if isinstance(node, DAGInNode): if isinstance(node.wire, Qubit): label = register_bit_labels.get( node.wire, f"q_{dag.find_bit(node.wire).index}" ) else: label = register_bit_labels.get( node.wire, f"c_{dag.find_bit(node.wire).index}" ) n["label"] = label n["color"] = "black" n["style"] = "filled" n["fillcolor"] = "green" if isinstance(node, DAGOutNode): if isinstance(node.wire, Qubit): label = register_bit_labels.get( node.wire, f"q[{dag.find_bit(node.wire).index}]" ) else: label = register_bit_labels.get( node.wire, f"c[{dag.find_bit(node.wire).index}]" ) n["label"] = label n["color"] = "black" n["style"] = "filled" n["fillcolor"] = "red" return n else: raise VisualizationError("Invalid style %s" % style) def edge_attr_func(edge): e = {} if isinstance(edge, Qubit): label = register_bit_labels.get(edge, f"q_{dag.find_bit(edge).index}") else: label = register_bit_labels.get(edge, f"c_{dag.find_bit(edge).index}") e["label"] = label return e image_type = None if filename: if "." not in filename: raise InvalidFileError("Parameter 'filename' must be in format 'name.extension'") image_type = filename.split(".")[-1] return graphviz_draw( dag._multi_graph, node_attr_func, edge_attr_func, graph_attrs, filename, image_type, )
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A module for visualizing device coupling maps.""" import math from typing import List import numpy as np from qiskit.exceptions import MissingOptionalLibraryError, QiskitError from qiskit.providers.backend import BackendV2 from qiskit.tools.visualization import HAS_MATPLOTLIB, VisualizationError from qiskit.visualization.utils import matplotlib_close_if_inline def plot_gate_map( backend, figsize=None, plot_directed=False, label_qubits=True, qubit_size=None, line_width=4, font_size=None, qubit_color=None, qubit_labels=None, line_color=None, font_color="w", ax=None, filename=None, qubit_coordinates=None, ): """Plots the gate map of a device. Args: backend (BaseBackend): The backend instance that will be used to plot the device gate map. figsize (tuple): Output figure size (wxh) in inches. plot_directed (bool): Plot directed coupling map. label_qubits (bool): Label the qubits. qubit_size (float): Size of qubit marker. line_width (float): Width of lines. font_size (int): Font size of qubit labels. qubit_color (list): A list of colors for the qubits qubit_labels (list): A list of qubit labels line_color (list): A list of colors for each line from coupling_map. font_color (str): The font color for the qubit labels. ax (Axes): A Matplotlib axes instance. filename (str): file path to save image to. Returns: Figure: A Matplotlib figure instance. Raises: QiskitError: if tried to pass a simulator, or if the backend is None, but one of num_qubits, mpl_data, or cmap is None. MissingOptionalLibraryError: if matplotlib not installed. Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: from qiskit import QuantumCircuit, execute, IBMQ from qiskit.visualization import plot_gate_map %matplotlib inline provider = IBMQ.load_account() accountProvider = IBMQ.get_provider(hub='ibm-q') backend = accountProvider.get_backend('ibmq_vigo') plot_gate_map(backend) """ if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_gate_map", pip_install="pip install matplotlib", ) if isinstance(backend, BackendV2): pass elif backend.configuration().simulator: raise QiskitError("Requires a device backend, not simulator.") qubit_coordinates_map = {} qubit_coordinates_map[1] = [[0, 0]] qubit_coordinates_map[5] = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]] qubit_coordinates_map[7] = [[0, 0], [0, 1], [0, 2], [1, 1], [2, 0], [2, 1], [2, 2]] qubit_coordinates_map[20] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 1], [1, 2], [1, 3], [1, 4], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [3, 3], [3, 4], ] qubit_coordinates_map[15] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 7], [1, 6], [1, 5], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], ] qubit_coordinates_map[16] = [ [1, 0], [1, 1], [2, 1], [3, 1], [1, 2], [3, 2], [0, 3], [1, 3], [3, 3], [4, 3], [1, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6], ] qubit_coordinates_map[27] = [ [1, 0], [1, 1], [2, 1], [3, 1], [1, 2], [3, 2], [0, 3], [1, 3], [3, 3], [4, 3], [1, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6], [3, 6], [0, 7], [1, 7], [3, 7], [4, 7], [1, 8], [3, 8], [1, 9], [2, 9], [3, 9], [3, 10], ] qubit_coordinates_map[28] = [ [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 2], [1, 6], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [3, 0], [3, 4], [3, 8], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], ] qubit_coordinates_map[53] = [ [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 2], [1, 6], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [3, 0], [3, 4], [3, 8], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [5, 2], [5, 6], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [7, 0], [7, 4], [7, 8], [8, 0], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [9, 2], [9, 6], ] qubit_coordinates_map[65] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [1, 0], [1, 4], [1, 8], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [2, 9], [2, 10], [3, 2], [3, 6], [3, 10], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [4, 9], [4, 10], [5, 0], [5, 4], [5, 8], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [6, 9], [6, 10], [7, 2], [7, 6], [7, 10], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [8, 9], [8, 10], ] if isinstance(backend, BackendV2): num_qubits = backend.num_qubits coupling_map = backend.plot_coupling_map else: config = backend.configuration() num_qubits = config.n_qubits coupling_map = config.coupling_map # don't reference dictionary if provided as a parameter if qubit_coordinates is None: qubit_coordinates = qubit_coordinates_map.get(num_qubits) # try to adjust num_qubits to match the next highest hardcoded grid size if qubit_coordinates is None: if any([num_qubits < key for key in qubit_coordinates_map.keys()]): num_qubits_roundup = max(qubit_coordinates_map.keys()) for key in qubit_coordinates_map.keys(): if key < num_qubits_roundup and key > num_qubits: num_qubits_roundup = key qubit_coordinates = qubit_coordinates_map.get(num_qubits_roundup) return plot_coupling_map( num_qubits, qubit_coordinates, coupling_map, figsize, plot_directed, label_qubits, qubit_size, line_width, font_size, qubit_color, qubit_labels, line_color, font_color, ax, filename, ) def plot_coupling_map( num_qubits: int, qubit_coordinates: List[List[int]], coupling_map: List[List[int]], figsize=None, plot_directed=False, label_qubits=True, qubit_size=None, line_width=4, font_size=None, qubit_color=None, qubit_labels=None, line_color=None, font_color="w", ax=None, filename=None, ): """Plots an arbitrary coupling map of qubits (embedded in a plane). Args: num_qubits (int): The number of qubits defined and plotted. qubit_coordinates (List[List[int]]): A list of two-element lists, with entries of each nested list being the planar coordinates in a 0-based square grid where each qubit is located. coupling_map (List[List[int]]): A list of two-element lists, with entries of each nested list being the qubit numbers of the bonds to be plotted. figsize (tuple): Output figure size (wxh) in inches. plot_directed (bool): Plot directed coupling map. label_qubits (bool): Label the qubits. qubit_size (float): Size of qubit marker. line_width (float): Width of lines. font_size (int): Font size of qubit labels. qubit_color (list): A list of colors for the qubits qubit_labels (list): A list of qubit labels line_color (list): A list of colors for each line from coupling_map. font_color (str): The font color for the qubit labels. ax (Axes): A Matplotlib axes instance. filename (str): file path to save image to. Returns: Figure: A Matplotlib figure instance. Raises: MissingOptionalLibraryError: if matplotlib not installed. QiskitError: If length of qubit labels does not match number of qubits. Example: .. jupyter-execute:: from qiskit.visualization import plot_coupling_map %matplotlib inline num_qubits = 8 coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]] qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]] plot_coupling_map(num_qubits, coupling_map, qubit_coordinates) """ if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_coupling_map", pip_install="pip install matplotlib", ) import matplotlib.patches as mpatches import matplotlib.pyplot as plt input_axes = False if ax: input_axes = True if font_size is None: font_size = 12 if qubit_size is None: qubit_size = 24 if num_qubits > 20: qubit_size = 28 font_size = 10 if qubit_labels is None: qubit_labels = list(range(num_qubits)) else: if len(qubit_labels) != num_qubits: raise QiskitError("Length of qubit labels does not equal number of qubits.") if qubit_coordinates is not None: grid_data = qubit_coordinates else: if not input_axes: fig, ax = plt.subplots(figsize=(5, 5)) ax.axis("off") if filename: fig.savefig(filename) return fig x_max = max(d[1] for d in grid_data) y_max = max(d[0] for d in grid_data) max_dim = max(x_max, y_max) if figsize is None: if num_qubits == 1 or (x_max / max_dim > 0.33 and y_max / max_dim > 0.33): figsize = (5, 5) else: figsize = (9, 3) if ax is None: fig, ax = plt.subplots(figsize=figsize) ax.axis("off") # set coloring if qubit_color is None: qubit_color = ["#648fff"] * num_qubits if line_color is None: line_color = ["#648fff"] * len(coupling_map) if coupling_map else [] # Add lines for couplings if num_qubits != 1: for ind, edge in enumerate(coupling_map): is_symmetric = False if edge[::-1] in coupling_map: is_symmetric = True y_start = grid_data[edge[0]][0] x_start = grid_data[edge[0]][1] y_end = grid_data[edge[1]][0] x_end = grid_data[edge[1]][1] if is_symmetric: if y_start == y_end: x_end = (x_end - x_start) / 2 + x_start elif x_start == x_end: y_end = (y_end - y_start) / 2 + y_start else: x_end = (x_end - x_start) / 2 + x_start y_end = (y_end - y_start) / 2 + y_start ax.add_artist( plt.Line2D( [x_start, x_end], [-y_start, -y_end], color=line_color[ind], linewidth=line_width, zorder=0, ) ) if plot_directed: dx = x_end - x_start dy = y_end - y_start if is_symmetric: x_arrow = x_start + dx * 0.95 y_arrow = -y_start - dy * 0.95 dx_arrow = dx * 0.01 dy_arrow = -dy * 0.01 head_width = 0.15 else: x_arrow = x_start + dx * 0.5 y_arrow = -y_start - dy * 0.5 dx_arrow = dx * 0.2 dy_arrow = -dy * 0.2 head_width = 0.2 ax.add_patch( mpatches.FancyArrow( x_arrow, y_arrow, dx_arrow, dy_arrow, head_width=head_width, length_includes_head=True, edgecolor=None, linewidth=0, facecolor=line_color[ind], zorder=1, ) ) # Add circles for qubits for var, idx in enumerate(grid_data): # add check if num_qubits had been rounded up if var >= num_qubits: break _idx = [idx[1], -idx[0]] ax.add_artist( mpatches.Ellipse( _idx, qubit_size / 48, qubit_size / 48, # This is here so that the changes color=qubit_color[var], zorder=1, ) ) # to how qubits are plotted does if label_qubits: # not affect qubit size kwarg. ax.text( *_idx, s=qubit_labels[var], horizontalalignment="center", verticalalignment="center", color=font_color, size=font_size, weight="bold", ) ax.set_xlim([-1, x_max + 1]) ax.set_ylim([-(y_max + 1), 1]) ax.set_aspect("equal") if not input_axes: matplotlib_close_if_inline(fig) if filename: fig.savefig(filename) return fig return None def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None): """Plot the layout of a circuit transpiled for a given target backend. Args: circuit (QuantumCircuit): Input quantum circuit. backend (BaseBackend): Target backend. view (str): Layout view: either 'virtual' or 'physical'. Returns: Figure: A matplotlib figure showing layout. Raises: QiskitError: Invalid view type given. VisualizationError: Circuit has no layout attribute. Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: import numpy as np from qiskit import QuantumCircuit, IBMQ, transpile from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt %matplotlib inline IBMQ.load_account() ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_vigo') new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend) """ if circuit._layout is None: raise QiskitError("Circuit has no layout. Perhaps it has not been transpiled.") if isinstance(backend, BackendV2): num_qubits = backend.num_qubits else: num_qubits = backend.configuration().n_qubits qubits = [] qubit_labels = [None] * num_qubits bit_locations = { bit: {"register": register, "index": index} for register in circuit._layout.get_registers() for index, bit in enumerate(register) } for index, qubit in enumerate(circuit._layout.get_virtual_bits()): if qubit not in bit_locations: bit_locations[qubit] = {"register": None, "index": index} if view == "virtual": for key, val in circuit._layout.get_virtual_bits().items(): bit_register = bit_locations[key]["register"] if bit_register is None or bit_register.name != "ancilla": qubits.append(val) qubit_labels[val] = bit_locations[key]["index"] elif view == "physical": for key, val in circuit._layout.get_physical_bits().items(): bit_register = bit_locations[val]["register"] if bit_register is None or bit_register.name != "ancilla": qubits.append(key) qubit_labels[key] = key else: raise VisualizationError("Layout view must be 'virtual' or 'physical'.") qcolors = ["#648fff"] * num_qubits for k in qubits: qcolors[k] = "k" if isinstance(backend, BackendV2): cmap = backend.plot_coupling_map else: cmap = backend.configuration().coupling_map lcolors = ["#648fff"] * len(cmap) for idx, edge in enumerate(cmap): if edge[0] in qubits and edge[1] in qubits: lcolors[idx] = "k" fig = plot_gate_map( backend, qubit_color=qcolors, qubit_labels=qubit_labels, line_color=lcolors, qubit_coordinates=qubit_coordinates, ) return fig def plot_error_map(backend, figsize=(12, 9), show_title=True): """Plots the error map of a given backend. Args: backend (IBMQBackend): Given backend. figsize (tuple): Figure size in inches. show_title (bool): Show the title or not. Returns: Figure: A matplotlib figure showing error map. Raises: VisualizationError: Input is not IBMQ backend. VisualizationError: The backend does not provide gate errors for the 'sx' gate. MissingOptionalLibraryError: If seaborn is not installed Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: from qiskit import QuantumCircuit, execute, IBMQ from qiskit.visualization import plot_error_map %matplotlib inline IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_vigo') plot_error_map(backend) """ try: import seaborn as sns except ImportError as ex: raise MissingOptionalLibraryError( libname="seaborn", name="plot_error_map", pip_install="pip install seaborn", ) from ex if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_error_map", pip_install="pip install matplotlib", ) import matplotlib import matplotlib.pyplot as plt from matplotlib import gridspec, ticker color_map = sns.cubehelix_palette(reverse=True, as_cmap=True) props = backend.properties().to_dict() config = backend.configuration().to_dict() num_qubits = config["n_qubits"] # sx error rates single_gate_errors = [0] * num_qubits for gate in props["gates"]: if gate["gate"] == "sx": _qubit = gate["qubits"][0] for param in gate["parameters"]: if param["name"] == "gate_error": single_gate_errors[_qubit] = param["value"] break else: raise VisualizationError( f"Backend '{backend}' did not supply an error for the 'sx' gate." ) # Convert to percent single_gate_errors = 100 * np.asarray(single_gate_errors) avg_1q_err = np.mean(single_gate_errors) single_norm = matplotlib.colors.Normalize( vmin=min(single_gate_errors), vmax=max(single_gate_errors) ) q_colors = [color_map(single_norm(err)) for err in single_gate_errors] cmap = config["coupling_map"] directed = False line_colors = [] if cmap: directed = False if num_qubits < 20: for edge in cmap: if [edge[1], edge[0]] not in cmap: directed = True break cx_errors = [] for line in cmap: for item in props["gates"]: if item["qubits"] == line: cx_errors.append(item["parameters"][0]["value"]) break else: continue # Convert to percent cx_errors = 100 * np.asarray(cx_errors) avg_cx_err = np.mean(cx_errors) cx_norm = matplotlib.colors.Normalize(vmin=min(cx_errors), vmax=max(cx_errors)) line_colors = [color_map(cx_norm(err)) for err in cx_errors] # Measurement errors read_err = [] for qubit in range(num_qubits): for item in props["qubits"][qubit]: if item["name"] == "readout_error": read_err.append(item["value"]) read_err = 100 * np.asarray(read_err) avg_read_err = np.mean(read_err) max_read_err = np.max(read_err) fig = plt.figure(figsize=figsize) gridspec.GridSpec(nrows=2, ncols=3) grid_spec = gridspec.GridSpec( 12, 12, height_ratios=[1] * 11 + [0.5], width_ratios=[2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2], ) left_ax = plt.subplot(grid_spec[2:10, :1]) main_ax = plt.subplot(grid_spec[:11, 1:11]) right_ax = plt.subplot(grid_spec[2:10, 11:]) bleft_ax = plt.subplot(grid_spec[-1, :5]) if cmap: bright_ax = plt.subplot(grid_spec[-1, 7:]) qubit_size = 28 if num_qubits <= 5: qubit_size = 20 plot_gate_map( backend, qubit_color=q_colors, line_color=line_colors, qubit_size=qubit_size, line_width=5, plot_directed=directed, ax=main_ax, ) main_ax.axis("off") main_ax.set_aspect(1) if cmap: single_cb = matplotlib.colorbar.ColorbarBase( bleft_ax, cmap=color_map, norm=single_norm, orientation="horizontal" ) tick_locator = ticker.MaxNLocator(nbins=5) single_cb.locator = tick_locator single_cb.update_ticks() single_cb.update_ticks() bleft_ax.set_title(f"H error rate (%) [Avg. = {round(avg_1q_err, 3)}]") if cmap is None: bleft_ax.axis("off") bleft_ax.set_title(f"H error rate (%) = {round(avg_1q_err, 3)}") if cmap: cx_cb = matplotlib.colorbar.ColorbarBase( bright_ax, cmap=color_map, norm=cx_norm, orientation="horizontal" ) tick_locator = ticker.MaxNLocator(nbins=5) cx_cb.locator = tick_locator cx_cb.update_ticks() bright_ax.set_title(f"CNOT error rate (%) [Avg. = {round(avg_cx_err, 3)}]") if num_qubits < 10: num_left = num_qubits num_right = 0 else: num_left = math.ceil(num_qubits / 2) num_right = num_qubits - num_left left_ax.barh(range(num_left), read_err[:num_left], align="center", color="#DDBBBA") left_ax.axvline(avg_read_err, linestyle="--", color="#212121") left_ax.set_yticks(range(num_left)) left_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)]) left_ax.set_yticklabels([str(kk) for kk in range(num_left)], fontsize=12) left_ax.invert_yaxis() left_ax.set_title("Readout Error (%)", fontsize=12) for spine in left_ax.spines.values(): spine.set_visible(False) if num_right: right_ax.barh( range(num_left, num_qubits), read_err[num_left:], align="center", color="#DDBBBA", ) right_ax.axvline(avg_read_err, linestyle="--", color="#212121") right_ax.set_yticks(range(num_left, num_qubits)) right_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)]) right_ax.set_yticklabels( [str(kk) for kk in range(num_left, num_qubits)], fontsize=12 ) right_ax.invert_yaxis() right_ax.invert_xaxis() right_ax.yaxis.set_label_position("right") right_ax.yaxis.tick_right() right_ax.set_title("Readout Error (%)", fontsize=12) else: right_ax.axis("off") for spine in right_ax.spines.values(): spine.set_visible(False) if show_title: fig.suptitle(f"{backend.name()} Error Map", fontsize=24, y=0.9) matplotlib_close_if_inline(fig) return fig
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name,no-name-in-module,ungrouped-imports """A circuit library widget module""" import ipywidgets as wid from IPython.display import display from qiskit import QuantumCircuit from qiskit.utils import optionals as _optionals from qiskit.utils.deprecation import deprecate_func @_optionals.HAS_MATPLOTLIB.require_in_call def _generate_circuit_library_visualization(circuit: QuantumCircuit): import matplotlib.pyplot as plt circuit = circuit.decompose() ops = circuit.count_ops() num_nl = circuit.num_nonlocal_gates() _fig, (ax0, ax1) = plt.subplots(2, 1) circuit.draw("mpl", ax=ax0) ax1.axis("off") ax1.grid(visible=None) ax1.table( [[circuit.name], [circuit.width()], [circuit.depth()], [sum(ops.values())], [num_nl]], rowLabels=["Circuit Name", "Width", "Depth", "Total Gates", "Non-local Gates"], ) plt.tight_layout() plt.show() @deprecate_func( since="0.25.0", additional_msg="This is unused by Qiskit, and no replacement will be publicly provided.", ) def circuit_data_table(circuit: QuantumCircuit) -> wid.HTML: """Create a HTML table widget for a given quantum circuit. Args: circuit: Input quantum circuit. Returns: Output widget. """ circuit = circuit.decompose() ops = circuit.count_ops() num_nl = circuit.num_nonlocal_gates() html = "<table>" html += """<style> table { font-family: "IBM Plex Sans", Arial, Helvetica, sans-serif; border-collapse: collapse; width: 100%; border-left: 2px solid #212121; } th { text-align: left; padding: 5px 5px 5px 5px; width: 100%; background-color: #988AFC; color: #fff; font-size: 14px; border-left: 2px solid #988AFC; } td { text-align: left; padding: 5px 5px 5px 5px; width: 100%; font-size: 12px; font-weight: medium; } tr:nth-child(even) {background-color: #f6f6f6;} </style>""" html += f"<tr><th>{circuit.name}</th><th></tr>" html += f"<tr><td>Width</td><td>{circuit.width()}</td></tr>" html += f"<tr><td>Depth</td><td>{circuit.depth()}</td></tr>" html += f"<tr><td>Total Gates</td><td>{sum(ops.values())}</td></tr>" html += f"<tr><td>Non-local Gates</td><td>{num_nl}</td></tr>" html += "</table>" out_wid = wid.HTML(html) return out_wid head_style = ( "font-family: IBM Plex Sans, Arial, Helvetica, sans-serif;" " font-size: 20px; font-weight: medium;" ) property_label = wid.HTML( f"<p style='{head_style}'>Circuit Properties</p>", layout=wid.Layout(margin="0px 0px 10px 0px"), ) @deprecate_func( since="0.25.0", additional_msg="This is unused by Qiskit, and no replacement will be publicly provided.", ) def properties_widget(circuit: QuantumCircuit) -> wid.VBox: """Create a HTML table widget with header for a given quantum circuit. Args: circuit: Input quantum circuit. Returns: Output widget. """ properties = wid.VBox( children=[property_label, circuit_data_table(circuit)], layout=wid.Layout(width="40%", height="auto"), ) return properties @_optionals.HAS_PYGMENTS.require_in_call @deprecate_func( since="0.25.0", additional_msg="This is unused by Qiskit, and no replacement will be publicly provided.", ) def qasm_widget(circuit: QuantumCircuit) -> wid.VBox: """Generate a QASM widget with header for a quantum circuit. Args: circuit: Input quantum circuit. Returns: Output widget. """ import pygments from pygments.formatters import HtmlFormatter from qiskit.qasm.pygments import QasmHTMLStyle, OpenQASMLexer qasm_code = circuit.qasm() code = pygments.highlight(qasm_code, OpenQASMLexer(), HtmlFormatter()) html_style = HtmlFormatter(style=QasmHTMLStyle).get_style_defs(".highlight") code_style = ( """ <style> .highlight { font-family: monospace; font-size: 14px; line-height: 1.7em; } .highlight .err { color: #000000; background-color: #FFFFFF } %s </style> """ % html_style ) out = wid.HTML( code_style + code, layout=wid.Layout(max_height="500px", height="auto", overflow="scroll scroll"), ) out_label = wid.HTML( f"<p style='{head_style}'>OpenQASM</p>", layout=wid.Layout(margin="0px 0px 10px 0px"), ) qasm = wid.VBox( children=[out_label, out], layout=wid.Layout( height="auto", max_height="500px", width="60%", margin="0px 0px 0px 20px" ), ) qasm._code_length = len(qasm_code.split("\n")) return qasm @deprecate_func( since="0.25.0", additional_msg="This is unused by Qiskit, and no replacement will be publicly provided.", ) def circuit_diagram_widget() -> wid.Box: """Create a circuit diagram widget. Returns: Output widget. """ # The max circuit height corresponds to a 20Q circuit with flat # classical register. top_out = wid.Output( layout=wid.Layout( width="100%", height="auto", max_height="1000px", overflow="hidden scroll", ) ) top = wid.Box(children=[top_out], layout=wid.Layout(width="100%", height="auto")) return top @deprecate_func( since="0.25.0", additional_msg="This is unused by Qiskit, and no replacement will be publicly provided.", ) def circuit_library_widget(circuit: QuantumCircuit) -> None: """Create a circuit library widget. Args: circuit: Input quantum circuit. """ qasm_wid = qasm_widget(circuit) sep_length = str(min(20 * qasm_wid._code_length, 495)) # The separator widget sep = wid.HTML( f"<div style='border-left: 3px solid #212121;height: {sep_length}px;'></div>", layout=wid.Layout(height="auto", max_height="495px", margin="40px 0px 0px 20px"), ) bottom = wid.HBox( children=[properties_widget(circuit), sep, qasm_widget(circuit)], layout=wid.Layout(max_height="550px", height="auto"), ) top = circuit_diagram_widget() with top.children[0]: display(circuit.decompose().draw(output="mpl")) display(wid.VBox(children=[top, bottom], layout=wid.Layout(width="100%", height="auto")))
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Visualization function for a pass manager. Passes are grouped based on their flow controller, and coloured based on the type of pass. """ import os import inspect import tempfile from qiskit.utils import optionals as _optionals from qiskit.transpiler.basepasses import AnalysisPass, TransformationPass from .exceptions import VisualizationError DEFAULT_STYLE = {AnalysisPass: "red", TransformationPass: "blue"} @_optionals.HAS_GRAPHVIZ.require_in_call @_optionals.HAS_PYDOT.require_in_call def pass_manager_drawer(pass_manager, filename=None, style=None, raw=False): """ Draws the pass manager. This function needs `pydot <https://github.com/erocarrera/pydot>`__, which in turn needs `Graphviz <https://www.graphviz.org/>`__ to be installed. Args: pass_manager (PassManager): the pass manager to be drawn filename (str): file path to save image to style (dict or OrderedDict): keys are the pass classes and the values are the colors to make them. An example can be seen in the DEFAULT_STYLE. An ordered dict can be used to ensure a priority coloring when pass falls into multiple categories. Any values not included in the provided dict will be filled in from the default dict raw (Bool) : True if you want to save the raw Dot output not an image. The default is False. Returns: PIL.Image or None: an in-memory representation of the pass manager. Or None if no image was generated or PIL is not installed. Raises: MissingOptionalLibraryError: when nxpd or pydot not installed. VisualizationError: If raw=True and filename=None. Example: .. code-block:: %matplotlib inline from qiskit import QuantumCircuit from qiskit.compiler import transpile from qiskit.transpiler import PassManager from qiskit.visualization import pass_manager_drawer from qiskit.transpiler.passes import Unroller circ = QuantumCircuit(3) circ.ccx(0, 1, 2) circ.draw() pass_ = Unroller(['u1', 'u2', 'u3', 'cx']) pm = PassManager(pass_) new_circ = pm.run(circ) new_circ.draw(output='mpl') pass_manager_drawer(pm, "passmanager.jpg") """ import pydot passes = pass_manager.passes() if not style: style = DEFAULT_STYLE # create the overall graph graph = pydot.Dot() # identifiers for nodes need to be unique, so assign an id # can't just use python's id in case the exact same pass was # appended more than once component_id = 0 prev_node = None for index, controller_group in enumerate(passes): subgraph, component_id, prev_node = draw_subgraph( controller_group, component_id, style, prev_node, index ) graph.add_subgraph(subgraph) output = make_output(graph, raw, filename) return output def _get_node_color(pss, style): # look in the user provided dict first for typ, color in style.items(): if isinstance(pss, typ): return color # failing that, look in the default for typ, color in DEFAULT_STYLE.items(): if isinstance(pss, typ): return color return "black" @_optionals.HAS_GRAPHVIZ.require_in_call @_optionals.HAS_PYDOT.require_in_call def staged_pass_manager_drawer(pass_manager, filename=None, style=None, raw=False): """ Draws the staged pass manager. This function needs `pydot <https://github.com/erocarrera/pydot>`__, which in turn needs `Graphviz <https://www.graphviz.org/>`__ to be installed. Args: pass_manager (StagedPassManager): the staged pass manager to be drawn filename (str): file path to save image to style (dict or OrderedDict): keys are the pass classes and the values are the colors to make them. An example can be seen in the DEFAULT_STYLE. An ordered dict can be used to ensure a priority coloring when pass falls into multiple categories. Any values not included in the provided dict will be filled in from the default dict raw (Bool) : True if you want to save the raw Dot output not an image. The default is False. Returns: PIL.Image or None: an in-memory representation of the pass manager. Or None if no image was generated or PIL is not installed. Raises: MissingOptionalLibraryError: when nxpd or pydot not installed. VisualizationError: If raw=True and filename=None. Example: .. code-block:: %matplotlib inline from qiskit.providers.fake_provider import FakeLagosV2 from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager pass_manager = generate_preset_pass_manager(3, FakeLagosV2()) pass_manager.draw() """ import pydot # only include stages that have passes stages = list(filter(lambda s: s is not None, pass_manager.expanded_stages)) if not style: style = DEFAULT_STYLE # create the overall graph graph = pydot.Dot() # identifiers for nodes need to be unique, so assign an id # can't just use python's id in case the exact same pass was # appended more than once component_id = 0 # keep a running count of indexes across stages idx = 0 prev_node = None for st in stages: stage = getattr(pass_manager, st) if stage is not None: passes = stage.passes() stagegraph = pydot.Cluster(str(st), label=str(st), fontname="helvetica", labeljust="l") for controller_group in passes: subgraph, component_id, prev_node = draw_subgraph( controller_group, component_id, style, prev_node, idx ) stagegraph.add_subgraph(subgraph) idx += 1 graph.add_subgraph(stagegraph) output = make_output(graph, raw, filename) return output def draw_subgraph(controller_group, component_id, style, prev_node, idx): """Draw subgraph.""" import pydot # label is the name of the flow controller parameter label = "[{}] {}".format(idx, ", ".join(controller_group["flow_controllers"])) # create the subgraph for this controller subgraph = pydot.Cluster(str(component_id), label=label, fontname="helvetica", labeljust="l") component_id += 1 for pass_ in controller_group["passes"]: # label is the name of the pass node = pydot.Node( str(component_id), label=str(type(pass_).__name__), color=_get_node_color(pass_, style), shape="rectangle", fontname="helvetica", ) subgraph.add_node(node) component_id += 1 # the arguments that were provided to the pass when it was created arg_spec = inspect.getfullargspec(pass_.__init__) # 0 is the args, 1: to remove the self arg args = arg_spec[0][1:] num_optional = len(arg_spec[3]) if arg_spec[3] else 0 # add in the inputs to the pass for arg_index, arg in enumerate(args): nd_style = "solid" # any optional args are dashed # the num of optional counts from the end towards the start of the list if arg_index >= (len(args) - num_optional): nd_style = "dashed" input_node = pydot.Node( component_id, label=arg, color="black", shape="ellipse", fontsize=10, style=nd_style, fontname="helvetica", ) subgraph.add_node(input_node) component_id += 1 subgraph.add_edge(pydot.Edge(input_node, node)) # if there is a previous node, add an edge between them if prev_node: subgraph.add_edge(pydot.Edge(prev_node, node)) prev_node = node return subgraph, component_id, prev_node def make_output(graph, raw, filename): """Produce output for pass_manager.""" if raw: if filename: graph.write(filename, format="raw") return None else: raise VisualizationError("if format=raw, then a filename is required.") if not _optionals.HAS_PIL and filename: # pylint says this isn't a method - it is graph.write_png(filename) return None _optionals.HAS_PIL.require_now("pass manager drawer") with tempfile.TemporaryDirectory() as tmpdirname: from PIL import Image tmppath = os.path.join(tmpdirname, "pass_manager.png") # pylint says this isn't a method - it is graph.write_png(tmppath) image = Image.open(tmppath) os.remove(tmppath) if filename: image.save(filename, "PNG") return image
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name # pylint: disable=missing-param-doc,missing-type-doc,unused-argument """ Visualization functions for quantum states. """ from typing import Optional, List, Union from functools import reduce import colorsys import numpy as np from qiskit import user_config from qiskit.quantum_info.states.statevector import Statevector from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic import PauliList, SparsePauliOp from qiskit.quantum_info.states.densitymatrix import DensityMatrix from qiskit.utils.deprecation import deprecate_arg, deprecate_func from qiskit.utils import optionals as _optionals from qiskit.circuit.tools.pi_check import pi_check from .array import _num_to_latex, array_to_latex from .utils import matplotlib_close_if_inline from .exceptions import VisualizationError @deprecate_arg("rho", new_alias="state", since="0.15.1") @_optionals.HAS_MATPLOTLIB.require_in_call def plot_state_hinton( state, title="", figsize=None, ax_real=None, ax_imag=None, *, rho=None, filename=None ): """Plot a hinton diagram for the density matrix of a quantum state. The hinton diagram represents the values of a matrix using squares, whose size indicate the magnitude of their corresponding value and their color, its sign. A white square means the value is positive and a black one means negative. Args: state (Statevector or DensityMatrix or ndarray): An N-qubit quantum state. title (str): a string that represents the plot title figsize (tuple): Figure size in inches. filename (str): file path to save image to. ax_real (matplotlib.axes.Axes): An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. If this is specified without an ax_imag only the real component plot will be generated. Additionally, if specified there will be no returned Figure since it is redundant. ax_imag (matplotlib.axes.Axes): An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. If this is specified without an ax_imag only the real component plot will be generated. Additionally, if specified there will be no returned Figure since it is redundant. Returns: :class:`matplotlib:matplotlib.figure.Figure` : The matplotlib.Figure of the visualization if neither ax_real or ax_imag is set. Raises: MissingOptionalLibraryError: Requires matplotlib. VisualizationError: if input is not a valid N-qubit state. Examples: .. plot:: :include-source: import numpy as np from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_hinton qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3 , 0) qc.rx(np.pi/5, 1) state = DensityMatrix(qc) plot_state_hinton(state, title="New Hinton Plot") """ from matplotlib import pyplot as plt # Figure data rho = DensityMatrix(state) num = rho.num_qubits if num is None: raise VisualizationError("Input is not a multi-qubit quantum state.") max_weight = 2 ** np.ceil(np.log(np.abs(rho.data).max()) / np.log(2)) datareal = np.real(rho.data) dataimag = np.imag(rho.data) if figsize is None: figsize = (8, 5) if not ax_real and not ax_imag: fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize) else: if ax_real: fig = ax_real.get_figure() else: fig = ax_imag.get_figure() ax1 = ax_real ax2 = ax_imag # Reversal is to account for Qiskit's endianness. column_names = [bin(i)[2:].zfill(num) for i in range(2**num)] row_names = [bin(i)[2:].zfill(num) for i in range(2**num)][::-1] ly, lx = datareal.shape # Real if ax1: ax1.patch.set_facecolor("gray") ax1.set_aspect("equal", "box") ax1.xaxis.set_major_locator(plt.NullLocator()) ax1.yaxis.set_major_locator(plt.NullLocator()) for (x, y), w in np.ndenumerate(datareal): # Convert from matrix co-ordinates to plot co-ordinates. plot_x, plot_y = y, lx - x - 1 color = "white" if w > 0 else "black" size = np.sqrt(np.abs(w) / max_weight) rect = plt.Rectangle( [0.5 + plot_x - size / 2, 0.5 + plot_y - size / 2], size, size, facecolor=color, edgecolor=color, ) ax1.add_patch(rect) ax1.set_xticks(0.5 + np.arange(lx)) ax1.set_yticks(0.5 + np.arange(ly)) ax1.set_xlim([0, lx]) ax1.set_ylim([0, ly]) ax1.set_yticklabels(row_names, fontsize=14) ax1.set_xticklabels(column_names, fontsize=14, rotation=90) ax1.set_title("Re[$\\rho$]", fontsize=14) # Imaginary if ax2: ax2.patch.set_facecolor("gray") ax2.set_aspect("equal", "box") ax2.xaxis.set_major_locator(plt.NullLocator()) ax2.yaxis.set_major_locator(plt.NullLocator()) for (x, y), w in np.ndenumerate(dataimag): # Convert from matrix co-ordinates to plot co-ordinates. plot_x, plot_y = y, lx - x - 1 color = "white" if w > 0 else "black" size = np.sqrt(np.abs(w) / max_weight) rect = plt.Rectangle( [0.5 + plot_x - size / 2, 0.5 + plot_y - size / 2], size, size, facecolor=color, edgecolor=color, ) ax2.add_patch(rect) ax2.set_xticks(0.5 + np.arange(lx)) ax2.set_yticks(0.5 + np.arange(ly)) ax2.set_xlim([0, lx]) ax2.set_ylim([0, ly]) ax2.set_yticklabels(row_names, fontsize=14) ax2.set_xticklabels(column_names, fontsize=14, rotation=90) ax2.set_title("Im[$\\rho$]", fontsize=14) fig.tight_layout() if title: fig.suptitle(title, fontsize=16) if ax_real is None and ax_imag is None: matplotlib_close_if_inline(fig) if filename is None: return fig else: return fig.savefig(filename) @_optionals.HAS_MATPLOTLIB.require_in_call def plot_bloch_vector( bloch, title="", ax=None, figsize=None, coord_type="cartesian", font_size=None ): """Plot the Bloch sphere. Plot a Bloch sphere with the specified coordinates, that can be given in both cartesian and spherical systems. Args: bloch (list[double]): array of three elements where [<x>, <y>, <z>] (Cartesian) or [<r>, <theta>, <phi>] (spherical in radians) <theta> is inclination angle from +z direction <phi> is azimuth from +x direction title (str): a string that represents the plot title ax (matplotlib.axes.Axes): An Axes to use for rendering the bloch sphere figsize (tuple): Figure size in inches. Has no effect is passing ``ax``. coord_type (str): a string that specifies coordinate type for bloch (Cartesian or spherical), default is Cartesian font_size (float): Font size. Returns: :class:`matplotlib:matplotlib.figure.Figure` : A matplotlib figure instance if ``ax = None``. Raises: MissingOptionalLibraryError: Requires matplotlib. Examples: .. plot:: :include-source: from qiskit.visualization import plot_bloch_vector plot_bloch_vector([0,1,0], title="New Bloch Sphere") .. plot:: :include-source: import numpy as np from qiskit.visualization import plot_bloch_vector # You can use spherical coordinates instead of cartesian. plot_bloch_vector([1, np.pi/2, np.pi/3], coord_type='spherical') """ from .bloch import Bloch if figsize is None: figsize = (5, 5) B = Bloch(axes=ax, font_size=font_size) if coord_type == "spherical": r, theta, phi = bloch[0], bloch[1], bloch[2] bloch[0] = r * np.sin(theta) * np.cos(phi) bloch[1] = r * np.sin(theta) * np.sin(phi) bloch[2] = r * np.cos(theta) B.add_vectors(bloch) B.render(title=title) if ax is None: fig = B.fig fig.set_size_inches(figsize[0], figsize[1]) matplotlib_close_if_inline(fig) return fig return None @deprecate_arg("rho", new_alias="state", since="0.15.1") @_optionals.HAS_MATPLOTLIB.require_in_call def plot_bloch_multivector( state, title="", figsize=None, *, rho=None, reverse_bits=False, filename=None, font_size=None, title_font_size=None, title_pad=1, ): r"""Plot a Bloch sphere for each qubit. Each component :math:`(x,y,z)` of the Bloch sphere labeled as 'qubit i' represents the expected value of the corresponding Pauli operator acting only on that qubit, that is, the expected value of :math:`I_{N-1} \otimes\dotsb\otimes I_{i+1}\otimes P_i \otimes I_{i-1}\otimes\dotsb\otimes I_0`, where :math:`N` is the number of qubits, :math:`P\in \{X,Y,Z\}` and :math:`I` is the identity operator. Args: state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state. title (str): a string that represents the plot title figsize (tuple): size of each individual Bloch sphere figure, in inches. reverse_bits (bool): If True, plots qubits following Qiskit's convention [Default:False]. font_size (float): Font size for the Bloch ball figures. title_font_size (float): Font size for the title. title_pad (float): Padding for the title (suptitle `y` position is `y=1+title_pad/100`). Returns: :class:`matplotlib:matplotlib.figure.Figure` : A matplotlib figure instance. Raises: MissingOptionalLibraryError: Requires matplotlib. VisualizationError: if input is not a valid N-qubit state. Examples: .. plot:: :include-source: from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(2) qc.h(0) qc.x(1) state = Statevector(qc) plot_bloch_multivector(state) .. plot:: :include-source: from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(2) qc.h(0) qc.x(1) # You can reverse the order of the qubits. from qiskit.quantum_info import DensityMatrix qc = QuantumCircuit(2) qc.h([0, 1]) qc.t(1) qc.s(0) qc.cx(0,1) matrix = DensityMatrix(qc) plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True) """ from matplotlib import pyplot as plt # Data bloch_data = ( _bloch_multivector_data(state)[::-1] if reverse_bits else _bloch_multivector_data(state) ) num = len(bloch_data) if figsize is not None: width, height = figsize width *= num else: width, height = plt.figaspect(1 / num) default_title_font_size = font_size if font_size is not None else 16 title_font_size = title_font_size if title_font_size is not None else default_title_font_size fig = plt.figure(figsize=(width, height)) for i in range(num): pos = num - 1 - i if reverse_bits else i ax = fig.add_subplot(1, num, i + 1, projection="3d") plot_bloch_vector( bloch_data[i], "qubit " + str(pos), ax=ax, figsize=figsize, font_size=font_size ) fig.suptitle(title, fontsize=title_font_size, y=1.0 + title_pad / 100) matplotlib_close_if_inline(fig) if filename is None: return fig else: return fig.savefig(filename) @deprecate_arg("rho", new_alias="state", since="0.15.1") @_optionals.HAS_MATPLOTLIB.require_in_call def plot_state_city( state, title="", figsize=None, color=None, alpha=1, ax_real=None, ax_imag=None, *, rho=None, filename=None, ): """Plot the cityscape of quantum state. Plot two 3d bar graphs (two dimensional) of the real and imaginary part of the density matrix rho. Args: state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state. title (str): a string that represents the plot title figsize (tuple): Figure size in inches. color (list): A list of len=2 giving colors for real and imaginary components of matrix elements. alpha (float): Transparency value for bars ax_real (matplotlib.axes.Axes): An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. If this is specified without an ax_imag only the real component plot will be generated. Additionally, if specified there will be no returned Figure since it is redundant. ax_imag (matplotlib.axes.Axes): An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. If this is specified without an ax_real only the imaginary component plot will be generated. Additionally, if specified there will be no returned Figure since it is redundant. Returns: :class:`matplotlib:matplotlib.figure.Figure` : The matplotlib.Figure of the visualization if the ``ax_real`` and ``ax_imag`` kwargs are not set Raises: MissingOptionalLibraryError: Requires matplotlib. ValueError: When 'color' is not a list of len=2. VisualizationError: if input is not a valid N-qubit state. Examples: .. plot:: :include-source: # You can choose different colors for the real and imaginary parts of the density matrix. from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = DensityMatrix(qc) plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City") .. plot:: :include-source: # You can make the bars more transparent to better see the ones that are behind # if they overlap. import numpy as np from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_city from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) state = Statevector(qc) plot_state_city(state, alpha=0.6) """ from matplotlib import pyplot as plt from mpl_toolkits.mplot3d.art3d import Poly3DCollection rho = DensityMatrix(state) num = rho.num_qubits if num is None: raise VisualizationError("Input is not a multi-qubit quantum state.") # get the real and imag parts of rho datareal = np.real(rho.data) dataimag = np.imag(rho.data) # get the labels column_names = [bin(i)[2:].zfill(num) for i in range(2**num)] row_names = [bin(i)[2:].zfill(num) for i in range(2**num)] lx = len(datareal[0]) # Work out matrix dimensions ly = len(datareal[:, 0]) xpos = np.arange(0, lx, 1) # Set up a mesh of positions ypos = np.arange(0, ly, 1) xpos, ypos = np.meshgrid(xpos + 0.25, ypos + 0.25) xpos = xpos.flatten() ypos = ypos.flatten() zpos = np.zeros(lx * ly) dx = 0.5 * np.ones_like(zpos) # width of bars dy = dx.copy() dzr = datareal.flatten() dzi = dataimag.flatten() if color is None: color = ["#648fff", "#648fff"] else: if len(color) != 2: raise ValueError("'color' must be a list of len=2.") if color[0] is None: color[0] = "#648fff" if color[1] is None: color[1] = "#648fff" if ax_real is None and ax_imag is None: # set default figure size if figsize is None: figsize = (15, 5) fig = plt.figure(figsize=figsize) ax1 = fig.add_subplot(1, 2, 1, projection="3d") ax2 = fig.add_subplot(1, 2, 2, projection="3d") elif ax_real is not None: fig = ax_real.get_figure() ax1 = ax_real ax2 = ax_imag else: fig = ax_imag.get_figure() ax1 = None ax2 = ax_imag max_dzr = max(dzr) min_dzr = min(dzr) min_dzi = np.min(dzi) max_dzi = np.max(dzi) # There seems to be a rounding error in which some zero bars are negative dzr = np.clip(dzr, 0, None) if ax1 is not None: fc1 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzr, color[0]) for idx, cur_zpos in enumerate(zpos): if dzr[idx] > 0: zorder = 2 else: zorder = 0 b1 = ax1.bar3d( xpos[idx], ypos[idx], cur_zpos, dx[idx], dy[idx], dzr[idx], alpha=alpha, zorder=zorder, ) b1.set_facecolors(fc1[6 * idx : 6 * idx + 6]) xlim, ylim = ax1.get_xlim(), ax1.get_ylim() x = [xlim[0], xlim[1], xlim[1], xlim[0]] y = [ylim[0], ylim[0], ylim[1], ylim[1]] z = [0, 0, 0, 0] verts = [list(zip(x, y, z))] pc1 = Poly3DCollection(verts, alpha=0.15, facecolor="k", linewidths=1, zorder=1) if min(dzr) < 0 < max(dzr): ax1.add_collection3d(pc1) ax1.set_xticks(np.arange(0.5, lx + 0.5, 1)) ax1.set_yticks(np.arange(0.5, ly + 0.5, 1)) if max_dzr != min_dzr: ax1.axes.set_zlim3d(np.min(dzr), max(np.max(dzr) + 1e-9, max_dzi)) else: if min_dzr == 0: ax1.axes.set_zlim3d(np.min(dzr), max(np.max(dzr) + 1e-9, np.max(dzi))) else: ax1.axes.set_zlim3d(auto=True) ax1.get_autoscalez_on() ax1.xaxis.set_ticklabels(row_names, fontsize=14, rotation=45, ha="right", va="top") ax1.yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5, ha="left", va="center") ax1.set_zlabel("Re[$\\rho$]", fontsize=14) for tick in ax1.zaxis.get_major_ticks(): tick.label1.set_fontsize(14) if ax2 is not None: fc2 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzi, color[1]) for idx, cur_zpos in enumerate(zpos): if dzi[idx] > 0: zorder = 2 else: zorder = 0 b2 = ax2.bar3d( xpos[idx], ypos[idx], cur_zpos, dx[idx], dy[idx], dzi[idx], alpha=alpha, zorder=zorder, ) b2.set_facecolors(fc2[6 * idx : 6 * idx + 6]) xlim, ylim = ax2.get_xlim(), ax2.get_ylim() x = [xlim[0], xlim[1], xlim[1], xlim[0]] y = [ylim[0], ylim[0], ylim[1], ylim[1]] z = [0, 0, 0, 0] verts = [list(zip(x, y, z))] pc2 = Poly3DCollection(verts, alpha=0.2, facecolor="k", linewidths=1, zorder=1) if min(dzi) < 0 < max(dzi): ax2.add_collection3d(pc2) ax2.set_xticks(np.arange(0.5, lx + 0.5, 1)) ax2.set_yticks(np.arange(0.5, ly + 0.5, 1)) if min_dzi != max_dzi: eps = 0 ax2.axes.set_zlim3d(np.min(dzi), max(np.max(dzr) + 1e-9, np.max(dzi) + eps)) else: if min_dzi == 0: ax2.set_zticks([0]) eps = 1e-9 ax2.axes.set_zlim3d(np.min(dzi), max(np.max(dzr) + 1e-9, np.max(dzi) + eps)) else: ax2.axes.set_zlim3d(auto=True) ax2.xaxis.set_ticklabels(row_names, fontsize=14, rotation=45, ha="right", va="top") ax2.yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5, ha="left", va="center") ax2.set_zlabel("Im[$\\rho$]", fontsize=14) for tick in ax2.zaxis.get_major_ticks(): tick.label1.set_fontsize(14) ax2.get_autoscalez_on() fig.suptitle(title, fontsize=16) if ax_real is None and ax_imag is None: matplotlib_close_if_inline(fig) if filename is None: return fig else: return fig.savefig(filename) @deprecate_arg("rho", new_alias="state", since="0.15.1") @_optionals.HAS_MATPLOTLIB.require_in_call def plot_state_paulivec( state, title="", figsize=None, color=None, ax=None, *, rho=None, filename=None ): r"""Plot the Pauli-vector representation of a quantum state as bar graph. The Pauli-vector of a density matrix :math:`\rho` is defined by the expectation of each possible tensor product of single-qubit Pauli operators (including the identity), that is .. math :: \rho = \frac{1}{2^n} \sum_{\sigma \in \{I, X, Y, Z\}^{\otimes n}} \mathrm{Tr}(\sigma \rho) \sigma. This function plots the coefficients :math:`\mathrm{Tr}(\sigma\rho)` as bar graph. Args: state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state. title (str): a string that represents the plot title figsize (tuple): Figure size in inches. color (list or str): Color of the coefficient value bars. ax (matplotlib.axes.Axes): An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. Returns: :class:`matplotlib:matplotlib.figure.Figure` : The matplotlib.Figure of the visualization if the ``ax`` kwarg is not set Raises: MissingOptionalLibraryError: Requires matplotlib. VisualizationError: if input is not a valid N-qubit state. Examples: .. plot:: :include-source: # You can set a color for all the bars. from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot") .. plot:: :include-source: # If you introduce a list with less colors than bars, the color of the bars will # alternate following the sequence from the list. import numpy as np from qiskit.quantum_info import DensityMatrix from qiskit import QuantumCircuit from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0, 1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) matrix = DensityMatrix(qc) plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen']) """ from matplotlib import pyplot as plt labels, values = _paulivec_data(state) numelem = len(values) if figsize is None: figsize = (7, 5) if color is None: color = "#648fff" ind = np.arange(numelem) # the x locations for the groups width = 0.5 # the width of the bars if ax is None: return_fig = True fig, ax = plt.subplots(figsize=figsize) else: return_fig = False fig = ax.get_figure() ax.grid(zorder=0, linewidth=1, linestyle="--") ax.bar(ind, values, width, color=color, zorder=2) ax.axhline(linewidth=1, color="k") # add some text for labels, title, and axes ticks ax.set_ylabel("Coefficients", fontsize=14) ax.set_xticks(ind) ax.set_yticks([-1, -0.5, 0, 0.5, 1]) ax.set_xticklabels(labels, fontsize=14, rotation=70) ax.set_xlabel("Pauli", fontsize=14) ax.set_ylim([-1, 1]) ax.set_facecolor("#eeeeee") for tick in ax.xaxis.get_major_ticks() + ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(14) ax.set_title(title, fontsize=16) if return_fig: matplotlib_close_if_inline(fig) if filename is None: return fig else: return fig.savefig(filename) def n_choose_k(n, k): """Return the number of combinations for n choose k. Args: n (int): the total number of options . k (int): The number of elements. Returns: int: returns the binomial coefficient """ if n == 0: return 0 return reduce(lambda x, y: x * y[0] / y[1], zip(range(n - k + 1, n + 1), range(1, k + 1)), 1) def lex_index(n, k, lst): """Return the lex index of a combination.. Args: n (int): the total number of options . k (int): The number of elements. lst (list): list Returns: int: returns int index for lex order Raises: VisualizationError: if length of list is not equal to k """ if len(lst) != k: raise VisualizationError("list should have length k") comb = [n - 1 - x for x in lst] dualm = sum(n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)) return int(dualm) def bit_string_index(s): """Return the index of a string of 0s and 1s.""" n = len(s) k = s.count("1") if s.count("0") != n - k: raise VisualizationError("s must be a string of 0 and 1") ones = [pos for pos, char in enumerate(s) if char == "1"] return lex_index(n, k, ones) def phase_to_rgb(complex_number): """Map a phase of a complexnumber to a color in (r,g,b). complex_number is phase is first mapped to angle in the range [0, 2pi] and then to the HSL color wheel """ angles = (np.angle(complex_number) + (np.pi * 5 / 4)) % (np.pi * 2) rgb = colorsys.hls_to_rgb(angles / (np.pi * 2), 0.5, 0.5) return rgb @deprecate_arg("rho", new_alias="state", since="0.15.1") @_optionals.HAS_MATPLOTLIB.require_in_call @_optionals.HAS_SEABORN.require_in_call def plot_state_qsphere( state, figsize=None, ax=None, show_state_labels=True, show_state_phases=False, use_degrees=False, *, rho=None, filename=None, ): """Plot the qsphere representation of a quantum state. Here, the size of the points is proportional to the probability of the corresponding term in the state and the color represents the phase. Args: state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state. figsize (tuple): Figure size in inches. ax (matplotlib.axes.Axes): An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. show_state_labels (bool): An optional boolean indicating whether to show labels for each basis state. show_state_phases (bool): An optional boolean indicating whether to show the phase for each basis state. use_degrees (bool): An optional boolean indicating whether to use radians or degrees for the phase values in the plot. Returns: :class:`matplotlib:matplotlib.figure.Figure` : A matplotlib figure instance if the ``ax`` kwarg is not set Raises: MissingOptionalLibraryError: Requires matplotlib. VisualizationError: if input is not a valid N-qubit state. QiskitError: Input statevector does not have valid dimensions. Examples: .. plot:: :include-source: from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_qsphere(state) .. plot:: :include-source: # You can show the phase of each state and use # degrees instead of radians from qiskit.quantum_info import DensityMatrix import numpy as np from qiskit import QuantumCircuit from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) qc.z(1) matrix = DensityMatrix(qc) plot_state_qsphere(matrix, show_state_phases = True, use_degrees = True) """ from matplotlib import gridspec from matplotlib import pyplot as plt from matplotlib.patches import Circle import seaborn as sns from scipy import linalg from .bloch import Arrow3D rho = DensityMatrix(state) num = rho.num_qubits if num is None: raise VisualizationError("Input is not a multi-qubit quantum state.") # get the eigenvectors and eigenvalues eigvals, eigvecs = linalg.eigh(rho.data) if figsize is None: figsize = (7, 7) if ax is None: return_fig = True fig = plt.figure(figsize=figsize) else: return_fig = False fig = ax.get_figure() gs = gridspec.GridSpec(nrows=3, ncols=3) ax = fig.add_subplot(gs[0:3, 0:3], projection="3d") ax.axes.set_xlim3d(-1.0, 1.0) ax.axes.set_ylim3d(-1.0, 1.0) ax.axes.set_zlim3d(-1.0, 1.0) ax.axes.grid(False) ax.view_init(elev=5, azim=275) # Force aspect ratio # MPL 3.2 or previous do not have set_box_aspect if hasattr(ax.axes, "set_box_aspect"): ax.axes.set_box_aspect((1, 1, 1)) # start the plotting # Plot semi-transparent sphere u = np.linspace(0, 2 * np.pi, 25) v = np.linspace(0, np.pi, 25) x = np.outer(np.cos(u), np.sin(v)) y = np.outer(np.sin(u), np.sin(v)) z = np.outer(np.ones(np.size(u)), np.cos(v)) ax.plot_surface( x, y, z, rstride=1, cstride=1, color=plt.rcParams["grid.color"], alpha=0.2, linewidth=0 ) # Get rid of the panes ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) # Get rid of the spines ax.xaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) ax.yaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) ax.zaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) # Get rid of the ticks ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([]) # traversing the eigvals/vecs backward as sorted low->high for idx in range(eigvals.shape[0] - 1, -1, -1): if eigvals[idx] > 0.001: # get the max eigenvalue state = eigvecs[:, idx] loc = np.absolute(state).argmax() # remove the global phase from max element angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi) angleset = np.exp(-1j * angles) state = angleset * state d = num for i in range(2**num): # get x,y,z points element = bin(i)[2:].zfill(num) weight = element.count("1") zvalue = -2 * weight / d + 1 number_of_divisions = n_choose_k(d, weight) weight_order = bit_string_index(element) angle = (float(weight) / d) * (np.pi * 2) + ( weight_order * 2 * (np.pi / number_of_divisions) ) if (weight > d / 2) or ( (weight == d / 2) and (weight_order >= number_of_divisions / 2) ): angle = np.pi - angle - (2 * np.pi / number_of_divisions) xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle) yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle) # get prob and angle - prob will be shade and angle color prob = np.real(np.dot(state[i], state[i].conj())) prob = min(prob, 1) # See https://github.com/Qiskit/qiskit-terra/issues/4666 colorstate = phase_to_rgb(state[i]) alfa = 1 if yvalue >= 0.1: alfa = 1.0 - yvalue if not np.isclose(prob, 0) and show_state_labels: rprime = 1.3 angle_theta = np.arctan2(np.sqrt(1 - zvalue**2), zvalue) xvalue_text = rprime * np.sin(angle_theta) * np.cos(angle) yvalue_text = rprime * np.sin(angle_theta) * np.sin(angle) zvalue_text = rprime * np.cos(angle_theta) element_text = "$\\vert" + element + "\\rangle$" if show_state_phases: element_angle = (np.angle(state[i]) + (np.pi * 4)) % (np.pi * 2) if use_degrees: element_text += "\n$%.1f^\\circ$" % (element_angle * 180 / np.pi) else: element_angle = pi_check(element_angle, ndigits=3).replace("pi", "\\pi") element_text += "\n$%s$" % (element_angle) ax.text( xvalue_text, yvalue_text, zvalue_text, element_text, ha="center", va="center", size=12, ) ax.plot( [xvalue], [yvalue], [zvalue], markerfacecolor=colorstate, markeredgecolor=colorstate, marker="o", markersize=np.sqrt(prob) * 30, alpha=alfa, ) a = Arrow3D( [0, xvalue], [0, yvalue], [0, zvalue], mutation_scale=20, alpha=prob, arrowstyle="-", color=colorstate, lw=2, ) ax.add_artist(a) # add weight lines for weight in range(d + 1): theta = np.linspace(-2 * np.pi, 2 * np.pi, 100) z = -2 * weight / d + 1 r = np.sqrt(1 - z**2) x = r * np.cos(theta) y = r * np.sin(theta) ax.plot(x, y, z, color=(0.5, 0.5, 0.5), lw=1, ls=":", alpha=0.5) # add center point ax.plot( [0], [0], [0], markerfacecolor=(0.5, 0.5, 0.5), markeredgecolor=(0.5, 0.5, 0.5), marker="o", markersize=3, alpha=1, ) else: break n = 64 theta = np.ones(n) colors = sns.hls_palette(n) ax2 = fig.add_subplot(gs[2:, 2:]) ax2.pie(theta, colors=colors[5 * n // 8 :] + colors[: 5 * n // 8], radius=0.75) ax2.add_artist(Circle((0, 0), 0.5, color="white", zorder=1)) offset = 0.95 # since radius of sphere is one. if use_degrees: labels = ["Phase\n(Deg)", "0", "90", "180 ", "270"] else: labels = ["Phase", "$0$", "$\\pi/2$", "$\\pi$", "$3\\pi/2$"] ax2.text(0, 0, labels[0], horizontalalignment="center", verticalalignment="center", fontsize=14) ax2.text( offset, 0, labels[1], horizontalalignment="center", verticalalignment="center", fontsize=14 ) ax2.text( 0, offset, labels[2], horizontalalignment="center", verticalalignment="center", fontsize=14 ) ax2.text( -offset, 0, labels[3], horizontalalignment="center", verticalalignment="center", fontsize=14 ) ax2.text( 0, -offset, labels[4], horizontalalignment="center", verticalalignment="center", fontsize=14 ) if return_fig: matplotlib_close_if_inline(fig) if filename is None: return fig else: return fig.savefig(filename) @_optionals.HAS_MATPLOTLIB.require_in_call def generate_facecolors(x, y, z, dx, dy, dz, color): """Generates shaded facecolors for shaded bars. This is here to work around a Matplotlib bug where alpha does not work in Bar3D. Args: x (array_like): The x- coordinates of the anchor point of the bars. y (array_like): The y- coordinates of the anchor point of the bars. z (array_like): The z- coordinates of the anchor point of the bars. dx (array_like): Width of bars. dy (array_like): Depth of bars. dz (array_like): Height of bars. color (array_like): sequence of valid color specifications, optional Returns: list: Shaded colors for bars. Raises: MissingOptionalLibraryError: If matplotlib is not installed """ import matplotlib.colors as mcolors cuboid = np.array( [ # -z ( (0, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 0), ), # +z ( (0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1), ), # -y ( (0, 0, 0), (1, 0, 0), (1, 0, 1), (0, 0, 1), ), # +y ( (0, 1, 0), (0, 1, 1), (1, 1, 1), (1, 1, 0), ), # -x ( (0, 0, 0), (0, 0, 1), (0, 1, 1), (0, 1, 0), ), # +x ( (1, 0, 0), (1, 1, 0), (1, 1, 1), (1, 0, 1), ), ] ) # indexed by [bar, face, vertex, coord] polys = np.empty(x.shape + cuboid.shape) # handle each coordinate separately for i, p, dp in [(0, x, dx), (1, y, dy), (2, z, dz)]: p = p[..., np.newaxis, np.newaxis] dp = dp[..., np.newaxis, np.newaxis] polys[..., i] = p + dp * cuboid[..., i] # collapse the first two axes polys = polys.reshape((-1,) + polys.shape[2:]) facecolors = [] if len(color) == len(x): # bar colors specified, need to expand to number of faces for c in color: facecolors.extend([c] * 6) else: # a single color specified, or face colors specified explicitly facecolors = list(mcolors.to_rgba_array(color)) if len(facecolors) < len(x): facecolors *= 6 * len(x) normals = _generate_normals(polys) return _shade_colors(facecolors, normals) def _generate_normals(polygons): """Takes a list of polygons and return an array of their normals. Normals point towards the viewer for a face with its vertices in counterclockwise order, following the right hand rule. Uses three points equally spaced around the polygon. This normal of course might not make sense for polygons with more than three points not lying in a plane, but it's a plausible and fast approximation. Args: polygons (list): list of (M_i, 3) array_like, or (..., M, 3) array_like A sequence of polygons to compute normals for, which can have varying numbers of vertices. If the polygons all have the same number of vertices and array is passed, then the operation will be vectorized. Returns: normals: (..., 3) array_like A normal vector estimated for the polygon. """ if isinstance(polygons, np.ndarray): # optimization: polygons all have the same number of points, so can # vectorize n = polygons.shape[-2] i1, i2, i3 = 0, n // 3, 2 * n // 3 v1 = polygons[..., i1, :] - polygons[..., i2, :] v2 = polygons[..., i2, :] - polygons[..., i3, :] else: # The subtraction doesn't vectorize because polygons is jagged. v1 = np.empty((len(polygons), 3)) v2 = np.empty((len(polygons), 3)) for poly_i, ps in enumerate(polygons): n = len(ps) i1, i2, i3 = 0, n // 3, 2 * n // 3 v1[poly_i, :] = ps[i1, :] - ps[i2, :] v2[poly_i, :] = ps[i2, :] - ps[i3, :] return np.cross(v1, v2) def _shade_colors(color, normals, lightsource=None): """ Shade *color* using normal vectors given by *normals*. *color* can also be an array of the same length as *normals*. """ from matplotlib.colors import Normalize, LightSource import matplotlib.colors as mcolors if lightsource is None: # chosen for backwards-compatibility lightsource = LightSource(azdeg=225, altdeg=19.4712) def mod(v): return np.sqrt(v[0] ** 2 + v[1] ** 2 + v[2] ** 2) shade = np.array( [np.dot(n / mod(n), lightsource.direction) if mod(n) else np.nan for n in normals] ) mask = ~np.isnan(shade) if mask.any(): norm = Normalize(min(shade[mask]), max(shade[mask])) shade[~mask] = min(shade[mask]) color = mcolors.to_rgba_array(color) # shape of color should be (M, 4) (where M is number of faces) # shape of shade should be (M,) # colors should have final shape of (M, 4) alpha = color[:, 3] colors = (0.5 + norm(shade)[:, np.newaxis] * 0.5) * color colors[:, 3] = alpha else: colors = np.asanyarray(color).copy() return colors def state_to_latex( state: Union[Statevector, DensityMatrix], dims: bool = None, convention: str = "ket", **args ) -> str: """Return a Latex representation of a state. Wrapper function for `qiskit.visualization.array_to_latex` for convention 'vector'. Adds dims if necessary. Intended for use within `state_drawer`. Args: state: State to be drawn dims (bool): Whether to display the state's `dims` convention (str): Either 'vector' or 'ket'. For 'ket' plot the state in the ket-notation. Otherwise plot as a vector **args: Arguments to be passed directly to `array_to_latex` for convention 'ket' Returns: Latex representation of the state """ if dims is None: # show dims if state is not only qubits if set(state.dims()) == {2}: dims = False else: dims = True prefix = "" suffix = "" if dims: prefix = "\\begin{align}\n" dims_str = state._op_shape.dims_l() suffix = f"\\\\\n\\text{{dims={dims_str}}}\n\\end{{align}}" operator_shape = state._op_shape # we only use the ket convetion for qubit statevectors # this means the operator shape should hve no input dimensions and all output dimensions equal to 2 is_qubit_statevector = len(operator_shape.dims_r()) == 0 and set(operator_shape.dims_l()) == {2} if convention == "ket" and is_qubit_statevector: latex_str = _state_to_latex_ket(state._data, **args) else: latex_str = array_to_latex(state._data, source=True, **args) return prefix + latex_str + suffix @deprecate_func( additional_msg="For similar functionality, see sympy's ``nsimplify`` and ``latex`` functions.", since="0.23.0", ) def num_to_latex_ket(raw_value: complex, first_term: bool, decimals: int = 10) -> Optional[str]: """Convert a complex number to latex code suitable for a ket expression Args: raw_value: Value to convert first_term: If True then generate latex code for the first term in an expression decimals: Number of decimal places to round to (default: 10). Returns: String with latex code or None if no term is required """ if np.around(np.abs(raw_value), decimals=decimals) == 0: return None return _num_to_latex(raw_value, first_term=first_term, decimals=decimals, coefficient=True) @deprecate_func( additional_msg="For similar functionality, see sympy's ``nsimplify`` and ``latex`` functions.", since="0.23.0", ) def numbers_to_latex_terms(numbers: List[complex], decimals: int = 10) -> List[str]: """Convert a list of numbers to latex formatted terms The first non-zero term is treated differently. For this term a leading + is suppressed. Args: numbers: List of numbers to format decimals: Number of decimal places to round to (default: 10). Returns: List of formatted terms """ first_term = True terms = [] for number in numbers: term = num_to_latex_ket(number, first_term, decimals) if term is not None: first_term = False terms.append(term) return terms def _numbers_to_latex_terms(numbers: List[complex], decimals: int = 10) -> List[str]: """Convert a list of numbers to latex formatted terms The first non-zero term is treated differently. For this term a leading + is suppressed. Args: numbers: List of numbers to format decimals: Number of decimal places to round to (default: 10). Returns: List of formatted terms """ first_term = True terms = [] for number in numbers: term = _num_to_latex(number, decimals=decimals, first_term=first_term, coefficient=True) terms.append(term) first_term = False return terms def _state_to_latex_ket( data: List[complex], max_size: int = 12, prefix: str = "", decimals: int = 10 ) -> str: """Convert state vector to latex representation Args: data: State vector max_size: Maximum number of non-zero terms in the expression. If the number of non-zero terms is larger than the max_size, then the representation is truncated. prefix: Latex string to be prepended to the latex, intended for labels. decimals: Number of decimal places to round to (default: 10). Returns: String with LaTeX representation of the state vector """ num = int(np.log2(len(data))) def ket_name(i): return bin(i)[2:].zfill(num) data = np.around(data, decimals) nonzero_indices = np.where(data != 0)[0].tolist() if len(nonzero_indices) > max_size: nonzero_indices = ( nonzero_indices[: max_size // 2] + [0] + nonzero_indices[-max_size // 2 + 1 :] ) latex_terms = _numbers_to_latex_terms(data[nonzero_indices], decimals) nonzero_indices[max_size // 2] = None else: latex_terms = _numbers_to_latex_terms(data[nonzero_indices], decimals) latex_str = "" for idx, ket_idx in enumerate(nonzero_indices): if ket_idx is None: latex_str += r" + \ldots " else: term = latex_terms[idx] ket = ket_name(ket_idx) latex_str += f"{term} |{ket}\\rangle" return prefix + latex_str class TextMatrix: """Text representation of an array, with `__str__` method so it displays nicely in Jupyter notebooks""" def __init__(self, state, max_size=8, dims=None, prefix="", suffix=""): self.state = state self.max_size = max_size if dims is None: # show dims if state is not only qubits if (isinstance(state, (Statevector, DensityMatrix)) and set(state.dims()) == {2}) or ( isinstance(state, Operator) and len(state.input_dims()) == len(state.output_dims()) and set(state.input_dims()) == set(state.output_dims()) == {2} ): dims = False else: dims = True self.dims = dims self.prefix = prefix self.suffix = suffix if isinstance(max_size, int): self.max_size = max_size elif isinstance(state, DensityMatrix): # density matrices are square, so threshold for # summarization is shortest side squared self.max_size = min(max_size) ** 2 else: self.max_size = max_size[0] def __str__(self): threshold = self.max_size data = np.array2string( self.state._data, prefix=self.prefix, threshold=threshold, separator="," ) dimstr = "" if self.dims: data += ",\n" dimstr += " " * len(self.prefix) if isinstance(self.state, (Statevector, DensityMatrix)): dimstr += f"dims={self.state._op_shape.dims_l()}" else: dimstr += f"input_dims={self.state.input_dims()}, " dimstr += f"output_dims={self.state.output_dims()}" return self.prefix + data + dimstr + self.suffix def __repr__(self): return self.__str__() def state_drawer(state, output=None, **drawer_args): """Returns a visualization of the state. **repr**: ASCII TextMatrix of the state's ``_repr_``. **text**: ASCII TextMatrix that can be printed in the console. **latex**: An IPython Latex object for displaying in Jupyter Notebooks. **latex_source**: Raw, uncompiled ASCII source to generate array using LaTeX. **qsphere**: Matplotlib figure, rendering of statevector using `plot_state_qsphere()`. **hinton**: Matplotlib figure, rendering of statevector using `plot_state_hinton()`. **bloch**: Matplotlib figure, rendering of statevector using `plot_bloch_multivector()`. **city**: Matplotlib figure, rendering of statevector using `plot_state_city()`. **paulivec**: Matplotlib figure, rendering of statevector using `plot_state_paulivec()`. Args: output (str): Select the output method to use for drawing the circuit. Valid choices are ``text``, ``latex``, ``latex_source``, ``qsphere``, ``hinton``, ``bloch``, ``city`` or ``paulivec``. Default is `'text`'. drawer_args: Arguments to be passed to the relevant drawer. For 'latex' and 'latex_source' see ``array_to_latex`` Returns: :class:`matplotlib.figure` or :class:`str` or :class:`TextMatrix` or :class:`IPython.display.Latex`: Drawing of the state. Raises: MissingOptionalLibraryError: when `output` is `latex` and IPython is not installed. ValueError: when `output` is not a valid selection. """ config = user_config.get_config() # Get default 'output' from config file else use 'repr' default_output = "repr" if output is None: if config: default_output = config.get("state_drawer", "repr") output = default_output output = output.lower() # Choose drawing backend: drawers = { "text": TextMatrix, "latex_source": state_to_latex, "qsphere": plot_state_qsphere, "hinton": plot_state_hinton, "bloch": plot_bloch_multivector, "city": plot_state_city, "paulivec": plot_state_paulivec, } if output == "latex": _optionals.HAS_IPYTHON.require_now("state_drawer") from IPython.display import Latex draw_func = drawers["latex_source"] return Latex(f"$${draw_func(state, **drawer_args)}$$") if output == "repr": return state.__repr__() try: draw_func = drawers[output] return draw_func(state, **drawer_args) except KeyError as err: raise ValueError( """'{}' is not a valid option for drawing {} objects. Please choose from: 'text', 'latex', 'latex_source', 'qsphere', 'hinton', 'bloch', 'city' or 'paulivec'.""".format( output, type(state).__name__ ) ) from err def _bloch_multivector_data(state): """Return list of Bloch vectors for each qubit Args: state (DensityMatrix or Statevector): an N-qubit state. Returns: list: list of Bloch vectors (x, y, z) for each qubit. Raises: VisualizationError: if input is not an N-qubit state. """ rho = DensityMatrix(state) num = rho.num_qubits if num is None: raise VisualizationError("Input is not a multi-qubit quantum state.") pauli_singles = PauliList(["X", "Y", "Z"]) bloch_data = [] for i in range(num): if num > 1: paulis = PauliList.from_symplectic( np.zeros((3, (num - 1)), dtype=bool), np.zeros((3, (num - 1)), dtype=bool) ).insert(i, pauli_singles, qubit=True) else: paulis = pauli_singles bloch_state = [np.real(np.trace(np.dot(mat, rho.data))) for mat in paulis.matrix_iter()] bloch_data.append(bloch_state) return bloch_data def _paulivec_data(state): """Return paulivec data for plotting. Args: state (DensityMatrix or Statevector): an N-qubit state. Returns: tuple: (labels, values) for Pauli vector. Raises: VisualizationError: if input is not an N-qubit state. """ rho = SparsePauliOp.from_operator(DensityMatrix(state)) if rho.num_qubits is None: raise VisualizationError("Input is not a multi-qubit quantum state.") return rho.paulis.to_labels(), np.real(rho.coeffs * 2**rho.num_qubits)
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # 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/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """mpl circuit visualization style.""" import json import os from warnings import warn from qiskit import user_config class DefaultStyle: """Creates a Default Style dictionary **Style Dict Details** The style dict contains numerous options that define the style of the output circuit visualization. The style dict is used by the `mpl` or `latex` output. The options available in the style dict are defined below: name (str): the name of the style. The name can be set to ``iqx``, ``iqx-dark``, ``textbook``, ``bw``, ``default``, or the name of a user-created json file. This overrides the setting in the user config file (usually ``~/.qiskit/settings.conf``). textcolor (str): the color code to use for all text not inside a gate. Defaults to ``#000000`` subtextcolor (str): the color code to use for subtext. Defaults to ``#000000`` linecolor (str): the color code to use for lines. Defaults to ``#000000`` creglinecolor (str): the color code to use for classical register lines. Defaults to ``#778899`` gatetextcolor (str): the color code to use for gate text. Defaults to ``#000000`` gatefacecolor (str): the color code to use for a gate if no color specified in the 'displaycolor' dict. Defaults to ``#BB8BFF`` barrierfacecolor (str): the color code to use for barriers. Defaults to ``#BDBDBD`` backgroundcolor (str): the color code to use for the background. Defaults to ``#FFFFFF`` edgecolor (str): the color code to use for gate edges when using the `bw` style. Defaults to ``#000000``. fontsize (int): the font size to use for text. Defaults to 13. subfontsize (int): the font size to use for subtext. Defaults to 8. showindex (bool): if set to True, show the index numbers at the top. Defaults to False. figwidth (int): the maximum width (in inches) for the output figure. If set to -1, the maximum displayable width will be used. Defaults to -1. dpi (int): the DPI to use for the output image. Defaults to 150. margin (list): a list of margin values to adjust spacing around output image. Takes a list of 4 ints: [x left, x right, y bottom, y top]. Defaults to [2.0, 0.1, 0.1, 0.3]. 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``. displaytext (dict): a dictionary of the text to use for certain element types in the output visualization. These items allow the use of LaTeX formatting for gate names. The 'displaytext' dict can contain any number of elements. User created names and labels may be used as keys, which allow these to have Latex formatting. The default values are (`default.json`):: { 'u1': 'U_1', 'u2': 'U_2', 'u3': 'U_3', 'sdg': 'S^\\dagger', 'sx': '\\sqrt{X}', 'sxdg': '\\sqrt{X}^\\dagger', 't': 'T', 'tdg': 'T^\\dagger', 'dcx': 'Dcx', 'iswap': 'Iswap', 'ms': 'MS', 'rx': 'R_X', 'ry': 'R_Y', 'rz': 'R_Z', 'rxx': 'R_{XX}', 'ryy': 'R_{YY}', 'rzx': 'R_{ZX}', 'rzz': 'ZZ', 'reset': '\\left|0\\right\\rangle', 'initialize': '|\\psi\\rangle' } displaycolor (dict): the color codes to use for each circuit element in the form (gate_color, text_color). Colors can also be entered without the text color, such as 'u1': '#FA74A6', in which case the text color will always be `gatetextcolor`. The `displaycolor` dict can contain any number of elements. User names and labels may be used as keys, which allows for custom colors for user-created gates. The default values are (`default.json`):: { 'u1': ('#FA74A6', '#000000'), 'u2': ('#FA74A6', '#000000'), 'u3': ('#FA74A6', '#000000'), 'id': ('#05BAB6', '#000000'), 'u': ('#BB8BFF', '#000000'), 'p': ('#BB8BFF', '#000000'), 'x': ('#05BAB6', '#000000'), 'y': ('#05BAB6', '#000000'), 'z': ('#05BAB6', '#000000'), 'h': ('#6FA4FF', '#000000'), 'cx': ('#6FA4FF', '#000000'), 'ccx': ('#BB8BFF', '#000000'), 'mcx': ('#BB8BFF', '#000000'), 'mcx_gray': ('#BB8BFF', '#000000'), 'cy': ('#6FA4FF', '#000000'), 'cz': ('#6FA4FF', '#000000'), 'swap': ('#6FA4FF', '#000000'), 'cswap': ('#BB8BFF', '#000000'), 'ccswap': ('#BB8BFF', '#000000'), 'dcx': ('#6FA4FF', '#000000'), 'cdcx': ('#BB8BFF', '#000000'), 'ccdcx': ('#BB8BFF', '#000000'), 'iswap': ('#6FA4FF', '#000000'), 's': ('#6FA4FF', '#000000'), 'sdg': ('#6FA4FF', '#000000'), 't': ('#BB8BFF', '#000000'), 'tdg': ('#BB8BFF', '#000000'), 'sx': ('#6FA4FF', '#000000'), 'sxdg': ('#6FA4FF', '#000000') 'r': ('#BB8BFF', '#000000'), 'rx': ('#BB8BFF', '#000000'), 'ry': ('#BB8BFF', '#000000'), 'rz': ('#BB8BFF', '#000000'), 'rxx': ('#BB8BFF', '#000000'), 'ryy': ('#BB8BFF', '#000000'), 'rzx': ('#BB8BFF', '#000000'), 'reset': ('#000000', '#FFFFFF'), 'target': ('#FFFFFF', '#FFFFFF'), 'measure': ('#000000', '#FFFFFF'), } """ def __init__(self): colors = { "### Default Colors": "Default Colors", "basis": "#FA74A6", # Red "clifford": "#6FA4FF", # Light Blue "pauli": "#05BAB6", # Green "def_other": "#BB8BFF", # Purple "### IQX Colors": "IQX Colors", "classical": "#002D9C", # Dark Blue "phase": "#33B1FF", # Cyan "hadamard": "#FA4D56", # Light Red "non_unitary": "#A8A8A8", # Medium Gray "iqx_other": "#9F1853", # Dark Red "### B/W": "B/W", "black": "#000000", "white": "#FFFFFF", "dark_gray": "#778899", "light_gray": "#BDBDBD", } self.style = { "name": "default", "tc": colors["black"], # Non-gate Text Color "gt": colors["black"], # Gate Text Color "sc": colors["black"], # Gate Subtext Color "lc": colors["black"], # Line Color "cc": colors["dark_gray"], # creg Line Color "gc": colors["def_other"], # Default Gate Color "bc": colors["light_gray"], # Barrier Color "bg": colors["white"], # Background Color "ec": None, # Edge Color (B/W only) "fs": 13, # Gate Font Size "sfs": 8, # Subtext Font Size "index": False, "figwidth": -1, "dpi": 150, "margin": [2.0, 0.1, 0.1, 0.3], "cline": "doublet", "disptex": { "u1": "U_1", "u2": "U_2", "u3": "U_3", "id": "I", "sdg": "S^\\dagger", "sx": "\\sqrt{X}", "sxdg": "\\sqrt{X}^\\dagger", "tdg": "T^\\dagger", "ms": "MS", "rx": "R_X", "ry": "R_Y", "rz": "R_Z", "rxx": "R_{XX}", "ryy": "R_{YY}", "rzx": "R_{ZX}", "rzz": "ZZ", "reset": "\\left|0\\right\\rangle", "initialize": "$|\\psi\\rangle$", }, "dispcol": { "u1": (colors["basis"], colors["black"]), "u2": (colors["basis"], colors["black"]), "u3": (colors["basis"], colors["black"]), "u": (colors["def_other"], colors["black"]), "p": (colors["def_other"], colors["black"]), "id": (colors["pauli"], colors["black"]), "x": (colors["pauli"], colors["black"]), "y": (colors["pauli"], colors["black"]), "z": (colors["pauli"], colors["black"]), "h": (colors["clifford"], colors["black"]), "cx": (colors["clifford"], colors["black"]), "ccx": (colors["def_other"], colors["black"]), "mcx": (colors["def_other"], colors["black"]), "mcx_gray": (colors["def_other"], colors["black"]), "cy": (colors["clifford"], colors["black"]), "cz": (colors["clifford"], colors["black"]), "swap": (colors["clifford"], colors["black"]), "cswap": (colors["def_other"], colors["black"]), "ccswap": (colors["def_other"], colors["black"]), "dcx": (colors["clifford"], colors["black"]), "cdcx": (colors["def_other"], colors["black"]), "ccdcx": (colors["def_other"], colors["black"]), "iswap": (colors["clifford"], colors["black"]), "s": (colors["clifford"], colors["black"]), "sdg": (colors["clifford"], colors["black"]), "t": (colors["def_other"], colors["black"]), "tdg": (colors["def_other"], colors["black"]), "sx": (colors["clifford"], colors["black"]), "sxdg": (colors["clifford"], colors["black"]), "r": (colors["def_other"], colors["black"]), "rx": (colors["def_other"], colors["black"]), "ry": (colors["def_other"], colors["black"]), "rz": (colors["def_other"], colors["black"]), "rxx": (colors["def_other"], colors["black"]), "ryy": (colors["def_other"], colors["black"]), "rzx": (colors["def_other"], colors["black"]), "reset": (colors["black"], colors["white"]), "target": (colors["white"], colors["white"]), "measure": (colors["black"], colors["white"]), }, } def load_style(style): """Utility function to load style from json files and call set_style.""" current_style = DefaultStyle().style style_name = "default" def_font_ratio = current_style["fs"] / current_style["sfs"] config = user_config.get_config() if style is None: if config: style = config.get("circuit_mpl_style", "default") else: style = "default" if style is False: style_name = "bw" elif isinstance(style, dict) and "name" in style: style_name = style["name"] elif isinstance(style, str): style_name = style elif not isinstance(style, (str, dict)): warn( f"style parameter '{style}' must be a str or a dictionary. Will use default style.", UserWarning, 2, ) if style_name.endswith(".json"): style_name = style_name[:-5] # Search for file in 'styles' dir, then config_path, and finally 'cwd' style_path = [] if style_name != "default": style_name = style_name + ".json" spath = os.path.dirname(os.path.abspath(__file__)) style_path.append(os.path.join(spath, "styles", style_name)) if config: config_path = config.get("circuit_mpl_style_path", "") if config_path: for path in config_path: style_path.append(os.path.normpath(os.path.join(path, style_name))) style_path.append(os.path.normpath(os.path.join("", style_name))) for path in style_path: exp_user = os.path.expanduser(path) if os.path.isfile(exp_user): try: with open(exp_user) as infile: json_style = json.load(infile) set_style(current_style, json_style) break except json.JSONDecodeError as err: warn( f"Could not decode JSON in file '{path}': {str(err)}. " "Will use default style.", UserWarning, 2, ) break except (OSError, FileNotFoundError): warn( f"Error loading JSON file '{path}'. Will use default style.", UserWarning, 2, ) break else: warn( f"Style JSON file '{style_name}' not found in any of these locations: " f"{', '.join(style_path)}. " "Will use default style.", UserWarning, 2, ) if isinstance(style, dict): set_style(current_style, style) return current_style, def_font_ratio def set_style(current_style, new_style): """Utility function to take elements in new_style and write them into current_style. """ valid_fields = { "name", "textcolor", "gatetextcolor", "subtextcolor", "linecolor", "creglinecolor", "gatefacecolor", "barrierfacecolor", "backgroundcolor", "edgecolor", "fontsize", "subfontsize", "showindex", "figwidth", "dpi", "margin", "creglinestyle", "displaytext", "displaycolor", } current_style.update(new_style) current_style["tc"] = current_style.get("textcolor", current_style["tc"]) current_style["gt"] = current_style.get("gatetextcolor", current_style["gt"]) current_style["sc"] = current_style.get("subtextcolor", current_style["sc"]) current_style["lc"] = current_style.get("linecolor", current_style["lc"]) current_style["cc"] = current_style.get("creglinecolor", current_style["cc"]) current_style["gc"] = current_style.get("gatefacecolor", current_style["gc"]) current_style["bc"] = current_style.get("barrierfacecolor", current_style["bc"]) current_style["bg"] = current_style.get("backgroundcolor", current_style["bg"]) current_style["ec"] = current_style.get("edgecolor", current_style["ec"]) current_style["fs"] = current_style.get("fontsize", current_style["fs"]) current_style["sfs"] = current_style.get("subfontsize", current_style["sfs"]) current_style["index"] = current_style.get("showindex", current_style["index"]) current_style["cline"] = current_style.get("creglinestyle", current_style["cline"]) current_style["disptex"] = {**current_style["disptex"], **new_style.get("displaytext", {})} current_style["dispcol"] = {**current_style["dispcol"], **new_style.get("displaycolor", {})} unsupported_keys = set(new_style) - valid_fields if unsupported_keys: warn( f"style option/s ({', '.join(unsupported_keys)}) is/are not supported", UserWarning, 2, )