repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 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. """Measurement error mitigation""" import copy from typing import List, Optional, Tuple, Dict, Callable from qiskit import compiler from qiskit.providers import Backend from qiskit.circuit import QuantumCircuit from qiskit.qobj import QasmQobj from qiskit.assembler.run_config import RunConfig from qiskit.exceptions import QiskitError from qiskit.utils.mitigation import ( complete_meas_cal, tensored_meas_cal, CompleteMeasFitter, TensoredMeasFitter, ) from qiskit.utils.deprecation import deprecate_func @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def get_measured_qubits( transpiled_circuits: List[QuantumCircuit], ) -> Tuple[List[int], Dict[str, List[int]]]: """ Deprecated: Retrieve the measured qubits from transpiled circuits. Args: transpiled_circuits: a list of transpiled circuits Returns: The used and sorted qubit index Key is qubit index str connected by '_', value is the experiment index. {str: list[int]} Raises: QiskitError: invalid qubit mapping """ qubit_index = None qubit_mappings = {} for idx, qc in enumerate(transpiled_circuits): measured_qubits = [] for instruction in qc.data: if instruction.operation.name != "measure": continue for qreg in qc.qregs: if instruction.qubits[0] in qreg: index = qreg[:].index(instruction.qubits[0]) measured_qubits.append(index) break measured_qubits_str = "_".join([str(x) for x in measured_qubits]) if measured_qubits_str not in qubit_mappings: qubit_mappings[measured_qubits_str] = [] qubit_mappings[measured_qubits_str].append(idx) if qubit_index is None: qubit_index = measured_qubits elif set(qubit_index) != set(measured_qubits): raise QiskitError( "The used qubit index are different. ({}) vs ({}).\nCurrently, " "we only support all circuits using the same set of qubits " "regardless qubit order.".format(qubit_index, measured_qubits) ) return sorted(qubit_index), qubit_mappings @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def get_measured_qubits_from_qobj(qobj: QasmQobj) -> Tuple[List[int], Dict[str, List[int]]]: """ Deprecated: Retrieve the measured qubits from transpiled circuits. Args: qobj: qobj Returns: the used and sorted qubit index key is qubit index str connected by '_', value is the experiment index. {str: list[int]} Raises: QiskitError: invalid qubit mapping """ qubit_index = None qubit_mappings = {} for idx, exp in enumerate(qobj.experiments): measured_qubits = [] for instr in exp.instructions: if instr.name != "measure": continue measured_qubits.append(instr.qubits[0]) measured_qubits_str = "_".join([str(x) for x in measured_qubits]) if measured_qubits_str not in qubit_mappings: qubit_mappings[measured_qubits_str] = [] qubit_mappings[measured_qubits_str].append(idx) if qubit_index is None: qubit_index = measured_qubits else: if set(qubit_index) != set(measured_qubits): raise QiskitError( "The used qubit index are different. ({}) vs ({}).\nCurrently, " "we only support all circuits using the same set of qubits " "regardless qubit order.".format(qubit_index, measured_qubits) ) return sorted(qubit_index), qubit_mappings @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def build_measurement_error_mitigation_circuits( qubit_list: List[int], fitter_cls: Callable, backend: Backend, backend_config: Optional[Dict] = None, compile_config: Optional[Dict] = None, mit_pattern: Optional[List[List[int]]] = None, ) -> Tuple[QuantumCircuit, List[str], List[str]]: """Deprecated: Build measurement error mitigation circuits Args: qubit_list: list of ordered qubits used in the algorithm fitter_cls: CompleteMeasFitter or TensoredMeasFitter backend: backend instance backend_config: configuration for backend compile_config: configuration for compilation mit_pattern: Qubits on which to perform the measurement correction, divided to groups according to tensors. If `None` and `qr` is given then assumed to be performed over the entire `qr` as one group (default `None`). Returns: the circuit the state labels for build MeasFitter the labels of the calibration circuits Raises: QiskitError: when the fitter_cls is not recognizable. """ circlabel = "mcal" if not qubit_list: raise QiskitError("The measured qubit list can not be [].") run = False if fitter_cls == CompleteMeasFitter: meas_calibs_circuits, state_labels = complete_meas_cal( qubit_list=range(len(qubit_list)), circlabel=circlabel ) run = True elif fitter_cls == TensoredMeasFitter: meas_calibs_circuits, state_labels = tensored_meas_cal( mit_pattern=mit_pattern, circlabel=circlabel ) run = True if not run: try: from qiskit.ignis.mitigation.measurement import ( CompleteMeasFitter as CompleteMeasFitter_IG, TensoredMeasFitter as TensoredMeasFitter_IG, ) except ImportError as ex: # If ignis can't be imported we don't have a valid fitter # class so just fail here with an appropriate error message raise QiskitError(f"Unknown fitter {fitter_cls}") from ex if fitter_cls == CompleteMeasFitter_IG: meas_calibs_circuits, state_labels = complete_meas_cal( qubit_list=range(len(qubit_list)), circlabel=circlabel ) elif fitter_cls == TensoredMeasFitter_IG: meas_calibs_circuits, state_labels = tensored_meas_cal( mit_pattern=mit_pattern, circlabel=circlabel ) else: raise QiskitError(f"Unknown fitter {fitter_cls}") # the provided `qubit_list` would be used as the initial layout to # assure the consistent qubit mapping used in the main circuits. tmp_compile_config = copy.deepcopy(compile_config) tmp_compile_config["initial_layout"] = qubit_list t_meas_calibs_circuits = compiler.transpile( meas_calibs_circuits, backend, **backend_config, **tmp_compile_config ) return t_meas_calibs_circuits, state_labels, circlabel @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def build_measurement_error_mitigation_qobj( qubit_list: List[int], fitter_cls: Callable, backend: Backend, backend_config: Optional[Dict] = None, compile_config: Optional[Dict] = None, run_config: Optional[RunConfig] = None, mit_pattern: Optional[List[List[int]]] = None, ) -> Tuple[QasmQobj, List[str], List[str]]: """ Args: qubit_list: list of ordered qubits used in the algorithm fitter_cls: CompleteMeasFitter or TensoredMeasFitter backend: backend instance backend_config: configuration for backend compile_config: configuration for compilation run_config: configuration for running a circuit mit_pattern: Qubits on which to perform the measurement correction, divided to groups according to tensors. If `None` and `qr` is given then assumed to be performed over the entire `qr` as one group (default `None`). Returns: the Qobj with calibration circuits at the beginning the state labels for build MeasFitter the labels of the calibration circuits Raises: QiskitError: when the fitter_cls is not recognizable. MissingOptionalLibraryError: Qiskit-Ignis not installed """ circlabel = "mcal" if not qubit_list: raise QiskitError("The measured qubit list can not be [].") if fitter_cls == CompleteMeasFitter: meas_calibs_circuits, state_labels = complete_meas_cal( qubit_list=range(len(qubit_list)), circlabel=circlabel ) elif fitter_cls == TensoredMeasFitter: meas_calibs_circuits, state_labels = tensored_meas_cal( mit_pattern=mit_pattern, circlabel=circlabel ) else: raise QiskitError(f"Unknown fitter {fitter_cls}") # the provided `qubit_list` would be used as the initial layout to # assure the consistent qubit mapping used in the main circuits. tmp_compile_config = copy.deepcopy(compile_config) tmp_compile_config["initial_layout"] = qubit_list t_meas_calibs_circuits = compiler.transpile( meas_calibs_circuits, backend, **backend_config, **tmp_compile_config ) cals_qobj = compiler.assemble(t_meas_calibs_circuits, backend, **run_config.to_dict()) if hasattr(cals_qobj.config, "parameterizations"): del cals_qobj.config.parameterizations return cals_qobj, state_labels, circlabel
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import logging import time from qiskit import __version__ as terra_version from qiskit.assembler.run_config import RunConfig from qiskit.transpiler import Layout from .utils import (run_qobjs, compile_circuits, CircuitCache, get_measured_qubits_from_qobj, build_measurement_error_mitigation_fitter, mitigate_measurement_error) from .utils.backend_utils import (is_aer_provider, is_ibmq_provider, is_statevector_backend, is_simulator_backend, is_local_backend) logger = logging.getLogger(__name__) class QuantumInstance: """Quantum Backend including execution setting.""" BACKEND_CONFIG = ['basis_gates', 'coupling_map'] COMPILE_CONFIG = ['pass_manager', 'initial_layout', 'seed_transpiler'] RUN_CONFIG = ['shots', 'max_credits', 'memory', 'seed'] QJOB_CONFIG = ['timeout', 'wait'] NOISE_CONFIG = ['noise_model'] # https://github.com/Qiskit/qiskit-aer/blob/master/qiskit/providers/aer/backends/qasm_simulator.py BACKEND_OPTIONS_QASM_ONLY = ["statevector_sample_measure_opt", "max_parallel_shots"] BACKEND_OPTIONS = ["initial_statevector", "chop_threshold", "max_parallel_threads", "max_parallel_experiments", "statevector_parallel_threshold", "statevector_hpc_gate_opt"] + BACKEND_OPTIONS_QASM_ONLY def __init__(self, backend, shots=1024, seed=None, max_credits=10, basis_gates=None, coupling_map=None, initial_layout=None, pass_manager=None, seed_transpiler=None, backend_options=None, noise_model=None, timeout=None, wait=5, circuit_caching=True, cache_file=None, skip_qobj_deepcopy=True, skip_qobj_validation=True, measurement_error_mitigation_cls=None, cals_matrix_refresh_period=30): """Constructor. Args: backend (BaseBackend): instance of selected backend shots (int, optional): number of repetitions of each circuit, for sampling seed (int, optional): random seed for simulators max_credits (int, optional): maximum credits to use basis_gates (list[str], optional): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list[list]): coupling map (perhaps custom) to target in mapping initial_layout (dict, optional): initial layout of qubits in mapping pass_manager (PassManager, optional): pass manager to handle how to compile the circuits seed_transpiler (int, optional): the random seed for circuit mapper backend_options (dict, optional): all running options for backend, please refer to the provider. noise_model (qiskit.provider.aer.noise.noise_model.NoiseModel, optional): noise model for simulator timeout (float, optional): seconds to wait for job. If None, wait indefinitely. wait (float, optional): seconds between queries to result circuit_caching (bool, optional): USe CircuitCache when calling compile_and_run_circuits cache_file(str, optional): filename into which to store the cache as a pickle file skip_qobj_deepcopy (bool, optional): Reuses the same qobj object over and over to avoid deepcopying skip_qobj_validation (bool, optional): Bypass Qobj validation to decrease submission time measurement_error_mitigation_cls (callable, optional): the approach to mitigate measurement error, CompleteMeasFitter or TensoredMeasFitter cals_matrix_refresh_period (int): how long to refresh the calibration matrix in measurement mitigation, unit in minutes """ self._backend = backend # setup run config run_config = RunConfig(shots=shots, max_credits=max_credits) if seed: run_config.seed = seed if getattr(run_config, 'shots', None) is not None: if self.is_statevector and run_config.shots != 1: logger.info("statevector backend only works with shot=1, change " "shots from {} to 1.".format(run_config.shots)) run_config.shots = 1 self._run_config = run_config # setup backend config basis_gates = basis_gates or backend.configuration().basis_gates coupling_map = coupling_map or getattr(backend.configuration(), 'coupling_map', None) self._backend_config = { 'basis_gates': basis_gates, 'coupling_map': coupling_map } # setup noise config noise_config = None if noise_model is not None: if is_aer_provider(self._backend): if not self.is_statevector: noise_config = noise_model else: logger.info("The noise model can be only used with Aer qasm simulator. " "Change it to None.") else: logger.info("The noise model can be only used with Qiskit Aer. " "Please install it.") self._noise_config = {} if noise_config is None else {'noise_model': noise_config} # setup compile config if initial_layout is not None and not isinstance(initial_layout, Layout): initial_layout = Layout(initial_layout) self._compile_config = { 'pass_manager': pass_manager, 'initial_layout': initial_layout, 'seed_transpiler': seed_transpiler } # setup job config self._qjob_config = {'timeout': timeout} if self.is_local \ else {'timeout': timeout, 'wait': wait} # setup backend options for run self._backend_options = {} if is_ibmq_provider(self._backend): logger.info("backend_options can not used with the backends in IBMQ provider.") else: self._backend_options = {} if backend_options is None \ else {'backend_options': backend_options} self._shared_circuits = False self._circuit_summary = False self._circuit_cache = CircuitCache(skip_qobj_deepcopy=skip_qobj_deepcopy, cache_file=cache_file) if circuit_caching else None self._skip_qobj_validation = skip_qobj_validation self._measurement_error_mitigation_cls = None if self.is_statevector: if measurement_error_mitigation_cls is not None: logger.info("Measurement error mitigation does not work with statevector simulation, disable it.") else: self._measurement_error_mitigation_cls = measurement_error_mitigation_cls self._measurement_error_mitigation_fitter = None self._measurement_error_mitigation_method = 'least_squares' self._cals_matrix_refresh_period = cals_matrix_refresh_period self._prev_timestamp = 0 if self._measurement_error_mitigation_cls is not None: logger.info("The measurement error mitigation is enable. " "It will automatically submit an additional job to help calibrate the result of other jobs. " "The current approach will submit a job with 2^N circuits to build the calibration matrix, " "where N is the number of measured qubits. " "Furthermore, Aqua will re-use the calibration matrix for {} minutes " "and re-build it after that.".format(self._cals_matrix_refresh_period)) logger.info(self) def __str__(self): """Overload string. Returns: str: the info of the object. """ info = "\nQiskit Terra version: {}\n".format(terra_version) info += "Backend: '{} ({})', with following setting:\n{}\n{}\n{}\n{}\n{}\n{}".format( self.backend_name, self._backend.provider(), self._backend_config, self._compile_config, self._run_config, self._qjob_config, self._backend_options, self._noise_config) info += "\nMeasurement mitigation: {}".format(self._measurement_error_mitigation_cls) return info def execute(self, circuits, **kwargs): """ A wrapper to interface with quantum backend. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute Returns: Result: Result object """ qobjs = compile_circuits(circuits, self._backend, self._backend_config, self._compile_config, self._run_config, show_circuit_summary=self._circuit_summary, circuit_cache=self._circuit_cache, **kwargs) if self._measurement_error_mitigation_cls is not None: if self.maybe_refresh_cals_matrix(): logger.info("Building calibration matrix for measurement error mitigation.") qubit_list = get_measured_qubits_from_qobj(qobjs) self._measurement_error_mitigation_fitter = build_measurement_error_mitigation_fitter(qubit_list, self._measurement_error_mitigation_cls, self._backend, self._backend_config, self._compile_config, self._run_config, self._qjob_config, self._backend_options, self._noise_config) result = run_qobjs(qobjs, self._backend, self._qjob_config, self._backend_options, self._noise_config, self._skip_qobj_validation) if self._measurement_error_mitigation_fitter is not None: result = mitigate_measurement_error(result, self._measurement_error_mitigation_fitter, self._measurement_error_mitigation_method) if self._circuit_summary: self._circuit_summary = False return result def set_config(self, **kwargs): """Set configurations for the quantum instance.""" for k, v in kwargs.items(): if k in QuantumInstance.RUN_CONFIG: setattr(self._run_config, k, v) elif k in QuantumInstance.QJOB_CONFIG: self._qjob_config[k] = v elif k in QuantumInstance.COMPILE_CONFIG: self._compile_config[k] = v elif k in QuantumInstance.BACKEND_CONFIG: self._backend_config[k] = v elif k in QuantumInstance.BACKEND_OPTIONS: if is_ibmq_provider(self._backend): logger.info("backend_options can not used with the backends in IBMQ provider.") else: if k in QuantumInstance.BACKEND_OPTIONS_QASM_ONLY and self.is_statevector: logger.info("'{}' is only applicable for qasm simulator but " "statevector simulator is used. Skip the setting.") else: if 'backend_options' not in self._backend_options: self._backend_options['backend_options'] = {} self._backend_options['backend_options'][k] = v elif k in QuantumInstance.NOISE_CONFIG: self._noise_config[k] = v else: raise ValueError("unknown setting for the key ({}).".format(k)) @property def qjob_config(self): """Getter of qjob_config.""" return self._qjob_config @property def backend_config(self): """Getter of backend_config.""" return self._backend_config @property def compile_config(self): """Getter of compile_config.""" return self._compile_config @property def run_config(self): """Getter of run_config.""" return self._run_config @property def noise_config(self): """Getter of noise_config.""" return self._noise_config @property def backend_options(self): """Getter of backend_options.""" return self._backend_options @property def shared_circuits(self): """Getter of shared_circuits.""" return self._shared_circuits @shared_circuits.setter def shared_circuits(self, new_value): self._shared_circuits = new_value @property def circuit_summary(self): """Getter of circuit summary.""" return self._circuit_summary @circuit_summary.setter def circuit_summary(self, new_value): self._circuit_summary = new_value @property def backend(self): """Return BaseBackend backend object.""" return self._backend @property def backend_name(self): """Return backend name.""" return self._backend.name() @property def is_statevector(self): """Return True if backend is a statevector-type simulator.""" return is_statevector_backend(self._backend) @property def is_simulator(self): """Return True if backend is a simulator.""" return is_simulator_backend(self._backend) @property def is_local(self): """Return True if backend is a local backend.""" return is_local_backend(self._backend) @property def circuit_cache(self): return self._circuit_cache @property def has_circuit_caching(self): return self._circuit_cache is not None @property def skip_qobj_validation(self): return self._skip_qobj_validation @skip_qobj_validation.setter def skip_qobj_validation(self, new_value): self._skip_qobj_validation = new_value def maybe_refresh_cals_matrix(self): """ Calculate the time difference from the query of last time. Returns: bool: whether or not refresh the cals_matrix """ ret = False curr_timestamp = time.time() difference = int(curr_timestamp - self._prev_timestamp) / 60.0 if difference > self._cals_matrix_refresh_period: self._prev_timestamp = curr_timestamp ret = True return ret @property def cals_matrix(self): cals_matrix = None if self._measurement_error_mitigation_fitter is not None: cals_matrix = self._measurement_error_mitigation_fitter.cal_matrix return cals_matrix
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- 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 sys import logging import time import copy import os import uuid import numpy as np from qiskit import compiler from qiskit.assembler import assemble_circuits from qiskit.providers import BaseBackend, JobStatus, JobError from qiskit.providers.basicaer import BasicAerJob from qiskit.qobj import QobjHeader from qiskit.aqua.aqua_error import AquaError from qiskit.aqua.utils import summarize_circuits from qiskit.aqua.utils.backend_utils import (is_aer_provider, is_basicaer_provider, is_ibmq_provider, is_simulator_backend, is_local_backend) MAX_CIRCUITS_PER_JOB = os.environ.get('QISKIT_AQUA_MAX_CIRCUITS_PER_JOB', None) logger = logging.getLogger(__name__) def find_regs_by_name(circuit, name, qreg=True): """Find the registers in the circuits. Args: circuit (QuantumCircuit): the quantum circuit. name (str): name of register qreg (bool): quantum or classical register Returns: QuantumRegister or ClassicalRegister or None: if not found, return None. """ found_reg = None regs = circuit.qregs if qreg else circuit.cregs for reg in regs: if reg.name == name: found_reg = reg break return found_reg def _avoid_empty_circuits(circuits): new_circuits = [] for qc in circuits: if len(qc) == 0: tmp_q = None for q in qc.qregs: tmp_q = q break if tmp_q is None: raise NameError("A QASM without any quantum register is invalid.") qc.iden(tmp_q[0]) new_circuits.append(qc) return new_circuits def _combine_result_objects(results): """Tempoary helper function. TODO: This function would be removed after Terra supports job with infinite circuits. """ if len(results) == 1: return results[0] new_result = copy.deepcopy(results[0]) for idx in range(1, len(results)): new_result.results.extend(results[idx].results) return new_result def _maybe_add_aer_expectation_instruction(qobj, options): if 'expectation' in options: from qiskit.providers.aer.utils.qobj_utils import snapshot_instr, append_instr, get_instr_pos # add others, how to derive the correct used number of qubits? # the compiled qobj could be wrong if coupling map is used. params = options['expectation']['params'] num_qubits = options['expectation']['num_qubits'] for idx in range(len(qobj.experiments)): # if mulitple params are provided, we assume that each circuit is corresponding one param # otherwise, params are used for all circuits. param_idx = idx if len(params) > 1 else 0 snapshot_pos = get_instr_pos(qobj, idx, 'snapshot') if len(snapshot_pos) == 0: # does not append the instruction yet. new_ins = snapshot_instr('expectation_value_pauli', 'test', list(range(num_qubits)), params=params[param_idx]) qobj = append_instr(qobj, idx, new_ins) else: for i in snapshot_pos: # update all expectation_value_snapshot if qobj.experiments[idx].instructions[i].type == 'expectation_value_pauli': qobj.experiments[idx].instructions[i].params = params[param_idx] return qobj def _compile_wrapper(circuits, backend, backend_config, compile_config, run_config): transpiled_circuits = compiler.transpile(circuits, backend, **backend_config, **compile_config) if not isinstance(transpiled_circuits, list): transpiled_circuits = [transpiled_circuits] qobj = assemble_circuits(transpiled_circuits, qobj_id=str(uuid.uuid4()), qobj_header=QobjHeader(), run_config=run_config) return qobj, transpiled_circuits def compile_circuits(circuits, backend, backend_config=None, compile_config=None, run_config=None, show_circuit_summary=False, circuit_cache=None, **kwargs): """ An execution wrapper with Qiskit-Terra, with job auto recover capability. The autorecovery feature is only applied for non-simulator backend. This wraper will try to get the result no matter how long it costs. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute backend (BaseBackend): backend instance backend_config (dict, optional): configuration for backend compile_config (dict, optional): configuration for compilation run_config (RunConfig, optional): configuration for running a circuit show_circuit_summary (bool, optional): showing the summary of submitted circuits. circuit_cache (CircuitCache, optional): A CircuitCache to use when calling compile_and_run_circuits Returns: QasmObj: compiled qobj. Raises: AquaError: Any error except for JobError raised by Qiskit Terra """ backend_config = backend_config or {} compile_config = compile_config or {} run_config = run_config or {} if backend is None or not isinstance(backend, BaseBackend): raise ValueError('Backend is missing or not an instance of BaseBackend') if not isinstance(circuits, list): circuits = [circuits] if is_simulator_backend(backend): circuits = _avoid_empty_circuits(circuits) if MAX_CIRCUITS_PER_JOB is not None: max_circuits_per_job = int(MAX_CIRCUITS_PER_JOB) else: if is_local_backend(backend): max_circuits_per_job = sys.maxsize else: max_circuits_per_job = backend.configuration().max_experiments if circuit_cache is not None and circuit_cache.try_reusing_qobjs: # Check if all circuits are the same length. # If not, don't try to use the same qobj.experiment for all of them. if len(set([len(circ.data) for circ in circuits])) > 1: circuit_cache.try_reusing_qobjs = False else: # Try setting up the reusable qobj # Compile and cache first circuit if cache is empty. The load method will try to reuse it if circuit_cache.qobjs is None: qobj, transpiled_circuits = _compile_wrapper([circuits[0]], backend, backend_config, compile_config, run_config) if is_aer_provider(backend): qobj = _maybe_add_aer_expectation_instruction(qobj, kwargs) circuit_cache.cache_circuit(qobj, [circuits[0]], 0) qobjs = [] transpiled_circuits = [] chunks = int(np.ceil(len(circuits) / max_circuits_per_job)) for i in range(chunks): sub_circuits = circuits[i * max_circuits_per_job:(i + 1) * max_circuits_per_job] if circuit_cache is not None and circuit_cache.misses < circuit_cache.allowed_misses: try: if circuit_cache.cache_transpiled_circuits: transpiled_sub_circuits = compiler.transpile(sub_circuits, backend, **backend_config, **compile_config) qobj = circuit_cache.load_qobj_from_cache(transpiled_sub_circuits, i, run_config=run_config) else: qobj = circuit_cache.load_qobj_from_cache(sub_circuits, i, run_config=run_config) if is_aer_provider(backend): qobj = _maybe_add_aer_expectation_instruction(qobj, kwargs) # cache miss, fail gracefully except (TypeError, IndexError, FileNotFoundError, EOFError, AquaError, AttributeError) as e: circuit_cache.try_reusing_qobjs = False # Reusing Qobj didn't work if len(circuit_cache.qobjs) > 0: logger.info('Circuit cache miss, recompiling. Cache miss reason: ' + repr(e)) circuit_cache.misses += 1 else: logger.info('Circuit cache is empty, compiling from scratch.') circuit_cache.clear_cache() qobj, transpiled_sub_circuits = _compile_wrapper(sub_circuits, backend, backend_config, compile_config, run_config) transpiled_circuits.extend(transpiled_sub_circuits) if is_aer_provider(backend): qobj = _maybe_add_aer_expectation_instruction(qobj, kwargs) try: circuit_cache.cache_circuit(qobj, sub_circuits, i) except (TypeError, IndexError, AquaError, AttributeError, KeyError) as e: try: circuit_cache.cache_transpiled_circuits = True circuit_cache.cache_circuit(qobj, transpiled_sub_circuits, i) except (TypeError, IndexError, AquaError, AttributeError, KeyError) as e: logger.info('Circuit could not be cached for reason: ' + repr(e)) logger.info('Transpilation may be too aggressive. Try skipping transpiler.') else: qobj, transpiled_sub_circuits = _compile_wrapper(sub_circuits, backend, backend_config, compile_config, run_config) transpiled_circuits.extend(transpiled_sub_circuits) if is_aer_provider(backend): qobj = _maybe_add_aer_expectation_instruction(qobj, kwargs) qobjs.append(qobj) if logger.isEnabledFor(logging.DEBUG) and show_circuit_summary: logger.debug("==== Before transpiler ====") logger.debug(summarize_circuits(circuits)) logger.debug("==== After transpiler ====") logger.debug(summarize_circuits(transpiled_circuits)) return qobjs def _safe_submit_qobj(qobj, backend, backend_options, noise_config, skip_qobj_validation): # assure get job ids while True: job = run_on_backend(backend, qobj, backend_options=backend_options, noise_config=noise_config, skip_qobj_validation=skip_qobj_validation) try: job_id = job.job_id() break except JobError as e: logger.warning("FAILURE: Can not get job id, Resubmit the qobj to get job id." "Terra job error: {} ".format(e)) except Exception as e: logger.warning("FAILURE: Can not get job id, Resubmit the qobj to get job id." "Error: {} ".format(e)) return job, job_id def run_qobjs(qobjs, backend, qjob_config=None, backend_options=None, noise_config=None, skip_qobj_validation=False): """ An execution wrapper with Qiskit-Terra, with job auto recover capability. The autorecovery feature is only applied for non-simulator backend. This wraper will try to get the result no matter how long it costs. Args: qobjs (list[QasmObj]): qobjs to execute backend (BaseBackend): backend instance qjob_config (dict, optional): configuration for quantum job object backend_options (dict, optional): configuration for simulator noise_config (dict, optional): configuration for noise model skip_qobj_validation (bool, optional): Bypass Qobj validation to decrease submission time Returns: Result: Result object Raises: AquaError: Any error except for JobError raised by Qiskit Terra """ qjob_config = qjob_config or {} backend_options = backend_options or {} noise_config = noise_config or {} if backend is None or not isinstance(backend, BaseBackend): raise ValueError('Backend is missing or not an instance of BaseBackend') with_autorecover = False if is_simulator_backend(backend) else True jobs = [] job_ids = [] for qobj in qobjs: job, job_id = _safe_submit_qobj(qobj, backend, backend_options, noise_config, skip_qobj_validation) job_ids.append(job_id) jobs.append(job) results = [] if with_autorecover: logger.info("Backend status: {}".format(backend.status())) logger.info("There are {} jobs are submitted.".format(len(jobs))) logger.info("All job ids:\n{}".format(job_ids)) for idx in range(len(jobs)): job = jobs[idx] job_id = job_ids[idx] while True: logger.info("Running {}-th qobj, job id: {}".format(idx, job_id)) # try to get result if possible try: result = job.result(**qjob_config) if result.success: results.append(result) logger.info("COMPLETED the {}-th qobj, " "job id: {}".format(idx, job_id)) break else: logger.warning("FAILURE: the {}-th qobj, " "job id: {}".format(idx, job_id)) except JobError as e: # if terra raise any error, which means something wrong, re-run it logger.warning("FAILURE: the {}-th qobj, job id: {} " "Terra job error: {} ".format(idx, job_id, e)) except Exception as e: raise AquaError("FAILURE: the {}-th qobj, job id: {} " "Unknown error: {} ".format(idx, job_id, e)) from e # something wrong here if reach here, querying the status to check how to handle it. # keep qeurying it until getting the status. while True: try: job_status = job.status() break except JobError as e: logger.warning("FAILURE: job id: {}, " "status: 'FAIL_TO_GET_STATUS' " "Terra job error: {}".format(job_id, e)) time.sleep(5) except Exception as e: raise AquaError("FAILURE: job id: {}, " "status: 'FAIL_TO_GET_STATUS' " "Unknown error: ({})".format(job_id, e)) from e logger.info("Job status: {}".format(job_status)) # handle the failure job based on job status if job_status == JobStatus.DONE: logger.info("Job ({}) is completed anyway, retrieve result " "from backend.".format(job_id)) job = backend.retrieve_job(job_id) elif job_status == JobStatus.RUNNING or job_status == JobStatus.QUEUED: logger.info("Job ({}) is {}, but encounter an exception, " "recover it from backend.".format(job_id, job_status)) job = backend.retrieve_job(job_id) else: logger.info("Fail to run Job ({}), resubmit it.".format(job_id)) qobj = qobjs[idx] # assure job get its id job, job_id = _safe_submit_qobj(qobj, backend, backend_options, noise_config, skip_qobj_validation) jobs[idx] = job job_ids[idx] = job_id else: results = [] for job in jobs: results.append(job.result(**qjob_config)) result = _combine_result_objects(results) if len(results) != 0 else None return result def compile_and_run_circuits(circuits, backend, backend_config=None, compile_config=None, run_config=None, qjob_config=None, backend_options=None, noise_config=None, show_circuit_summary=False, circuit_cache=None, skip_qobj_validation=False, **kwargs): """ An execution wrapper with Qiskit-Terra, with job auto recover capability. The autorecovery feature is only applied for non-simulator backend. This wraper will try to get the result no matter how long it costs. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute backend (BaseBackend): backend instance backend_config (dict, optional): configuration for backend compile_config (dict, optional): configuration for compilation run_config (RunConfig, optional): configuration for running a circuit qjob_config (dict, optional): configuration for quantum job object backend_options (dict, optional): configuration for simulator noise_config (dict, optional): configuration for noise model show_circuit_summary (bool, optional): showing the summary of submitted circuits. circuit_cache (CircuitCache, optional): A CircuitCache to use when calling compile_and_run_circuits skip_qobj_validation (bool, optional): Bypass Qobj validation to decrease submission time Returns: Result: Result object Raises: AquaError: Any error except for JobError raised by Qiskit Terra """ qobjs = compile_circuits(circuits, backend, backend_config, compile_config, run_config, show_circuit_summary, circuit_cache, **kwargs) result = run_qobjs(qobjs, backend, qjob_config, backend_options, noise_config, skip_qobj_validation) return result # skip_qobj_validation = True does what backend.run and aerjob.submit do, but without qobj validation. def run_on_backend(backend, qobj, backend_options=None, noise_config=None, skip_qobj_validation=False): if skip_qobj_validation: job_id = str(uuid.uuid4()) if is_aer_provider(backend): from qiskit.providers.aer.aerjob import AerJob temp_backend_options = backend_options['backend_options'] if backend_options != {} else None temp_noise_config = noise_config['noise_model'] if noise_config != {} else None job = AerJob(backend, job_id, backend._run_job, qobj, temp_backend_options, temp_noise_config, False) job._future = job._executor.submit(job._fn, job._job_id, job._qobj, *job._args) elif is_basicaer_provider(backend): backend._set_options(qobj_config=qobj.config, **backend_options) job = BasicAerJob(backend, job_id, backend._run_job, qobj) job._future = job._executor.submit(job._fn, job._job_id, job._qobj) elif is_ibmq_provider(backend): # TODO: IBMQJob performs validation during the constructor. the following lines does not # skip validation but run as is. from qiskit.providers.ibmq.ibmqjob import IBMQJob job = IBMQJob(backend, None, backend._api, qobj=qobj) job._future = job._executor.submit(job._submit_callback) else: logger.info("Can't skip qobj validation for the third-party provider.") job = backend.run(qobj, **backend_options, **noise_config) return job else: job = backend.run(qobj, **backend_options, **noise_config) return job
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Functions used for the analysis of randomized benchmarking results. """ from scipy.optimize import curve_fit import numpy as np from qiskit import QiskitError from ..tomography import marginal_counts from ...characterization.fitters import build_counts_dict_from_list try: from matplotlib import pyplot as plt HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False class RBFitter: """ Class for fitters for randomized benchmarking """ def __init__(self, backend_result, cliff_lengths, rb_pattern=None): """ Args: backend_result: list of results (qiskit.Result). cliff_lengths: the Clifford lengths, 2D list i x j where i is the number of patterns, j is the number of cliffords lengths rb_pattern: the pattern for the rb sequences. """ if rb_pattern is None: rb_pattern = [[0]] self._cliff_lengths = cliff_lengths self._rb_pattern = rb_pattern self._raw_data = [] self._ydata = [] self._fit = [] self._nseeds = 0 self._result_list = [] self.add_data(backend_result) @property def raw_data(self): """Return raw data.""" return self._raw_data @property def cliff_lengths(self): """Return clifford lengths.""" return self.cliff_lengths @property def ydata(self): """Return ydata (means and std devs).""" return self._ydata @property def fit(self): """Return fit.""" return self._fit @property def seeds(self): """Return the number of loaded seeds.""" return self._nseeds @property def results(self): """Return all the results.""" return self._result_list def add_data(self, new_backend_result, rerun_fit=True): """ Add a new result. Re calculate the raw data, means and fit. Args: new_backend_result: list of rb results rerun_fit: re caculate the means and fit the result Additional information: Assumes that 'result' was executed is the output of circuits generated by randomized_becnhmarking_seq, """ if new_backend_result is None: return if not isinstance(new_backend_result, list): new_backend_result = [new_backend_result] for result in new_backend_result: self._result_list.append(result) # update the number of seeds *if* new ones # added. Note, no checking if we've done all the # cliffords for rbcirc in result.results: nseeds_circ = int(rbcirc.header.name.split('_')[-1]) if (nseeds_circ+1) > self._nseeds: self._nseeds = nseeds_circ+1 for result in self._result_list: if not len(result.results) == len(self._cliff_lengths[0]): raise ValueError( "The number of clifford lengths must match the number of " "results") if rerun_fit: self.calc_data() self.calc_statistics() self.fit_data() @staticmethod def _rb_fit_fun(x, a, alpha, b): """Function used to fit rb.""" # pylint: disable=invalid-name return a * alpha ** x + b def calc_data(self): """ Retrieve probabilities of success from execution results. Outputs results into an internal variable _raw_data which is a 3-dimensional list, where item (i,j,k) is the probability to measure the ground state for the set of qubits in pattern "i" for seed no. j and vector length self._cliff_lengths[i][k]. Additional information: Assumes that 'result' was executed is the output of circuits generated by randomized_becnhmarking_seq, """ circ_counts = {} circ_shots = {} for seedidx in range(self._nseeds): for circ, _ in enumerate(self._cliff_lengths[0]): circ_name = 'rb_length_%d_seed_%d' % (circ, seedidx) count_list = [] for result in self._result_list: try: count_list.append(result.get_counts(circ_name)) except (QiskitError, KeyError): pass circ_counts[circ_name] = \ build_counts_dict_from_list(count_list) circ_shots[circ_name] = sum(circ_counts[circ_name].values()) self._raw_data = [] startind = 0 for patt_ind in range(len(self._rb_pattern)): string_of_0s = '' string_of_0s = string_of_0s.zfill(len(self._rb_pattern[patt_ind])) self._raw_data.append([]) endind = startind+len(self._rb_pattern[patt_ind]) for i in range(self._nseeds): self._raw_data[-1].append([]) for k, _ in enumerate(self._cliff_lengths[patt_ind]): circ_name = 'rb_length_%d_seed_%d' % (k, i) counts_subspace = marginal_counts( circ_counts[circ_name], np.arange(startind, endind)) self._raw_data[-1][i].append( counts_subspace.get(string_of_0s, 0) / circ_shots[circ_name]) startind += (endind) def calc_statistics(self): """ Extract averages and std dev from the raw data (self._raw_data). Assumes that self._calc_data has been run. Output into internal _ydata variable: ydata is a list of dictionaries (length number of patterns). Dictionary ydata[i]: ydata[i]['mean'] is a numpy_array of length n; entry j of this array contains the mean probability of success over seeds, for vector length self._cliff_lengths[i][j]. And ydata[i]['std'] is a numpy_array of length n; entry j of this array contains the std of the probability of success over seeds, for vector length self._cliff_lengths[i][j]. """ self._ydata = [] for patt_ind in range(len(self._rb_pattern)): self._ydata.append({}) self._ydata[-1]['mean'] = np.mean(self._raw_data[patt_ind], 0) if len(self._raw_data[patt_ind]) == 1: # 1 seed self._ydata[-1]['std'] = None else: self._ydata[-1]['std'] = np.std(self._raw_data[patt_ind], 0) def fit_data(self): """ Fit the RB results to an exponential curve. Fit each of the patterns Puts the results into a list of fit dictionaries: where each dictionary corresponds to a pattern and has fields: 'params' - three parameters of rb_fit_fun. The middle one is the exponent. 'err' - the error limits of the parameters. 'epc' - error per Clifford """ self._fit = [] for patt_ind, (lens, qubits) in enumerate(zip(self._cliff_lengths, self._rb_pattern)): # if at least one of the std values is zero, then sigma is replaced # by None if not self._ydata[patt_ind]['std'] is None: sigma = self._ydata[patt_ind]['std'].copy() if len(sigma) - np.count_nonzero(sigma) > 0: sigma = None else: sigma = None params, pcov = curve_fit(self._rb_fit_fun, lens, self._ydata[patt_ind]['mean'], sigma=sigma, p0=(1.0, 0.95, 0.0), bounds=([-2, 0, -2], [2, 1, 2])) alpha = params[1] # exponent params_err = np.sqrt(np.diag(pcov)) alpha_err = params_err[1] nrb = 2 ** len(qubits) epc = (nrb-1)/nrb*(1-alpha) epc_err = epc*alpha_err/alpha self._fit.append({'params': params, 'params_err': params_err, 'epc': epc, 'epc_err': epc_err}) def plot_rb_data(self, pattern_index=0, ax=None, add_label=True, show_plt=True): """ Plot randomized benchmarking data of a single pattern. Args: pattern_index: which RB pattern to plot ax (Axes or None): plot axis (if passed in). add_label (bool): Add an EPC label show_plt (bool): display the plot. Raises: ImportError: If matplotlib is not installed. """ fit_function = self._rb_fit_fun if not HAS_MATPLOTLIB: raise ImportError('The function plot_rb_data needs matplotlib. ' 'Run "pip install matplotlib" before.') if ax is None: plt.figure() ax = plt.gca() xdata = self._cliff_lengths[pattern_index] # Plot the result for each sequence for one_seed_data in self._raw_data[pattern_index]: ax.plot(xdata, one_seed_data, color='gray', linestyle='none', marker='x') # Plot the mean with error bars ax.errorbar(xdata, self._ydata[pattern_index]['mean'], yerr=self._ydata[pattern_index]['std'], color='r', linestyle='--', linewidth=3) # Plot the fit ax.plot(xdata, fit_function(xdata, *self._fit[pattern_index]['params']), color='blue', linestyle='-', linewidth=2) ax.tick_params(labelsize=14) ax.set_xlabel('Clifford Length', fontsize=16) ax.set_ylabel('Ground State Population', fontsize=16) ax.grid(True) if add_label: bbox_props = dict(boxstyle="round,pad=0.3", fc="white", ec="black", lw=2) ax.text(0.6, 0.9, "alpha: %.3f(%.1e) EPC: %.3e(%.1e)" % (self._fit[pattern_index]['params'][1], self._fit[pattern_index]['params_err'][1], self._fit[pattern_index]['epc'], self._fit[pattern_index]['epc_err']), ha="center", va="center", size=14, bbox=bbox_props, transform=ax.transAxes) if show_plt: plt.show()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 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. # This code was originally copied from the qiskit-ignis see: # https://github.com/Qiskit/qiskit-ignis/blob/b91066c72171bcd55a70e6e8993b813ec763cf41/qiskit/ignis/mitigation/measurement/filters.py # it was migrated as qiskit-ignis is being deprecated # pylint: disable=cell-var-from-loop """ Measurement correction filters. """ from typing import List from copy import deepcopy import numpy as np import qiskit from qiskit import QiskitError from qiskit.tools import parallel_map from qiskit.utils.mitigation.circuits import count_keys from qiskit.utils.deprecation import deprecate_func class MeasurementFilter: """ Deprecated: Measurement error mitigation filter. Produced from a measurement calibration fitter and can be applied to data. """ @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def __init__(self, cal_matrix: np.matrix, state_labels: list): """ Initialize a measurement error mitigation filter using the cal_matrix from a measurement calibration fitter. Args: cal_matrix: the calibration matrix for applying the correction state_labels: the states for the ordering of the cal matrix """ self._cal_matrix = cal_matrix self._state_labels = state_labels @property def cal_matrix(self): """Return cal_matrix.""" return self._cal_matrix @property def state_labels(self): """return the state label ordering of the cal matrix""" return self._state_labels @state_labels.setter def state_labels(self, new_state_labels): """set the state label ordering of the cal matrix""" self._state_labels = new_state_labels @cal_matrix.setter def cal_matrix(self, new_cal_matrix): """Set cal_matrix.""" self._cal_matrix = new_cal_matrix def apply(self, raw_data, method="least_squares"): """Apply the calibration matrix to results. Args: raw_data (dict or list): The data to be corrected. Can be in a number of forms: Form 1: a counts dictionary from results.get_counts Form 2: a list of counts of `length==len(state_labels)` Form 3: a list of counts of `length==M*len(state_labels)` where M is an integer (e.g. for use with the tomography data) Form 4: a qiskit Result method (str): fitting method. If `None`, then least_squares is used. ``pseudo_inverse``: direct inversion of the A matrix ``least_squares``: constrained to have physical probabilities Returns: dict or list: The corrected data in the same form as `raw_data` Raises: QiskitError: if `raw_data` is not an integer multiple of the number of calibrated states. """ from scipy.optimize import minimize from scipy import linalg as la # check forms of raw_data if isinstance(raw_data, dict): # counts dictionary for data_label in raw_data.keys(): if data_label not in self._state_labels: raise QiskitError( f"Unexpected state label '{data_label}'." " Verify the fitter's state labels correspond to the input data." ) data_format = 0 # convert to form2 raw_data2 = [np.zeros(len(self._state_labels), dtype=float)] for stateidx, state in enumerate(self._state_labels): raw_data2[0][stateidx] = raw_data.get(state, 0) elif isinstance(raw_data, list): size_ratio = len(raw_data) / len(self._state_labels) if len(raw_data) == len(self._state_labels): data_format = 1 raw_data2 = [raw_data] elif int(size_ratio) == size_ratio: data_format = 2 size_ratio = int(size_ratio) # make the list into chunks the size of state_labels for easier # processing raw_data2 = np.zeros([size_ratio, len(self._state_labels)]) for i in range(size_ratio): raw_data2[i][:] = raw_data[ i * len(self._state_labels) : (i + 1) * len(self._state_labels) ] else: raise QiskitError( "Data list is not an integer multiple of the number of calibrated states" ) elif isinstance(raw_data, qiskit.result.result.Result): # extract out all the counts, re-call the function with the # counts and push back into the new result new_result = deepcopy(raw_data) new_counts_list = parallel_map( self._apply_correction, [resultidx for resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method), ) for resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts = new_counts return new_result else: raise QiskitError("Unrecognized type for raw_data.") if method == "pseudo_inverse": pinv_cal_mat = la.pinv(self._cal_matrix) # Apply the correction for data_idx, _ in enumerate(raw_data2): if method == "pseudo_inverse": raw_data2[data_idx] = np.dot(pinv_cal_mat, raw_data2[data_idx]) elif method == "least_squares": nshots = sum(raw_data2[data_idx]) def fun(x): return sum((raw_data2[data_idx] - np.dot(self._cal_matrix, x)) ** 2) x0 = np.random.rand(len(self._state_labels)) x0 = x0 / sum(x0) cons = {"type": "eq", "fun": lambda x: nshots - sum(x)} bnds = tuple((0, nshots) for x in x0) res = minimize(fun, x0, method="SLSQP", constraints=cons, bounds=bnds, tol=1e-6) raw_data2[data_idx] = res.x else: raise QiskitError("Unrecognized method.") if data_format == 2: # flatten back out the list raw_data2 = raw_data2.flatten() elif data_format == 0: # convert back into a counts dictionary new_count_dict = {} for stateidx, state in enumerate(self._state_labels): if raw_data2[0][stateidx] != 0: new_count_dict[state] = raw_data2[0][stateidx] raw_data2 = new_count_dict else: # TODO: should probably change to: # raw_data2 = raw_data2[0].tolist() raw_data2 = raw_data2[0] return raw_data2 def _apply_correction(self, resultidx, raw_data, method): """Wrapper to call apply with a counts dictionary.""" new_counts = self.apply(raw_data.get_counts(resultidx), method=method) return resultidx, new_counts class TensoredFilter: """ Deprecated: Tensored measurement error mitigation filter. Produced from a tensored measurement calibration fitter and can be applied to data. """ @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def __init__(self, cal_matrices: np.matrix, substate_labels_list: list, mit_pattern: list): """ Initialize a tensored measurement error mitigation filter using the cal_matrices from a tensored measurement calibration fitter. A simple usage this class is explained [here] (https://qiskit.org/documentation/tutorials/noise/3_measurement_error_mitigation.html). Args: cal_matrices: the calibration matrices for applying the correction. substate_labels_list: for each calibration matrix a list of the states (as strings, states in the subspace) mit_pattern: for each calibration matrix a list of the logical qubit indices (as int, states in the subspace) """ self._cal_matrices = cal_matrices self._qubit_list_sizes = [] self._indices_list = [] self._substate_labels_list = [] self.substate_labels_list = substate_labels_list self._mit_pattern = mit_pattern @property def cal_matrices(self): """Return cal_matrices.""" return self._cal_matrices @cal_matrices.setter def cal_matrices(self, new_cal_matrices): """Set cal_matrices.""" self._cal_matrices = deepcopy(new_cal_matrices) @property def substate_labels_list(self): """Return _substate_labels_list""" return self._substate_labels_list @substate_labels_list.setter def substate_labels_list(self, new_substate_labels_list): """Return _substate_labels_list""" self._substate_labels_list = new_substate_labels_list # get the number of qubits in each subspace self._qubit_list_sizes = [] for _, substate_label_list in enumerate(self._substate_labels_list): self._qubit_list_sizes.append(int(np.log2(len(substate_label_list)))) # get the indices in the calibration matrix self._indices_list = [] for _, sub_labels in enumerate(self._substate_labels_list): self._indices_list.append({lab: ind for ind, lab in enumerate(sub_labels)}) @property def qubit_list_sizes(self): """Return _qubit_list_sizes.""" return self._qubit_list_sizes @property def nqubits(self): """Return the number of qubits. See also MeasurementFilter.apply()""" return sum(self._qubit_list_sizes) def apply( self, raw_data, method="least_squares", meas_layout=None, ): """ Apply the calibration matrices to results. Args: raw_data (dict or Result): The data to be corrected. Can be in one of two forms: * A counts dictionary from results.get_counts * A Qiskit Result method (str): fitting method. The following methods are supported: * 'pseudo_inverse': direct inversion of the cal matrices. Mitigated counts can contain negative values and the sum of counts would not equal to the shots. Mitigation is conducted qubit wise: For each qubit, mitigate the whole counts using the calibration matrices which affect the corresponding qubit. For example, assume we are mitigating the 3rd bit of the 4-bit counts using '2\times 2' calibration matrix `A_3`. When mitigating the count of '0110' in this step, the following formula is applied: `count['0110'] = A_3^{-1}[1, 0]*count['0100'] + A_3^{-1}[1, 1]*count['0110']`. The total time complexity of this method is `O(m2^{n + t})`, where `n` is the size of calibrated qubits, `m` is the number of sets in `mit_pattern`, and `t` is the size of largest set of mit_pattern. If the `mit_pattern` is shaped like `[[0], [1], [2], ..., [n-1]]`, which corresponds to the tensor product noise model without cross-talk, then the time complexity would be `O(n2^n)`. If the `mit_pattern` is shaped like `[[0, 1, 2, ..., n-1]]`, which exactly corresponds to the complete error mitigation, then the time complexity would be `O(2^(n+n)) = O(4^n)`. * 'least_squares': constrained to have physical probabilities. Instead of directly applying inverse calibration matrices, this method solve a constrained optimization problem to find the closest probability vector to the result from 'pseudo_inverse' method. Sequential least square quadratic programming (SLSQP) is used in the internal process. Every updating step in SLSQP takes `O(m2^{n+t})` time. Since this method is using the SLSQP optimization over the vector with lenght `2^n`, the mitigation for 8 bit counts with the `mit_pattern = [[0], [1], [2], ..., [n-1]]` would take 10 seconds or more. * If `None`, 'least_squares' is used. meas_layout (list of int): the mapping from classical registers to qubits * If you measure qubit `2` to clbit `0`, `0` to `1`, and `1` to `2`, the list becomes `[2, 0, 1]` * If `None`, flatten(mit_pattern) is used. Returns: dict or Result: The corrected data in the same form as raw_data Raises: QiskitError: if raw_data is not in a one of the defined forms. """ from scipy.optimize import minimize from scipy import linalg as la all_states = count_keys(self.nqubits) num_of_states = 2**self.nqubits if meas_layout is None: meas_layout = [] for qubits in self._mit_pattern: meas_layout += qubits # check forms of raw_data if isinstance(raw_data, dict): # counts dictionary # convert to list raw_data2 = [np.zeros(num_of_states, dtype=float)] for state, count in raw_data.items(): stateidx = int(state, 2) raw_data2[0][stateidx] = count elif isinstance(raw_data, qiskit.result.result.Result): # extract out all the counts, re-call the function with the # counts and push back into the new result new_result = deepcopy(raw_data) new_counts_list = parallel_map( self._apply_correction, [resultidx for resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method, meas_layout), ) for resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts = new_counts return new_result else: raise QiskitError("Unrecognized type for raw_data.") if method == "pseudo_inverse": pinv_cal_matrices = [] for cal_mat in self._cal_matrices: pinv_cal_matrices.append(la.pinv(cal_mat)) meas_layout = meas_layout[::-1] # reverse endian qubits_to_clbits = [-1 for _ in range(max(meas_layout) + 1)] for i, qubit in enumerate(meas_layout): qubits_to_clbits[qubit] = i # Apply the correction for data_idx, _ in enumerate(raw_data2): if method == "pseudo_inverse": for pinv_cal_mat, pos_qubits, indices in zip( pinv_cal_matrices, self._mit_pattern, self._indices_list ): inv_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits = [qubits_to_clbits[qubit] for qubit in pos_qubits] for state_idx, state in enumerate(all_states): first_index = self.compute_index_of_cal_mat(state, pos_clbits, indices) for i in range(len(pinv_cal_mat)): # i is index of pinv_cal_mat source_state = self.flip_state(state, i, pos_clbits) second_index = self.compute_index_of_cal_mat( source_state, pos_clbits, indices ) inv_mat_dot_x[state_idx] += ( pinv_cal_mat[first_index, second_index] * raw_data2[data_idx][int(source_state, 2)] ) raw_data2[data_idx] = inv_mat_dot_x elif method == "least_squares": def fun(x): mat_dot_x = deepcopy(x) for cal_mat, pos_qubits, indices in zip( self._cal_matrices, self._mit_pattern, self._indices_list ): res_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits = [qubits_to_clbits[qubit] for qubit in pos_qubits] for state_idx, state in enumerate(all_states): second_index = self.compute_index_of_cal_mat(state, pos_clbits, indices) for i in range(len(cal_mat)): target_state = self.flip_state(state, i, pos_clbits) first_index = self.compute_index_of_cal_mat( target_state, pos_clbits, indices ) res_mat_dot_x[int(target_state, 2)] += ( cal_mat[first_index, second_index] * mat_dot_x[state_idx] ) mat_dot_x = res_mat_dot_x return sum((raw_data2[data_idx] - mat_dot_x) ** 2) x0 = np.random.rand(num_of_states) x0 = x0 / sum(x0) nshots = sum(raw_data2[data_idx]) cons = {"type": "eq", "fun": lambda x: nshots - sum(x)} bnds = tuple((0, nshots) for x in x0) res = minimize(fun, x0, method="SLSQP", constraints=cons, bounds=bnds, tol=1e-6) raw_data2[data_idx] = res.x else: raise QiskitError("Unrecognized method.") # convert back into a counts dictionary new_count_dict = {} for state_idx, state in enumerate(all_states): if raw_data2[0][state_idx] != 0: new_count_dict[state] = raw_data2[0][state_idx] return new_count_dict def flip_state(self, state: str, mat_index: int, flip_poses: List[int]) -> str: """Flip the state according to the chosen qubit positions""" flip_poses = [pos for i, pos in enumerate(flip_poses) if (mat_index >> i) & 1] flip_poses = sorted(flip_poses) new_state = "" pos = 0 for flip_pos in flip_poses: new_state += state[pos:flip_pos] new_state += str(int(state[flip_pos], 2) ^ 1) # flip the state pos = flip_pos + 1 new_state += state[pos:] return new_state def compute_index_of_cal_mat(self, state: str, pos_qubits: List[int], indices: dict) -> int: """Return the index of (pseudo inverse) calibration matrix for the input quantum state""" sub_state = "" for pos in pos_qubits: sub_state += state[pos] return indices[sub_state] def _apply_correction( self, resultidx, raw_data, method, meas_layout, ): """Wrapper to call apply with a counts dictionary.""" new_counts = self.apply( raw_data.get_counts(resultidx), method=method, meas_layout=meas_layout ) return resultidx, new_counts
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """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-bench/Qiskit__qiskit
swe-bench
# 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-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=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-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- 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-bench/Qiskit__qiskit
swe-bench
# 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, )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Core module of the timeline drawer. This module provides the `DrawerCanvas` which is a collection of drawings. The canvas instance is not just a container of drawing objects, as it also performs data processing like binding abstract coordinates. Initialization ~~~~~~~~~~~~~~ The `DataCanvas` is not exposed to users as they are implicitly initialized in the interface function. It is noteworthy that the data canvas is agnostic to plotters. This means once the canvas instance is initialized we can reuse this data among multiple plotters. The canvas is initialized with a stylesheet. ```python canvas = DrawerCanvas(stylesheet=stylesheet) canvas.load_program(sched) canvas.update() ``` Once all properties are set, `.update` method is called to apply changes to drawings. Update ~~~~~~ To update the image, a user can set new values to canvas and then call the `.update` method. ```python canvas.set_time_range(2000, 3000) canvas.update() ``` All stored drawings are updated accordingly. The plotter API can access to drawings with `.collections` property of the canvas instance. This returns an iterator of drawings with the unique data key. If a plotter provides object handler for plotted shapes, the plotter API can manage the lookup table of the handler and the drawings by using this data key. """ from __future__ import annotations import warnings from collections.abc import Iterator from copy import deepcopy from functools import partial from enum import Enum import numpy as np from qiskit import circuit from qiskit.visualization.exceptions import VisualizationError from qiskit.visualization.timeline import drawings, types from qiskit.visualization.timeline.stylesheet import QiskitTimelineStyle class DrawerCanvas: """Data container for drawings.""" def __init__(self, stylesheet: QiskitTimelineStyle): """Create new data container.""" # stylesheet self.formatter = stylesheet.formatter self.generator = stylesheet.generator self.layout = stylesheet.layout # drawings self._collections: dict[str, drawings.ElementaryData] = {} self._output_dataset: dict[str, drawings.ElementaryData] = {} # vertical offset of bits self.bits: list[types.Bits] = [] self.assigned_coordinates: dict[types.Bits, float] = {} # visible controls self.disable_bits: set[types.Bits] = set() self.disable_types: set[str] = set() # time self._time_range = (0, 0) # graph height self.vmax = 0 self.vmin = 0 @property def time_range(self) -> tuple[int, int]: """Return current time range to draw. Calculate net duration and add side margin to edge location. Returns: Time window considering side margin. """ t0, t1 = self._time_range duration = t1 - t0 new_t0 = t0 - duration * self.formatter["margin.left_percent"] new_t1 = t1 + duration * self.formatter["margin.right_percent"] return new_t0, new_t1 @time_range.setter def time_range(self, new_range: tuple[int, int]): """Update time range to draw.""" self._time_range = new_range @property def collections(self) -> Iterator[tuple[str, drawings.ElementaryData]]: """Return currently active entries from drawing data collection. The object is returned with unique name as a key of an object handler. When the horizontal coordinate contains `AbstractCoordinate`, the value is substituted by current time range preference. """ yield from self._output_dataset.items() def add_data(self, data: drawings.ElementaryData): """Add drawing to collections. If the given object already exists in the collections, this interface replaces the old object instead of adding new entry. Args: data: New drawing to add. """ if not self.formatter["control.show_clbits"]: data.bits = [b for b in data.bits if not isinstance(b, circuit.Clbit)] self._collections[data.data_key] = data # pylint: disable=cyclic-import def load_program(self, program: circuit.QuantumCircuit): """Load quantum circuit and create drawing.. Args: program: Scheduled circuit object to draw. Raises: VisualizationError: When circuit is not scheduled. """ not_gate_like = (circuit.Barrier,) if getattr(program, "_op_start_times") is None: # Run scheduling for backward compatibility from qiskit import transpile from qiskit.transpiler import InstructionDurations, TranspilerError warnings.warn( "Visualizing un-scheduled circuit with timeline drawer has been deprecated. " "This circuit should be transpiled with scheduler though it consists of " "instructions with explicit durations.", DeprecationWarning, ) try: program = transpile( program, scheduling_method="alap", instruction_durations=InstructionDurations(), optimization_level=0, ) except TranspilerError as ex: raise VisualizationError( f"Input circuit {program.name} is not scheduled and it contains " "operations with unknown delays. This cannot be visualized." ) from ex for t0, instruction in zip(program.op_start_times, program.data): bits = list(instruction.qubits) + list(instruction.clbits) for bit_pos, bit in enumerate(bits): if not isinstance(instruction.operation, not_gate_like): # Generate draw object for gates gate_source = types.ScheduledGate( t0=t0, operand=instruction.operation, duration=instruction.operation.duration, bits=bits, bit_position=bit_pos, ) for gen in self.generator["gates"]: obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(gate_source): self.add_data(datum) if len(bits) > 1 and bit_pos == 0: # Generate draw object for gate-gate link line_pos = t0 + 0.5 * instruction.operation.duration link_source = types.GateLink( t0=line_pos, opname=instruction.operation.name, bits=bits ) for gen in self.generator["gate_links"]: obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(link_source): self.add_data(datum) if isinstance(instruction.operation, circuit.Barrier): # Generate draw object for barrier barrier_source = types.Barrier(t0=t0, bits=bits, bit_position=bit_pos) for gen in self.generator["barriers"]: obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(barrier_source): self.add_data(datum) self.bits = list(program.qubits) + list(program.clbits) for bit in self.bits: for gen in self.generator["bits"]: # Generate draw objects for bit obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(bit): self.add_data(datum) # update time range t_end = max(program.duration, self.formatter["margin.minimum_duration"]) self.set_time_range(t_start=0, t_end=t_end) def set_time_range(self, t_start: int, t_end: int): """Set time range to draw. Args: t_start: Left boundary of drawing in units of cycle time. t_end: Right boundary of drawing in units of cycle time. """ self.time_range = (t_start, t_end) def set_disable_bits(self, bit: types.Bits, remove: bool = True): """Interface method to control visibility of bits. Specified object in the blocked list will not be shown. Args: bit: A qubit or classical bit object to disable. remove: Set `True` to disable, set `False` to enable. """ if remove: self.disable_bits.add(bit) else: self.disable_bits.discard(bit) def set_disable_type(self, data_type: types.DataTypes, remove: bool = True): """Interface method to control visibility of data types. Specified object in the blocked list will not be shown. Args: data_type: A drawing data type to disable. remove: Set `True` to disable, set `False` to enable. """ if isinstance(data_type, Enum): data_type_str = str(data_type.value) else: data_type_str = data_type if remove: self.disable_types.add(data_type_str) else: self.disable_types.discard(data_type_str) def update(self): """Update all collections. This method should be called before the canvas is passed to the plotter. """ self._output_dataset.clear() self.assigned_coordinates.clear() # update coordinate y0 = -self.formatter["margin.top"] for bit in self.layout["bit_arrange"](self.bits): # remove classical bit if isinstance(bit, circuit.Clbit) and not self.formatter["control.show_clbits"]: continue # remove idle bit if not self._check_bit_visible(bit): continue offset = y0 - 0.5 self.assigned_coordinates[bit] = offset y0 = offset - 0.5 self.vmax = 0 self.vmin = y0 - self.formatter["margin.bottom"] # add data temp_gate_links = {} temp_data = {} for data_key, data in self._collections.items(): # deep copy to keep original data hash new_data = deepcopy(data) new_data.xvals = self._bind_coordinate(data.xvals) new_data.yvals = self._bind_coordinate(data.yvals) if data.data_type == str(types.LineType.GATE_LINK.value): temp_gate_links[data_key] = new_data else: temp_data[data_key] = new_data # update horizontal offset of gate links temp_data.update(self._check_link_overlap(temp_gate_links)) # push valid data for data_key, data in temp_data.items(): if self._check_data_visible(data): self._output_dataset[data_key] = data def _check_data_visible(self, data: drawings.ElementaryData) -> bool: """A helper function to check if the data is visible. Args: data: Drawing object to test. Returns: Return `True` if the data is visible. """ _barriers = [str(types.LineType.BARRIER.value)] _delays = [str(types.BoxType.DELAY.value), str(types.LabelType.DELAY.value)] def _time_range_check(_data): """If data is located outside the current time range.""" t0, t1 = self.time_range if np.max(_data.xvals) < t0 or np.min(_data.xvals) > t1: return False return True def _associated_bit_check(_data): """If any associated bit is not shown.""" if all(bit not in self.assigned_coordinates for bit in _data.bits): return False return True def _data_check(_data): """If data is valid.""" if _data.data_type == str(types.LineType.GATE_LINK.value): active_bits = [bit for bit in _data.bits if bit not in self.disable_bits] if len(active_bits) < 2: return False elif _data.data_type in _barriers and not self.formatter["control.show_barriers"]: return False elif _data.data_type in _delays and not self.formatter["control.show_delays"]: return False return True checks = [_time_range_check, _associated_bit_check, _data_check] if all(check(data) for check in checks): return True return False def _check_bit_visible(self, bit: types.Bits) -> bool: """A helper function to check if the bit is visible. Args: bit: Bit object to test. Returns: Return `True` if the bit is visible. """ _gates = [str(types.BoxType.SCHED_GATE.value), str(types.SymbolType.FRAME.value)] if bit in self.disable_bits: return False if self.formatter["control.show_idle"]: return True for data in self._collections.values(): if bit in data.bits and data.data_type in _gates: return True return False def _bind_coordinate(self, vals: Iterator[types.Coordinate]) -> np.ndarray: """A helper function to bind actual coordinates to an `AbstractCoordinate`. Args: vals: Sequence of coordinate objects associated with a drawing. Returns: Numpy data array with substituted values. """ def substitute(val: types.Coordinate): if val == types.AbstractCoordinate.LEFT: return self.time_range[0] if val == types.AbstractCoordinate.RIGHT: return self.time_range[1] if val == types.AbstractCoordinate.TOP: return self.vmax if val == types.AbstractCoordinate.BOTTOM: return self.vmin raise VisualizationError(f"Coordinate {val} is not supported.") try: return np.asarray(vals, dtype=float) except TypeError: return np.asarray(list(map(substitute, vals)), dtype=float) def _check_link_overlap( self, links: dict[str, drawings.GateLinkData] ) -> dict[str, drawings.GateLinkData]: """Helper method to check overlap of bit links. This method dynamically shifts horizontal position of links if they are overlapped. """ duration = self.time_range[1] - self.time_range[0] allowed_overlap = self.formatter["margin.link_interval_percent"] * duration # return y coordinates def y_coords(link: drawings.GateLinkData): return np.array([self.assigned_coordinates.get(bit, np.nan) for bit in link.bits]) # group overlapped links overlapped_group: list[list[str]] = [] data_keys = list(links.keys()) while len(data_keys) > 0: ref_key = data_keys.pop() overlaps = set() overlaps.add(ref_key) for key in data_keys[::-1]: # check horizontal overlap if np.abs(links[ref_key].xvals[0] - links[key].xvals[0]) < allowed_overlap: # check vertical overlap y0s = y_coords(links[ref_key]) y1s = y_coords(links[key]) v1 = np.nanmin(y0s) - np.nanmin(y1s) v2 = np.nanmax(y0s) - np.nanmax(y1s) v3 = np.nanmin(y0s) - np.nanmax(y1s) v4 = np.nanmax(y0s) - np.nanmin(y1s) if not (v1 * v2 > 0 and v3 * v4 > 0): overlaps.add(data_keys.pop(data_keys.index(key))) overlapped_group.append(list(overlaps)) # renew horizontal offset new_links = {} for overlaps in overlapped_group: if len(overlaps) > 1: xpos_mean = np.mean([links[key].xvals[0] for key in overlaps]) # sort link key by y position sorted_keys = sorted(overlaps, key=lambda x: np.nanmax(y_coords(links[x]))) x0 = xpos_mean - 0.5 * allowed_overlap * (len(overlaps) - 1) for ind, key in enumerate(sorted_keys): data = links[key] data.xvals = [x0 + ind * allowed_overlap] new_links[key] = data else: key = overlaps[0] new_links[key] = links[key] return {key: new_links[key] for key in links.keys()}
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A collection of backend information formatted to generate drawing data. This instance will be provided to generator functions. The module provides an abstract class :py:class:``DrawerBackendInfo`` with necessary methods to generate drawing objects. Because the data structure of backend class may depend on providers, this abstract class has an abstract factory method `create_from_backend`. Each subclass should provide the factory method which conforms to the associated provider. By default we provide :py:class:``OpenPulseBackendInfo`` class that has the factory method taking backends satisfying OpenPulse specification [1]. This class can be also initialized without the factory method by manually specifying required information. This may be convenient for visualizing a pulse program for simulator backend that only has a device Hamiltonian information. This requires two mapping objects for channel/qubit and channel/frequency along with the system cycle time. If those information are not provided, this class will be initialized with a set of empty data and the drawer illustrates a pulse program without any specific information. Reference: - [1] Qiskit Backend Specifications for OpenQASM and OpenPulse Experiments, https://arxiv.org/abs/1809.03452 """ from abc import ABC, abstractmethod from collections import defaultdict from typing import Dict, List, Union, Optional from qiskit import pulse from qiskit.providers import BackendConfigurationError from qiskit.providers.backend import Backend class DrawerBackendInfo(ABC): """Backend information to be used for the drawing data generation.""" def __init__( self, name: Optional[str] = None, dt: Optional[float] = None, channel_frequency_map: Optional[Dict[pulse.channels.Channel, float]] = None, qubit_channel_map: Optional[Dict[int, List[pulse.channels.Channel]]] = None, ): """Create new backend information. Args: name: Name of the backend. dt: System cycle time. channel_frequency_map: Mapping of channel and associated frequency. qubit_channel_map: Mapping of qubit and associated channels. """ self.backend_name = name or "no-backend" self._dt = dt self._chan_freq_map = channel_frequency_map or {} self._qubit_channel_map = qubit_channel_map or {} @classmethod @abstractmethod def create_from_backend(cls, backend: Backend): """Initialize a class with backend information provided by provider. Args: backend: Backend object. """ raise NotImplementedError @property def dt(self): """Return cycle time.""" return self._dt def get_qubit_index(self, chan: pulse.channels.Channel) -> Union[int, None]: """Get associated qubit index of given channel object.""" for qind, chans in self._qubit_channel_map.items(): if chan in chans: return qind return chan.index def get_channel_frequency(self, chan: pulse.channels.Channel) -> Union[float, None]: """Get frequency of given channel object.""" return self._chan_freq_map.get(chan, None) class OpenPulseBackendInfo(DrawerBackendInfo): """Drawing information of backend that conforms to OpenPulse specification.""" @classmethod def create_from_backend(cls, backend: Backend): """Initialize a class with backend information provided by provider. Args: backend: Backend object. Returns: OpenPulseBackendInfo: New configured instance. """ configuration = backend.configuration() defaults = backend.defaults() # load name name = backend.name() # load cycle time dt = configuration.dt # load frequencies chan_freqs = {} chan_freqs.update( {pulse.DriveChannel(qind): freq for qind, freq in enumerate(defaults.qubit_freq_est)} ) chan_freqs.update( {pulse.MeasureChannel(qind): freq for qind, freq in enumerate(defaults.meas_freq_est)} ) for qind, u_lo_mappers in enumerate(configuration.u_channel_lo): temp_val = 0.0 + 0.0j for u_lo_mapper in u_lo_mappers: temp_val += defaults.qubit_freq_est[u_lo_mapper.q] * u_lo_mapper.scale chan_freqs[pulse.ControlChannel(qind)] = temp_val.real # load qubit channel mapping qubit_channel_map = defaultdict(list) for qind in range(configuration.n_qubits): qubit_channel_map[qind].append(configuration.drive(qubit=qind)) qubit_channel_map[qind].append(configuration.measure(qubit=qind)) for tind in range(configuration.n_qubits): try: qubit_channel_map[qind].extend(configuration.control(qubits=(qind, tind))) except BackendConfigurationError: pass return OpenPulseBackendInfo( name=name, dt=dt, channel_frequency_map=chan_freqs, qubit_channel_map=qubit_channel_map )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. r""" Channel event manager for pulse schedules. This module provides a `ChannelEvents` class that manages a series of instructions for a pulse channel. Channel-wise filtering of the pulse program makes the arrangement of channels easier in the core drawer function. The `ChannelEvents` class is expected to be called by other programs (not by end-users). The `ChannelEvents` class instance is created with the class method ``load_program``: .. code-block:: python event = ChannelEvents.load_program(sched, DriveChannel(0)) The `ChannelEvents` is created for a specific pulse channel and loosely assorts pulse instructions within the channel with different visualization purposes. Phase and frequency related instructions are loosely grouped as frame changes. The instantaneous value of those operands are combined and provided as ``PhaseFreqTuple``. Instructions that have finite duration are grouped as waveforms. The grouped instructions are returned as an iterator by the corresponding method call: .. code-block:: python for t0, frame, instruction in event.get_waveforms(): ... for t0, frame_change, instructions in event.get_frame_changes(): ... The class method ``get_waveforms`` returns the iterator of waveform type instructions with the ``PhaseFreqTuple`` (frame) at the time when instruction is issued. This is because a pulse envelope of ``Waveform`` may be modulated with a phase factor $exp(-i \omega t - \phi)$ with frequency $\omega$ and phase $\phi$ and appear on the canvas. Thus, it is better to tell users in which phase and frequency the pulse envelope is modulated from a viewpoint of program debugging. On the other hand, the class method ``get_frame_changes`` returns a ``PhaseFreqTuple`` that represents a total amount of change at that time because it is convenient to know the operand value itself when we debug a program. Because frame change type instructions are usually zero duration, multiple instructions can be issued at the same time and those operand values should be appropriately combined. In Qiskit Pulse we have set and shift type instructions for the frame control, the set type instruction will be converted into the relevant shift amount for visualization. Note that these instructions are not interchangeable and the order should be kept. For example: .. code-block:: python sched1 = Schedule() sched1 = sched1.insert(0, ShiftPhase(-1.57, DriveChannel(0)) sched1 = sched1.insert(0, SetPhase(3.14, DriveChannel(0)) sched2 = Schedule() sched2 = sched2.insert(0, SetPhase(3.14, DriveChannel(0)) sched2 = sched2.insert(0, ShiftPhase(-1.57, DriveChannel(0)) In this example, ``sched1`` and ``sched2`` will have different frames. On the drawer canvas, the total frame change amount of +3.14 should be shown for ``sched1``, while ``sched2`` is +1.57. Since the `SetPhase` and the `ShiftPhase` instruction behave differently, we cannot simply sum up the operand values in visualization output. It should be also noted that zero duration instructions issued at the same time will be overlapped on the canvas. Thus it is convenient to plot a total frame change amount rather than plotting each operand value bound to the instruction. """ from __future__ import annotations from collections import defaultdict from collections.abc import Iterator from qiskit import pulse, circuit from qiskit.visualization.pulse_v2.types import PhaseFreqTuple, PulseInstruction class ChannelEvents: """Channel event manager.""" _waveform_group = ( pulse.instructions.Play, pulse.instructions.Delay, pulse.instructions.Acquire, ) _frame_group = ( pulse.instructions.SetFrequency, pulse.instructions.ShiftFrequency, pulse.instructions.SetPhase, pulse.instructions.ShiftPhase, ) def __init__( self, waveforms: dict[int, pulse.Instruction], frames: dict[int, list[pulse.Instruction]], channel: pulse.channels.Channel, ): """Create new event manager. Args: waveforms: List of waveforms shown in this channel. frames: List of frame change type instructions shown in this channel. channel: Channel object associated with this manager. """ self._waveforms = waveforms self._frames = frames self.channel = channel # initial frame self._init_phase = 0.0 self._init_frequency = 0.0 # time resolution self._dt = 0.0 @classmethod def load_program(cls, program: pulse.Schedule, channel: pulse.channels.Channel): """Load a pulse program represented by ``Schedule``. Args: program: Target ``Schedule`` to visualize. channel: The channel managed by this instance. Returns: ChannelEvents: The channel event manager for the specified channel. """ waveforms = {} frames = defaultdict(list) # parse instructions for t0, inst in program.filter(channels=[channel]).instructions: if isinstance(inst, cls._waveform_group): if inst.duration == 0: # special case, duration of delay can be zero continue waveforms[t0] = inst elif isinstance(inst, cls._frame_group): frames[t0].append(inst) return ChannelEvents(waveforms, frames, channel) def set_config(self, dt: float, init_frequency: float, init_phase: float): """Setup system status. Args: dt: Time resolution in sec. init_frequency: Modulation frequency in Hz. init_phase: Initial phase in rad. """ self._dt = dt or 1.0 self._init_frequency = init_frequency or 0.0 self._init_phase = init_phase or 0.0 def get_waveforms(self) -> Iterator[PulseInstruction]: """Return waveform type instructions with frame.""" sorted_frame_changes = sorted(self._frames.items(), key=lambda x: x[0], reverse=True) sorted_waveforms = sorted(self._waveforms.items(), key=lambda x: x[0]) # bind phase and frequency with instruction phase = self._init_phase frequency = self._init_frequency for t0, inst in sorted_waveforms: is_opaque = False while len(sorted_frame_changes) > 0 and sorted_frame_changes[-1][0] <= t0: _, frame_changes = sorted_frame_changes.pop() phase, frequency = ChannelEvents._calculate_current_frame( frame_changes=frame_changes, phase=phase, frequency=frequency ) # Convert parameter expression into float if isinstance(phase, circuit.ParameterExpression): phase = float(phase.bind({param: 0 for param in phase.parameters})) if isinstance(frequency, circuit.ParameterExpression): frequency = float(frequency.bind({param: 0 for param in frequency.parameters})) frame = PhaseFreqTuple(phase, frequency) # Check if pulse has unbound parameters if isinstance(inst, pulse.Play): is_opaque = inst.pulse.is_parameterized() yield PulseInstruction(t0, self._dt, frame, inst, is_opaque) def get_frame_changes(self) -> Iterator[PulseInstruction]: """Return frame change type instructions with total frame change amount.""" # TODO parse parametrised FCs correctly sorted_frame_changes = sorted(self._frames.items(), key=lambda x: x[0]) phase = self._init_phase frequency = self._init_frequency for t0, frame_changes in sorted_frame_changes: is_opaque = False pre_phase = phase pre_frequency = frequency phase, frequency = ChannelEvents._calculate_current_frame( frame_changes=frame_changes, phase=phase, frequency=frequency ) # keep parameter expression to check either phase or frequency is parameterized frame = PhaseFreqTuple(phase - pre_phase, frequency - pre_frequency) # remove parameter expressions to find if next frame is parameterized if isinstance(phase, circuit.ParameterExpression): phase = float(phase.bind({param: 0 for param in phase.parameters})) is_opaque = True if isinstance(frequency, circuit.ParameterExpression): frequency = float(frequency.bind({param: 0 for param in frequency.parameters})) is_opaque = True yield PulseInstruction(t0, self._dt, frame, frame_changes, is_opaque) @classmethod def _calculate_current_frame( cls, frame_changes: list[pulse.instructions.Instruction], phase: float, frequency: float ) -> tuple[float, float]: """Calculate the current frame from the previous frame. If parameter is unbound phase or frequency accumulation with this instruction is skipped. Args: frame_changes: List of frame change instructions at a specific time. phase: Phase of previous frame. frequency: Frequency of previous frame. Returns: Phase and frequency of new frame. """ for frame_change in frame_changes: if isinstance(frame_change, pulse.instructions.SetFrequency): frequency = frame_change.frequency elif isinstance(frame_change, pulse.instructions.ShiftFrequency): frequency += frame_change.frequency elif isinstance(frame_change, pulse.instructions.SetPhase): phase = frame_change.phase elif isinstance(frame_change, pulse.instructions.ShiftPhase): phase += frame_change.phase return phase, frequency
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ A collection of functions that decide the layout of an output image. See :py:mod:`~qiskit.visualization.timeline.types` for more info on the required data. There are 2 types of layout functions in this module. 1. layout.bit_arrange In this stylesheet entry the input data is a list of `types.Bits` and returns a sorted list of `types.Bits`. The function signature of the layout is restricted to: ```python def my_layout(bits: List[types.Bits]) -> List[types.Bits]: # your code here: sort input bits and return list of bits ``` 2. layout.time_axis_map In this stylesheet entry the input data is `Tuple[int, int]` that represents horizontal axis limit of the output image. The layout function returns `types.HorizontalAxis` data which is consumed by the plotter API to make horizontal axis. The function signature of the layout is restricted to: ```python def my_layout(time_window: Tuple[int, int]) -> types.HorizontalAxis: # your code here: create and return axis config ``` Arbitrary layout function satisfying the above format can be accepted. """ import warnings from typing import List, Tuple import numpy as np from qiskit import circuit from qiskit.visualization.exceptions import VisualizationError from qiskit.visualization.timeline import types def qreg_creg_ascending(bits: List[types.Bits]) -> List[types.Bits]: """Sort bits by ascending order. Bit order becomes Q0, Q1, ..., Cl0, Cl1, ... Args: bits: List of bits to sort. Returns: Sorted bits. """ qregs = [] cregs = [] for bit in bits: if isinstance(bit, circuit.Qubit): qregs.append(bit) elif isinstance(bit, circuit.Clbit): cregs.append(bit) else: raise VisualizationError(f"Unknown bit {bit} is provided.") with warnings.catch_warnings(): warnings.simplefilter("ignore") qregs = sorted(qregs, key=lambda x: x.index, reverse=False) cregs = sorted(cregs, key=lambda x: x.index, reverse=False) return qregs + cregs def qreg_creg_descending(bits: List[types.Bits]) -> List[types.Bits]: """Sort bits by descending order. Bit order becomes Q_N, Q_N-1, ..., Cl_N, Cl_N-1, ... Args: bits: List of bits to sort. Returns: Sorted bits. """ qregs = [] cregs = [] for bit in bits: if isinstance(bit, circuit.Qubit): qregs.append(bit) elif isinstance(bit, circuit.Clbit): cregs.append(bit) else: raise VisualizationError(f"Unknown bit {bit} is provided.") qregs = sorted(qregs, key=lambda x: x.index, reverse=True) cregs = sorted(cregs, key=lambda x: x.index, reverse=True) return qregs + cregs def time_map_in_dt(time_window: Tuple[int, int]) -> types.HorizontalAxis: """Layout function for the horizontal axis formatting. Generate equispaced 6 horizontal axis ticks. Args: time_window: Left and right edge of this graph. Returns: Axis formatter object. """ # shift time axis t0, t1 = time_window # axis label axis_loc = np.linspace(max(t0, 0), t1, 6) axis_label = axis_loc.copy() # consider time resolution label = "System cycle time (dt)" formatted_label = [f"{val:.0f}" for val in axis_label] return types.HorizontalAxis( window=(t0, t1), axis_map=dict(zip(axis_loc, formatted_label)), label=label )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Special data types. """ from enum import Enum from typing import NamedTuple, List, Union, NewType, Tuple, Dict from qiskit import circuit ScheduledGate = NamedTuple( "ScheduledGate", [ ("t0", int), ("operand", circuit.Gate), ("duration", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int), ], ) ScheduledGate.__doc__ = "A gate instruction with embedded time." ScheduledGate.t0.__doc__ = "Time when the instruction is issued." ScheduledGate.operand.__doc__ = "Gate object associated with the gate." ScheduledGate.duration.__doc__ = "Time duration of the instruction." ScheduledGate.bits.__doc__ = "List of bit associated with the gate." ScheduledGate.bit_position.__doc__ = "Position of bit associated with this drawing source." GateLink = NamedTuple( "GateLink", [("t0", int), ("opname", str), ("bits", List[Union[circuit.Qubit, circuit.Clbit]])] ) GateLink.__doc__ = "Dedicated object to represent a relationship between instructions." GateLink.t0.__doc__ = "A position where the link is placed." GateLink.opname.__doc__ = "Name of gate associated with this link." GateLink.bits.__doc__ = "List of bit associated with the instruction." Barrier = NamedTuple( "Barrier", [("t0", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int)], ) Barrier.__doc__ = "Dedicated object to represent a barrier instruction." Barrier.t0.__doc__ = "A position where the barrier is placed." Barrier.bits.__doc__ = "List of bit associated with the instruction." Barrier.bit_position.__doc__ = "Position of bit associated with this drawing source." HorizontalAxis = NamedTuple( "HorizontalAxis", [("window", Tuple[int, int]), ("axis_map", Dict[int, int]), ("label", str)] ) HorizontalAxis.__doc__ = "Data to represent configuration of horizontal axis." HorizontalAxis.window.__doc__ = "Left and right edge of graph." HorizontalAxis.axis_map.__doc__ = "Mapping of apparent coordinate system and actual location." HorizontalAxis.label.__doc__ = "Label of horizontal axis." class BoxType(str, Enum): """Box type. SCHED_GATE: Box that represents occupation time by gate. DELAY: Box associated with delay. TIMELINE: Box that represents time slot of a bit. """ SCHED_GATE = "Box.ScheduledGate" DELAY = "Box.Delay" TIMELINE = "Box.Timeline" class LineType(str, Enum): """Line type. BARRIER: Line that represents barrier instruction. GATE_LINK: Line that represents a link among gates. """ BARRIER = "Line.Barrier" GATE_LINK = "Line.GateLink" class SymbolType(str, Enum): """Symbol type. FRAME: Symbol that represents zero time frame change (Rz) instruction. """ FRAME = "Symbol.Frame" class LabelType(str, Enum): """Label type. GATE_NAME: Label that represents name of gate. DELAY: Label associated with delay. GATE_PARAM: Label that represents parameter of gate. BIT_NAME: Label that represents name of bit. """ GATE_NAME = "Label.Gate.Name" DELAY = "Label.Delay" GATE_PARAM = "Label.Gate.Param" BIT_NAME = "Label.Bit.Name" class AbstractCoordinate(Enum): """Abstract coordinate that the exact value depends on the user preference. RIGHT: The horizontal coordinate at t0 shifted by the left margin. LEFT: The horizontal coordinate at tf shifted by the right margin. TOP: The vertical coordinate at the top of the canvas. BOTTOM: The vertical coordinate at the bottom of the canvas. """ RIGHT = "RIGHT" LEFT = "LEFT" TOP = "TOP" BOTTOM = "BOTTOM" class Plotter(str, Enum): """Name of timeline plotter APIs. MPL: Matplotlib plotter interface. Show timeline in 2D canvas. """ MPL = "mpl" # convenient type to represent union of drawing data DataTypes = NewType("DataType", Union[BoxType, LabelType, LineType, SymbolType]) # convenient type to represent union of values to represent a coordinate Coordinate = NewType("Coordinate", Union[float, AbstractCoordinate]) # Valid bit objects Bits = NewType("Bits", Union[circuit.Qubit, circuit.Clbit])
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=unused-argument """Waveform generators. A collection of functions that generate drawings from formatted input data. See py:mod:`qiskit.visualization.pulse_v2.types` for more info on the required data. In this module the input data is `types.PulseInstruction`. An end-user can write arbitrary functions that generate custom drawings. Generators in this module are called with the `formatter` and `device` kwargs. These data provides stylesheet configuration and backend system configuration. The format of generator is restricted to: ```python def my_object_generator(data: PulseInstruction, formatter: Dict[str, Any], device: DrawerBackendInfo) -> List[ElementaryData]: pass ``` Arbitrary generator function satisfying the above format can be accepted. Returned `ElementaryData` can be arbitrary subclasses that are implemented in the plotter API. """ from __future__ import annotations import re from fractions import Fraction from typing import Any import numpy as np from qiskit import pulse, circuit from qiskit.pulse import instructions, library from qiskit.visualization.exceptions import VisualizationError from qiskit.visualization.pulse_v2 import drawings, types, device_info def gen_filled_waveform_stepwise( data: types.PulseInstruction, formatter: dict[str, Any], device: device_info.DrawerBackendInfo ) -> list[drawings.LineData | drawings.BoxData | drawings.TextData]: """Generate filled area objects of the real and the imaginary part of waveform envelope. The curve of envelope is not interpolated nor smoothed and presented as stepwise function at each data point. Stylesheets: - The `fill_waveform` style is applied. Args: data: Waveform instruction data to draw. formatter: Dictionary of stylesheet settings. device: Backend configuration. Returns: List of `LineData`, `BoxData`, or `TextData` drawings. Raises: VisualizationError: When the instruction parser returns invalid data format. """ # generate waveform data waveform_data = _parse_waveform(data) channel = data.inst.channel # update metadata meta = waveform_data.meta qind = device.get_qubit_index(channel) meta.update({"qubit": qind if qind is not None else "N/A"}) if isinstance(waveform_data, types.ParsedInstruction): # Draw waveform with fixed shape xdata = waveform_data.xvals ydata = waveform_data.yvals # phase modulation if formatter["control.apply_phase_modulation"]: ydata = np.asarray(ydata, dtype=complex) * np.exp(1j * data.frame.phase) else: ydata = np.asarray(ydata, dtype=complex) return _draw_shaped_waveform( xdata=xdata, ydata=ydata, meta=meta, channel=channel, formatter=formatter ) elif isinstance(waveform_data, types.OpaqueShape): # Draw parametric pulse with unbound parameters # parameter name unbound_params = [] for pname, pval in data.inst.pulse.parameters.items(): if isinstance(pval, circuit.ParameterExpression): unbound_params.append(pname) pulse_data = data.inst.pulse if isinstance(pulse_data, library.SymbolicPulse): pulse_shape = pulse_data.pulse_type else: pulse_shape = "Waveform" return _draw_opaque_waveform( init_time=data.t0, duration=waveform_data.duration, pulse_shape=pulse_shape, pnames=unbound_params, meta=meta, channel=channel, formatter=formatter, ) else: raise VisualizationError("Invalid data format is provided.") def gen_ibmq_latex_waveform_name( data: types.PulseInstruction, formatter: dict[str, Any], device: device_info.DrawerBackendInfo ) -> list[drawings.TextData]: r"""Generate the formatted instruction name associated with the waveform. Channel name and ID string are removed and the rotation angle is expressed in units of pi. The controlled rotation angle associated with the CR pulse name is divided by 2. Note that in many scientific articles the controlled rotation angle implies the actual rotation angle, but in IQX backend the rotation angle represents the difference between rotation angles with different control qubit states. For example: - 'X90p_d0_abcdefg' is converted into 'X(\frac{\pi}{2})' - 'CR90p_u0_abcdefg` is converted into 'CR(\frac{\pi}{4})' Stylesheets: - The `annotate` style is applied. Notes: This generator can convert pulse names used in the IQX backends. If pulses are provided by the third party providers or the user defined, the generator output may be the as-is pulse name. Args: data: Waveform instruction data to draw. formatter: Dictionary of stylesheet settings. device: Backend configuration. Returns: List of `TextData` drawings. """ if data.is_opaque: return [] style = { "zorder": formatter["layer.annotate"], "color": formatter["color.annotate"], "size": formatter["text_size.annotate"], "va": "center", "ha": "center", } if isinstance(data.inst, pulse.instructions.Acquire): systematic_name = "Acquire" latex_name = None elif isinstance(data.inst, instructions.Delay): systematic_name = data.inst.name or "Delay" latex_name = None else: pulse_data = data.inst.pulse if pulse_data.name: systematic_name = pulse_data.name else: if isinstance(pulse_data, library.SymbolicPulse): systematic_name = pulse_data.pulse_type else: systematic_name = "Waveform" template = r"(?P<op>[A-Z]+)(?P<angle>[0-9]+)?(?P<sign>[pm])_(?P<ch>[dum])[0-9]+" match_result = re.match(template, systematic_name) if match_result is not None: match_dict = match_result.groupdict() sign = "" if match_dict["sign"] == "p" else "-" if match_dict["op"] == "CR": # cross resonance if match_dict["ch"] == "u": op_name = r"{\rm CR}" else: op_name = r"\overline{\rm CR}" # IQX name def is not standard. Echo CR is annotated with pi/4 rather than pi/2 angle_val = match_dict["angle"] frac = Fraction(int(int(angle_val) / 2), 180) if frac.numerator == 1: angle = rf"\pi/{frac.denominator:d}" else: angle = r"{num:d}/{denom:d} \pi".format( num=frac.numerator, denom=frac.denominator ) else: # single qubit pulse op_name = r"{{\rm {}}}".format(match_dict["op"]) angle_val = match_dict["angle"] if angle_val is None: angle = r"\pi" else: frac = Fraction(int(angle_val), 180) if frac.numerator == 1: angle = rf"\pi/{frac.denominator:d}" else: angle = r"{num:d}/{denom:d} \pi".format( num=frac.numerator, denom=frac.denominator ) latex_name = rf"{op_name}({sign}{angle})" else: latex_name = None text = drawings.TextData( data_type=types.LabelType.PULSE_NAME, channels=data.inst.channel, xvals=[data.t0 + 0.5 * data.inst.duration], yvals=[-formatter["label_offset.pulse_name"]], text=systematic_name, latex=latex_name, ignore_scaling=True, styles=style, ) return [text] def gen_waveform_max_value( data: types.PulseInstruction, formatter: dict[str, Any], device: device_info.DrawerBackendInfo ) -> list[drawings.TextData]: """Generate the annotation for the maximum waveform height for the real and the imaginary part of the waveform envelope. Maximum values smaller than the vertical resolution limit is ignored. Stylesheets: - The `annotate` style is applied. Args: data: Waveform instruction data to draw. formatter: Dictionary of stylesheet settings. device: Backend configuration. Returns: List of `TextData` drawings. """ if data.is_opaque: return [] style = { "zorder": formatter["layer.annotate"], "color": formatter["color.annotate"], "size": formatter["text_size.annotate"], "ha": "center", } # only pulses. if isinstance(data.inst, instructions.Play): # pulse operand = data.inst.pulse if isinstance(operand, (pulse.ParametricPulse, pulse.SymbolicPulse)): pulse_data = operand.get_waveform() else: pulse_data = operand xdata = np.arange(pulse_data.duration) + data.t0 ydata = pulse_data.samples else: return [] # phase modulation if formatter["control.apply_phase_modulation"]: ydata = np.asarray(ydata, dtype=complex) * np.exp(1j * data.frame.phase) else: ydata = np.asarray(ydata, dtype=complex) texts = [] # max of real part re_maxind = np.argmax(np.abs(ydata.real)) if np.abs(ydata.real[re_maxind]) > 0.01: # generator shows only 2 digits after the decimal point. if ydata.real[re_maxind] > 0: max_val = f"{ydata.real[re_maxind]:.2f}\n\u25BE" re_style = {"va": "bottom"} else: max_val = f"\u25B4\n{ydata.real[re_maxind]:.2f}" re_style = {"va": "top"} re_style.update(style) re_text = drawings.TextData( data_type=types.LabelType.PULSE_INFO, channels=data.inst.channel, xvals=[xdata[re_maxind]], yvals=[ydata.real[re_maxind]], text=max_val, styles=re_style, ) texts.append(re_text) # max of imag part im_maxind = np.argmax(np.abs(ydata.imag)) if np.abs(ydata.imag[im_maxind]) > 0.01: # generator shows only 2 digits after the decimal point. if ydata.imag[im_maxind] > 0: max_val = f"{ydata.imag[im_maxind]:.2f}\n\u25BE" im_style = {"va": "bottom"} else: max_val = f"\u25B4\n{ydata.imag[im_maxind]:.2f}" im_style = {"va": "top"} im_style.update(style) im_text = drawings.TextData( data_type=types.LabelType.PULSE_INFO, channels=data.inst.channel, xvals=[xdata[im_maxind]], yvals=[ydata.imag[im_maxind]], text=max_val, styles=im_style, ) texts.append(im_text) return texts def _draw_shaped_waveform( xdata: np.ndarray, ydata: np.ndarray, meta: dict[str, Any], channel: pulse.channels.PulseChannel, formatter: dict[str, Any], ) -> list[drawings.LineData | drawings.BoxData | drawings.TextData]: """A private function that generates drawings of stepwise pulse lines. Args: xdata: Array of horizontal coordinate of waveform envelope. ydata: Array of vertical coordinate of waveform envelope. meta: Metadata dictionary of the waveform. channel: Channel associated with the waveform to draw. formatter: Dictionary of stylesheet settings. Returns: List of drawings. Raises: VisualizationError: When the waveform color for channel is not defined. """ fill_objs: list[drawings.LineData | drawings.BoxData | drawings.TextData] = [] resolution = formatter["general.vertical_resolution"] # stepwise interpolation xdata: np.ndarray = np.concatenate((xdata, [xdata[-1] + 1])) ydata = np.repeat(ydata, 2) re_y = np.real(ydata) im_y = np.imag(ydata) time: np.ndarray = np.concatenate(([xdata[0]], np.repeat(xdata[1:-1], 2), [xdata[-1]])) # setup style options style = { "alpha": formatter["alpha.fill_waveform"], "zorder": formatter["layer.fill_waveform"], "linewidth": formatter["line_width.fill_waveform"], "linestyle": formatter["line_style.fill_waveform"], } try: color_real, color_imag = formatter["color.waveforms"][channel.prefix.upper()] except KeyError as ex: raise VisualizationError( f"Waveform color for channel type {channel.prefix} is not defined" ) from ex # create real part if np.any(re_y): # data compression re_valid_inds = _find_consecutive_index(re_y, resolution) # stylesheet re_style = {"color": color_real} re_style.update(style) # metadata re_meta = {"data": "real"} re_meta.update(meta) # active xy data re_xvals = time[re_valid_inds] re_yvals = re_y[re_valid_inds] # object real = drawings.LineData( data_type=types.WaveformType.REAL, channels=channel, xvals=re_xvals, yvals=re_yvals, fill=formatter["control.fill_waveform"], meta=re_meta, styles=re_style, ) fill_objs.append(real) # create imaginary part if np.any(im_y): # data compression im_valid_inds = _find_consecutive_index(im_y, resolution) # stylesheet im_style = {"color": color_imag} im_style.update(style) # metadata im_meta = {"data": "imag"} im_meta.update(meta) # active xy data im_xvals = time[im_valid_inds] im_yvals = im_y[im_valid_inds] # object imag = drawings.LineData( data_type=types.WaveformType.IMAG, channels=channel, xvals=im_xvals, yvals=im_yvals, fill=formatter["control.fill_waveform"], meta=im_meta, styles=im_style, ) fill_objs.append(imag) return fill_objs def _draw_opaque_waveform( init_time: int, duration: int, pulse_shape: str, pnames: list[str], meta: dict[str, Any], channel: pulse.channels.PulseChannel, formatter: dict[str, Any], ) -> list[drawings.LineData | drawings.BoxData | drawings.TextData]: """A private function that generates drawings of stepwise pulse lines. Args: init_time: Time when the opaque waveform starts. duration: Duration of opaque waveform. This can be None or ParameterExpression. pulse_shape: String that represents pulse shape. pnames: List of parameter names. meta: Metadata dictionary of the waveform. channel: Channel associated with the waveform to draw. formatter: Dictionary of stylesheet settings. Returns: List of drawings. """ fill_objs: list[drawings.LineData | drawings.BoxData | drawings.TextData] = [] fc, ec = formatter["color.opaque_shape"] # setup style options box_style = { "zorder": formatter["layer.fill_waveform"], "alpha": formatter["alpha.opaque_shape"], "linewidth": formatter["line_width.opaque_shape"], "linestyle": formatter["line_style.opaque_shape"], "facecolor": fc, "edgecolor": ec, } if duration is None or isinstance(duration, circuit.ParameterExpression): duration = formatter["box_width.opaque_shape"] box_obj = drawings.BoxData( data_type=types.WaveformType.OPAQUE, channels=channel, xvals=[init_time, init_time + duration], yvals=[ -0.5 * formatter["box_height.opaque_shape"], 0.5 * formatter["box_height.opaque_shape"], ], meta=meta, ignore_scaling=True, styles=box_style, ) fill_objs.append(box_obj) # parameter name func_repr = "{func}({params})".format(func=pulse_shape, params=", ".join(pnames)) text_style = { "zorder": formatter["layer.annotate"], "color": formatter["color.annotate"], "size": formatter["text_size.annotate"], "va": "bottom", "ha": "center", } text_obj = drawings.TextData( data_type=types.LabelType.OPAQUE_BOXTEXT, channels=channel, xvals=[init_time + 0.5 * duration], yvals=[0.5 * formatter["box_height.opaque_shape"]], text=func_repr, ignore_scaling=True, styles=text_style, ) fill_objs.append(text_obj) return fill_objs def _find_consecutive_index(data_array: np.ndarray, resolution: float) -> np.ndarray: """A helper function to return non-consecutive index from the given list. This drastically reduces memory footprint to represent a drawing, especially for samples of very long flat-topped Gaussian pulses. Tiny value fluctuation smaller than `resolution` threshold is removed. Args: data_array: The array of numbers. resolution: Minimum resolution of sample values. Returns: The compressed data array. """ try: vector = np.asarray(data_array, dtype=float) diff = np.diff(vector) diff[np.where(np.abs(diff) < resolution)] = 0 # keep left and right edges consecutive_l = np.insert(diff.astype(bool), 0, True) consecutive_r = np.append(diff.astype(bool), True) return consecutive_l | consecutive_r except ValueError: return np.ones_like(data_array).astype(bool) def _parse_waveform( data: types.PulseInstruction, ) -> types.ParsedInstruction | types.OpaqueShape: """A helper function that generates an array for the waveform with instruction metadata. Args: data: Instruction data set Raises: VisualizationError: When invalid instruction type is loaded. Returns: A data source to generate a drawing. """ inst = data.inst meta: dict[str, Any] = {} if isinstance(inst, instructions.Play): # pulse operand = inst.pulse if isinstance(operand, (pulse.ParametricPulse, pulse.SymbolicPulse)): # parametric pulse params = operand.parameters duration = params.pop("duration", None) if isinstance(duration, circuit.Parameter): duration = None if isinstance(operand, library.SymbolicPulse): pulse_shape = operand.pulse_type else: pulse_shape = "Waveform" meta["waveform shape"] = pulse_shape meta.update( { key: val.name if isinstance(val, circuit.Parameter) else val for key, val in params.items() } ) if data.is_opaque: # parametric pulse with unbound parameter if duration: meta.update( { "duration (cycle time)": inst.duration, "duration (sec)": inst.duration * data.dt if data.dt else "N/A", } ) else: meta.update({"duration (cycle time)": "N/A", "duration (sec)": "N/A"}) meta.update( { "t0 (cycle time)": data.t0, "t0 (sec)": data.t0 * data.dt if data.dt else "N/A", "phase": data.frame.phase, "frequency": data.frame.freq, "name": inst.name, } ) return types.OpaqueShape(duration=duration, meta=meta) else: # fixed shape parametric pulse pulse_data = operand.get_waveform() else: # waveform pulse_data = operand xdata = np.arange(pulse_data.duration) + data.t0 ydata = pulse_data.samples elif isinstance(inst, instructions.Delay): # delay xdata = np.arange(inst.duration) + data.t0 ydata = np.zeros(inst.duration) elif isinstance(inst, instructions.Acquire): # acquire xdata = np.arange(inst.duration) + data.t0 ydata = np.ones(inst.duration) acq_data = { "memory slot": inst.mem_slot.name, "register slot": inst.reg_slot.name if inst.reg_slot else "N/A", "discriminator": inst.discriminator.name if inst.discriminator else "N/A", "kernel": inst.kernel.name if inst.kernel else "N/A", } meta.update(acq_data) else: raise VisualizationError( "Unsupported instruction {inst} by " "filled envelope.".format(inst=inst.__class__.__name__) ) meta.update( { "duration (cycle time)": inst.duration, "duration (sec)": inst.duration * data.dt if data.dt else "N/A", "t0 (cycle time)": data.t0, "t0 (sec)": data.t0 * data.dt if data.dt else "N/A", "phase": data.frame.phase, "frequency": data.frame.freq, "name": inst.name, } ) return types.ParsedInstruction(xvals=xdata, yvals=ydata, meta=meta)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Core module of the timeline drawer. This module provides the `DrawerCanvas` which is a collection of drawings. The canvas instance is not just a container of drawing objects, as it also performs data processing like binding abstract coordinates. Initialization ~~~~~~~~~~~~~~ The `DataCanvas` is not exposed to users as they are implicitly initialized in the interface function. It is noteworthy that the data canvas is agnostic to plotters. This means once the canvas instance is initialized we can reuse this data among multiple plotters. The canvas is initialized with a stylesheet. ```python canvas = DrawerCanvas(stylesheet=stylesheet) canvas.load_program(sched) canvas.update() ``` Once all properties are set, `.update` method is called to apply changes to drawings. Update ~~~~~~ To update the image, a user can set new values to canvas and then call the `.update` method. ```python canvas.set_time_range(2000, 3000) canvas.update() ``` All stored drawings are updated accordingly. The plotter API can access to drawings with `.collections` property of the canvas instance. This returns an iterator of drawings with the unique data key. If a plotter provides object handler for plotted shapes, the plotter API can manage the lookup table of the handler and the drawings by using this data key. """ from __future__ import annotations import warnings from collections.abc import Iterator from copy import deepcopy from functools import partial from enum import Enum import numpy as np from qiskit import circuit from qiskit.visualization.exceptions import VisualizationError from qiskit.visualization.timeline import drawings, types from qiskit.visualization.timeline.stylesheet import QiskitTimelineStyle class DrawerCanvas: """Data container for drawings.""" def __init__(self, stylesheet: QiskitTimelineStyle): """Create new data container.""" # stylesheet self.formatter = stylesheet.formatter self.generator = stylesheet.generator self.layout = stylesheet.layout # drawings self._collections: dict[str, drawings.ElementaryData] = {} self._output_dataset: dict[str, drawings.ElementaryData] = {} # vertical offset of bits self.bits: list[types.Bits] = [] self.assigned_coordinates: dict[types.Bits, float] = {} # visible controls self.disable_bits: set[types.Bits] = set() self.disable_types: set[str] = set() # time self._time_range = (0, 0) # graph height self.vmax = 0 self.vmin = 0 @property def time_range(self) -> tuple[int, int]: """Return current time range to draw. Calculate net duration and add side margin to edge location. Returns: Time window considering side margin. """ t0, t1 = self._time_range duration = t1 - t0 new_t0 = t0 - duration * self.formatter["margin.left_percent"] new_t1 = t1 + duration * self.formatter["margin.right_percent"] return new_t0, new_t1 @time_range.setter def time_range(self, new_range: tuple[int, int]): """Update time range to draw.""" self._time_range = new_range @property def collections(self) -> Iterator[tuple[str, drawings.ElementaryData]]: """Return currently active entries from drawing data collection. The object is returned with unique name as a key of an object handler. When the horizontal coordinate contains `AbstractCoordinate`, the value is substituted by current time range preference. """ yield from self._output_dataset.items() def add_data(self, data: drawings.ElementaryData): """Add drawing to collections. If the given object already exists in the collections, this interface replaces the old object instead of adding new entry. Args: data: New drawing to add. """ if not self.formatter["control.show_clbits"]: data.bits = [b for b in data.bits if not isinstance(b, circuit.Clbit)] self._collections[data.data_key] = data # pylint: disable=cyclic-import def load_program(self, program: circuit.QuantumCircuit): """Load quantum circuit and create drawing.. Args: program: Scheduled circuit object to draw. Raises: VisualizationError: When circuit is not scheduled. """ not_gate_like = (circuit.Barrier,) if getattr(program, "_op_start_times") is None: # Run scheduling for backward compatibility from qiskit import transpile from qiskit.transpiler import InstructionDurations, TranspilerError warnings.warn( "Visualizing un-scheduled circuit with timeline drawer has been deprecated. " "This circuit should be transpiled with scheduler though it consists of " "instructions with explicit durations.", DeprecationWarning, ) try: program = transpile( program, scheduling_method="alap", instruction_durations=InstructionDurations(), optimization_level=0, ) except TranspilerError as ex: raise VisualizationError( f"Input circuit {program.name} is not scheduled and it contains " "operations with unknown delays. This cannot be visualized." ) from ex for t0, instruction in zip(program.op_start_times, program.data): bits = list(instruction.qubits) + list(instruction.clbits) for bit_pos, bit in enumerate(bits): if not isinstance(instruction.operation, not_gate_like): # Generate draw object for gates gate_source = types.ScheduledGate( t0=t0, operand=instruction.operation, duration=instruction.operation.duration, bits=bits, bit_position=bit_pos, ) for gen in self.generator["gates"]: obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(gate_source): self.add_data(datum) if len(bits) > 1 and bit_pos == 0: # Generate draw object for gate-gate link line_pos = t0 + 0.5 * instruction.operation.duration link_source = types.GateLink( t0=line_pos, opname=instruction.operation.name, bits=bits ) for gen in self.generator["gate_links"]: obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(link_source): self.add_data(datum) if isinstance(instruction.operation, circuit.Barrier): # Generate draw object for barrier barrier_source = types.Barrier(t0=t0, bits=bits, bit_position=bit_pos) for gen in self.generator["barriers"]: obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(barrier_source): self.add_data(datum) self.bits = list(program.qubits) + list(program.clbits) for bit in self.bits: for gen in self.generator["bits"]: # Generate draw objects for bit obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(bit): self.add_data(datum) # update time range t_end = max(program.duration, self.formatter["margin.minimum_duration"]) self.set_time_range(t_start=0, t_end=t_end) def set_time_range(self, t_start: int, t_end: int): """Set time range to draw. Args: t_start: Left boundary of drawing in units of cycle time. t_end: Right boundary of drawing in units of cycle time. """ self.time_range = (t_start, t_end) def set_disable_bits(self, bit: types.Bits, remove: bool = True): """Interface method to control visibility of bits. Specified object in the blocked list will not be shown. Args: bit: A qubit or classical bit object to disable. remove: Set `True` to disable, set `False` to enable. """ if remove: self.disable_bits.add(bit) else: self.disable_bits.discard(bit) def set_disable_type(self, data_type: types.DataTypes, remove: bool = True): """Interface method to control visibility of data types. Specified object in the blocked list will not be shown. Args: data_type: A drawing data type to disable. remove: Set `True` to disable, set `False` to enable. """ if isinstance(data_type, Enum): data_type_str = str(data_type.value) else: data_type_str = data_type if remove: self.disable_types.add(data_type_str) else: self.disable_types.discard(data_type_str) def update(self): """Update all collections. This method should be called before the canvas is passed to the plotter. """ self._output_dataset.clear() self.assigned_coordinates.clear() # update coordinate y0 = -self.formatter["margin.top"] for bit in self.layout["bit_arrange"](self.bits): # remove classical bit if isinstance(bit, circuit.Clbit) and not self.formatter["control.show_clbits"]: continue # remove idle bit if not self._check_bit_visible(bit): continue offset = y0 - 0.5 self.assigned_coordinates[bit] = offset y0 = offset - 0.5 self.vmax = 0 self.vmin = y0 - self.formatter["margin.bottom"] # add data temp_gate_links = {} temp_data = {} for data_key, data in self._collections.items(): # deep copy to keep original data hash new_data = deepcopy(data) new_data.xvals = self._bind_coordinate(data.xvals) new_data.yvals = self._bind_coordinate(data.yvals) if data.data_type == str(types.LineType.GATE_LINK.value): temp_gate_links[data_key] = new_data else: temp_data[data_key] = new_data # update horizontal offset of gate links temp_data.update(self._check_link_overlap(temp_gate_links)) # push valid data for data_key, data in temp_data.items(): if self._check_data_visible(data): self._output_dataset[data_key] = data def _check_data_visible(self, data: drawings.ElementaryData) -> bool: """A helper function to check if the data is visible. Args: data: Drawing object to test. Returns: Return `True` if the data is visible. """ _barriers = [str(types.LineType.BARRIER.value)] _delays = [str(types.BoxType.DELAY.value), str(types.LabelType.DELAY.value)] def _time_range_check(_data): """If data is located outside the current time range.""" t0, t1 = self.time_range if np.max(_data.xvals) < t0 or np.min(_data.xvals) > t1: return False return True def _associated_bit_check(_data): """If any associated bit is not shown.""" if all(bit not in self.assigned_coordinates for bit in _data.bits): return False return True def _data_check(_data): """If data is valid.""" if _data.data_type == str(types.LineType.GATE_LINK.value): active_bits = [bit for bit in _data.bits if bit not in self.disable_bits] if len(active_bits) < 2: return False elif _data.data_type in _barriers and not self.formatter["control.show_barriers"]: return False elif _data.data_type in _delays and not self.formatter["control.show_delays"]: return False return True checks = [_time_range_check, _associated_bit_check, _data_check] if all(check(data) for check in checks): return True return False def _check_bit_visible(self, bit: types.Bits) -> bool: """A helper function to check if the bit is visible. Args: bit: Bit object to test. Returns: Return `True` if the bit is visible. """ _gates = [str(types.BoxType.SCHED_GATE.value), str(types.SymbolType.FRAME.value)] if bit in self.disable_bits: return False if self.formatter["control.show_idle"]: return True for data in self._collections.values(): if bit in data.bits and data.data_type in _gates: return True return False def _bind_coordinate(self, vals: Iterator[types.Coordinate]) -> np.ndarray: """A helper function to bind actual coordinates to an `AbstractCoordinate`. Args: vals: Sequence of coordinate objects associated with a drawing. Returns: Numpy data array with substituted values. """ def substitute(val: types.Coordinate): if val == types.AbstractCoordinate.LEFT: return self.time_range[0] if val == types.AbstractCoordinate.RIGHT: return self.time_range[1] if val == types.AbstractCoordinate.TOP: return self.vmax if val == types.AbstractCoordinate.BOTTOM: return self.vmin raise VisualizationError(f"Coordinate {val} is not supported.") try: return np.asarray(vals, dtype=float) except TypeError: return np.asarray(list(map(substitute, vals)), dtype=float) def _check_link_overlap( self, links: dict[str, drawings.GateLinkData] ) -> dict[str, drawings.GateLinkData]: """Helper method to check overlap of bit links. This method dynamically shifts horizontal position of links if they are overlapped. """ duration = self.time_range[1] - self.time_range[0] allowed_overlap = self.formatter["margin.link_interval_percent"] * duration # return y coordinates def y_coords(link: drawings.GateLinkData): return np.array([self.assigned_coordinates.get(bit, np.nan) for bit in link.bits]) # group overlapped links overlapped_group: list[list[str]] = [] data_keys = list(links.keys()) while len(data_keys) > 0: ref_key = data_keys.pop() overlaps = set() overlaps.add(ref_key) for key in data_keys[::-1]: # check horizontal overlap if np.abs(links[ref_key].xvals[0] - links[key].xvals[0]) < allowed_overlap: # check vertical overlap y0s = y_coords(links[ref_key]) y1s = y_coords(links[key]) v1 = np.nanmin(y0s) - np.nanmin(y1s) v2 = np.nanmax(y0s) - np.nanmax(y1s) v3 = np.nanmin(y0s) - np.nanmax(y1s) v4 = np.nanmax(y0s) - np.nanmin(y1s) if not (v1 * v2 > 0 and v3 * v4 > 0): overlaps.add(data_keys.pop(data_keys.index(key))) overlapped_group.append(list(overlaps)) # renew horizontal offset new_links = {} for overlaps in overlapped_group: if len(overlaps) > 1: xpos_mean = np.mean([links[key].xvals[0] for key in overlaps]) # sort link key by y position sorted_keys = sorted(overlaps, key=lambda x: np.nanmax(y_coords(links[x]))) x0 = xpos_mean - 0.5 * allowed_overlap * (len(overlaps) - 1) for ind, key in enumerate(sorted_keys): data = links[key] data.xvals = [x0 + ind * allowed_overlap] new_links[key] = data else: key = overlaps[0] new_links[key] = links[key] return {key: new_links[key] for key in links.keys()}
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Drawing objects for timeline drawer. Drawing objects play two important roles: - Allowing unittests of visualization module. Usually it is hard for image files to be tested. - Removing program parser from each plotter interface. We can easily add new plotter. This module is based on the structure of matplotlib as it is the primary plotter of the timeline drawer. However this interface is agnostic to the actual plotter. Design concept ~~~~~~~~~~~~~~ When we think about dynamically updating drawings, it will be most efficient to update only the changed properties of drawings rather than regenerating entirely from scratch. Thus the core :py:class:`~qiskit.visualization.timeline.core.DrawerCanvas` generates all possible drawings in the beginning and then the canvas instance manages visibility of each drawing according to the end-user request. Data key ~~~~~~~~ In the abstract class ``ElementaryData`` common attributes to represent a drawing are specified. In addition, drawings have the `data_key` property that returns an unique hash of the object for comparison. This key is generated from a data type, the location of the drawing in the canvas, and associated qubit or classical bit objects. See py:mod:`qiskit.visualization.timeline.types` for detail on the data type. If a data key cannot distinguish two independent objects, you need to add a new data type. The data key may be used in the plotter interface to identify the object. Drawing objects ~~~~~~~~~~~~~~~ To support not only `matplotlib` but also multiple plotters, those drawings should be universal and designed without strong dependency on modules in `matplotlib`. This means drawings that represent primitive geometries are preferred. It should be noted that there will be no unittest for each plotter API, which takes drawings and outputs image data, we should avoid adding a complicated geometry that has a context of the scheduled circuit program. For example, a two qubit scheduled gate may be drawn by two rectangles that represent time occupation of two quantum registers during the gate along with a line connecting these rectangles to identify the pair. This shape can be represented with two box-type objects with one line-type object instead of defining a new object dedicated to the two qubit gate. As many plotters don't support an API that visualizes such a linked-box shape, if we introduce such complex drawings and write a custom wrapper function on top of the existing API, it could be difficult to prevent bugs with the CI tools due to lack of the effective unittest for image data. Link between gates ~~~~~~~~~~~~~~~~~~ The ``GateLinkData`` is the special subclass of drawing that represents a link between bits. Usually objects are associated to the specific bit, but ``GateLinkData`` can be associated with multiple bits to illustrate relationship between quantum or classical bits during a gate operation. """ from abc import ABC from enum import Enum from typing import Optional, Dict, Any, List, Union import numpy as np from qiskit import circuit from qiskit.visualization.timeline import types from qiskit.visualization.exceptions import VisualizationError class ElementaryData(ABC): """Base class of the scheduled circuit visualization object. Note that drawings are mutable. """ __hash__ = None def __init__( self, data_type: Union[str, Enum], xvals: Union[np.ndarray, List[types.Coordinate]], yvals: Union[np.ndarray, List[types.Coordinate]], bits: Optional[Union[types.Bits, List[types.Bits]]] = None, meta: Optional[Dict[str, Any]] = None, styles: Optional[Dict[str, Any]] = None, ): """Create new drawing. Args: data_type: String representation of this drawing. xvals: Series of horizontal coordinate that the object is drawn. yvals: Series of vertical coordinate that the object is drawn. bits: Qubit or Clbit object bound to this drawing. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ if bits and isinstance(bits, (circuit.Qubit, circuit.Clbit)): bits = [bits] if isinstance(data_type, Enum): data_type = data_type.value self.data_type = str(data_type) self.xvals = xvals self.yvals = yvals self.bits = bits self.meta = meta self.styles = styles @property def data_key(self): """Return unique hash of this object.""" return str( hash( ( self.__class__.__name__, self.data_type, tuple(self.bits), tuple(self.xvals), tuple(self.yvals), ) ) ) def __repr__(self): return f"{self.__class__.__name__}(type={self.data_type}, key={self.data_key})" def __eq__(self, other): return isinstance(other, self.__class__) and self.data_key == other.data_key class LineData(ElementaryData): """Drawing object that represents line shape.""" def __init__( self, data_type: Union[str, Enum], xvals: Union[np.ndarray, List[types.Coordinate]], yvals: Union[np.ndarray, List[types.Coordinate]], bit: types.Bits, meta: Dict[str, Any] = None, styles: Dict[str, Any] = None, ): """Create new line. Args: data_type: String representation of this drawing. xvals: Series of horizontal coordinate that the object is drawn. yvals: Series of vertical coordinate that the object is drawn. bit: Bit associated to this object. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ super().__init__( data_type=data_type, xvals=xvals, yvals=yvals, bits=bit, meta=meta, styles=styles ) class BoxData(ElementaryData): """Drawing object that represents box shape.""" def __init__( self, data_type: Union[str, Enum], xvals: Union[np.ndarray, List[types.Coordinate]], yvals: Union[np.ndarray, List[types.Coordinate]], bit: types.Bits, meta: Dict[str, Any] = None, styles: Dict[str, Any] = None, ): """Create new box. Args: data_type: String representation of this drawing. xvals: Left and right coordinate that the object is drawn. yvals: Top and bottom coordinate that the object is drawn. bit: Bit associated to this object. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. Raises: VisualizationError: When number of data points are not equals to 2. """ if len(xvals) != 2 or len(yvals) != 2: raise VisualizationError("Length of data points are not equals to 2.") super().__init__( data_type=data_type, xvals=xvals, yvals=yvals, bits=bit, meta=meta, styles=styles ) class TextData(ElementaryData): """Drawing object that represents a text on canvas.""" def __init__( self, data_type: Union[str, Enum], xval: types.Coordinate, yval: types.Coordinate, bit: types.Bits, text: str, latex: Optional[str] = None, meta: Dict[str, Any] = None, styles: Dict[str, Any] = None, ): """Create new text. Args: data_type: String representation of this drawing. xval: Horizontal coordinate that the object is drawn. yval: Vertical coordinate that the object is drawn. bit: Bit associated to this object. text: A string to draw on the canvas. latex: If set this string is used instead of `text`. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ self.text = text self.latex = latex super().__init__( data_type=data_type, xvals=[xval], yvals=[yval], bits=bit, meta=meta, styles=styles ) class GateLinkData(ElementaryData): """A special drawing data type that represents bit link of multi-bit gates. Note this object takes multiple bits and dedicates them to the bit link. This may appear as a line on the canvas. """ def __init__( self, xval: types.Coordinate, bits: List[types.Bits], styles: Dict[str, Any] = None ): """Create new bit link. Args: xval: Horizontal coordinate that the object is drawn. bits: Bit associated to this object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ super().__init__( data_type=types.LineType.GATE_LINK, xvals=[xval], yvals=[0], bits=bits, meta=None, styles=styles, )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ A collection of functions that decide the layout of an output image. See :py:mod:`~qiskit.visualization.timeline.types` for more info on the required data. There are 2 types of layout functions in this module. 1. layout.bit_arrange In this stylesheet entry the input data is a list of `types.Bits` and returns a sorted list of `types.Bits`. The function signature of the layout is restricted to: ```python def my_layout(bits: List[types.Bits]) -> List[types.Bits]: # your code here: sort input bits and return list of bits ``` 2. layout.time_axis_map In this stylesheet entry the input data is `Tuple[int, int]` that represents horizontal axis limit of the output image. The layout function returns `types.HorizontalAxis` data which is consumed by the plotter API to make horizontal axis. The function signature of the layout is restricted to: ```python def my_layout(time_window: Tuple[int, int]) -> types.HorizontalAxis: # your code here: create and return axis config ``` Arbitrary layout function satisfying the above format can be accepted. """ import warnings from typing import List, Tuple import numpy as np from qiskit import circuit from qiskit.visualization.exceptions import VisualizationError from qiskit.visualization.timeline import types def qreg_creg_ascending(bits: List[types.Bits]) -> List[types.Bits]: """Sort bits by ascending order. Bit order becomes Q0, Q1, ..., Cl0, Cl1, ... Args: bits: List of bits to sort. Returns: Sorted bits. """ qregs = [] cregs = [] for bit in bits: if isinstance(bit, circuit.Qubit): qregs.append(bit) elif isinstance(bit, circuit.Clbit): cregs.append(bit) else: raise VisualizationError(f"Unknown bit {bit} is provided.") with warnings.catch_warnings(): warnings.simplefilter("ignore") qregs = sorted(qregs, key=lambda x: x.index, reverse=False) cregs = sorted(cregs, key=lambda x: x.index, reverse=False) return qregs + cregs def qreg_creg_descending(bits: List[types.Bits]) -> List[types.Bits]: """Sort bits by descending order. Bit order becomes Q_N, Q_N-1, ..., Cl_N, Cl_N-1, ... Args: bits: List of bits to sort. Returns: Sorted bits. """ qregs = [] cregs = [] for bit in bits: if isinstance(bit, circuit.Qubit): qregs.append(bit) elif isinstance(bit, circuit.Clbit): cregs.append(bit) else: raise VisualizationError(f"Unknown bit {bit} is provided.") qregs = sorted(qregs, key=lambda x: x.index, reverse=True) cregs = sorted(cregs, key=lambda x: x.index, reverse=True) return qregs + cregs def time_map_in_dt(time_window: Tuple[int, int]) -> types.HorizontalAxis: """Layout function for the horizontal axis formatting. Generate equispaced 6 horizontal axis ticks. Args: time_window: Left and right edge of this graph. Returns: Axis formatter object. """ # shift time axis t0, t1 = time_window # axis label axis_loc = np.linspace(max(t0, 0), t1, 6) axis_label = axis_loc.copy() # consider time resolution label = "System cycle time (dt)" formatted_label = [f"{val:.0f}" for val in axis_label] return types.HorizontalAxis( window=(t0, t1), axis_map=dict(zip(axis_loc, formatted_label)), label=label )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Special data types. """ from enum import Enum from typing import NamedTuple, List, Union, NewType, Tuple, Dict from qiskit import circuit ScheduledGate = NamedTuple( "ScheduledGate", [ ("t0", int), ("operand", circuit.Gate), ("duration", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int), ], ) ScheduledGate.__doc__ = "A gate instruction with embedded time." ScheduledGate.t0.__doc__ = "Time when the instruction is issued." ScheduledGate.operand.__doc__ = "Gate object associated with the gate." ScheduledGate.duration.__doc__ = "Time duration of the instruction." ScheduledGate.bits.__doc__ = "List of bit associated with the gate." ScheduledGate.bit_position.__doc__ = "Position of bit associated with this drawing source." GateLink = NamedTuple( "GateLink", [("t0", int), ("opname", str), ("bits", List[Union[circuit.Qubit, circuit.Clbit]])] ) GateLink.__doc__ = "Dedicated object to represent a relationship between instructions." GateLink.t0.__doc__ = "A position where the link is placed." GateLink.opname.__doc__ = "Name of gate associated with this link." GateLink.bits.__doc__ = "List of bit associated with the instruction." Barrier = NamedTuple( "Barrier", [("t0", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int)], ) Barrier.__doc__ = "Dedicated object to represent a barrier instruction." Barrier.t0.__doc__ = "A position where the barrier is placed." Barrier.bits.__doc__ = "List of bit associated with the instruction." Barrier.bit_position.__doc__ = "Position of bit associated with this drawing source." HorizontalAxis = NamedTuple( "HorizontalAxis", [("window", Tuple[int, int]), ("axis_map", Dict[int, int]), ("label", str)] ) HorizontalAxis.__doc__ = "Data to represent configuration of horizontal axis." HorizontalAxis.window.__doc__ = "Left and right edge of graph." HorizontalAxis.axis_map.__doc__ = "Mapping of apparent coordinate system and actual location." HorizontalAxis.label.__doc__ = "Label of horizontal axis." class BoxType(str, Enum): """Box type. SCHED_GATE: Box that represents occupation time by gate. DELAY: Box associated with delay. TIMELINE: Box that represents time slot of a bit. """ SCHED_GATE = "Box.ScheduledGate" DELAY = "Box.Delay" TIMELINE = "Box.Timeline" class LineType(str, Enum): """Line type. BARRIER: Line that represents barrier instruction. GATE_LINK: Line that represents a link among gates. """ BARRIER = "Line.Barrier" GATE_LINK = "Line.GateLink" class SymbolType(str, Enum): """Symbol type. FRAME: Symbol that represents zero time frame change (Rz) instruction. """ FRAME = "Symbol.Frame" class LabelType(str, Enum): """Label type. GATE_NAME: Label that represents name of gate. DELAY: Label associated with delay. GATE_PARAM: Label that represents parameter of gate. BIT_NAME: Label that represents name of bit. """ GATE_NAME = "Label.Gate.Name" DELAY = "Label.Delay" GATE_PARAM = "Label.Gate.Param" BIT_NAME = "Label.Bit.Name" class AbstractCoordinate(Enum): """Abstract coordinate that the exact value depends on the user preference. RIGHT: The horizontal coordinate at t0 shifted by the left margin. LEFT: The horizontal coordinate at tf shifted by the right margin. TOP: The vertical coordinate at the top of the canvas. BOTTOM: The vertical coordinate at the bottom of the canvas. """ RIGHT = "RIGHT" LEFT = "LEFT" TOP = "TOP" BOTTOM = "BOTTOM" class Plotter(str, Enum): """Name of timeline plotter APIs. MPL: Matplotlib plotter interface. Show timeline in 2D canvas. """ MPL = "mpl" # convenient type to represent union of drawing data DataTypes = NewType("DataType", Union[BoxType, LabelType, LineType, SymbolType]) # convenient type to represent union of values to represent a coordinate Coordinate = NewType("Coordinate", Union[float, AbstractCoordinate]) # Valid bit objects Bits = NewType("Bits", Union[circuit.Qubit, circuit.Clbit])
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-docstring,invalid-name,no-member # pylint: disable=attribute-defined-outside-init import itertools from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit import Parameter def build_circuit(width, gates): qr = QuantumRegister(width) qc = QuantumCircuit(qr) while len(qc) < gates: for k in range(width): qc.h(qr[k]) for k in range(width - 1): qc.cx(qr[k], qr[k + 1]) return qc class CircuitConstructionBench: params = ([1, 2, 5, 8, 14, 20], [8, 128, 2048, 8192, 32768, 131072]) param_names = ["width", "gates"] timeout = 600 def setup(self, width, gates): self.empty_circuit = build_circuit(width, 0) self.sample_circuit = build_circuit(width, gates) def time_circuit_construction(self, width, gates): build_circuit(width, gates) def time_circuit_extend(self, _, __): self.empty_circuit.extend(self.sample_circuit) def time_circuit_copy(self, _, __): self.sample_circuit.copy() def build_parameterized_circuit(width, gates, param_count): params = [Parameter("param-%s" % x) for x in range(param_count)] param_iter = itertools.cycle(params) qr = QuantumRegister(width) qc = QuantumCircuit(qr) while len(qc) < gates: for k in range(width): param = next(param_iter) qc.u2(0, param, qr[k]) for k in range(width - 1): param = next(param_iter) qc.crx(param, qr[k], qr[k + 1]) return qc, params class ParameterizedCircuitConstructionBench: params = ([20], [8, 128, 2048, 8192, 32768, 131072], [8, 128, 2048, 8192, 32768, 131072]) param_names = ["width", "gates", "number of params"] timeout = 600 def setup(self, _, gates, params): if params > gates: raise NotImplementedError def time_build_parameterized_circuit(self, width, gates, params): build_parameterized_circuit(width, gates, params) class ParameterizedCircuitBindBench: params = ([20], [8, 128, 2048, 8192, 32768, 131072], [8, 128, 2048, 8192, 32768, 131072]) param_names = ["width", "gates", "number of params"] timeout = 600 def setup(self, width, gates, params): if params > gates: raise NotImplementedError self.circuit, self.params = build_parameterized_circuit(width, gates, params) def time_bind_params(self, _, __, ___): self.circuit.bind_parameters({x: 3.14 for x in self.params})
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object from qiskit import converters from qiskit import qasm from .utils import random_circuit class ConverterBenchmarks: params = ([1, 2, 5, 8, 14, 20, 32, 53], [8, 128, 2048, 8192]) param_names = ["n_qubits", "depth"] timeout = 600 def setup(self, n_qubits, depth): seed = 42 # NOTE: Remove the benchmarks larger than 20x2048 and 14x8192, this is # a tradeoff for speed of benchmarking, creating circuits this size # takes more time than is worth it for benchmarks that take a couple # seconds if n_qubits >= 20: if depth >= 2048: raise NotImplementedError elif n_qubits == 14: if depth > 2048: raise NotImplementedError self.qc = random_circuit(n_qubits, depth, measure=True, conditional=True, seed=seed) self.dag = converters.circuit_to_dag(self.qc) self.qasm = qasm.Qasm(data=self.qc.qasm()).parse() def time_circuit_to_dag(self, *_): converters.circuit_to_dag(self.qc) def time_circuit_to_instruction(self, *_): converters.circuit_to_instruction(self.qc) def time_dag_to_circuit(self, *_): converters.dag_to_circuit(self.dag) def time_ast_to_circuit(self, *_): converters.ast_to_dag(self.qasm)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object """Module for estimating import times.""" from sys import executable from subprocess import call class QiskitImport: def time_qiskit_import(self): call((executable, "-c", "import qiskit"))
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-docstring,invalid-name,no-member # pylint: disable=attribute-defined-outside-init # pylint: disable=unused-argument from qiskit import QuantumRegister, QuantumCircuit from qiskit.compiler import transpile from qiskit.quantum_info.random import random_unitary class IsometryTranspileBench: params = ([0, 1, 2, 3], [3, 4, 5, 6]) param_names = ["number of input qubits", "number of output qubits"] def setup(self, m, n): q = QuantumRegister(n) qc = QuantumCircuit(q) if not hasattr(qc, "iso"): raise NotImplementedError iso = random_unitary(2**n, seed=0).data[:, 0 : 2**m] if len(iso.shape) == 1: iso = iso.reshape((len(iso), 1)) qc.iso(iso, q[:m], q[m:]) self.circuit = qc def track_cnot_counts_after_mapping_to_ibmq_16_melbourne(self, *unused): coupling = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit = transpile( self.circuit, basis_gates=["u1", "u3", "u2", "cx"], coupling_map=coupling, seed_transpiler=0, ) counts = circuit.count_ops() cnot_count = counts.get("cx", 0) return cnot_count
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- 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-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object import os from qiskit import QuantumCircuit from qiskit.compiler import transpile class QUEKOTranspilerBench: params = ([0, 1, 2, 3], [None, "sabre"]) param_names = ["optimization level", "routing/layout method"] timeout = 600 # pylint: disable=unused-argument def setup(self, optimization_level, routing_method): self.rochester_coupling_map = [ [0, 5], [0, 1], [1, 2], [1, 0], [2, 3], [2, 1], [3, 4], [3, 2], [4, 6], [4, 3], [5, 9], [5, 0], [6, 13], [6, 4], [7, 16], [7, 8], [8, 9], [8, 7], [9, 10], [9, 8], [9, 5], [10, 11], [10, 9], [11, 17], [11, 12], [11, 10], [12, 13], [12, 11], [13, 14], [13, 12], [13, 6], [14, 15], [14, 13], [15, 18], [15, 14], [16, 19], [16, 7], [17, 23], [17, 11], [18, 27], [18, 15], [19, 20], [19, 16], [20, 21], [20, 19], [21, 28], [21, 22], [21, 20], [22, 23], [22, 21], [23, 24], [23, 22], [23, 17], [24, 25], [24, 23], [25, 29], [25, 26], [25, 24], [26, 27], [26, 25], [27, 26], [27, 18], [28, 32], [28, 21], [29, 36], [29, 25], [30, 39], [30, 31], [31, 32], [31, 30], [32, 33], [32, 31], [32, 28], [33, 34], [33, 32], [34, 40], [34, 35], [34, 33], [35, 36], [35, 34], [36, 37], [36, 35], [36, 29], [37, 38], [37, 36], [38, 41], [38, 37], [39, 42], [39, 30], [40, 46], [40, 34], [41, 50], [41, 38], [42, 43], [42, 39], [43, 44], [43, 42], [44, 51], [44, 45], [44, 43], [45, 46], [45, 44], [46, 47], [46, 45], [46, 40], [47, 48], [47, 46], [48, 52], [48, 49], [48, 47], [49, 50], [49, 48], [50, 49], [50, 41], [51, 44], [52, 48], ] self.tokyo_coupling_map = [ [0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [1, 6], [1, 7], [2, 6], [2, 7], [3, 8], [3, 9], [4, 8], [4, 9], [5, 6], [6, 7], [7, 8], [8, 9], [5, 10], [5, 11], [6, 10], [6, 11], [7, 12], [7, 13], [8, 12], [8, 13], [9, 14], [10, 11], [11, 12], [12, 13], [13, 14], [10, 15], [11, 16], [11, 17], [12, 16], [12, 17], [13, 18], [13, 19], [14, 18], [14, 19], [15, 16], [16, 17], [17, 18], [18, 19], ] self.sycamore_coupling_map = [ [0, 6], [1, 6], [1, 7], [2, 7], [2, 8], [3, 8], [3, 9], [4, 9], [4, 10], [5, 10], [5, 11], [6, 12], [6, 13], [7, 13], [7, 14], [8, 14], [8, 15], [9, 15], [9, 16], [10, 16], [10, 17], [11, 17], [12, 18], [13, 18], [13, 19], [14, 19], [14, 20], [15, 20], [15, 21], [16, 21], [16, 22], [17, 22], [17, 23], [18, 24], [18, 25], [19, 25], [19, 26], [20, 26], [20, 27], [21, 27], [21, 28], [22, 28], [22, 29], [23, 29], [24, 30], [25, 30], [25, 31], [26, 31], [26, 32], [27, 32], [27, 33], [28, 33], [28, 34], [29, 34], [29, 35], [30, 36], [30, 37], [31, 37], [31, 38], [32, 38], [32, 39], [33, 39], [33, 40], [34, 40], [34, 41], [35, 41], [36, 42], [37, 42], [37, 43], [38, 43], [38, 44], [39, 44], [39, 45], [40, 45], [40, 46], [41, 46], [41, 47], [42, 48], [42, 49], [43, 49], [43, 50], [44, 50], [44, 51], [45, 51], [45, 52], [46, 52], [46, 53], [47, 53], ] self.basis_gates = ["id", "rz", "sx", "x", "cx"] self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm")) self.bigd = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "20QBT_45CYC_.0D1_.1D2_3.qasm") ) self.bss = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "53QBT_100CYC_QSE_3.qasm") ) self.bntf = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "54QBT_25CYC_QSE_3.qasm") ) def track_depth_bntf_optimal_depth_25(self, optimization_level, routing_method): return transpile( self.bntf, coupling_map=self.sycamore_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def track_depth_bss_optimal_depth_100(self, optimization_level, routing_method): return transpile( self.bss, coupling_map=self.rochester_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def track_depth_bigd_optimal_depth_45(self, optimization_level, routing_method): return transpile( self.bigd, coupling_map=self.tokyo_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def time_transpile_bntf(self, optimization_level, routing_method): transpile( self.bntf, coupling_map=self.sycamore_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def time_transpile_bss(self, optimization_level, routing_method): transpile( self.bss, coupling_map=self.rochester_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def time_transpile_bigd(self, optimization_level, routing_method): transpile( self.bigd, coupling_map=self.tokyo_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-docstring,invalid-name,no-member # pylint: disable=attribute-defined-outside-init import copy from qiskit.quantum_info.synthesis import OneQubitEulerDecomposer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister try: from qiskit.compiler import transpile TRANSPILER_SEED_KEYWORD = "seed_transpiler" except ImportError: from qiskit.transpiler import transpile TRANSPILER_SEED_KEYWORD = "seed_mapper" try: from qiskit.quantum_info.random import random_unitary HAS_RANDOM_UNITARY = True except ImportError: from qiskit.tools.qi.qi import random_unitary_matrix HAS_RANDOM_UNITARY = False # Make a random circuit on a ring def make_circuit_ring(nq, depth, seed): assert int(nq / 2) == nq / 2 # for now size of ring must be even # Create a Quantum Register q = QuantumRegister(nq) # Create a Classical Register c = ClassicalRegister(nq) # Create a Quantum Circuit qc = QuantumCircuit(q, c) offset = 1 decomposer = OneQubitEulerDecomposer() # initial round of random single-qubit unitaries for i in range(nq): qc.h(q[i]) for j in range(depth): for i in range(int(nq / 2)): # round of CNOTS k = i * 2 + offset + j % 2 # j%2 makes alternating rounds overlap qc.cx(q[k % nq], q[(k + 1) % nq]) for i in range(nq): # round of single-qubit unitaries if HAS_RANDOM_UNITARY: u = random_unitary(2, seed).data else: u = random_unitary_matrix(2) # pylint: disable=used-before-assignment # noqa angles = decomposer.angles(u) qc.u3(angles[0], angles[1], angles[2], q[i]) # insert the final measurements qcm = copy.deepcopy(qc) for i in range(nq): qcm.measure(q[i], c[i]) return [qc, qcm, nq] class BenchRandomCircuitHex: params = [2 * i for i in range(2, 8)] param_names = ["n_qubits"] version = 3 def setup(self, n): depth = 2 * n self.seed = 0 self.circuit = make_circuit_ring(n, depth, self.seed)[0] def time_ibmq_backend_transpile(self, _): # Run with ibmq_16_melbourne configuration coupling_map = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] transpile( self.circuit, basis_gates=["u1", "u2", "u3", "cx", "id"], coupling_map=coupling_map, **{TRANSPILER_SEED_KEYWORD: self.seed}, ) def track_depth_ibmq_backend_transpile(self, _): # Run with ibmq_16_melbourne configuration coupling_map = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] return transpile( self.circuit, basis_gates=["u1", "u2", "u3", "cx", "id"], coupling_map=coupling_map, **{TRANSPILER_SEED_KEYWORD: self.seed}, ).depth()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object from qiskit import transpile from qiskit.transpiler import CouplingMap from .utils import build_ripple_adder_circuit class RippleAdderConstruction: params = ([10, 50, 100, 200, 500],) param_names = ["size"] version = 1 timeout = 600 def time_build_ripple_adder(self, size): build_ripple_adder_circuit(size) class RippleAdderTranspile: params = ([10, 20], [0, 1, 2, 3]) param_names = ["size", "level"] version = 1 timeout = 600 def setup(self, size, _): edge_len = int((2 * size + 2) ** 0.5) + 1 self.coupling_map = CouplingMap.from_grid(edge_len, edge_len) self.circuit = build_ripple_adder_circuit(size) def time_transpile_square_grid_ripple_adder(self, _, level): transpile( self.circuit, coupling_map=self.coupling_map, basis_gates=["u1", "u2", "u3", "cx", "id"], optimization_level=level, seed_transpiler=20220125, ) def track_depth_transpile_square_grid_ripple_adder(self, _, level): return transpile( self.circuit, coupling_map=self.coupling_map, basis_gates=["u1", "u2", "u3", "cx", "id"], optimization_level=level, seed_transpiler=20220125, ).depth()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name,missing-docstring # pylint: disable=attribute-defined-outside-init from qiskit import transpile from qiskit.circuit.library.standard_gates import XGate from qiskit.transpiler import CouplingMap from qiskit.transpiler import InstructionDurations from qiskit.transpiler.passes import ( TimeUnitConversion, ASAPSchedule, ALAPSchedule, DynamicalDecoupling, ) from qiskit.converters import circuit_to_dag from .utils import random_circuit class SchedulingPassBenchmarks: params = ([5, 10, 20], [500, 1000]) param_names = ["n_qubits", "depth"] timeout = 300 def setup(self, n_qubits, depth): seed = 42 self.circuit = random_circuit( n_qubits, depth, measure=True, conditional=True, reset=True, seed=seed, max_operands=2 ) self.basis_gates = ["rz", "sx", "x", "cx", "id", "reset"] self.cmap = [ [0, 1], [1, 0], [1, 2], [1, 6], [2, 1], [2, 3], [3, 2], [3, 4], [3, 8], [4, 3], [5, 6], [5, 10], [6, 1], [6, 5], [6, 7], [7, 6], [7, 8], [7, 12], [8, 3], [8, 7], [8, 9], [9, 8], [9, 14], [10, 5], [10, 11], [11, 10], [11, 12], [11, 16], [12, 7], [12, 11], [12, 13], [13, 12], [13, 14], [13, 18], [14, 9], [14, 13], [15, 16], [16, 11], [16, 15], [16, 17], [17, 16], [17, 18], [18, 13], [18, 17], [18, 19], [19, 18], ] self.coupling_map = CouplingMap(self.cmap) self.transpiled_circuit = transpile( self.circuit, basis_gates=self.basis_gates, coupling_map=self.coupling_map, optimization_level=1, ) self.dag = circuit_to_dag(self.transpiled_circuit) self.durations = InstructionDurations( [ ("rz", None, 0), ("id", None, 160), ("sx", None, 160), ("x", None, 160), ("cx", None, 800), ("measure", None, 3200), ("reset", None, 3600), ], dt=1e-9, ) self.timed_dag = TimeUnitConversion(self.durations).run(self.dag) _pass = ALAPSchedule(self.durations) _pass.property_set["time_unit"] = "dt" self.scheduled_dag = _pass.run(self.timed_dag) def time_time_unit_conversion_pass(self, _, __): TimeUnitConversion(self.durations).run(self.dag) def time_alap_schedule_pass(self, _, __): _pass = ALAPSchedule(self.durations) _pass.property_set["time_unit"] = "dt" _pass.run(self.timed_dag) def time_asap_schedule_pass(self, _, __): _pass = ASAPSchedule(self.durations) _pass.property_set["time_unit"] = "dt" _pass.run(self.timed_dag) def time_dynamical_decoupling_pass(self, _, __): DynamicalDecoupling(self.durations, dd_sequence=[XGate(), XGate()]).run(self.scheduled_dag)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-docstring,invalid-name,no-member,broad-except # pylint: disable=no-else-return, attribute-defined-outside-init # pylint: disable=import-error from qiskit_experiments.library import StateTomography import qiskit class StateTomographyBench: params = [2, 3, 4, 5] param_names = ["n_qubits"] version = "0.3.0" timeout = 120.0 def setup(self, _): self.qasm_backend = qiskit.BasicAer.get_backend("qasm_simulator") def time_state_tomography_bell(self, n_qubits): meas_qubits = [n_qubits - 2, n_qubits - 1] qr_full = qiskit.QuantumRegister(n_qubits) bell = qiskit.QuantumCircuit(qr_full) bell.h(qr_full[meas_qubits[0]]) bell.cx(qr_full[meas_qubits[0]], qr_full[meas_qubits[1]]) qst_exp = StateTomography(bell, measurement_qubits=meas_qubits) expdata = qst_exp.run(self.qasm_backend, shots=5000).block_for_results() expdata.analysis_results("state") expdata.analysis_results("state_fidelity") def time_state_tomography_cat(self, n_qubits): qr = qiskit.QuantumRegister(n_qubits, "qr") circ = qiskit.QuantumCircuit(qr, name="cat") circ.h(qr[0]) for i in range(1, n_qubits): circ.cx(qr[0], qr[i]) qst_exp = StateTomography(circ) expdata = qst_exp.run(self.qasm_backend, shots=5000).block_for_results() expdata.analysis_results("state") expdata.analysis_results("state_fidelity")
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-docstring,invalid-name,no-member # pylint: disable=attribute-defined-outside-init import os import qiskit class TranspilerBenchSuite: def _build_cx_circuit(self): cx_register = qiskit.QuantumRegister(2) cx_circuit = qiskit.QuantumCircuit(cx_register) cx_circuit.h(cx_register[0]) cx_circuit.h(cx_register[0]) cx_circuit.cx(cx_register[0], cx_register[1]) cx_circuit.cx(cx_register[0], cx_register[1]) cx_circuit.cx(cx_register[0], cx_register[1]) cx_circuit.cx(cx_register[0], cx_register[1]) return cx_circuit def _build_single_gate_circuit(self): single_register = qiskit.QuantumRegister(1) single_gate_circuit = qiskit.QuantumCircuit(single_register) single_gate_circuit.h(single_register[0]) return single_gate_circuit def setup(self): self.single_gate_circuit = self._build_single_gate_circuit() self.cx_circuit = self._build_cx_circuit() self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm")) large_qasm_path = os.path.join(self.qasm_path, "test_eoh_qasm.qasm") self.large_qasm = qiskit.QuantumCircuit.from_qasm_file(large_qasm_path) self.coupling_map = [ [0, 1], [1, 0], [1, 2], [1, 4], [2, 1], [2, 3], [3, 2], [3, 5], [4, 1], [4, 7], [5, 3], [5, 8], [6, 7], [7, 4], [7, 6], [7, 10], [8, 5], [8, 9], [8, 11], [9, 8], [10, 7], [10, 12], [11, 8], [11, 14], [12, 10], [12, 13], [12, 15], [13, 12], [13, 14], [14, 11], [14, 13], [14, 16], [15, 12], [15, 18], [16, 14], [16, 19], [17, 18], [18, 15], [18, 17], [18, 21], [19, 16], [19, 20], [19, 22], [20, 19], [21, 18], [21, 23], [22, 19], [22, 25], [23, 21], [23, 24], [24, 23], [24, 25], [25, 22], [25, 24], [25, 26], [26, 25], ] self.basis = ["id", "rz", "sx", "x", "cx", "reset"] def time_single_gate_compile(self): circ = qiskit.compiler.transpile( self.single_gate_circuit, coupling_map=self.coupling_map, basis_gates=self.basis, seed_transpiler=20220125, ) qiskit.compiler.assemble(circ) def time_cx_compile(self): circ = qiskit.compiler.transpile( self.cx_circuit, coupling_map=self.coupling_map, basis_gates=self.basis, seed_transpiler=20220125, ) qiskit.compiler.assemble(circ) def time_compile_from_large_qasm(self): circ = qiskit.compiler.transpile( self.large_qasm, coupling_map=self.coupling_map, basis_gates=self.basis, seed_transpiler=20220125, ) qiskit.compiler.assemble(circ)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object import os from qiskit.compiler import transpile from qiskit import QuantumCircuit from qiskit.transpiler import InstructionDurations from qiskit.providers.fake_provider import FakeMelbourne from .utils import build_qv_model_circuit class TranspilerLevelBenchmarks: params = [0, 1, 2, 3] param_names = ["transpiler optimization level"] timeout = 600 def setup(self, _): self.rochester_coupling_map = [ [0, 5], [0, 1], [1, 2], [1, 0], [2, 3], [2, 1], [3, 4], [3, 2], [4, 6], [4, 3], [5, 9], [5, 0], [6, 13], [6, 4], [7, 16], [7, 8], [8, 9], [8, 7], [9, 10], [9, 8], [9, 5], [10, 11], [10, 9], [11, 17], [11, 12], [11, 10], [12, 13], [12, 11], [13, 14], [13, 12], [13, 6], [14, 15], [14, 13], [15, 18], [15, 14], [16, 19], [16, 7], [17, 23], [17, 11], [18, 27], [18, 15], [19, 20], [19, 16], [20, 21], [20, 19], [21, 28], [21, 22], [21, 20], [22, 23], [22, 21], [23, 24], [23, 22], [23, 17], [24, 25], [24, 23], [25, 29], [25, 26], [25, 24], [26, 27], [26, 25], [27, 26], [27, 18], [28, 32], [28, 21], [29, 36], [29, 25], [30, 39], [30, 31], [31, 32], [31, 30], [32, 33], [32, 31], [32, 28], [33, 34], [33, 32], [34, 40], [34, 35], [34, 33], [35, 36], [35, 34], [36, 37], [36, 35], [36, 29], [37, 38], [37, 36], [38, 41], [38, 37], [39, 42], [39, 30], [40, 46], [40, 34], [41, 50], [41, 38], [42, 43], [42, 39], [43, 44], [43, 42], [44, 51], [44, 45], [44, 43], [45, 46], [45, 44], [46, 47], [46, 45], [46, 40], [47, 48], [47, 46], [48, 52], [48, 49], [48, 47], [49, 50], [49, 48], [50, 49], [50, 41], [51, 44], [52, 48], ] self.basis_gates = ["u1", "u2", "u3", "cx", "id"] self.qv_50_x_20 = build_qv_model_circuit(50, 20, 0) self.qv_14_x_14 = build_qv_model_circuit(14, 14, 0) self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm")) large_qasm_path = os.path.join(self.qasm_path, "test_eoh_qasm.qasm") self.large_qasm = QuantumCircuit.from_qasm_file(large_qasm_path) self.melbourne = FakeMelbourne() self.durations = InstructionDurations( [ ("u1", None, 0), ("id", None, 160), ("u2", None, 160), ("u3", None, 320), ("cx", None, 800), ("measure", None, 3200), ], dt=1e-9, ) def time_quantum_volume_transpile_50_x_20(self, transpiler_level): transpile( self.qv_50_x_20, basis_gates=self.basis_gates, coupling_map=self.rochester_coupling_map, seed_transpiler=0, optimization_level=transpiler_level, ) def track_depth_quantum_volume_transpile_50_x_20(self, transpiler_level): return transpile( self.qv_50_x_20, basis_gates=self.basis_gates, coupling_map=self.rochester_coupling_map, seed_transpiler=0, optimization_level=transpiler_level, ).depth() def time_transpile_from_large_qasm(self, transpiler_level): transpile( self.large_qasm, basis_gates=self.basis_gates, coupling_map=self.rochester_coupling_map, seed_transpiler=0, optimization_level=transpiler_level, ) def track_depth_transpile_from_large_qasm(self, transpiler_level): return transpile( self.large_qasm, basis_gates=self.basis_gates, coupling_map=self.rochester_coupling_map, seed_transpiler=0, optimization_level=transpiler_level, ).depth() def time_transpile_from_large_qasm_backend_with_prop(self, transpiler_level): transpile( self.large_qasm, self.melbourne, seed_transpiler=0, optimization_level=transpiler_level ) def track_depth_transpile_from_large_qasm_backend_with_prop(self, transpiler_level): return transpile( self.large_qasm, self.melbourne, seed_transpiler=0, optimization_level=transpiler_level ).depth() def time_transpile_qv_14_x_14(self, transpiler_level): transpile( self.qv_14_x_14, self.melbourne, seed_transpiler=0, optimization_level=transpiler_level ) def track_depth_transpile_qv_14_x_14(self, transpiler_level): return transpile( self.qv_14_x_14, self.melbourne, seed_transpiler=0, optimization_level=transpiler_level ).depth() def time_schedule_qv_14_x_14(self, transpiler_level): transpile( self.qv_14_x_14, self.melbourne, seed_transpiler=0, optimization_level=transpiler_level, scheduling_method="alap", instruction_durations=self.durations, ) # limit optimization levels to reduce time time_schedule_qv_14_x_14.params = [0, 1]
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object import os from qiskit import QuantumCircuit from qiskit.compiler import transpile from qiskit.test.mock import FakeToronto class TranspilerQualitativeBench: params = ([0, 1, 2, 3], ["stochastic", "sabre"], ["dense", "noise_adaptive", "sabre"]) param_names = ["optimization level", "routing method", "layout method"] timeout = 600 # pylint: disable=unused-argument def setup(self, optimization_level, routing_method, layout_method): self.backend = FakeToronto() self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm")) self.depth_4gt10_v1_81 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "depth_4gt10-v1_81.qasm") ) self.depth_4mod5_v0_19 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "depth_4mod5-v0_19.qasm") ) self.depth_mod8_10_178 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "depth_mod8-10_178.qasm") ) self.time_cnt3_5_179 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "time_cnt3-5_179.qasm") ) self.time_cnt3_5_180 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "time_cnt3-5_180.qasm") ) self.time_qft_16 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "time_qft_16.qasm") ) def track_depth_transpile_4gt10_v1_81(self, optimization_level, routing_method, layout_method): return transpile( self.depth_4gt10_v1_81, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def track_depth_transpile_4mod5_v0_19(self, optimization_level, routing_method, layout_method): return transpile( self.depth_4mod5_v0_19, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def track_depth_transpile_mod8_10_178(self, optimization_level, routing_method, layout_method): return transpile( self.depth_mod8_10_178, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def time_transpile_time_cnt3_5_179(self, optimization_level, routing_method, layout_method): transpile( self.time_cnt3_5_179, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, ) def time_transpile_time_cnt3_5_180(self, optimization_level, routing_method, layout_method): transpile( self.time_cnt3_5_180, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, ) def time_transpile_time_qft_16(self, optimization_level, routing_method, layout_method): transpile( self.time_qft_16, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Test examples scripts.""" import os import subprocess import sys import unittest from qiskit.test import QiskitTestCase, online_test, slow_test examples_dir = os.path.abspath( os.path.join( os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "examples"), "python", ) ) ibmq_examples_dir = os.path.join(examples_dir, "ibmq") class TestPythonExamples(QiskitTestCase): """Test example scripts""" @unittest.skipIf( sys.platform == "darwin", "Multiprocess spawn fails on macOS python >=3.8 without __name__ == '__main__' guard", ) def test_all_examples(self): """Execute the example python files and pass if it returns 0.""" examples = [] if os.path.isdir(examples_dir): examples = [x for x in os.listdir(examples_dir) if x.endswith(".py")] for example in examples: with self.subTest(example=example): example_path = os.path.join(examples_dir, example) cmd = [sys.executable, example_path] with subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={**os.environ, "PYTHONIOENCODING": "utf8"}, ) as run_example: stdout, stderr = run_example.communicate() error_string = ( f"Running example {example} failed with return code" f"{run_example.returncode}\n" f"stdout:{stdout}\nstderr: {stderr}" ) self.assertEqual(run_example.returncode, 0, error_string) @unittest.skipIf( sys.platform == "darwin", "Multiprocess spawn fails on macOS python >=3.8 without __name__ == '__main__' guard", ) @online_test @slow_test def test_all_ibmq_examples(self, qe_token, qe_url): """Execute the ibmq example python files and pass if it returns 0.""" from qiskit import IBMQ IBMQ.enable_account(qe_token, qe_url) self.addCleanup(IBMQ.disable_account, token=qe_token, url=qe_url) ibmq_examples = [] if os.path.isdir(ibmq_examples_dir): ibmq_examples = [x for x in os.listdir(ibmq_examples_dir) if x.endswith(".py")] for example in ibmq_examples: with self.subTest(example=example): example_path = os.path.join(ibmq_examples_dir, example) cmd = [sys.executable, example_path] with subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={**os.environ, "PYTHONIOENCODING": "utf8"}, ) as run_example: stdout, stderr = run_example.communicate() error_string = ( f"Running example {example} failed with return code" f"{run_example.returncode}\n" f"stdout:{stdout}\nstderr: {stderr}" ) self.assertEqual(run_example.returncode, 0, error_string)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-docstring import os import configparser as cp from uuid import uuid4 from unittest import mock from qiskit import exceptions from qiskit.test import QiskitTestCase from qiskit import user_config class TestUserConfig(QiskitTestCase): def setUp(self): super().setUp() self.file_path = "test_%s.conf" % uuid4() def test_empty_file_read(self): config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({}, config.settings) def test_invalid_optimization_level(self): test_config = """ [default] transpile_optimization_level = 76 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_invalid_circuit_drawer(self): test_config = """ [default] circuit_drawer = MSPaint """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_circuit_drawer_valid(self): test_config = """ [default] circuit_drawer = latex """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"circuit_drawer": "latex"}, config.settings) def test_invalid_circuit_reverse_bits(self): test_config = """ [default] circuit_reverse_bits = Neither """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_circuit_reverse_bits_valid(self): test_config = """ [default] circuit_reverse_bits = false """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"circuit_reverse_bits": False}, config.settings) def test_optimization_level_valid(self): test_config = """ [default] transpile_optimization_level = 1 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"transpile_optimization_level": 1}, config.settings) def test_invalid_num_processes(self): test_config = """ [default] num_processes = -256 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_valid_num_processes(self): test_config = """ [default] num_processes = 31 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"num_processes": 31}, config.settings) def test_valid_parallel(self): test_config = """ [default] parallel = False """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"parallel_enabled": False}, config.settings) def test_all_options_valid(self): test_config = """ [default] circuit_drawer = latex circuit_mpl_style = default circuit_mpl_style_path = ~:~/.qiskit circuit_reverse_bits = false transpile_optimization_level = 3 suppress_packaging_warnings = true parallel = false num_processes = 15 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual( { "circuit_drawer": "latex", "circuit_mpl_style": "default", "circuit_mpl_style_path": ["~", "~/.qiskit"], "circuit_reverse_bits": False, "transpile_optimization_level": 3, "num_processes": 15, "parallel_enabled": False, }, config.settings, ) def test_set_config_all_options_valid(self): self.addCleanup(os.remove, self.file_path) user_config.set_config("circuit_drawer", "latex", file_path=self.file_path) user_config.set_config("circuit_mpl_style", "default", file_path=self.file_path) user_config.set_config("circuit_mpl_style_path", "~:~/.qiskit", file_path=self.file_path) user_config.set_config("circuit_reverse_bits", "false", file_path=self.file_path) user_config.set_config("transpile_optimization_level", "3", file_path=self.file_path) user_config.set_config("parallel", "false", file_path=self.file_path) user_config.set_config("num_processes", "15", file_path=self.file_path) config_settings = None with mock.patch.dict(os.environ, {"QISKIT_SETTINGS": self.file_path}, clear=True): config_settings = user_config.get_config() self.assertEqual( { "circuit_drawer": "latex", "circuit_mpl_style": "default", "circuit_mpl_style_path": ["~", "~/.qiskit"], "circuit_reverse_bits": False, "transpile_optimization_level": 3, "num_processes": 15, "parallel_enabled": False, }, config_settings, ) def test_set_config_multiple_sections(self): self.addCleanup(os.remove, self.file_path) user_config.set_config("circuit_drawer", "latex", file_path=self.file_path) user_config.set_config("circuit_mpl_style", "default", file_path=self.file_path) user_config.set_config("transpile_optimization_level", "3", file_path=self.file_path) user_config.set_config("circuit_drawer", "latex", section="test", file_path=self.file_path) user_config.set_config("parallel", "false", section="test", file_path=self.file_path) user_config.set_config("num_processes", "15", section="test", file_path=self.file_path) config = cp.ConfigParser() config.read(self.file_path) self.assertEqual(config.sections(), ["default", "test"]) self.assertEqual( { "circuit_drawer": "latex", "circuit_mpl_style": "default", "transpile_optimization_level": "3", }, dict(config.items("default")), )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for qiskit/version.py""" from qiskit import __qiskit_version__ from qiskit import __version__ from qiskit.test import QiskitTestCase class TestVersion(QiskitTestCase): """Tests for qiskit/version.py""" def test_qiskit_version(self): """Test qiskit-version sets the correct version for terra.""" with self.assertWarnsRegex(DeprecationWarning, "__qiskit_version__"): self.assertEqual(__version__, __qiskit_version__["qiskit-terra"])
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the quantum amplitude estimation algorithm.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import ddt, idata, data, unpack from qiskit import QuantumRegister, QuantumCircuit, BasicAer from qiskit.circuit.library import QFT, GroverOperator from qiskit.utils import QuantumInstance from qiskit_algorithms import ( AmplitudeEstimation, MaximumLikelihoodAmplitudeEstimation, IterativeAmplitudeEstimation, FasterAmplitudeEstimation, EstimationProblem, ) from qiskit.quantum_info import Operator, Statevector from qiskit.primitives import Sampler class BernoulliStateIn(QuantumCircuit): """A circuit preparing sqrt(1 - p)|0> + sqrt(p)|1>.""" def __init__(self, probability): super().__init__(1) angle = 2 * np.arcsin(np.sqrt(probability)) self.ry(angle, 0) class BernoulliGrover(QuantumCircuit): """The Grover operator corresponding to the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1, global_phase=np.pi) self.angle = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self.angle, 0) def power(self, power, matrix_power=False): if matrix_power: return super().power(power, True) powered = QuantumCircuit(1) powered.ry(power * 2 * self.angle, 0) return powered class SineIntegral(QuantumCircuit): r"""Construct the A operator to approximate the integral \int_0^1 \sin^2(x) d x with a specified number of qubits. """ def __init__(self, num_qubits): qr_state = QuantumRegister(num_qubits, "state") qr_objective = QuantumRegister(1, "obj") super().__init__(qr_state, qr_objective) # prepare 1/sqrt{2^n} sum_x |x>_n self.h(qr_state) # apply the sine/cosine term self.ry(2 * 1 / 2 / 2**num_qubits, qr_objective[0]) for i, qubit in enumerate(qr_state): self.cry(2 * 2**i / 2**num_qubits, qubit, qr_objective[0]) @ddt class TestBernoulli(QiskitAlgorithmsTestCase): """Tests based on the Bernoulli A operator. This class tests * the estimation result * the constructed circuits """ def setUp(self): super().setUp() with self.assertWarns(DeprecationWarning): self._statevector = QuantumInstance( backend=BasicAer.get_backend("statevector_simulator"), seed_simulator=2, seed_transpiler=2, ) self._sampler = Sampler(options={"seed": 2}) def qasm(shots=100): with self.assertWarns(DeprecationWarning): qi = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=shots, seed_simulator=2, seed_transpiler=2, ) return qi self._qasm = qasm def sampler_shots(shots=100): return Sampler(options={"shots": shots, "seed": 2}) self._sampler_shots = sampler_shots @idata( [ [0.2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2}], [0.49, AmplitudeEstimation(3), {"estimation": 0.5, "mle": 0.49}], [0.2, MaximumLikelihoodAmplitudeEstimation([0, 1, 2]), {"estimation": 0.2}], [0.49, MaximumLikelihoodAmplitudeEstimation(3), {"estimation": 0.49}], [0.2, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.2}], [0.49, IterativeAmplitudeEstimation(0.001, 0.01), {"estimation": 0.49}], [0.2, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.2}], [0.12, FasterAmplitudeEstimation(0.1, 2, rescale=False), {"estimation": 0.12}], ] ) @unpack def test_statevector(self, prob, qae, expect): """statevector test""" problem = EstimationProblem(BernoulliStateIn(prob), 0, BernoulliGrover(prob)) with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._statevector result = qae.estimate(problem) self._statevector.reset_execution_results() for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [0.2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2}], [0.49, AmplitudeEstimation(3), {"estimation": 0.5, "mle": 0.49}], [0.2, MaximumLikelihoodAmplitudeEstimation([0, 1, 2]), {"estimation": 0.2}], [0.49, MaximumLikelihoodAmplitudeEstimation(3), {"estimation": 0.49}], [0.2, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.2}], [0.49, IterativeAmplitudeEstimation(0.001, 0.01), {"estimation": 0.49}], [0.2, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.199}], [0.12, FasterAmplitudeEstimation(0.1, 2, rescale=False), {"estimation": 0.12}], ] ) @unpack def test_sampler(self, prob, qae, expect): """sampler test""" qae.sampler = self._sampler problem = EstimationProblem(BernoulliStateIn(prob), 0, BernoulliGrover(prob)) result = qae.estimate(problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [0.2, 100, AmplitudeEstimation(4), {"estimation": 0.14644, "mle": 0.193888}], [0.0, 1000, AmplitudeEstimation(2), {"estimation": 0.0, "mle": 0.0}], [ 0.2, 100, MaximumLikelihoodAmplitudeEstimation([0, 1, 2, 4, 8]), {"estimation": 0.199606}, ], [0.8, 10, IterativeAmplitudeEstimation(0.1, 0.05), {"estimation": 0.811711}], [0.2, 1000, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.198640}], [ 0.12, 100, FasterAmplitudeEstimation(0.01, 3, rescale=False), {"estimation": 0.119037}, ], ] ) @unpack def test_qasm(self, prob, shots, qae, expect): """qasm test""" with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._qasm(shots) problem = EstimationProblem(BernoulliStateIn(prob), [0], BernoulliGrover(prob)) result = qae.estimate(problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [0.2, 100, AmplitudeEstimation(4), {"estimation": 0.14644, "mle": 0.198783}], [0.0, 1000, AmplitudeEstimation(2), {"estimation": 0.0, "mle": 0.0}], [ 0.2, 100, MaximumLikelihoodAmplitudeEstimation([0, 1, 2, 4, 8]), {"estimation": 0.200308}, ], [0.8, 10, IterativeAmplitudeEstimation(0.1, 0.05), {"estimation": 0.811711}], [0.2, 1000, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.198640}], [ 0.12, 100, FasterAmplitudeEstimation(0.01, 3, rescale=False), {"estimation": 0.120017}, ], ] ) @unpack def test_sampler_with_shots(self, prob, shots, qae, expect): """sampler with shots test""" qae.sampler = self._sampler_shots(shots) problem = EstimationProblem(BernoulliStateIn(prob), [0], BernoulliGrover(prob)) result = qae.estimate(problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @data(True, False) def test_qae_circuit(self, efficient_circuit): """Test circuits resulting from canonical amplitude estimation. Build the circuit manually and from the algorithm and compare the resulting unitaries. """ prob = 0.5 problem = EstimationProblem(BernoulliStateIn(prob), objective_qubits=[0]) for m in [2, 5]: qae = AmplitudeEstimation(m) angle = 2 * np.arcsin(np.sqrt(prob)) # manually set up the inefficient AE circuit qr_eval = QuantumRegister(m, "a") qr_objective = QuantumRegister(1, "q") circuit = QuantumCircuit(qr_eval, qr_objective) # initial Hadamard gates for i in range(m): circuit.h(qr_eval[i]) # A operator circuit.ry(angle, qr_objective) if efficient_circuit: qae.grover_operator = BernoulliGrover(prob) for power in range(m): circuit.cry(2 * 2**power * angle, qr_eval[power], qr_objective[0]) else: oracle = QuantumCircuit(1) oracle.z(0) state_preparation = QuantumCircuit(1) state_preparation.ry(angle, 0) grover_op = GroverOperator(oracle, state_preparation) for power in range(m): circuit.compose( grover_op.power(2**power).control(), qubits=[qr_eval[power], qr_objective[0]], inplace=True, ) # fourier transform iqft = QFT(m, do_swaps=False).inverse().reverse_bits() circuit.append(iqft.to_instruction(), qr_eval) actual_circuit = qae.construct_circuit(problem, measurement=False) self.assertEqual(Operator(circuit), Operator(actual_circuit)) @data(True, False) def test_iqae_circuits(self, efficient_circuit): """Test circuits resulting from iterative amplitude estimation. Build the circuit manually and from the algorithm and compare the resulting unitaries. """ prob = 0.5 problem = EstimationProblem(BernoulliStateIn(prob), objective_qubits=[0]) for k in [2, 5]: qae = IterativeAmplitudeEstimation(0.01, 0.05) angle = 2 * np.arcsin(np.sqrt(prob)) # manually set up the inefficient AE circuit q_objective = QuantumRegister(1, "q") circuit = QuantumCircuit(q_objective) # A operator circuit.ry(angle, q_objective) if efficient_circuit: qae.grover_operator = BernoulliGrover(prob) circuit.ry(2 * k * angle, q_objective[0]) else: oracle = QuantumCircuit(1) oracle.z(0) state_preparation = QuantumCircuit(1) state_preparation.ry(angle, 0) grover_op = GroverOperator(oracle, state_preparation) for _ in range(k): circuit.compose(grover_op, inplace=True) actual_circuit = qae.construct_circuit(problem, k, measurement=False) self.assertEqual(Operator(circuit), Operator(actual_circuit)) @data(True, False) def test_mlae_circuits(self, efficient_circuit): """Test the circuits constructed for MLAE""" prob = 0.5 problem = EstimationProblem(BernoulliStateIn(prob), objective_qubits=[0]) for k in [2, 5]: qae = MaximumLikelihoodAmplitudeEstimation(k) angle = 2 * np.arcsin(np.sqrt(prob)) # compute all the circuits used for MLAE circuits = [] # 0th power q_objective = QuantumRegister(1, "q") circuit = QuantumCircuit(q_objective) circuit.ry(angle, q_objective) circuits += [circuit] # powers of 2 for power in range(k): q_objective = QuantumRegister(1, "q") circuit = QuantumCircuit(q_objective) # A operator circuit.ry(angle, q_objective) # Q^(2^j) operator if efficient_circuit: qae.grover_operator = BernoulliGrover(prob) circuit.ry(2 * 2**power * angle, q_objective[0]) else: oracle = QuantumCircuit(1) oracle.z(0) state_preparation = QuantumCircuit(1) state_preparation.ry(angle, 0) grover_op = GroverOperator(oracle, state_preparation) for _ in range(2**power): circuit.compose(grover_op, inplace=True) circuits += [circuit] actual_circuits = qae.construct_circuits(problem, measurement=False) for actual, expected in zip(actual_circuits, circuits): self.assertEqual(Operator(actual), Operator(expected)) @ddt class TestSineIntegral(QiskitAlgorithmsTestCase): """Tests based on the A operator to integrate sin^2(x). This class tests * the estimation result * the confidence intervals """ def setUp(self): super().setUp() with self.assertWarns(DeprecationWarning): self._statevector = QuantumInstance( backend=BasicAer.get_backend("statevector_simulator"), seed_simulator=123, seed_transpiler=41, ) self._sampler = Sampler(options={"seed": 123}) def qasm(shots=100): with self.assertWarns(DeprecationWarning): qi = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=shots, seed_simulator=7192, seed_transpiler=90000, ) return qi self._qasm = qasm def sampler_shots(shots=100): return Sampler(options={"shots": shots, "seed": 7192}) self._sampler_shots = sampler_shots @idata( [ [2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.270290}], [4, MaximumLikelihoodAmplitudeEstimation(4), {"estimation": 0.272675}], [3, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.272082}], [3, FasterAmplitudeEstimation(0.01, 1), {"estimation": 0.272082}], ] ) @unpack def test_statevector(self, n, qae, expect): """Statevector end-to-end test""" # construct factories for A and Q # qae.state_preparation = SineIntegral(n) estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._statevector # result = qae.run(self._statevector) result = qae.estimate(estimation_problem) self._statevector.reset_execution_results() for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2702}], [4, MaximumLikelihoodAmplitudeEstimation(4), {"estimation": 0.2725}], [3, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.2721}], [3, FasterAmplitudeEstimation(0.01, 1), {"estimation": 0.2792}], ] ) @unpack def test_sampler(self, n, qae, expect): """sampler end-to-end test""" # construct factories for A and Q # qae.state_preparation = SineIntegral(n) qae.sampler = self._sampler estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) result = qae.estimate(estimation_problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [4, 100, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.281196}], [3, 10, MaximumLikelihoodAmplitudeEstimation(2), {"estimation": 0.256878}], [3, 1000, IterativeAmplitudeEstimation(0.01, 0.01), {"estimation": 0.271790}], [3, 1000, FasterAmplitudeEstimation(0.1, 4), {"estimation": 0.274168}], ] ) @unpack def test_qasm(self, n, shots, qae, expect): """QASM simulator end-to-end test.""" estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._qasm(shots) result = qae.estimate(estimation_problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [4, 1000, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2636}], [3, 10, MaximumLikelihoodAmplitudeEstimation(2), {"estimation": 0.2904}], [3, 1000, IterativeAmplitudeEstimation(0.01, 0.01), {"estimation": 0.2706}], [3, 1000, FasterAmplitudeEstimation(0.1, 4), {"estimation": 0.2764}], ] ) @unpack def test_sampler_with_shots(self, n, shots, qae, expect): """Sampler with shots end-to-end test.""" # construct factories for A and Q qae.sampler = self._sampler_shots(shots) estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) result = qae.estimate(estimation_problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [ AmplitudeEstimation(3), "mle", { "likelihood_ratio": (0.2494734, 0.3003771), "fisher": (0.2486176, 0.2999286), "observed_fisher": (0.2484562, 0.3000900), }, ], [ MaximumLikelihoodAmplitudeEstimation(3), "estimation", { "likelihood_ratio": (0.2598794, 0.2798536), "fisher": (0.2584889, 0.2797018), "observed_fisher": (0.2659279, 0.2722627), }, ], ] ) @unpack def test_confidence_intervals(self, qae, key, expect): """End-to-end test for all confidence intervals.""" n = 3 estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._statevector # statevector simulator result = qae.estimate(estimation_problem) self._statevector.reset_execution_results() methods = ["lr", "fi", "oi"] # short for likelihood_ratio, fisher, observed_fisher alphas = [0.1, 0.00001, 0.9] # alpha shouldn't matter in statevector for alpha, method in zip(alphas, methods): confint = qae.compute_confidence_interval(result, alpha, method) # confidence interval based on statevector should be empty, as we are sure of the result self.assertAlmostEqual(confint[1] - confint[0], 0.0) self.assertAlmostEqual(confint[0], getattr(result, key)) # qasm simulator shots = 100 alpha = 0.01 with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._qasm(shots) result = qae.estimate(estimation_problem) for method, expected_confint in expect.items(): confint = qae.compute_confidence_interval(result, alpha, method) np.testing.assert_array_almost_equal(confint, expected_confint) self.assertTrue(confint[0] <= getattr(result, key) <= confint[1]) def test_iqae_confidence_intervals(self): """End-to-end test for the IQAE confidence interval.""" n = 3 expected_confint = (0.1984050, 0.3511015) estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) with self.assertWarns(DeprecationWarning): qae = IterativeAmplitudeEstimation(0.1, 0.01, quantum_instance=self._statevector) # statevector simulator result = qae.estimate(estimation_problem) self._statevector.reset_execution_results() confint = result.confidence_interval # confidence interval based on statevector should be empty, as we are sure of the result self.assertAlmostEqual(confint[1] - confint[0], 0.0) self.assertAlmostEqual(confint[0], result.estimation) # qasm simulator shots = 100 with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._qasm(shots) result = qae.estimate(estimation_problem) confint = result.confidence_interval np.testing.assert_array_almost_equal(confint, expected_confint) self.assertTrue(confint[0] <= result.estimation <= confint[1]) class TestAmplitudeEstimation(QiskitAlgorithmsTestCase): """Specific tests for canonical AE.""" def test_warns_if_good_state_set(self): """Check AE warns if is_good_state is set.""" circuit = QuantumCircuit(1) problem = EstimationProblem(circuit, objective_qubits=[0], is_good_state=lambda x: True) qae = AmplitudeEstimation(num_eval_qubits=1, sampler=Sampler()) with self.assertWarns(Warning): _ = qae.estimate(problem) @ddt class TestFasterAmplitudeEstimation(QiskitAlgorithmsTestCase): """Specific tests for Faster AE.""" def setUp(self): super().setUp() self._sampler = Sampler(options={"seed": 2}) def test_rescaling(self): """Test the rescaling.""" amplitude = 0.8 scaling = 0.25 circuit = QuantumCircuit(1) circuit.ry(2 * np.arcsin(amplitude), 0) problem = EstimationProblem(circuit, objective_qubits=[0]) rescaled = problem.rescale(scaling) rescaled_amplitude = Statevector.from_instruction(rescaled.state_preparation).data[3] self.assertAlmostEqual(scaling * amplitude, rescaled_amplitude) def test_run_without_rescaling(self): """Run Faster AE without rescaling if the amplitude is in [0, 1/4].""" # construct estimation problem prob = 0.11 a_op = QuantumCircuit(1) a_op.ry(2 * np.arcsin(np.sqrt(prob)), 0) problem = EstimationProblem(a_op, objective_qubits=[0]) # construct algo without rescaling backend = BasicAer.get_backend("statevector_simulator") with self.assertWarns(DeprecationWarning): fae = FasterAmplitudeEstimation(0.1, 1, rescale=False, quantum_instance=backend) # run the algo result = fae.estimate(problem) # assert the result is correct self.assertAlmostEqual(result.estimation, prob) # assert no rescaling was used theta = np.mean(result.theta_intervals[-1]) value_without_scaling = np.sin(theta) ** 2 self.assertAlmostEqual(result.estimation, value_without_scaling) def test_sampler_run_without_rescaling(self): """Run Faster AE without rescaling if the amplitude is in [0, 1/4].""" # construct estimation problem prob = 0.11 a_op = QuantumCircuit(1) a_op.ry(2 * np.arcsin(np.sqrt(prob)), 0) problem = EstimationProblem(a_op, objective_qubits=[0]) # construct algo without rescaling fae = FasterAmplitudeEstimation(0.1, 1, rescale=False, sampler=self._sampler) # run the algo result = fae.estimate(problem) # assert the result is correct self.assertAlmostEqual(result.estimation, prob, places=2) # assert no rescaling was used theta = np.mean(result.theta_intervals[-1]) value_without_scaling = np.sin(theta) ** 2 self.assertAlmostEqual(result.estimation, value_without_scaling) def test_rescaling_with_custom_grover_raises(self): """Test that the rescaling option fails if a custom Grover operator is used.""" prob = 0.8 a_op = BernoulliStateIn(prob) q_op = BernoulliGrover(prob) problem = EstimationProblem(a_op, objective_qubits=[0], grover_operator=q_op) # construct algo without rescaling backend = BasicAer.get_backend("statevector_simulator") with self.assertWarns(DeprecationWarning): fae = FasterAmplitudeEstimation(0.1, 1, quantum_instance=backend) # run the algo with self.assertWarns(Warning): _ = fae.estimate(problem) @data(("statevector_simulator", 0.2), ("qasm_simulator", 0.199440)) @unpack def test_good_state(self, backend_str, expect): """Test with a good state function.""" def is_good_state(bitstr): return bitstr[1] == "1" # construct the estimation problem where the second qubit is ignored a_op = QuantumCircuit(2) a_op.ry(2 * np.arcsin(np.sqrt(0.2)), 0) # oracle only affects first qubit oracle = QuantumCircuit(2) oracle.z(0) # reflect only on first qubit q_op = GroverOperator(oracle, a_op, reflection_qubits=[0]) # but we measure both qubits (hence both are objective qubits) problem = EstimationProblem( a_op, objective_qubits=[0, 1], grover_operator=q_op, is_good_state=is_good_state ) # construct algo with self.assertWarns(DeprecationWarning): backend = QuantumInstance( BasicAer.get_backend(backend_str), seed_simulator=2, seed_transpiler=2 ) # cannot use rescaling with a custom grover operator with self.assertWarns(DeprecationWarning): fae = FasterAmplitudeEstimation(0.01, 5, rescale=False, quantum_instance=backend) # run the algo result = fae.estimate(problem) # assert the result is correct self.assertAlmostEqual(result.estimation, expect, places=5) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests evaluator of auxiliary operators for algorithms.""" import unittest from typing import Tuple, Union from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import ddt, data from qiskit_algorithms.list_or_dict import ListOrDict from qiskit.providers import Backend from qiskit.quantum_info import Statevector from qiskit_algorithms import eval_observables from qiskit import BasicAer, QuantumCircuit from qiskit.circuit.library import EfficientSU2 from qiskit.opflow import ( PauliSumOp, X, Z, I, ExpectationFactory, OperatorBase, ExpectationBase, StateFn, ) from qiskit.utils import QuantumInstance, algorithm_globals @ddt class TestAuxOpsEvaluator(QiskitAlgorithmsTestCase): """Tests evaluator of auxiliary operators for algorithms.""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed with self.assertWarns(DeprecationWarning): self.h2_op = ( -1.052373245772859 * (I ^ I) + 0.39793742484318045 * (I ^ Z) - 0.39793742484318045 * (Z ^ I) - 0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 * (X ^ X) ) self.threshold = 1e-8 self.backend_names = ["statevector_simulator", "qasm_simulator"] def get_exact_expectation(self, ansatz: QuantumCircuit, observables: ListOrDict[OperatorBase]): """ Calculates the exact expectation to be used as an expected result for unit tests. """ if isinstance(observables, dict): observables_list = list(observables.values()) else: observables_list = observables # the exact value is a list of (mean, variance) where we expect 0 variance exact = [ (Statevector(ansatz).expectation_value(observable), 0) for observable in observables_list ] if isinstance(observables, dict): return dict(zip(observables.keys(), exact)) return exact def _run_test( self, expected_result: ListOrDict[Tuple[complex, complex]], quantum_state: Union[QuantumCircuit, Statevector], decimal: int, expectation: ExpectationBase, observables: ListOrDict[OperatorBase], quantum_instance: Union[QuantumInstance, Backend], ): with self.assertWarns(DeprecationWarning): result = eval_observables( quantum_instance, quantum_state, observables, expectation, self.threshold ) if isinstance(observables, dict): np.testing.assert_equal(list(result.keys()), list(expected_result.keys())) np.testing.assert_array_almost_equal( list(result.values()), list(expected_result.values()), decimal=decimal ) else: np.testing.assert_array_almost_equal(result, expected_result, decimal=decimal) @data( [ PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]), PauliSumOp.from_list([("II", 2.0)]), ], [ PauliSumOp.from_list([("ZZ", 2.0)]), ], { "op1": PauliSumOp.from_list([("II", 2.0)]), "op2": PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]), }, { "op1": PauliSumOp.from_list([("ZZ", 2.0)]), }, ) def test_eval_observables(self, observables: ListOrDict[OperatorBase]): """Tests evaluator of auxiliary operators for algorithms.""" ansatz = EfficientSU2(2) parameters = np.array( [1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0], dtype=float, ) bound_ansatz = ansatz.bind_parameters(parameters) expected_result = self.get_exact_expectation(bound_ansatz, observables) for backend_name in self.backend_names: shots = 4096 if backend_name == "qasm_simulator" else 1 decimal = ( 1 if backend_name == "qasm_simulator" else 6 ) # to accommodate for qasm being imperfect with self.subTest(msg=f"Test {backend_name} backend."): backend = BasicAer.get_backend(backend_name) with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, shots=shots, seed_simulator=self.seed, seed_transpiler=self.seed, ) expectation = ExpectationFactory.build( operator=self.h2_op, backend=quantum_instance, ) with self.subTest(msg="Test QuantumCircuit."): self._run_test( expected_result, bound_ansatz, decimal, expectation, observables, quantum_instance, ) with self.subTest(msg="Test QuantumCircuit with Backend."): self._run_test( expected_result, bound_ansatz, decimal, expectation, observables, backend, ) with self.subTest(msg="Test Statevector."): statevector = Statevector(bound_ansatz) self._run_test( expected_result, statevector, decimal, expectation, observables, quantum_instance, ) with self.assertWarns(DeprecationWarning): with self.subTest(msg="Test StateFn."): statefn = StateFn(bound_ansatz) self._run_test( expected_result, statefn, decimal, expectation, observables, quantum_instance, ) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Providers that support BackendV1 interface""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeProvider from qiskit.utils import QuantumInstance, algorithm_globals from qiskit_algorithms import VQE, Grover, AmplificationProblem from qiskit.opflow import X, Z, I from qiskit_algorithms.optimizers import SPSA from qiskit.circuit.library import TwoLocal, EfficientSU2 from qiskit.utils.mitigation import CompleteMeasFitter class TestBackendV1(QiskitAlgorithmsTestCase): """test BackendV1 interface""" def setUp(self): super().setUp() self._provider = FakeProvider() self._qasm = self._provider.get_backend("fake_qasm_simulator") self.seed = 50 def test_vqe_qasm(self): """Test the VQE on QASM simulator.""" optimizer = SPSA(maxiter=300, last_avg=5) wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") with self.assertWarns(DeprecationWarning): h2_op = ( -1.052373245772859 * (I ^ I) + 0.39793742484318045 * (I ^ Z) - 0.39793742484318045 * (Z ^ I) - 0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 * (X ^ X) ) qasm_simulator = QuantumInstance( self._qasm, shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed ) with self.assertWarns(DeprecationWarning): vqe = VQE( ansatz=wavefunction, optimizer=optimizer, max_evals_grouped=1, quantum_instance=qasm_simulator, ) result = vqe.compute_minimum_eigenvalue(operator=h2_op) self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) def test_run_circuit_oracle(self): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) with self.assertWarns(DeprecationWarning): qi = QuantumInstance( self._provider.get_backend("fake_vigo"), seed_simulator=12, seed_transpiler=32 ) with self.assertWarns(DeprecationWarning): grover = Grover(quantum_instance=qi) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) def test_run_circuit_oracle_single_experiment_backend(self): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) backend = self._provider.get_backend("fake_vigo") backend._configuration.max_experiments = 1 with self.assertWarns(DeprecationWarning): qi = QuantumInstance(backend, seed_simulator=12, seed_transpiler=32) with self.assertWarns(DeprecationWarning): grover = Grover(quantum_instance=qi) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) def test_measurement_error_mitigation_with_vqe(self): """measurement error mitigation test with vqe""" try: from qiskit.providers.aer import noise except ImportError as ex: self.skipTest(f"Package doesn't appear to be installed. Error: '{str(ex)}'") return algorithm_globals.random_seed = 0 # build noise model noise_model = noise.NoiseModel() read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]]) noise_model.add_all_qubit_readout_error(read_err) backend = self._qasm with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, seed_simulator=167, seed_transpiler=167, noise_model=noise_model, measurement_error_mitigation_cls=CompleteMeasFitter, ) h2_hamiltonian = ( -1.052373245772859 * (I ^ I) + 0.39793742484318045 * (I ^ Z) - 0.39793742484318045 * (Z ^ I) - 0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 * (X ^ X) ) optimizer = SPSA(maxiter=200) ansatz = EfficientSU2(2, reps=1) with self.assertWarns(DeprecationWarning): vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance) result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) self.assertGreater(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Providers that support BackendV2 interface""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeProvider from qiskit.providers.fake_provider.fake_backend_v2 import FakeBackendSimple from qiskit.utils import QuantumInstance from qiskit_algorithms import VQE, Grover, AmplificationProblem from qiskit.opflow import X, Z, I from qiskit_algorithms.optimizers import SPSA from qiskit.circuit.library import TwoLocal class TestBackendV2(QiskitAlgorithmsTestCase): """test BackendV2 interface""" def setUp(self): super().setUp() self._provider = FakeProvider() self._qasm = FakeBackendSimple() self.seed = 50 def test_vqe_qasm(self): """Test the VQE on QASM simulator.""" optimizer = SPSA(maxiter=300, last_avg=5) wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") with self.assertWarns(DeprecationWarning): h2_op = ( -1.052373245772859 * (I ^ I) + 0.39793742484318045 * (I ^ Z) - 0.39793742484318045 * (Z ^ I) - 0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 * (X ^ X) ) qasm_simulator = QuantumInstance( self._qasm, shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed ) with self.assertWarns(DeprecationWarning): vqe = VQE( ansatz=wavefunction, optimizer=optimizer, max_evals_grouped=1, quantum_instance=qasm_simulator, ) result = vqe.compute_minimum_eigenvalue(operator=h2_op) self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) def test_run_circuit_oracle(self): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) with self.assertWarns(DeprecationWarning): qi = QuantumInstance( self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32 ) with self.assertWarns(DeprecationWarning): grover = Grover(quantum_instance=qi) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) def test_run_circuit_oracle_single_experiment_backend(self): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) backend = self._provider.get_backend("fake_yorktown") backend._configuration.max_experiments = 1 with self.assertWarns(DeprecationWarning): qi = QuantumInstance( self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32 ) with self.assertWarns(DeprecationWarning): grover = Grover(quantum_instance=qi) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Grover's algorithm.""" import itertools import unittest from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import data, ddt, idata, unpack from qiskit import BasicAer, QuantumCircuit from qiskit_algorithms import AmplificationProblem, Grover from qiskit.circuit.library import GroverOperator, PhaseOracle from qiskit.primitives import Sampler from qiskit.quantum_info import Operator, Statevector from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.utils.optionals import HAS_TWEEDLEDUM @ddt class TestAmplificationProblem(QiskitAlgorithmsTestCase): """Test the amplification problem.""" def setUp(self): super().setUp() oracle = QuantumCircuit(2) oracle.cz(0, 1) self._expected_grover_op = GroverOperator(oracle=oracle) @data("oracle_only", "oracle_and_stateprep") def test_groverop_getter(self, kind): """Test the default construction of the Grover operator.""" oracle = QuantumCircuit(2) oracle.cz(0, 1) if kind == "oracle_only": problem = AmplificationProblem(oracle, is_good_state=["11"]) expected = GroverOperator(oracle) else: stateprep = QuantumCircuit(2) stateprep.ry(0.2, [0, 1]) problem = AmplificationProblem( oracle, state_preparation=stateprep, is_good_state=["11"] ) expected = GroverOperator(oracle, stateprep) self.assertEqual(Operator(expected), Operator(problem.grover_operator)) @data("list_str", "list_int", "statevector", "callable") def test_is_good_state(self, kind): """Test is_good_state works on different input types.""" if kind == "list_str": is_good_state = ["01", "11"] elif kind == "list_int": is_good_state = [1] # means bitstr[1] == '1' elif kind == "statevector": is_good_state = Statevector(np.array([0, 1, 0, 1]) / np.sqrt(2)) else: def is_good_state(bitstr): # same as ``bitstr in ['01', '11']`` return bitstr[1] == "1" possible_states = [ "".join(list(map(str, item))) for item in itertools.product([0, 1], repeat=2) ] oracle = QuantumCircuit(2) problem = AmplificationProblem(oracle, is_good_state=is_good_state) expected = [state in ["01", "11"] for state in possible_states] actual = [problem.is_good_state(state) for state in possible_states] self.assertListEqual(expected, actual) @ddt class TestGrover(QiskitAlgorithmsTestCase): """Test for the functionality of Grover""" def setUp(self): super().setUp() with self.assertWarns(DeprecationWarning): self.statevector = QuantumInstance( BasicAer.get_backend("statevector_simulator"), seed_simulator=12, seed_transpiler=32 ) self.qasm = QuantumInstance( BasicAer.get_backend("qasm_simulator"), seed_simulator=12, seed_transpiler=32 ) self._sampler = Sampler() self._sampler_with_shots = Sampler(options={"shots": 1024, "seed": 123}) algorithm_globals.random_seed = 123 @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") @data("ideal", "shots", False) def test_implicit_phase_oracle_is_good_state(self, use_sampler): """Test implicit default for is_good_state with PhaseOracle.""" grover = self._prepare_grover(use_sampler) oracle = PhaseOracle("x & y") problem = AmplificationProblem(oracle) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "11") @idata(itertools.product(["ideal", "shots", False], [[1, 2, 3], None, 2])) @unpack def test_iterations_with_good_state(self, use_sampler, iterations): """Test the algorithm with different iteration types and with good state""" grover = self._prepare_grover(use_sampler, iterations) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @idata(itertools.product(["shots", False], [[1, 2, 3], None, 2])) @unpack def test_iterations_with_good_state_sample_from_iterations(self, use_sampler, iterations): """Test the algorithm with different iteration types and with good state""" grover = self._prepare_grover(use_sampler, iterations, sample_from_iterations=True) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) def test_fixed_iterations_without_good_state(self, use_sampler): """Test the algorithm with iterations as an int and without good state""" grover = self._prepare_grover(use_sampler, iterations=2) problem = AmplificationProblem(Statevector.from_label("111")) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @idata(itertools.product(["ideal", "shots", False], [[1, 2, 3], None])) @unpack def test_iterations_without_good_state(self, use_sampler, iterations): """Test the correct error is thrown for none/list of iterations and without good state""" grover = self._prepare_grover(use_sampler, iterations=iterations) problem = AmplificationProblem(Statevector.from_label("111")) with self.assertRaisesRegex( TypeError, "An is_good_state function is required with the provided oracle" ): if not use_sampler: with self.assertWarns(DeprecationWarning): grover.amplify(problem) else: grover.amplify(problem) @data("ideal", "shots", False) def test_iterator(self, use_sampler): """Test running the algorithm on an iterator.""" # step-function iterator def iterator(): wait, value, count = 3, 1, 0 while True: yield value count += 1 if count % wait == 0: value += 1 grover = self._prepare_grover(use_sampler, iterations=iterator()) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) def test_growth_rate(self, use_sampler): """Test running the algorithm on a growth rate""" grover = self._prepare_grover(use_sampler, growth_rate=8 / 7) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) def test_max_num_iterations(self, use_sampler): """Test the iteration stops when the maximum number of iterations is reached.""" def zero(): while True: yield 0 grover = self._prepare_grover(use_sampler, iterations=zero()) n = 5 problem = AmplificationProblem(Statevector.from_label("1" * n), is_good_state=["1" * n]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(len(result.iterations), 2**n) @data("ideal", "shots", False) def test_max_power(self, use_sampler): """Test the iteration stops when the maximum power is reached.""" lam = 10.0 grover = self._prepare_grover(use_sampler, growth_rate=lam) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) result = grover.amplify(problem) self.assertEqual(len(result.iterations), 0) @data("ideal", "shots", False) def test_run_circuit_oracle(self, use_sampler): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) @data("ideal", "shots", False) def test_run_state_vector_oracle(self, use_sampler): """Test execution with a state vector oracle""" mark_state = Statevector.from_label("11") problem = AmplificationProblem(mark_state, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) @data("ideal", "shots", False) def test_run_custom_grover_operator(self, use_sampler): """Test execution with a grover operator oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) grover_op = GroverOperator(oracle) problem = AmplificationProblem( oracle=oracle, grover_operator=grover_op, is_good_state=["11"] ) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) def test_optimal_num_iterations(self): """Test optimal_num_iterations""" num_qubits = 7 for num_solutions in range(1, 2**num_qubits): amplitude = np.sqrt(num_solutions / 2**num_qubits) expected = round(np.arccos(amplitude) / (2 * np.arcsin(amplitude))) actual = Grover.optimal_num_iterations(num_solutions, num_qubits) self.assertEqual(actual, expected) def test_construct_circuit(self): """Test construct_circuit""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = Grover() constructed = grover.construct_circuit(problem, 2, measurement=False) grover_op = GroverOperator(oracle) expected = QuantumCircuit(2) expected.h([0, 1]) expected.compose(grover_op.power(2), inplace=True) self.assertTrue(Operator(constructed).equiv(Operator(expected))) @data("ideal", "shots", False) def test_circuit_result(self, use_sampler): """Test circuit_result""" oracle = QuantumCircuit(2) oracle.cz(0, 1) # is_good_state=['00'] is intentionally selected to obtain a list of results problem = AmplificationProblem(oracle, is_good_state=["00"]) grover = self._prepare_grover(use_sampler, iterations=[1, 2, 3, 4]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) if use_sampler: for i, dist in enumerate(result.circuit_results): keys, values = zip(*sorted(dist.items())) if i in (0, 3): self.assertTupleEqual(keys, ("11",)) np.testing.assert_allclose(values, [1], atol=0.2) else: self.assertTupleEqual(keys, ("00", "01", "10", "11")) np.testing.assert_allclose(values, [0.25, 0.25, 0.25, 0.25], atol=0.2) else: expected_results = [ {"11": 1024}, {"00": 238, "01": 253, "10": 263, "11": 270}, {"00": 238, "01": 253, "10": 263, "11": 270}, {"11": 1024}, ] self.assertEqual(result.circuit_results, expected_results) @data("ideal", "shots", False) def test_max_probability(self, use_sampler): """Test max_probability""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertAlmostEqual(result.max_probability, 1.0) @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") @data("ideal", "shots", False) def test_oracle_evaluation(self, use_sampler): """Test oracle_evaluation for PhaseOracle""" oracle = PhaseOracle("x1 & x2 & (not x3)") problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertTrue(result.oracle_evaluation) self.assertEqual("011", result.top_measurement) def test_sampler_setter(self): """Test sampler setter""" grover = Grover() grover.sampler = self._sampler self.assertEqual(grover.sampler, self._sampler) def _prepare_grover( self, use_sampler, iterations=None, growth_rate=None, sample_from_iterations=False ): """Prepare Grover instance for test""" if use_sampler == "ideal": grover = Grover( sampler=self._sampler, iterations=iterations, growth_rate=growth_rate, sample_from_iterations=sample_from_iterations, ) elif use_sampler == "shots": grover = Grover( sampler=self._sampler_with_shots, iterations=iterations, growth_rate=growth_rate, sample_from_iterations=sample_from_iterations, ) else: with self.assertWarns(DeprecationWarning): grover = Grover( quantum_instance=self.qasm, iterations=iterations, growth_rate=growth_rate, sample_from_iterations=sample_from_iterations, ) return grover if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Measurement Error Mitigation""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy as np import rustworkx as rx from qiskit import QuantumCircuit, execute from qiskit.quantum_info import Pauli from qiskit.exceptions import QiskitError from qiskit.utils import QuantumInstance, algorithm_globals from qiskit_algorithms import VQE, QAOA from qiskit.opflow import I, X, Z, PauliSumOp from qiskit_algorithms.optimizers import SPSA, COBYLA from qiskit.circuit.library import EfficientSU2 from qiskit.utils.mitigation import CompleteMeasFitter, TensoredMeasFitter from qiskit.utils.measurement_error_mitigation import build_measurement_error_mitigation_circuits from qiskit.utils import optionals if optionals.HAS_AER: # pylint: disable=no-name-in-module from qiskit import Aer from qiskit.providers.aer import noise if optionals.HAS_IGNIS: # pylint: disable=no-name-in-module from qiskit.ignis.mitigation.measurement import ( CompleteMeasFitter as CompleteMeasFitter_IG, TensoredMeasFitter as TensoredMeasFitter_IG, ) @ddt class TestMeasurementErrorMitigation(QiskitAlgorithmsTestCase): """Test measurement error mitigation.""" @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") @data( ("CompleteMeasFitter", None, False), ("TensoredMeasFitter", None, False), ("TensoredMeasFitter", [[0, 1]], True), ("TensoredMeasFitter", [[1], [0]], False), ) @unpack def test_measurement_error_mitigation_with_diff_qubit_order( self, fitter_str, mit_pattern, fails, ): """measurement error mitigation with different qubit order""" algorithm_globals.random_seed = 0 # build noise model noise_model = noise.NoiseModel() read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]]) noise_model.add_all_qubit_readout_error(read_err) fitter_cls = ( CompleteMeasFitter if fitter_str == "CompleteMeasFitter" else TensoredMeasFitter ) backend = Aer.get_backend("aer_simulator") with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, seed_simulator=1679, seed_transpiler=167, shots=1000, noise_model=noise_model, measurement_error_mitigation_cls=fitter_cls, cals_matrix_refresh_period=0, mit_pattern=mit_pattern, ) # circuit qc1 = QuantumCircuit(2, 2) qc1.h(0) qc1.cx(0, 1) qc1.measure(0, 0) qc1.measure(1, 1) qc2 = QuantumCircuit(2, 2) qc2.h(0) qc2.cx(0, 1) qc2.measure(1, 0) qc2.measure(0, 1) with self.assertWarns(DeprecationWarning): if fails: self.assertRaisesRegex( QiskitError, "Each element in the mit pattern should have length 1.", quantum_instance.execute, [qc1, qc2], ) else: quantum_instance.execute([qc1, qc2]) self.assertGreater(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() # failure case qc3 = QuantumCircuit(3, 3) qc3.h(2) qc3.cx(1, 2) qc3.measure(2, 1) qc3.measure(1, 2) with self.assertWarns(DeprecationWarning): self.assertRaises(QiskitError, quantum_instance.execute, [qc1, qc3]) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") @data(("CompleteMeasFitter", None), ("TensoredMeasFitter", [[0], [1]])) def test_measurement_error_mitigation_with_vqe(self, config): """measurement error mitigation test with vqe""" fitter_str, mit_pattern = config algorithm_globals.random_seed = 0 # build noise model noise_model = noise.NoiseModel() read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]]) noise_model.add_all_qubit_readout_error(read_err) fitter_cls = ( CompleteMeasFitter if fitter_str == "CompleteMeasFitter" else TensoredMeasFitter ) backend = Aer.get_backend("aer_simulator") with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, seed_simulator=167, seed_transpiler=167, noise_model=noise_model, measurement_error_mitigation_cls=fitter_cls, mit_pattern=mit_pattern, ) optimizer = SPSA(maxiter=200) ansatz = EfficientSU2(2, reps=1) with self.assertWarns(DeprecationWarning): h2_hamiltonian = ( -1.052373245772859 * (I ^ I) + 0.39793742484318045 * (I ^ Z) - 0.39793742484318045 * (Z ^ I) - 0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 * (X ^ X) ) with self.assertWarns(DeprecationWarning): vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance) result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) self.assertGreater(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) def _get_operator(self, weight_matrix): """Generate Hamiltonian for the max-cut problem of a graph. Args: weight_matrix (numpy.ndarray) : adjacency matrix. Returns: PauliSumOp: operator for the Hamiltonian float: a constant shift for the obj function. """ num_nodes = weight_matrix.shape[0] pauli_list = [] shift = 0 for i in range(num_nodes): for j in range(i): if weight_matrix[i, j] != 0: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))]) shift -= 0.5 * weight_matrix[i, j] opflow_list = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list] with self.assertWarns(DeprecationWarning): return PauliSumOp.from_list(opflow_list), shift @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") def test_measurement_error_mitigation_qaoa(self): """measurement error mitigation test with QAOA""" algorithm_globals.random_seed = 167 backend = Aer.get_backend("aer_simulator") w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) initial_point = np.asarray([0.0, 0.0]) # Compute first without noise with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) with self.assertWarns(DeprecationWarning): qaoa = QAOA( optimizer=COBYLA(maxiter=3), quantum_instance=quantum_instance, initial_point=initial_point, ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) ref_eigenvalue = result.eigenvalue.real # compute with noise # build noise model noise_model = noise.NoiseModel() read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]]) noise_model.add_all_qubit_readout_error(read_err) with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, noise_model=noise_model, measurement_error_mitigation_cls=CompleteMeasFitter, shots=10000, ) with self.assertWarns(DeprecationWarning): qaoa = QAOA( optimizer=COBYLA(maxiter=3), quantum_instance=quantum_instance, initial_point=initial_point, ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) self.assertAlmostEqual(result.eigenvalue.real, ref_eigenvalue, delta=0.05) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") @unittest.skipUnless(optionals.HAS_IGNIS, "qiskit-ignis is required to run this test") @data("CompleteMeasFitter", "TensoredMeasFitter") def test_measurement_error_mitigation_with_diff_qubit_order_ignis(self, fitter_str): """measurement error mitigation with different qubit order""" algorithm_globals.random_seed = 0 # build noise model noise_model = noise.NoiseModel() read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]]) noise_model.add_all_qubit_readout_error(read_err) fitter_cls = ( CompleteMeasFitter_IG if fitter_str == "CompleteMeasFitter" else TensoredMeasFitter_IG ) backend = Aer.get_backend("aer_simulator") with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, seed_simulator=1679, seed_transpiler=167, shots=1000, noise_model=noise_model, measurement_error_mitigation_cls=fitter_cls, cals_matrix_refresh_period=0, ) # circuit qc1 = QuantumCircuit(2, 2) qc1.h(0) qc1.cx(0, 1) qc1.measure(0, 0) qc1.measure(1, 1) qc2 = QuantumCircuit(2, 2) qc2.h(0) qc2.cx(0, 1) qc2.measure(1, 0) qc2.measure(0, 1) if fitter_cls == TensoredMeasFitter_IG: with self.assertWarnsRegex(DeprecationWarning, r".*ignis.*"): self.assertRaisesRegex( QiskitError, "TensoredMeasFitter doesn't support subset_fitter.", quantum_instance.execute, [qc1, qc2], ) else: # this should run smoothly with self.assertWarnsRegex(DeprecationWarning, r".*ignis.*"): quantum_instance.execute([qc1, qc2]) self.assertGreater(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() # failure case qc3 = QuantumCircuit(3, 3) qc3.h(2) qc3.cx(1, 2) qc3.measure(2, 1) qc3.measure(1, 2) self.assertRaises(QiskitError, quantum_instance.execute, [qc1, qc3]) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") @unittest.skipUnless(optionals.HAS_IGNIS, "qiskit-ignis is required to run this test") @data(("CompleteMeasFitter", None), ("TensoredMeasFitter", [[0], [1]])) def test_measurement_error_mitigation_with_vqe_ignis(self, config): """measurement error mitigation test with vqe""" fitter_str, mit_pattern = config algorithm_globals.random_seed = 0 # build noise model noise_model = noise.NoiseModel() read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]]) noise_model.add_all_qubit_readout_error(read_err) fitter_cls = ( CompleteMeasFitter_IG if fitter_str == "CompleteMeasFitter" else TensoredMeasFitter_IG ) backend = Aer.get_backend("aer_simulator") with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, seed_simulator=167, seed_transpiler=167, noise_model=noise_model, measurement_error_mitigation_cls=fitter_cls, mit_pattern=mit_pattern, ) h2_hamiltonian = ( -1.052373245772859 * (I ^ I) + 0.39793742484318045 * (I ^ Z) - 0.39793742484318045 * (Z ^ I) - 0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 * (X ^ X) ) optimizer = SPSA(maxiter=200) ansatz = EfficientSU2(2, reps=1) with self.assertWarnsRegex(DeprecationWarning): vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance) result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) self.assertGreater(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") @unittest.skipUnless(optionals.HAS_IGNIS, "qiskit-ignis is required to run this test") def test_calibration_results(self): """check that results counts are the same with/without error mitigation""" algorithm_globals.random_seed = 1679 np.random.seed(algorithm_globals.random_seed) qc = QuantumCircuit(1) qc.x(0) qc_meas = qc.copy() qc_meas.measure_all() backend = Aer.get_backend("aer_simulator") counts_array = [None, None] for idx, is_use_mitigation in enumerate([True, False]): with self.assertWarns(DeprecationWarning): if is_use_mitigation: quantum_instance = QuantumInstance( backend, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, shots=1024, measurement_error_mitigation_cls=CompleteMeasFitter_IG, ) with self.assertWarnsRegex(DeprecationWarning, r".*ignis.*"): counts_array[idx] = quantum_instance.execute(qc_meas).get_counts() else: quantum_instance = QuantumInstance( backend, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, shots=1024, ) counts_array[idx] = quantum_instance.execute(qc_meas).get_counts() self.assertEqual( counts_array[0], counts_array[1], msg="Counts different with/without fitter." ) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") def test_circuit_modified(self): """tests that circuits don't get modified on QI execute with error mitigation as per issue #7449 """ algorithm_globals.random_seed = 1679 np.random.seed(algorithm_globals.random_seed) circuit = QuantumCircuit(1) circuit.x(0) circuit.measure_all() with self.assertWarns(DeprecationWarning): qi = QuantumInstance( Aer.get_backend("aer_simulator"), seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, shots=1024, measurement_error_mitigation_cls=CompleteMeasFitter, ) # The error happens on transpiled circuits since "execute" was changing the input array # Non transpiled circuits didn't have a problem because a new transpiled array was created # internally. circuits_ref = qi.transpile(circuit) # always returns a new array circuits_input = circuits_ref.copy() with self.assertWarns(DeprecationWarning): _ = qi.execute(circuits_input, had_transpiled=True) self.assertEqual(circuits_ref, circuits_input, msg="Transpiled circuit array modified.") @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") def test_tensor_subset_fitter(self): """Test the subset fitter method of the tensor fitter.""" # Construct a noise model where readout has errors of different strengths. noise_model = noise.NoiseModel() # big error read_err0 = noise.errors.readout_error.ReadoutError([[0.90, 0.10], [0.25, 0.75]]) # ideal read_err1 = noise.errors.readout_error.ReadoutError([[1.00, 0.00], [0.00, 1.00]]) # small error read_err2 = noise.errors.readout_error.ReadoutError([[0.98, 0.02], [0.03, 0.97]]) noise_model.add_readout_error(read_err0, (0,)) noise_model.add_readout_error(read_err1, (1,)) noise_model.add_readout_error(read_err2, (2,)) mit_pattern = [[idx] for idx in range(3)] backend = Aer.get_backend("aer_simulator") backend.set_options(seed_simulator=123) with self.assertWarns(DeprecationWarning): mit_circuits = build_measurement_error_mitigation_circuits( [0, 1, 2], TensoredMeasFitter, backend, backend_config={}, compile_config={}, mit_pattern=mit_pattern, ) result = execute(mit_circuits[0], backend, noise_model=noise_model).result() fitter = TensoredMeasFitter(result, mit_pattern=mit_pattern) cal_matrices = fitter.cal_matrices # Check that permutations and permuted subsets match. for subset in [[1, 0], [1, 2], [0, 2], [2, 0, 1]]: with self.subTest(subset=subset): with self.assertWarns(DeprecationWarning): new_fitter = fitter.subset_fitter(subset) for idx, qubit in enumerate(subset): self.assertTrue(np.allclose(new_fitter.cal_matrices[idx], cal_matrices[qubit])) self.assertRaisesRegex( QiskitError, "Qubit 3 is not in the mit pattern", fitter.subset_fitter, [0, 2, 3], ) # Test that we properly correct a circuit with permuted measurements. circuit = QuantumCircuit(3, 3) circuit.x(range(3)) circuit.measure(1, 0) circuit.measure(2, 1) circuit.measure(0, 2) result = execute( circuit, backend, noise_model=noise_model, shots=1000, seed_simulator=0 ).result() with self.subTest(subset=subset): with self.assertWarns(DeprecationWarning): new_result = fitter.subset_fitter([1, 2, 0]).filter.apply(result) # The noisy result should have a poor 111 state, the mit. result should be good. self.assertTrue(result.get_counts()["111"] < 800) self.assertTrue(new_result.get_counts()["111"] > 990) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests evaluator of auxiliary operators for algorithms.""" from __future__ import annotations import unittest from typing import Tuple from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import ddt, data from qiskit_algorithms.list_or_dict import ListOrDict from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit_algorithms import estimate_observables from qiskit.primitives import Estimator from qiskit.quantum_info import Statevector, SparsePauliOp from qiskit import QuantumCircuit from qiskit.circuit.library import EfficientSU2 from qiskit.opflow import PauliSumOp from qiskit.utils import algorithm_globals @ddt class TestObservablesEvaluator(QiskitAlgorithmsTestCase): """Tests evaluator of auxiliary operators for algorithms.""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed self.threshold = 1e-8 def get_exact_expectation( self, ansatz: QuantumCircuit, observables: ListOrDict[BaseOperator | PauliSumOp] ): """ Calculates the exact expectation to be used as an expected result for unit tests. """ if isinstance(observables, dict): observables_list = list(observables.values()) else: observables_list = observables # the exact value is a list of (mean, (variance, shots)) where we expect 0 variance and # 0 shots exact = [ (Statevector(ansatz).expectation_value(observable), {}) for observable in observables_list ] if isinstance(observables, dict): return dict(zip(observables.keys(), exact)) return exact def _run_test( self, expected_result: ListOrDict[Tuple[complex, complex]], quantum_state: QuantumCircuit, decimal: int, observables: ListOrDict[BaseOperator | PauliSumOp], estimator: Estimator, ): result = estimate_observables(estimator, quantum_state, observables, None, self.threshold) if isinstance(observables, dict): np.testing.assert_equal(list(result.keys()), list(expected_result.keys())) means = [element[0] for element in result.values()] expected_means = [element[0] for element in expected_result.values()] np.testing.assert_array_almost_equal(means, expected_means, decimal=decimal) vars_and_shots = [element[1] for element in result.values()] expected_vars_and_shots = [element[1] for element in expected_result.values()] np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots) else: means = [element[0] for element in result] expected_means = [element[0] for element in expected_result] np.testing.assert_array_almost_equal(means, expected_means, decimal=decimal) vars_and_shots = [element[1] for element in result] expected_vars_and_shots = [element[1] for element in expected_result] np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots) @data( [ PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]), PauliSumOp.from_list([("II", 2.0)]), ], [ PauliSumOp.from_list([("ZZ", 2.0)]), ], { "op1": PauliSumOp.from_list([("II", 2.0)]), "op2": PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]), }, { "op1": PauliSumOp.from_list([("ZZ", 2.0)]), }, [], {}, ) def test_estimate_observables(self, observables: ListOrDict[BaseOperator | PauliSumOp]): """Tests evaluator of auxiliary operators for algorithms.""" ansatz = EfficientSU2(2) parameters = np.array( [1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0], dtype=float, ) bound_ansatz = ansatz.bind_parameters(parameters) states = bound_ansatz expected_result = self.get_exact_expectation(bound_ansatz, observables) estimator = Estimator() decimal = 6 self._run_test( expected_result, states, decimal, observables, estimator, ) def test_estimate_observables_zero_op(self): """Tests if a zero operator is handled correctly.""" ansatz = EfficientSU2(2) parameters = np.array( [1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0], dtype=float, ) bound_ansatz = ansatz.bind_parameters(parameters) state = bound_ansatz estimator = Estimator() observables = [SparsePauliOp(["XX", "YY"]), 0] result = estimate_observables(estimator, state, observables, None, self.threshold) expected_result = [(0.015607318055509564, {}), (0.0, {})] means = [element[0] for element in result] expected_means = [element[0] for element in expected_result] np.testing.assert_array_almost_equal(means, expected_means, decimal=0.01) vars_and_shots = [element[1] for element in result] expected_vars_and_shots = [element[1] for element in expected_result] np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots) def test_estimate_observables_shots(self): """Tests that variances and shots are returned properly.""" ansatz = EfficientSU2(2) parameters = np.array( [1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0], dtype=float, ) bound_ansatz = ansatz.bind_parameters(parameters) state = bound_ansatz estimator = Estimator(options={"shots": 2048}) with self.assertWarns(DeprecationWarning): observables = [PauliSumOp.from_list([("ZZ", 2.0)])] result = estimate_observables(estimator, state, observables, None, self.threshold) exact_result = self.get_exact_expectation(bound_ansatz, observables) expected_result = [(exact_result[0][0], {"variance": 1.0898, "shots": 2048})] means = [element[0] for element in result] expected_means = [element[0] for element in expected_result] np.testing.assert_array_almost_equal(means, expected_means, decimal=0.01) vars_and_shots = [element[1] for element in result] expected_vars_and_shots = [element[1] for element in expected_result] for computed, expected in zip(vars_and_shots, expected_vars_and_shots): self.assertAlmostEqual(computed.pop("variance"), expected.pop("variance"), 2) self.assertEqual(computed.pop("shots"), expected.pop("shots")) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test phase estimation""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy as np from qiskit.circuit.library import ZGate, XGate, HGate, IGate from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector, Operator from qiskit.synthesis import MatrixExponential, SuzukiTrotter from qiskit.primitives import Sampler from qiskit_algorithms import PhaseEstimationScale from qiskit_algorithms.phase_estimators import ( PhaseEstimation, HamiltonianPhaseEstimation, IterativePhaseEstimation, ) import qiskit from qiskit import QuantumCircuit from qiskit.opflow import ( H, X, Y, Z, I, StateFn, PauliTrotterEvolution, MatrixEvolution, PauliSumOp, ) from qiskit.test import slow_test @ddt class TestHamiltonianPhaseEstimation(QiskitAlgorithmsTestCase): """Tests for obtaining eigenvalues from phase estimation""" def hamiltonian_pe( self, hamiltonian, state_preparation=None, num_evaluation_qubits=6, backend=None, evolution=None, bound=None, ): """Run HamiltonianPhaseEstimation and return result with all phases.""" if backend is None: backend = qiskit.BasicAer.get_backend("statevector_simulator") with self.assertWarns(DeprecationWarning): quantum_instance = qiskit.utils.QuantumInstance(backend=backend, shots=10000) with self.assertWarns(DeprecationWarning): phase_est = HamiltonianPhaseEstimation( num_evaluation_qubits=num_evaluation_qubits, quantum_instance=quantum_instance ) result = phase_est.estimate( hamiltonian=hamiltonian, state_preparation=state_preparation, evolution=evolution, bound=bound, ) return result @data(MatrixEvolution(), PauliTrotterEvolution("suzuki", 4)) def test_pauli_sum_1(self, evolution): """Two eigenvalues from Pauli sum with X, Z""" with self.assertWarns(DeprecationWarning): hamiltonian = 0.5 * X + Z state_preparation = StateFn(H.to_circuit()) result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=evolution) phase_dict = result.filter_phases(0.162, as_float=True) phases = list(phase_dict.keys()) phases.sort() self.assertAlmostEqual(phases[0], -1.125, delta=0.001) self.assertAlmostEqual(phases[1], 1.125, delta=0.001) @data(MatrixEvolution(), PauliTrotterEvolution("suzuki", 3)) def test_pauli_sum_2(self, evolution): """Two eigenvalues from Pauli sum with X, Y, Z""" with self.assertWarns(DeprecationWarning): hamiltonian = 0.5 * X + Y + Z state_preparation = None result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=evolution) phase_dict = result.filter_phases(0.1, as_float=True) phases = list(phase_dict.keys()) phases.sort() self.assertAlmostEqual(phases[0], -1.484, delta=0.001) self.assertAlmostEqual(phases[1], 1.484, delta=0.001) def test_single_pauli_op(self): """Two eigenvalues from Pauli sum with X, Y, Z""" hamiltonian = Z state_preparation = None with self.assertWarns(DeprecationWarning): result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=None) eigv = result.most_likely_eigenvalue with self.subTest("First eigenvalue"): self.assertAlmostEqual(eigv, 1.0, delta=0.001) with self.assertWarns(DeprecationWarning): state_preparation = StateFn(X.to_circuit()) result = self.hamiltonian_pe(hamiltonian, state_preparation, bound=1.05) eigv = result.most_likely_eigenvalue with self.subTest("Second eigenvalue"): self.assertAlmostEqual(eigv, -0.98, delta=0.01) @slow_test def test_H2_hamiltonian(self): """Test H2 hamiltonian""" with self.assertWarns(DeprecationWarning): hamiltonian = ( (-1.0523732457728587 * (I ^ I)) + (0.3979374248431802 * (I ^ Z)) + (-0.3979374248431802 * (Z ^ I)) + (-0.011280104256235324 * (Z ^ Z)) + (0.18093119978423147 * (X ^ X)) ) state_preparation = StateFn((I ^ H).to_circuit()) evo = PauliTrotterEvolution(trotter_mode="suzuki", reps=4) with self.assertWarns(DeprecationWarning): result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=evo) with self.subTest("Most likely eigenvalues"): self.assertAlmostEqual(result.most_likely_eigenvalue, -1.855, delta=0.001) with self.subTest("Most likely phase"): self.assertAlmostEqual(result.phase, 0.5937, delta=0.001) with self.subTest("All eigenvalues"): phase_dict = result.filter_phases(0.1) phases = list(phase_dict.keys()) self.assertAlmostEqual(phases[0], -0.8979, delta=0.001) self.assertAlmostEqual(phases[1], -1.8551, delta=0.001) self.assertAlmostEqual(phases[2], -1.2376, delta=0.001) def test_matrix_evolution(self): """1Q Hamiltonian with MatrixEvolution""" with self.assertWarns(DeprecationWarning): hamiltonian = (0.5 * X) + (0.6 * Y) + (0.7 * I) state_preparation = None result = self.hamiltonian_pe( hamiltonian, state_preparation, evolution=MatrixEvolution() ) phase_dict = result.filter_phases(0.2, as_float=True) phases = list(phase_dict.keys()) self.assertAlmostEqual(phases[0], 1.490, delta=0.001) self.assertAlmostEqual(phases[1], -0.090, delta=0.001) def _setup_from_bound(self, evolution, op_class): with self.assertWarns(DeprecationWarning): hamiltonian = 0.5 * X + Y + Z state_preparation = None bound = 1.2 * sum(abs(hamiltonian.coeff * coeff) for coeff in hamiltonian.coeffs) if op_class == "MatrixOp": hamiltonian = hamiltonian.to_matrix_op() backend = qiskit.BasicAer.get_backend("statevector_simulator") with self.assertWarns(DeprecationWarning): qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) with self.assertWarns(DeprecationWarning): phase_est = HamiltonianPhaseEstimation(num_evaluation_qubits=6, quantum_instance=qi) result = phase_est.estimate( hamiltonian=hamiltonian, bound=bound, evolution=evolution, state_preparation=state_preparation, ) return result def test_from_bound(self): """HamiltonianPhaseEstimation with bound""" with self.assertWarns(DeprecationWarning): for op_class in ("SummedOp", "MatrixOp"): result = self._setup_from_bound(MatrixEvolution(), op_class) cutoff = 0.01 phases = result.filter_phases(cutoff) with self.subTest(f"test phases has the correct length: {op_class}"): self.assertEqual(len(phases), 2) with self.subTest(f"test scaled phases are correct: {op_class}"): self.assertEqual(list(phases.keys()), [1.5, -1.5]) phases = result.filter_phases(cutoff, scaled=False) with self.subTest(f"test unscaled phases are correct: {op_class}"): self.assertEqual(list(phases.keys()), [0.25, 0.75]) def test_trotter_from_bound(self): """HamiltonianPhaseEstimation with bound and Trotterization""" with self.assertWarns(DeprecationWarning): result = self._setup_from_bound( PauliTrotterEvolution(trotter_mode="suzuki", reps=3), op_class="SummedOp" ) phase_dict = result.filter_phases(0.1) phases = list(phase_dict.keys()) with self.subTest("test phases has the correct length"): self.assertEqual(len(phases), 2) with self.subTest("test phases has correct values"): self.assertAlmostEqual(phases[0], 1.5, delta=0.001) self.assertAlmostEqual(phases[1], -1.5, delta=0.001) # sampler tests def hamiltonian_pe_sampler( self, hamiltonian, state_preparation=None, num_evaluation_qubits=6, evolution=None, bound=None, uses_opflow=True, ): """Run HamiltonianPhaseEstimation and return result with all phases.""" sampler = Sampler() phase_est = HamiltonianPhaseEstimation( num_evaluation_qubits=num_evaluation_qubits, sampler=sampler ) if uses_opflow: with self.assertWarns(DeprecationWarning): result = phase_est.estimate( hamiltonian=hamiltonian, state_preparation=state_preparation, evolution=evolution, bound=bound, ) else: result = phase_est.estimate( hamiltonian=hamiltonian, state_preparation=state_preparation, evolution=evolution, bound=bound, ) return result @data(MatrixExponential(), SuzukiTrotter(reps=4)) def test_pauli_sum_1_sampler(self, evolution): """Two eigenvalues from Pauli sum with X, Z""" with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Z", 1)])) state_preparation = QuantumCircuit(1).compose(HGate()) result = self.hamiltonian_pe_sampler(hamiltonian, state_preparation, evolution=evolution) phase_dict = result.filter_phases(0.162, as_float=True) phases = list(phase_dict.keys()) phases.sort() self.assertAlmostEqual(phases[0], -1.125, delta=0.001) self.assertAlmostEqual(phases[1], 1.125, delta=0.001) @data(MatrixExponential(), SuzukiTrotter(reps=3)) def test_pauli_sum_2_sampler(self, evolution): """Two eigenvalues from Pauli sum with X, Y, Z""" with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Z", 1), ("Y", 1)])) state_preparation = None result = self.hamiltonian_pe_sampler(hamiltonian, state_preparation, evolution=evolution) phase_dict = result.filter_phases(0.1, as_float=True) phases = list(phase_dict.keys()) phases.sort() self.assertAlmostEqual(phases[0], -1.484, delta=0.001) self.assertAlmostEqual(phases[1], 1.484, delta=0.001) def test_single_pauli_op_sampler(self): """Two eigenvalues from Pauli sum with X, Y, Z""" hamiltonian = SparsePauliOp(Pauli("Z")) state_preparation = None result = self.hamiltonian_pe_sampler( hamiltonian, state_preparation, evolution=None, uses_opflow=False ) eigv = result.most_likely_eigenvalue with self.subTest("First eigenvalue"): self.assertAlmostEqual(eigv, 1.0, delta=0.001) state_preparation = QuantumCircuit(1).compose(XGate()) result = self.hamiltonian_pe_sampler( hamiltonian, state_preparation, bound=1.05, uses_opflow=False ) eigv = result.most_likely_eigenvalue with self.subTest("Second eigenvalue"): self.assertAlmostEqual(eigv, -0.98, delta=0.01) @data( Statevector(QuantumCircuit(2).compose(IGate()).compose(HGate())), QuantumCircuit(2).compose(IGate()).compose(HGate()), ) def test_H2_hamiltonian_sampler(self, state_preparation): """Test H2 hamiltonian""" with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp( SparsePauliOp.from_list( [ ("II", -1.0523732457728587), ("IZ", 0.3979374248431802), ("ZI", -0.3979374248431802), ("ZZ", -0.011280104256235324), ("XX", 0.18093119978423147), ] ) ) evo = SuzukiTrotter(reps=4) result = self.hamiltonian_pe_sampler(hamiltonian, state_preparation, evolution=evo) with self.subTest("Most likely eigenvalues"): self.assertAlmostEqual(result.most_likely_eigenvalue, -1.855, delta=0.001) with self.subTest("Most likely phase"): self.assertAlmostEqual(result.phase, 0.5937, delta=0.001) with self.subTest("All eigenvalues"): phase_dict = result.filter_phases(0.1) phases = sorted(phase_dict.keys()) self.assertAlmostEqual(phases[0], -1.8551, delta=0.001) self.assertAlmostEqual(phases[1], -1.2376, delta=0.001) self.assertAlmostEqual(phases[2], -0.8979, delta=0.001) def test_matrix_evolution_sampler(self): """1Q Hamiltonian with MatrixEvolution""" with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Y", 0.6), ("I", 0.7)])) state_preparation = None result = self.hamiltonian_pe_sampler( hamiltonian, state_preparation, evolution=MatrixExponential() ) phase_dict = result.filter_phases(0.2, as_float=True) phases = sorted(phase_dict.keys()) self.assertAlmostEqual(phases[0], -0.090, delta=0.001) self.assertAlmostEqual(phases[1], 1.490, delta=0.001) @ddt class TestPhaseEstimation(QiskitAlgorithmsTestCase): """Evolution tests.""" def one_phase( self, unitary_circuit, state_preparation=None, backend_type=None, phase_estimator=None, num_iterations=6, ): """Run phase estimation with operator, eigenvalue pair `unitary_circuit`, `state_preparation`. Return the estimated phase as a value in :math:`[0,1)`. """ if backend_type is None: backend_type = "qasm_simulator" backend = qiskit.BasicAer.get_backend(backend_type) if phase_estimator is None: phase_estimator = IterativePhaseEstimation with self.assertWarns(DeprecationWarning): qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) with self.assertWarns(DeprecationWarning): if phase_estimator == IterativePhaseEstimation: p_est = IterativePhaseEstimation(num_iterations=num_iterations, quantum_instance=qi) elif phase_estimator == PhaseEstimation: p_est = PhaseEstimation(num_evaluation_qubits=6, quantum_instance=qi) else: raise ValueError("Unrecognized phase_estimator") result = p_est.estimate(unitary=unitary_circuit, state_preparation=state_preparation) phase = result.phase return phase @data( (X.to_circuit(), 0.5, "statevector_simulator", IterativePhaseEstimation), (X.to_circuit(), 0.5, "qasm_simulator", IterativePhaseEstimation), (None, 0.0, "qasm_simulator", IterativePhaseEstimation), (X.to_circuit(), 0.5, "qasm_simulator", PhaseEstimation), (None, 0.0, "qasm_simulator", PhaseEstimation), (X.to_circuit(), 0.5, "statevector_simulator", PhaseEstimation), ) @unpack def test_qpe_Z(self, state_preparation, expected_phase, backend_type, phase_estimator): """eigenproblem Z, |0> and |1>""" unitary_circuit = Z.to_circuit() with self.assertWarns(DeprecationWarning): phase = self.one_phase( unitary_circuit, state_preparation, backend_type=backend_type, phase_estimator=phase_estimator, ) self.assertEqual(phase, expected_phase) @data( (H.to_circuit(), 0.0, IterativePhaseEstimation), ((H @ X).to_circuit(), 0.5, IterativePhaseEstimation), (H.to_circuit(), 0.0, PhaseEstimation), ((H @ X).to_circuit(), 0.5, PhaseEstimation), ) @unpack def test_qpe_X_plus_minus(self, state_preparation, expected_phase, phase_estimator): """eigenproblem X, (|+>, |->)""" unitary_circuit = X.to_circuit() with self.assertWarns(DeprecationWarning): phase = self.one_phase( unitary_circuit, state_preparation, phase_estimator=phase_estimator ) self.assertEqual(phase, expected_phase) @data( (X.to_circuit(), 0.125, IterativePhaseEstimation), (I.to_circuit(), 0.875, IterativePhaseEstimation), (X.to_circuit(), 0.125, PhaseEstimation), (I.to_circuit(), 0.875, PhaseEstimation), ) @unpack def test_qpe_RZ(self, state_preparation, expected_phase, phase_estimator): """eigenproblem RZ, (|0>, |1>)""" alpha = np.pi / 2 unitary_circuit = QuantumCircuit(1) unitary_circuit.rz(alpha, 0) with self.assertWarns(DeprecationWarning): phase = self.one_phase( unitary_circuit, state_preparation, phase_estimator=phase_estimator ) self.assertEqual(phase, expected_phase) def test_check_num_iterations(self): """test check for num_iterations greater than zero""" unitary_circuit = X.to_circuit() state_preparation = None with self.assertRaises(ValueError): self.one_phase(unitary_circuit, state_preparation, num_iterations=-1) def phase_estimation( self, unitary_circuit, state_preparation=None, num_evaluation_qubits=6, backend=None, construct_circuit=False, ): """Run phase estimation with operator, eigenvalue pair `unitary_circuit`, `state_preparation`. Return all results """ if backend is None: backend = qiskit.BasicAer.get_backend("statevector_simulator") with self.assertWarns(DeprecationWarning): qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) with self.assertWarns(DeprecationWarning): phase_est = PhaseEstimation( num_evaluation_qubits=num_evaluation_qubits, quantum_instance=qi ) if construct_circuit: pe_circuit = phase_est.construct_circuit(unitary_circuit, state_preparation) result = phase_est.estimate_from_pe_circuit(pe_circuit, unitary_circuit.num_qubits) else: result = phase_est.estimate( unitary=unitary_circuit, state_preparation=state_preparation ) return result @data(True, False) def test_qpe_Zplus(self, construct_circuit): """superposition eigenproblem Z, |+>""" unitary_circuit = Z.to_circuit() state_preparation = H.to_circuit() # prepare |+> with self.assertWarns(DeprecationWarning): result = self.phase_estimation( unitary_circuit, state_preparation, backend=qiskit.BasicAer.get_backend("statevector_simulator"), construct_circuit=construct_circuit, ) phases = result.filter_phases(1e-15, as_float=True) with self.subTest("test phases has correct values"): self.assertEqual(list(phases.keys()), [0.0, 0.5]) with self.subTest("test phases has correct probabilities"): np.testing.assert_allclose(list(phases.values()), [0.5, 0.5]) with self.subTest("test bitstring representation"): phases = result.filter_phases(1e-15, as_float=False) self.assertEqual(list(phases.keys()), ["000000", "100000"]) # sampler tests def one_phase_sampler( self, unitary_circuit, state_preparation=None, phase_estimator=None, num_iterations=6, shots=None, ): """Run phase estimation with operator, eigenvalue pair `unitary_circuit`, `state_preparation`. Return the estimated phase as a value in :math:`[0,1)`. """ if shots is not None: options = {"shots": shots} else: options = {} sampler = Sampler(options=options) if phase_estimator is None: phase_estimator = IterativePhaseEstimation if phase_estimator == IterativePhaseEstimation: p_est = IterativePhaseEstimation(num_iterations=num_iterations, sampler=sampler) elif phase_estimator == PhaseEstimation: p_est = PhaseEstimation(num_evaluation_qubits=6, sampler=sampler) else: raise ValueError("Unrecognized phase_estimator") result = p_est.estimate(unitary=unitary_circuit, state_preparation=state_preparation) phase = result.phase return phase @data( (QuantumCircuit(1).compose(XGate()), 0.5, None, IterativePhaseEstimation), (QuantumCircuit(1).compose(XGate()), 0.5, 1000, IterativePhaseEstimation), (None, 0.0, 1000, IterativePhaseEstimation), (QuantumCircuit(1).compose(XGate()), 0.5, 1000, PhaseEstimation), (None, 0.0, 1000, PhaseEstimation), (QuantumCircuit(1).compose(XGate()), 0.5, None, PhaseEstimation), ) @unpack def test_qpe_Z_sampler(self, state_preparation, expected_phase, shots, phase_estimator): """eigenproblem Z, |0> and |1>""" unitary_circuit = QuantumCircuit(1).compose(ZGate()) phase = self.one_phase_sampler( unitary_circuit, state_preparation=state_preparation, phase_estimator=phase_estimator, shots=shots, ) self.assertEqual(phase, expected_phase) @data( (QuantumCircuit(1).compose(HGate()), 0.0, IterativePhaseEstimation), (QuantumCircuit(1).compose(HGate()).compose(ZGate()), 0.5, IterativePhaseEstimation), (QuantumCircuit(1).compose(HGate()), 0.0, PhaseEstimation), (QuantumCircuit(1).compose(HGate()).compose(ZGate()), 0.5, PhaseEstimation), ) @unpack def test_qpe_X_plus_minus_sampler(self, state_preparation, expected_phase, phase_estimator): """eigenproblem X, (|+>, |->)""" unitary_circuit = QuantumCircuit(1).compose(XGate()) phase = self.one_phase_sampler( unitary_circuit, state_preparation, phase_estimator, ) self.assertEqual(phase, expected_phase) @data( (QuantumCircuit(1).compose(XGate()), 0.125, IterativePhaseEstimation), (QuantumCircuit(1).compose(IGate()), 0.875, IterativePhaseEstimation), (QuantumCircuit(1).compose(XGate()), 0.125, PhaseEstimation), (QuantumCircuit(1).compose(IGate()), 0.875, PhaseEstimation), ) @unpack def test_qpe_RZ_sampler(self, state_preparation, expected_phase, phase_estimator): """eigenproblem RZ, (|0>, |1>)""" alpha = np.pi / 2 unitary_circuit = QuantumCircuit(1) unitary_circuit.rz(alpha, 0) phase = self.one_phase_sampler( unitary_circuit, state_preparation, phase_estimator, ) self.assertEqual(phase, expected_phase) @data( ((X ^ X).to_circuit(), 0.25, IterativePhaseEstimation), ((I ^ X).to_circuit(), 0.125, IterativePhaseEstimation), ((X ^ X).to_circuit(), 0.25, PhaseEstimation), ((I ^ X).to_circuit(), 0.125, PhaseEstimation), ) @unpack def test_qpe_two_qubit_unitary(self, state_preparation, expected_phase, phase_estimator): """two qubit unitary T ^ T""" unitary_circuit = QuantumCircuit(2) unitary_circuit.t(0) unitary_circuit.t(1) phase = self.one_phase_sampler( unitary_circuit, state_preparation, phase_estimator, ) self.assertEqual(phase, expected_phase) def test_check_num_iterations_sampler(self): """test check for num_iterations greater than zero""" unitary_circuit = QuantumCircuit(1).compose(XGate()) state_preparation = None with self.assertRaises(ValueError): self.one_phase_sampler(unitary_circuit, state_preparation, num_iterations=-1) def test_phase_estimation_scale_from_operator(self): """test that PhaseEstimationScale from_pauli_sum works with Operator""" circ = QuantumCircuit(2) op = Operator(circ) scale = PhaseEstimationScale.from_pauli_sum(op) self.assertEqual(scale._bound, 4.0) def phase_estimation_sampler( self, unitary_circuit, sampler: Sampler, state_preparation=None, num_evaluation_qubits=6, construct_circuit=False, ): """Run phase estimation with operator, eigenvalue pair `unitary_circuit`, `state_preparation`. Return all results """ phase_est = PhaseEstimation(num_evaluation_qubits=num_evaluation_qubits, sampler=sampler) if construct_circuit: pe_circuit = phase_est.construct_circuit(unitary_circuit, state_preparation) result = phase_est.estimate_from_pe_circuit(pe_circuit, unitary_circuit.num_qubits) else: result = phase_est.estimate( unitary=unitary_circuit, state_preparation=state_preparation ) return result @data(True, False) def test_qpe_Zplus_sampler(self, construct_circuit): """superposition eigenproblem Z, |+>""" unitary_circuit = QuantumCircuit(1).compose(ZGate()) state_preparation = QuantumCircuit(1).compose(HGate()) # prepare |+> sampler = Sampler() result = self.phase_estimation_sampler( unitary_circuit, sampler, state_preparation, construct_circuit=construct_circuit, ) phases = result.filter_phases(1e-15, as_float=True) with self.subTest("test phases has correct values"): self.assertEqual(list(phases.keys()), [0.0, 0.5]) with self.subTest("test phases has correct probabilities"): np.testing.assert_allclose(list(phases.values()), [0.5, 0.5]) with self.subTest("test bitstring representation"): phases = result.filter_phases(1e-15, as_float=False) self.assertEqual(list(phases.keys()), ["000000", "100000"]) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the QAOA algorithm.""" import unittest from functools import partial from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np import rustworkx as rx from ddt import ddt, idata, unpack from scipy.optimize import minimize as scipy_minimize from qiskit import QuantumCircuit from qiskit_algorithms.minimum_eigensolvers import QAOA from qiskit_algorithms.optimizers import COBYLA, NELDER_MEAD from qiskit.circuit import Parameter from qiskit.primitives import Sampler from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.result import QuasiDistribution from qiskit.utils import algorithm_globals W1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) P1 = 1 M1 = SparsePauliOp.from_list( [ ("IIIX", 1), ("IIXI", 1), ("IXII", 1), ("XIII", 1), ] ) S1 = {"0101", "1010"} W2 = np.array( [ [0.0, 8.0, -9.0, 0.0], [8.0, 0.0, 7.0, 9.0], [-9.0, 7.0, 0.0, -8.0], [0.0, 9.0, -8.0, 0.0], ] ) P2 = 1 M2 = None S2 = {"1011", "0100"} CUSTOM_SUPERPOSITION = [1 / np.sqrt(15)] * 15 + [0] @ddt class TestQAOA(QiskitAlgorithmsTestCase): """Test QAOA with MaxCut.""" def setUp(self): super().setUp() self.seed = 10598 algorithm_globals.random_seed = self.seed self.sampler = Sampler() @idata( [ [W1, P1, M1, S1], [W2, P2, M2, S2], ] ) @unpack def test_qaoa(self, w, reps, mixer, solutions): """QAOA test""" self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", reps, w) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) @idata( [ [W1, P1, S1], [W2, P2, S2], ] ) @unpack def test_qaoa_qc_mixer(self, w, prob, solutions): """QAOA test with a mixer as a parameterized circuit""" self.log.debug( "Testing %s-step QAOA with MaxCut on graph with a mixer as a parameterized circuit\n%s", prob, w, ) optimizer = COBYLA() qubit_op, _ = self._get_operator(w) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) theta = Parameter("θ") mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) def test_qaoa_qc_mixer_many_parameters(self): """QAOA test with a mixer as a parameterized circuit with the num of parameters > 1.""" optimizer = COBYLA() qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) for i in range(num_qubits): theta = Parameter("θ" + str(i)) mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) self.log.debug(x) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, S1) def test_qaoa_qc_mixer_no_parameters(self): """QAOA test with a mixer as a parameterized circuit with zero parameters.""" qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) # just arbitrary circuit mixer.rx(np.pi / 2, range(num_qubits)) qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) # we just assert that we get a result, it is not meaningful. self.assertIsNotNone(result.eigenstate) def test_change_operator_size(self): """QAOA change operator size test""" qubit_op, _ = self._get_operator( np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) ) qaoa = QAOA(self.sampler, COBYLA(), reps=1) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 4x4"): self.assertIn(graph_solution, {"0101", "1010"}) qubit_op, _ = self._get_operator( np.array( [ [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], ] ) ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 6x6"): self.assertIn(graph_solution, {"010101", "101010"}) @idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]]) @unpack def test_qaoa_initial_point(self, w, solutions, init_pt): """Check first parameter value used is initial point as expected""" qubit_op, _ = self._get_operator(w) first_pt = [] def cb_callback(eval_count, parameters, mean, metadata): nonlocal first_pt if eval_count == 1: first_pt = list(parameters) qaoa = QAOA( self.sampler, COBYLA(), initial_point=init_pt, callback=cb_callback, ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest("Initial Point"): # If None the preferred random initial point of QAOA variational form if init_pt is None: self.assertLess(result.eigenvalue, -0.97) else: self.assertListEqual(init_pt, first_pt) with self.subTest("Solution"): self.assertIn(graph_solution, solutions) def test_qaoa_random_initial_point(self): """QAOA random initial point""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) self.assertLess(result.eigenvalue, -0.97) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA( self.sampler, partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}), ) result = qaoa.compute_minimum_eigenvalue(qubit_op) self.assertEqual(result.cost_function_evals, 5) def _get_operator(self, weight_matrix): """Generate Hamiltonian for the max-cut problem of a graph. Args: weight_matrix (numpy.ndarray) : adjacency matrix. Returns: PauliSumOp: operator for the Hamiltonian float: a constant shift for the obj function. """ num_nodes = weight_matrix.shape[0] pauli_list = [] shift = 0 for i in range(num_nodes): for j in range(i): if weight_matrix[i, j] != 0: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))]) shift -= 0.5 * weight_matrix[i, j] lst = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list] return SparsePauliOp.from_list(lst), shift def _get_graph_solution(self, x: np.ndarray) -> str: """Get graph solution from binary string. Args: x : binary string as numpy array. Returns: a graph solution as string. """ return "".join([str(int(i)) for i in 1 - x]) def _sample_most_likely(self, state_vector: QuasiDistribution) -> np.ndarray: """Compute the most likely binary string from state vector. Args: state_vector: Quasi-distribution. Returns: Binary string as numpy.ndarray of ints. """ values = list(state_vector.values()) n = int(np.log2(len(values))) k = np.argmax(np.abs(values)) x = np.zeros(n) for i in range(n): x[i] = k % 2 k >>= 1 return x if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Skip Qobj Validation""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer from qiskit.utils import QuantumInstance from qiskit.exceptions import QiskitError def _compare_dict(dict1, dict2): equal = True for key1, value1 in dict1.items(): if key1 not in dict2: equal = False break if value1 != dict2[key1]: equal = False break return equal class TestSkipQobjValidation(QiskitAlgorithmsTestCase): """Test Skip Qobj Validation""" def setUp(self): super().setUp() self.random_seed = 10598 # ┌───┐ ░ ┌─┐ ░ # q0_0: ┤ H ├──■───░─┤M├─░──── # └───┘┌─┴─┐ ░ └╥┘ ░ ┌─┐ # q0_1: ─────┤ X ├─░──╫──░─┤M├ # └───┘ ░ ║ ░ └╥┘ # c0: 2/══════════════╩═════╩═ # 0 1 qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) # Ensure qubit 0 is measured before qubit 1 qc.barrier(qr) qc.measure(qr[0], cr[0]) qc.barrier(qr) qc.measure(qr[1], cr[1]) self.qc = qc self.backend = BasicAer.get_backend("qasm_simulator") def test_wo_backend_options(self): """without backend options test""" with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( self.backend, seed_transpiler=self.random_seed, seed_simulator=self.random_seed, shots=1024, ) # run without backend_options and without noise res_wo_bo = quantum_instance.execute(self.qc).get_counts(self.qc) self.assertGreaterEqual(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() quantum_instance.skip_qobj_validation = True res_wo_bo_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) self.assertGreaterEqual(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertTrue(_compare_dict(res_wo_bo, res_wo_bo_skip_validation)) def test_w_backend_options(self): """with backend options test""" # run with backend_options with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( self.backend, seed_transpiler=self.random_seed, seed_simulator=self.random_seed, shots=1024, backend_options={"initial_statevector": [0.5, 0.5, 0.5, 0.5]}, ) res_w_bo = quantum_instance.execute(self.qc).get_counts(self.qc) self.assertGreaterEqual(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() quantum_instance.skip_qobj_validation = True res_w_bo_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) self.assertGreaterEqual(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertTrue(_compare_dict(res_w_bo, res_w_bo_skip_validation)) def test_w_noise(self): """with noise test""" # build noise model # Asymmetric readout error on qubit-0 only try: from qiskit.providers.aer.noise import NoiseModel from qiskit import Aer self.backend = Aer.get_backend("qasm_simulator") except ImportError as ex: self.skipTest(f"Aer doesn't appear to be installed. Error: '{str(ex)}'") return probs_given0 = [0.9, 0.1] probs_given1 = [0.3, 0.7] noise_model = NoiseModel() noise_model.add_readout_error([probs_given0, probs_given1], [0]) with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( self.backend, seed_transpiler=self.random_seed, seed_simulator=self.random_seed, shots=1024, noise_model=noise_model, ) res_w_noise = quantum_instance.execute(self.qc).get_counts(self.qc) quantum_instance.skip_qobj_validation = True res_w_noise_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) self.assertTrue(_compare_dict(res_w_noise, res_w_noise_skip_validation)) with self.assertWarns(DeprecationWarning): # BasicAer should fail: with self.assertRaises(QiskitError): _ = QuantumInstance(BasicAer.get_backend("qasm_simulator"), noise_model=noise_model) with self.assertRaises(QiskitError): quantum_instance = QuantumInstance(BasicAer.get_backend("qasm_simulator")) quantum_instance.set_config(noise_model=noise_model) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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 unittest import qiskit from qiskit.circuit.library import TwoLocal from qiskit import BasicAer from qiskit.utils import QuantumInstance from qiskit.opflow import Z, I from volta.vqd import VQD from volta.utils import classical_solver class TestVQDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="swap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] message = ( "VQD with SWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))" ) self.assertAlmostEqual(want, got, decimal_place, message) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] message = "VQD with SWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))" self.assertAlmostEqual(want, got, decimal_place, message) class TestVQDDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() # backend = BasicAer.get_backend("qasm_simulator") backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="dswap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class TestVQDAmplitude(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="amplitude", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class VQDRaiseError(unittest.TestCase): def test_not_implemented_overlapping_method(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000 ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) with self.assertRaises(NotImplementedError): VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="test", ), if __name__ == "__main__": unittest.main(argv=[""], verbosity=2, exit=False)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the variational quantum eigensolver algorithm.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial import numpy as np from scipy.optimize import minimize as scipy_minimize from ddt import data, ddt from qiskit import QuantumCircuit from qiskit_algorithms import AlgorithmError from qiskit_algorithms.gradients import ParamShiftEstimatorGradient from qiskit_algorithms.minimum_eigensolvers import VQE from qiskit_algorithms.optimizers import ( CG, COBYLA, GradientDescent, L_BFGS_B, OptimizerResult, P_BFGS, QNSPSA, SLSQP, SPSA, TNC, ) from qiskit_algorithms.state_fidelities import ComputeUncompute from qiskit.circuit.library import RealAmplitudes, TwoLocal from qiskit.opflow import PauliSumOp, TwoQubitReduction from qiskit.quantum_info import SparsePauliOp, Operator, Pauli from qiskit.primitives import Estimator, Sampler from qiskit.utils import algorithm_globals # pylint: disable=invalid-name def _mock_optimizer(fun, x0, jac=None, bounds=None, inputs=None) -> OptimizerResult: """A mock of a callable that can be used as minimizer in the VQE.""" result = OptimizerResult() result.x = np.zeros_like(x0) result.fun = fun(result.x) result.nit = 0 if inputs is not None: inputs.update({"fun": fun, "x0": x0, "jac": jac, "bounds": bounds}) return result @ddt class TestVQE(QiskitAlgorithmsTestCase): """Test VQE""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed self.h2_op = SparsePauliOp( ["II", "IZ", "ZI", "ZZ", "XX"], coeffs=[ -1.052373245772859, 0.39793742484318045, -0.39793742484318045, -0.01128010425623538, 0.18093119978423156, ], ) self.h2_energy = -1.85727503 self.ryrz_wavefunction = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") self.ry_wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") @data(L_BFGS_B(), COBYLA()) def test_basic_aer_statevector(self, estimator): """Test VQE using reference Estimator.""" vqe = VQE(Estimator(), self.ryrz_wavefunction, estimator) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) with self.subTest(msg="test eigenvalue"): self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) with self.subTest(msg="test optimal_value"): self.assertAlmostEqual(result.optimal_value, self.h2_energy) with self.subTest(msg="test dimension of optimal point"): self.assertEqual(len(result.optimal_point), 16) with self.subTest(msg="assert cost_function_evals is set"): self.assertIsNotNone(result.cost_function_evals) with self.subTest(msg="assert optimizer_time is set"): self.assertIsNotNone(result.optimizer_time) with self.subTest(msg="assert optimizer_result is set"): self.assertIsNotNone(result.optimizer_result) with self.subTest(msg="assert optimizer_result."): self.assertAlmostEqual(result.optimizer_result.fun, self.h2_energy, places=5) with self.subTest(msg="assert return ansatz is set"): estimator = Estimator() job = estimator.run(result.optimal_circuit, self.h2_op, result.optimal_point) np.testing.assert_array_almost_equal(job.result().values, result.eigenvalue, 6) def test_invalid_initial_point(self): """Test the proper error is raised when the initial point has the wrong size.""" ansatz = self.ryrz_wavefunction initial_point = np.array([1]) vqe = VQE( Estimator(), ansatz, SLSQP(), initial_point=initial_point, ) with self.assertRaises(ValueError): _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_ansatz_resize(self): """Test the ansatz is properly resized if it's a blueprint circuit.""" ansatz = RealAmplitudes(1, reps=1) vqe = VQE(Estimator(), ansatz, SLSQP()) result = vqe.compute_minimum_eigenvalue(self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_invalid_ansatz_size(self): """Test an error is raised if the ansatz has the wrong number of qubits.""" ansatz = QuantumCircuit(1) ansatz.compose(RealAmplitudes(1, reps=2)) vqe = VQE(Estimator(), ansatz, SLSQP()) with self.assertRaises(AlgorithmError): _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_missing_ansatz_params(self): """Test specifying an ansatz with no parameters raises an error.""" ansatz = QuantumCircuit(self.h2_op.num_qubits) vqe = VQE(Estimator(), ansatz, SLSQP()) with self.assertRaises(AlgorithmError): vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_max_evals_grouped(self): """Test with SLSQP with max_evals_grouped.""" optimizer = SLSQP(maxiter=50, max_evals_grouped=5) vqe = VQE( Estimator(), self.ryrz_wavefunction, optimizer, ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) @data( CG(), L_BFGS_B(), P_BFGS(), SLSQP(), TNC(), ) def test_with_gradient(self, optimizer): """Test VQE using gradient primitive.""" estimator = Estimator() vqe = VQE( estimator, self.ry_wavefunction, optimizer, gradient=ParamShiftEstimatorGradient(estimator), ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_gradient_passed(self): """Test the gradient is properly passed into the optimizer.""" inputs = {} estimator = Estimator() vqe = VQE( estimator, RealAmplitudes(), partial(_mock_optimizer, inputs=inputs), gradient=ParamShiftEstimatorGradient(estimator), ) _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertIsNotNone(inputs["jac"]) def test_gradient_run(self): """Test using the gradient to calculate the minimum.""" estimator = Estimator() vqe = VQE( estimator, RealAmplitudes(), GradientDescent(maxiter=200, learning_rate=0.1), gradient=ParamShiftEstimatorGradient(estimator), ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_with_two_qubit_reduction(self): """Test the VQE using TwoQubitReduction.""" with self.assertWarns(DeprecationWarning): qubit_op = PauliSumOp.from_list( [ ("IIII", -0.8105479805373266), ("IIIZ", 0.17218393261915552), ("IIZZ", -0.22575349222402472), ("IZZI", 0.1721839326191556), ("ZZII", -0.22575349222402466), ("IIZI", 0.1209126326177663), ("IZZZ", 0.16892753870087912), ("IXZX", -0.045232799946057854), ("ZXIX", 0.045232799946057854), ("IXIX", 0.045232799946057854), ("ZXZX", -0.045232799946057854), ("ZZIZ", 0.16614543256382414), ("IZIZ", 0.16614543256382414), ("ZZZZ", 0.17464343068300453), ("ZIZI", 0.1209126326177663), ] ) tapered_qubit_op = TwoQubitReduction(num_particles=2).convert(qubit_op) vqe = VQE( Estimator(), self.ry_wavefunction, SPSA(maxiter=300, last_avg=5), ) result = vqe.compute_minimum_eigenvalue(tapered_qubit_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=2) def test_callback(self): """Test the callback on VQE.""" history = {"eval_count": [], "parameters": [], "mean": [], "metadata": []} def store_intermediate_result(eval_count, parameters, mean, metadata): history["eval_count"].append(eval_count) history["parameters"].append(parameters) history["mean"].append(mean) history["metadata"].append(metadata) optimizer = COBYLA(maxiter=3) wavefunction = self.ry_wavefunction estimator = Estimator() vqe = VQE( estimator, wavefunction, optimizer, callback=store_intermediate_result, ) vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertTrue(all(isinstance(count, int) for count in history["eval_count"])) self.assertTrue(all(isinstance(mean, float) for mean in history["mean"])) self.assertTrue(all(isinstance(metadata, dict) for metadata in history["metadata"])) for params in history["parameters"]: self.assertTrue(all(isinstance(param, float) for param in params)) def test_reuse(self): """Test re-using a VQE algorithm instance.""" ansatz = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") vqe = VQE(Estimator(), ansatz, SLSQP(maxiter=300)) with self.subTest(msg="assert VQE works once all info is available"): result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) operator = Operator(np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]])) with self.subTest(msg="assert vqe works on re-use."): result = vqe.compute_minimum_eigenvalue(operator=operator) self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5) def test_vqe_optimizer_reuse(self): """Test running same VQE twice to re-use optimizer, then switch optimizer""" vqe = VQE( Estimator(), self.ryrz_wavefunction, SLSQP(), ) def run_check(): result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) run_check() with self.subTest("Optimizer re-use."): run_check() with self.subTest("Optimizer replace."): vqe.optimizer = L_BFGS_B() run_check() def test_default_batch_evaluation_on_spsa(self): """Test the default batching works.""" ansatz = TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz") wrapped_estimator = Estimator() inner_estimator = Estimator() callcount = {"estimator": 0} def wrapped_estimator_run(*args, **kwargs): kwargs["callcount"]["estimator"] += 1 return inner_estimator.run(*args, **kwargs) wrapped_estimator.run = partial(wrapped_estimator_run, callcount=callcount) spsa = SPSA(maxiter=5) vqe = VQE(wrapped_estimator, ansatz, spsa) _ = vqe.compute_minimum_eigenvalue(Pauli("ZZ")) # 1 calibration + 5 loss + 1 return loss expected_estimator_runs = 1 + 5 + 1 with self.subTest(msg="check callcount"): self.assertEqual(callcount["estimator"], expected_estimator_runs) with self.subTest(msg="check reset to original max evals grouped"): self.assertIsNone(spsa._max_evals_grouped) def test_batch_evaluate_with_qnspsa(self): """Test batch evaluating with QNSPSA works.""" ansatz = TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz") wrapped_sampler = Sampler() inner_sampler = Sampler() wrapped_estimator = Estimator() inner_estimator = Estimator() callcount = {"sampler": 0, "estimator": 0} def wrapped_estimator_run(*args, **kwargs): kwargs["callcount"]["estimator"] += 1 return inner_estimator.run(*args, **kwargs) def wrapped_sampler_run(*args, **kwargs): kwargs["callcount"]["sampler"] += 1 return inner_sampler.run(*args, **kwargs) wrapped_estimator.run = partial(wrapped_estimator_run, callcount=callcount) wrapped_sampler.run = partial(wrapped_sampler_run, callcount=callcount) fidelity = ComputeUncompute(wrapped_sampler) def fidelity_callable(left, right): batchsize = np.asarray(left).shape[0] job = fidelity.run(batchsize * [ansatz], batchsize * [ansatz], left, right) return job.result().fidelities qnspsa = QNSPSA(fidelity_callable, maxiter=5) qnspsa.set_max_evals_grouped(100) vqe = VQE( wrapped_estimator, ansatz, qnspsa, ) _ = vqe.compute_minimum_eigenvalue(Pauli("ZZ")) # 5 (fidelity) expected_sampler_runs = 5 # 1 calibration + 1 stddev estimation + 1 initial blocking # + 5 (1 loss + 1 blocking) + 1 return loss expected_estimator_runs = 1 + 1 + 1 + 5 * 2 + 1 self.assertEqual(callcount["sampler"], expected_sampler_runs) self.assertEqual(callcount["estimator"], expected_estimator_runs) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" vqe = VQE( Estimator(), self.ryrz_wavefunction, partial(scipy_minimize, method="L-BFGS-B", options={"maxiter": 10}), ) result = vqe.compute_minimum_eigenvalue(self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=2) def test_optimizer_callable(self): """Test passing a optimizer directly as callable.""" ansatz = RealAmplitudes(1, reps=1) vqe = VQE(Estimator(), ansatz, _mock_optimizer) result = vqe.compute_minimum_eigenvalue(SparsePauliOp("Z")) self.assertTrue(np.all(result.optimal_point == np.zeros(ansatz.num_parameters))) def test_aux_operators_list(self): """Test list-based aux_operators.""" vqe = VQE(Estimator(), self.ry_wavefunction, SLSQP(maxiter=300)) with self.subTest("Test with an empty list."): result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=[]) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertIsInstance(result.aux_operators_evaluated, list) self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): with self.assertWarns(DeprecationWarning): aux_op1 = PauliSumOp.from_list([("II", 2.0)]) aux_op2 = PauliSumOp.from_list( [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] ) aux_ops = [aux_op1, aux_op2] result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0], 2.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[1][0], 0.0, places=6) # metadata self.assertIsInstance(result.aux_operators_evaluated[0][1], dict) self.assertIsInstance(result.aux_operators_evaluated[1][1], dict) with self.subTest("Test with additional zero operator."): extra_ops = [*aux_ops, 0] result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0], 2.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[1][0], 0.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[2][0], 0.0) # metadata self.assertIsInstance(result.aux_operators_evaluated[0][1], dict) self.assertIsInstance(result.aux_operators_evaluated[1][1], dict) self.assertIsInstance(result.aux_operators_evaluated[2][1], dict) def test_aux_operators_dict(self): """Test dictionary compatibility of aux_operators""" vqe = VQE(Estimator(), self.ry_wavefunction, SLSQP(maxiter=300)) with self.subTest("Test with an empty dictionary."): result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators={}) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertIsInstance(result.aux_operators_evaluated, dict) self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): with self.assertWarns(DeprecationWarning): aux_op1 = PauliSumOp.from_list([("II", 2.0)]) aux_op2 = PauliSumOp.from_list( [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] ) aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated["aux_op1"][0], 2.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["aux_op2"][0], 0.0, places=5) # metadata self.assertIsInstance(result.aux_operators_evaluated["aux_op1"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["aux_op2"][1], dict) with self.subTest("Test with additional zero operator."): extra_ops = {**aux_ops, "zero_operator": 0} result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated["aux_op1"][0], 2.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["aux_op2"][0], 0.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["zero_operator"][0], 0.0) # metadata self.assertIsInstance(result.aux_operators_evaluated["aux_op1"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["aux_op2"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["zero_operator"][1], dict) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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 unittest import qiskit from qiskit.circuit.library import TwoLocal from qiskit import BasicAer from qiskit.utils import QuantumInstance from qiskit.opflow import Z, I from volta.vqd import VQD from volta.utils import classical_solver class TestVQDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="swap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] message = ( "VQD with SWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))" ) self.assertAlmostEqual(want, got, decimal_place, message) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] message = "VQD with SWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))" self.assertAlmostEqual(want, got, decimal_place, message) class TestVQDDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() # backend = BasicAer.get_backend("qasm_simulator") backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="dswap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class TestVQDAmplitude(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="amplitude", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class VQDRaiseError(unittest.TestCase): def test_not_implemented_overlapping_method(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000 ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) with self.assertRaises(NotImplementedError): VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="test", ), if __name__ == "__main__": unittest.main(argv=[""], verbosity=2, exit=False)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test TrotterQRTE.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy as np from scipy.linalg import expm from numpy.testing import assert_raises from qiskit_algorithms.time_evolvers import TimeEvolutionProblem, TrotterQRTE from qiskit.primitives import Estimator from qiskit import QuantumCircuit from qiskit.circuit.library import ZGate from qiskit.quantum_info import Statevector, Pauli, SparsePauliOp from qiskit.utils import algorithm_globals from qiskit.circuit import Parameter from qiskit.opflow import PauliSumOp, X, MatrixOp from qiskit.synthesis import SuzukiTrotter, QDrift @ddt class TestTrotterQRTE(QiskitAlgorithmsTestCase): """TrotterQRTE tests.""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed @data( ( None, Statevector([0.29192658 - 0.45464871j, 0.70807342 - 0.45464871j]), ), ( SuzukiTrotter(), Statevector([0.29192658 - 0.84147098j, 0.0 - 0.45464871j]), ), ) @unpack def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state): """Test for default TrotterQRTE on a single qubit.""" with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) initial_state = QuantumCircuit(1) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) trotter_qrte = TrotterQRTE(product_formula=product_formula) evolution_result_state_circuit = trotter_qrte.evolve(evolution_problem).evolved_state np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result_state_circuit).data, expected_state.data ) @data((SparsePauliOp(["X", "Z"]), None), (SparsePauliOp(["X", "Z"]), Parameter("t"))) @unpack def test_trotter_qrte_trotter(self, operator, t_param): """Test for default TrotterQRTE on a single qubit with auxiliary operators.""" if not t_param is None: operator = SparsePauliOp(operator.paulis, np.array([t_param, 1])) # LieTrotter with 1 rep aux_ops = [Pauli("X"), Pauli("Y")] initial_state = QuantumCircuit(1) time = 3 num_timesteps = 2 evolution_problem = TimeEvolutionProblem( operator, time, initial_state, aux_ops, t_param=t_param ) estimator = Estimator() expected_psi, expected_observables_result = self._get_expected_trotter_qrte( operator, time, num_timesteps, initial_state, aux_ops, t_param, ) expected_evolved_state = Statevector(expected_psi) algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator, num_timesteps=num_timesteps) evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, expected_evolved_state.data, ) aux_ops_result = evolution_result.aux_ops_evaluated expected_aux_ops_result = [ (expected_observables_result[-1][0], {"variance": 0, "shots": 0}), (expected_observables_result[-1][1], {"variance": 0, "shots": 0}), ] means = [element[0] for element in aux_ops_result] expected_means = [element[0] for element in expected_aux_ops_result] np.testing.assert_array_almost_equal(means, expected_means) vars_and_shots = [element[1] for element in aux_ops_result] expected_vars_and_shots = [element[1] for element in expected_aux_ops_result] observables_result = evolution_result.observables expected_observables_result = [ [(o, {"variance": 0, "shots": 0}) for o in eor] for eor in expected_observables_result ] means = [sub_element[0] for element in observables_result for sub_element in element] expected_means = [ sub_element[0] for element in expected_observables_result for sub_element in element ] np.testing.assert_array_almost_equal(means, expected_means) for computed, expected in zip(vars_and_shots, expected_vars_and_shots): self.assertAlmostEqual(computed.pop("variance", 0), expected["variance"], 2) self.assertEqual(computed.pop("shots", 0), expected["shots"]) @data( ( PauliSumOp(SparsePauliOp([Pauli("XY"), Pauli("YX")])), Statevector([-0.41614684 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.90929743 + 0.0j]), ), ( PauliSumOp(SparsePauliOp([Pauli("ZZ"), Pauli("ZI"), Pauli("IZ")])), Statevector([-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j]), ), ( Pauli("YY"), Statevector([0.54030231 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.84147098j]), ), ) @unpack def test_trotter_qrte_trotter_two_qubits(self, operator, expected_state): """Test for TrotterQRTE on two qubits with various types of a Hamiltonian.""" # LieTrotter with 1 rep initial_state = QuantumCircuit(2) evolution_problem = TimeEvolutionProblem(operator, 1, initial_state) trotter_qrte = TrotterQRTE() evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, expected_state.data ) @data( (QuantumCircuit(1), Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j])), ( QuantumCircuit(1).compose(ZGate(), [0]), Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j]), ), ) @unpack def test_trotter_qrte_qdrift(self, initial_state, expected_state): """Test for TrotterQRTE with QDrift.""" with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(product_formula=QDrift()) evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, expected_state.data, ) @data((Parameter("t"), {}), (None, {Parameter("x"): 2}), (None, None)) @unpack def test_trotter_qrte_trotter_param_errors(self, t_param, param_value_dict): """Test TrotterQRTE with raising errors for parameters.""" with self.assertWarns(DeprecationWarning): operator = Parameter("t") * PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( SparsePauliOp([Pauli("Z")]) ) initial_state = QuantumCircuit(1) self._run_error_test(initial_state, operator, None, None, t_param, param_value_dict) @data(([Pauli("X"), Pauli("Y")], None)) @unpack def test_trotter_qrte_trotter_aux_ops_errors(self, aux_ops, estimator): """Test TrotterQRTE with raising errors.""" with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( SparsePauliOp([Pauli("Z")]) ) initial_state = QuantumCircuit(1) self._run_error_test(initial_state, operator, aux_ops, estimator, None, None) @data( (X, QuantumCircuit(1)), (MatrixOp([[1, 1], [0, 1]]), QuantumCircuit(1)), (PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp(SparsePauliOp([Pauli("Z")])), None), ( SparsePauliOp([Pauli("X"), Pauli("Z")], np.array([Parameter("a"), Parameter("b")])), QuantumCircuit(1), ), ) @unpack def test_trotter_qrte_trotter_hamiltonian_errors(self, operator, initial_state): """Test TrotterQRTE with raising errors for evolution problem content.""" self._run_error_test(initial_state, operator, None, None, None, None) @staticmethod def _run_error_test(initial_state, operator, aux_ops, estimator, t_param, param_value_dict): time = 1 algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator) with assert_raises(ValueError): evolution_problem = TimeEvolutionProblem( operator, time, initial_state, aux_ops, t_param=t_param, param_value_map=param_value_dict, ) _ = trotter_qrte.evolve(evolution_problem) @staticmethod def _get_expected_trotter_qrte(operator, time, num_timesteps, init_state, observables, t_param): """Compute reference values for Trotter evolution via exact matrix exponentiation.""" dt = time / num_timesteps observables = [obs.to_matrix() for obs in observables] psi = Statevector(init_state).data if t_param is None: ops = [Pauli(op).to_matrix() * np.real(coeff) for op, coeff in operator.to_list()] observable_results = [] observable_results.append([np.real(np.conj(psi).dot(obs).dot(psi)) for obs in observables]) for n in range(num_timesteps): if t_param is not None: time_value = (n + 1) * dt bound = operator.assign_parameters([time_value]) ops = [Pauli(op).to_matrix() * np.real(coeff) for op, coeff in bound.to_list()] for op in ops: psi = expm(-1j * op * dt).dot(psi) observable_results.append( [np.real(np.conj(psi).dot(obs).dot(psi)) for obs in observables] ) return psi, observable_results if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. # ============================================================================= """Test Estimator Gradients""" import unittest import numpy as np from ddt import ddt, data, unpack from qiskit import QuantumCircuit from qiskit_algorithms.gradients import ( FiniteDiffEstimatorGradient, LinCombEstimatorGradient, ParamShiftEstimatorGradient, SPSAEstimatorGradient, ReverseEstimatorGradient, DerivativeType, ) from qiskit.circuit import Parameter from qiskit.circuit.library import EfficientSU2, RealAmplitudes from qiskit.circuit.library.standard_gates import RXXGate, RYYGate, RZXGate, RZZGate from qiskit.primitives import Estimator from qiskit.quantum_info import Operator, SparsePauliOp, Pauli from qiskit.quantum_info.random import random_pauli_list from qiskit.test import QiskitTestCase from .logging_primitives import LoggingEstimator gradient_factories = [ lambda estimator: FiniteDiffEstimatorGradient(estimator, epsilon=1e-6, method="central"), lambda estimator: FiniteDiffEstimatorGradient(estimator, epsilon=1e-6, method="forward"), lambda estimator: FiniteDiffEstimatorGradient(estimator, epsilon=1e-6, method="backward"), ParamShiftEstimatorGradient, LinCombEstimatorGradient, lambda estimator: ReverseEstimatorGradient(), # does not take an estimator! ] @ddt class TestEstimatorGradient(QiskitTestCase): """Test Estimator Gradient""" @data(*gradient_factories) def test_gradient_operators(self, grad): """Test the estimator gradient for different operators""" estimator = Estimator() a = Parameter("a") qc = QuantumCircuit(1) qc.h(0) qc.p(a, 0) qc.h(0) gradient = grad(estimator) op = SparsePauliOp.from_list([("Z", 1)]) correct_result = -1 / np.sqrt(2) param = [np.pi / 4] value = gradient.run([qc], [op], [param]).result().gradients[0] self.assertAlmostEqual(value[0], correct_result, 3) op = SparsePauliOp.from_list([("Z", 1)]) value = gradient.run([qc], [op], [param]).result().gradients[0] self.assertAlmostEqual(value[0], correct_result, 3) op = Operator.from_label("Z") value = gradient.run([qc], [op], [param]).result().gradients[0] self.assertAlmostEqual(value[0], correct_result, 3) @data(*gradient_factories) def test_single_circuit_observable(self, grad): """Test the estimator gradient for a single circuit and observable""" estimator = Estimator() a = Parameter("a") qc = QuantumCircuit(1) qc.h(0) qc.p(a, 0) qc.h(0) gradient = grad(estimator) op = SparsePauliOp.from_list([("Z", 1)]) correct_result = -1 / np.sqrt(2) param = [np.pi / 4] value = gradient.run(qc, op, [param]).result().gradients[0] self.assertAlmostEqual(value[0], correct_result, 3) @data(*gradient_factories) def test_gradient_p(self, grad): """Test the estimator gradient for p""" estimator = Estimator() a = Parameter("a") qc = QuantumCircuit(1) qc.h(0) qc.p(a, 0) qc.h(0) gradient = grad(estimator) op = SparsePauliOp.from_list([("Z", 1)]) param_list = [[np.pi / 4], [0], [np.pi / 2]] correct_results = [[-1 / np.sqrt(2)], [0], [-1]] for i, param in enumerate(param_list): gradients = gradient.run([qc], [op], [param]).result().gradients[0] for j, value in enumerate(gradients): self.assertAlmostEqual(value, correct_results[i][j], 3) @data(*gradient_factories) def test_gradient_u(self, grad): """Test the estimator gradient for u""" estimator = Estimator() a = Parameter("a") b = Parameter("b") c = Parameter("c") qc = QuantumCircuit(1) qc.h(0) qc.u(a, b, c, 0) qc.h(0) gradient = grad(estimator) op = SparsePauliOp.from_list([("Z", 1)]) param_list = [[np.pi / 4, 0, 0], [np.pi / 4, np.pi / 4, np.pi / 4]] correct_results = [[-0.70710678, 0.0, 0.0], [-0.35355339, -0.85355339, -0.85355339]] for i, param in enumerate(param_list): gradients = gradient.run([qc], [op], [param]).result().gradients[0] for j, value in enumerate(gradients): self.assertAlmostEqual(value, correct_results[i][j], 3) @data(*gradient_factories) def test_gradient_efficient_su2(self, grad): """Test the estimator gradient for EfficientSU2""" estimator = Estimator() qc = EfficientSU2(2, reps=1) op = SparsePauliOp.from_list([("ZI", 1)]) gradient = grad(estimator) param_list = [ [np.pi / 4 for param in qc.parameters], [np.pi / 2 for param in qc.parameters], ] correct_results = [ [ -0.35355339, -0.70710678, 0, 0.35355339, 0, -0.70710678, 0, 0, ], [0, 0, 0, 1, 0, 0, 0, 0], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [op], [param]).result().gradients[0] np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3) @data(*gradient_factories) def test_gradient_2qubit_gate(self, grad): """Test the estimator gradient for 2 qubit gates""" estimator = Estimator() for gate in [RXXGate, RYYGate, RZZGate, RZXGate]: param_list = [[np.pi / 4], [np.pi / 2]] correct_results = [ [-0.70710678], [-1], ] op = SparsePauliOp.from_list([("ZI", 1)]) for i, param in enumerate(param_list): a = Parameter("a") qc = QuantumCircuit(2) gradient = grad(estimator) if gate is RZZGate: qc.h([0, 1]) qc.append(gate(a), [qc.qubits[0], qc.qubits[1]], []) qc.h([0, 1]) else: qc.append(gate(a), [qc.qubits[0], qc.qubits[1]], []) gradients = gradient.run([qc], [op], [param]).result().gradients[0] np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3) @data(*gradient_factories) def test_gradient_parameter_coefficient(self, grad): """Test the estimator gradient for parameter variables with coefficients""" estimator = Estimator() qc = RealAmplitudes(num_qubits=2, reps=1) qc.rz(qc.parameters[0].exp() + 2 * qc.parameters[1], 0) qc.rx(3.0 * qc.parameters[0] + qc.parameters[1].sin(), 1) qc.u(qc.parameters[0], qc.parameters[1], qc.parameters[3], 1) qc.p(2 * qc.parameters[0] + 1, 0) qc.rxx(qc.parameters[0] + 2, 0, 1) gradient = grad(estimator) param_list = [[np.pi / 4 for _ in qc.parameters], [np.pi / 2 for _ in qc.parameters]] correct_results = [ [-0.7266653, -0.4905135, -0.0068606, -0.9228880], [-3.5972095, 0.10237173, -0.3117748, 0], ] op = SparsePauliOp.from_list([("ZI", 1)]) for i, param in enumerate(param_list): gradients = gradient.run([qc], [op], [param]).result().gradients[0] np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3) @data(*gradient_factories) def test_gradient_parameters(self, grad): """Test the estimator gradient for parameters""" estimator = Estimator() a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.rx(b, 0) gradient = grad(estimator) param_list = [[np.pi / 4, np.pi / 2]] correct_results = [ [-0.70710678], ] op = SparsePauliOp.from_list([("Z", 1)]) for i, param in enumerate(param_list): gradients = gradient.run([qc], [op], [param], parameters=[[a]]).result().gradients[0] np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3) # parameter order with self.subTest(msg="The order of gradients"): c = Parameter("c") qc = QuantumCircuit(1) qc.rx(a, 0) qc.rz(b, 0) qc.rx(c, 0) param_list = [[np.pi / 4, np.pi / 2, np.pi / 3]] correct_results = [ [-0.35355339, 0.61237244, -0.61237244], [-0.61237244, 0.61237244, -0.35355339], [-0.35355339, -0.61237244], [-0.61237244, -0.35355339], ] param = [[a, b, c], [c, b, a], [a, c], [c, a]] op = SparsePauliOp.from_list([("Z", 1)]) for i, p in enumerate(param): gradient = grad(estimator) gradients = ( gradient.run([qc], [op], param_list, parameters=[p]).result().gradients[0] ) np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3) @data(*gradient_factories) def test_gradient_multi_arguments(self, grad): """Test the estimator gradient for multiple arguments""" estimator = Estimator() a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc2 = QuantumCircuit(1) qc2.rx(b, 0) gradient = grad(estimator) param_list = [[np.pi / 4], [np.pi / 2]] correct_results = [ [-0.70710678], [-1], ] op = SparsePauliOp.from_list([("Z", 1)]) gradients = gradient.run([qc, qc2], [op] * 2, param_list).result().gradients np.testing.assert_allclose(gradients, correct_results, atol=1e-3) c = Parameter("c") qc3 = QuantumCircuit(1) qc3.rx(c, 0) qc3.ry(a, 0) param_list2 = [[np.pi / 4], [np.pi / 4, np.pi / 4], [np.pi / 4, np.pi / 4]] correct_results2 = [ [-0.70710678], [-0.5], [-0.5, -0.5], ] gradients2 = ( gradient.run([qc, qc3, qc3], [op] * 3, param_list2, parameters=[[a], [c], None]) .result() .gradients ) np.testing.assert_allclose(gradients2[0], correct_results2[0], atol=1e-3) np.testing.assert_allclose(gradients2[1], correct_results2[1], atol=1e-3) np.testing.assert_allclose(gradients2[2], correct_results2[2], atol=1e-3) @data(*gradient_factories) def test_gradient_validation(self, grad): """Test estimator gradient's validation""" estimator = Estimator() a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) gradient = grad(estimator) param_list = [[np.pi / 4], [np.pi / 2]] op = SparsePauliOp.from_list([("Z", 1)]) with self.assertRaises(ValueError): gradient.run([qc], [op], param_list) with self.assertRaises(ValueError): gradient.run([qc, qc], [op, op], param_list, parameters=[[a]]) with self.assertRaises(ValueError): gradient.run([qc, qc], [op], param_list, parameters=[[a]]) with self.assertRaises(ValueError): gradient.run([qc], [op], [[np.pi / 4, np.pi / 4]]) def test_spsa_gradient(self): """Test the SPSA estimator gradient""" estimator = Estimator() with self.assertRaises(ValueError): _ = SPSAEstimatorGradient(estimator, epsilon=-0.1) a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(2) qc.rx(b, 0) qc.rx(a, 1) param_list = [[1, 1]] correct_results = [[-0.84147098, 0.84147098]] op = SparsePauliOp.from_list([("ZI", 1)]) gradient = SPSAEstimatorGradient(estimator, epsilon=1e-6, seed=123) gradients = gradient.run([qc], [op], param_list).result().gradients np.testing.assert_allclose(gradients, correct_results, atol=1e-3) # multi parameters with self.subTest(msg="Multiple parameters"): gradient = SPSAEstimatorGradient(estimator, epsilon=1e-6, seed=123) param_list2 = [[1, 1], [1, 1], [3, 3]] gradients2 = ( gradient.run([qc] * 3, [op] * 3, param_list2, parameters=[None, [b], None]) .result() .gradients ) correct_results2 = [[-0.84147098, 0.84147098], [0.84147098], [-0.14112001, 0.14112001]] for grad, correct in zip(gradients2, correct_results2): np.testing.assert_allclose(grad, correct, atol=1e-3) # batch size with self.subTest(msg="Batch size"): correct_results = [[-0.84147098, 0.1682942]] gradient = SPSAEstimatorGradient(estimator, epsilon=1e-6, batch_size=5, seed=123) gradients = gradient.run([qc], [op], param_list).result().gradients np.testing.assert_allclose(gradients, correct_results, atol=1e-3) # parameter order with self.subTest(msg="The order of gradients"): gradient = SPSAEstimatorGradient(estimator, epsilon=1e-6, seed=123) c = Parameter("c") qc = QuantumCircuit(1) qc.rx(a, 0) qc.rz(b, 0) qc.rx(c, 0) op = SparsePauliOp.from_list([("Z", 1)]) param_list3 = [[np.pi / 4, np.pi / 2, np.pi / 3]] param = [[a, b, c], [c, b, a], [a, c], [c, a]] expected = [ [-0.3535525, 0.3535525, 0.3535525], [0.3535525, 0.3535525, -0.3535525], [-0.3535525, 0.3535525], [0.3535525, -0.3535525], ] for i, p in enumerate(param): gradient = SPSAEstimatorGradient(estimator, epsilon=1e-6, seed=123) gradients = ( gradient.run([qc], [op], param_list3, parameters=[p]).result().gradients[0] ) np.testing.assert_allclose(gradients, expected[i], atol=1e-3) @data(ParamShiftEstimatorGradient, LinCombEstimatorGradient) def test_gradient_random_parameters(self, grad): """Test param shift and lin comb w/ random parameters""" rng = np.random.default_rng(123) qc = RealAmplitudes(num_qubits=3, reps=1) params = qc.parameters qc.rx(3.0 * params[0] + params[1].sin(), 0) qc.ry(params[0].exp() + 2 * params[1], 1) qc.rz(params[0] * params[1] - params[2], 2) qc.p(2 * params[0] + 1, 0) qc.u(params[0].sin(), params[1] - 2, params[2] * params[3], 1) qc.sx(2) qc.rxx(params[0].sin(), 1, 2) qc.ryy(params[1].cos(), 2, 0) qc.rzz(params[2] * 2, 0, 1) qc.crx(params[0].exp(), 1, 2) qc.cry(params[1].arctan(), 2, 0) qc.crz(params[2] * -2, 0, 1) qc.dcx(0, 1) qc.csdg(0, 1) qc.toffoli(0, 1, 2) qc.iswap(0, 2) qc.swap(1, 2) qc.global_phase = params[0] * params[1] + params[2].cos().exp() size = 10 op = SparsePauliOp(random_pauli_list(num_qubits=qc.num_qubits, size=size, seed=rng)) op.coeffs = rng.normal(0, 10, size) estimator = Estimator() findiff = FiniteDiffEstimatorGradient(estimator, 1e-6) gradient = grad(estimator) num_tries = 10 param_values = rng.normal(0, 2, (num_tries, qc.num_parameters)).tolist() np.testing.assert_allclose( findiff.run([qc] * num_tries, [op] * num_tries, param_values).result().gradients, gradient.run([qc] * num_tries, [op] * num_tries, param_values).result().gradients, rtol=1e-4, ) @data((DerivativeType.IMAG, -1.0), (DerivativeType.COMPLEX, -1.0j)) @unpack def test_complex_gradient(self, derivative_type, expected_gradient_value): """Tests if the ``LinCombEstimatorGradient`` has the correct value.""" estimator = Estimator() lcu = LinCombEstimatorGradient(estimator, derivative_type=derivative_type) reverse = ReverseEstimatorGradient(derivative_type=derivative_type) for gradient in [lcu, reverse]: with self.subTest(gradient=gradient): c = QuantumCircuit(1) c.rz(Parameter("p"), 0) result = gradient.run([c], [Pauli("I")], [[0.0]]).result() self.assertAlmostEqual(result.gradients[0][0], expected_gradient_value) @data( FiniteDiffEstimatorGradient, ParamShiftEstimatorGradient, LinCombEstimatorGradient, SPSAEstimatorGradient, ) def test_options(self, grad): """Test estimator gradient's run options""" a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) op = SparsePauliOp.from_list([("Z", 1)]) estimator = Estimator(options={"shots": 100}) with self.subTest("estimator"): if grad is FiniteDiffEstimatorGradient or grad is SPSAEstimatorGradient: gradient = grad(estimator, epsilon=1e-6) else: gradient = grad(estimator) options = gradient.options result = gradient.run([qc], [op], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("gradient init"): if grad is FiniteDiffEstimatorGradient or grad is SPSAEstimatorGradient: gradient = grad(estimator, epsilon=1e-6, options={"shots": 200}) else: gradient = grad(estimator, options={"shots": 200}) options = gradient.options result = gradient.run([qc], [op], [[1]]).result() self.assertEqual(result.options.get("shots"), 200) self.assertEqual(options.get("shots"), 200) with self.subTest("gradient update"): if grad is FiniteDiffEstimatorGradient or grad is SPSAEstimatorGradient: gradient = grad(estimator, epsilon=1e-6, options={"shots": 200}) else: gradient = grad(estimator, options={"shots": 200}) gradient.update_default_options(shots=100) options = gradient.options result = gradient.run([qc], [op], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("gradient run"): if grad is FiniteDiffEstimatorGradient or grad is SPSAEstimatorGradient: gradient = grad(estimator, epsilon=1e-6, options={"shots": 200}) else: gradient = grad(estimator, options={"shots": 200}) options = gradient.options result = gradient.run([qc], [op], [[1]], shots=300).result() self.assertEqual(result.options.get("shots"), 300) # Only default + estimator options. Not run. self.assertEqual(options.get("shots"), 200) @data( FiniteDiffEstimatorGradient, ParamShiftEstimatorGradient, LinCombEstimatorGradient, SPSAEstimatorGradient, ) def test_operations_preserved(self, gradient_cls): """Test non-parameterized instructions are preserved and not unrolled.""" x = Parameter("x") circuit = QuantumCircuit(2) circuit.initialize([0.5, 0.5, 0.5, 0.5]) # this should remain as initialize circuit.crx(x, 0, 1) # this should get unrolled values = [np.pi / 2] expect = -1 / (2 * np.sqrt(2)) observable = SparsePauliOp(["XX"]) ops = [] def operations_callback(op): ops.append(op) estimator = LoggingEstimator(operations_callback=operations_callback) if gradient_cls in [SPSAEstimatorGradient, FiniteDiffEstimatorGradient]: gradient = gradient_cls(estimator, epsilon=0.01) else: gradient = gradient_cls(estimator) job = gradient.run([circuit], [observable], [values]) result = job.result() with self.subTest(msg="assert initialize is preserved"): self.assertTrue(all("initialize" in ops_i[0].keys() for ops_i in ops)) with self.subTest(msg="assert result is correct"): self.assertAlmostEqual(result.gradients[0].item(), expect, places=5) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # ============================================================================= """Test QFI.""" import unittest from ddt import ddt, data import numpy as np from qiskit import QuantumCircuit from qiskit_algorithms.gradients import LinCombQGT, ReverseQGT, QFI, DerivativeType from qiskit.circuit import Parameter from qiskit.circuit.parametervector import ParameterVector from qiskit.primitives import Estimator from qiskit.test import QiskitTestCase @ddt class TestQFI(QiskitTestCase): """Test QFI""" def setUp(self): super().setUp() self.estimator = Estimator() self.lcu_qgt = LinCombQGT(self.estimator, derivative_type=DerivativeType.REAL) self.reverse_qgt = ReverseQGT(derivative_type=DerivativeType.REAL) def test_qfi(self): """Test if the quantum fisher information calculation is correct for a simple test case. QFI = [[1, 0], [0, 1]] - [[0, 0], [0, cos^2(a)]] """ # create the circuit a, b = Parameter("a"), Parameter("b") qc = QuantumCircuit(1) qc.h(0) qc.rz(a, 0) qc.rx(b, 0) param_list = [[np.pi / 4, 0.1], [np.pi, 0.1], [np.pi / 2, 0.1]] correct_values = [[[1, 0], [0, 0.5]], [[1, 0], [0, 0]], [[1, 0], [0, 1]]] qfi = QFI(self.lcu_qgt) for i, param in enumerate(param_list): qfis = qfi.run([qc], [param]).result().qfis np.testing.assert_allclose(qfis[0], correct_values[i], atol=1e-3) def test_qfi_phase_fix(self): """Test the phase-fix argument in the QFI calculation""" # create the circuit a, b = Parameter("a"), Parameter("b") qc = QuantumCircuit(1) qc.h(0) qc.rz(a, 0) qc.rx(b, 0) param = [np.pi / 4, 0.1] # test for different values correct_values = [[1, 0], [0, 1]] qgt = LinCombQGT(self.estimator, phase_fix=False) qfi = QFI(qgt) qfis = qfi.run([qc], [param]).result().qfis np.testing.assert_allclose(qfis[0], correct_values, atol=1e-3) @data("lcu", "reverse") def test_qfi_maxcut(self, qgt_kind): """Test the QFI for a simple MaxCut problem. This is interesting because it contains the same parameters in different gates. """ # create maxcut circuit for the hamiltonian # H = (I ^ I ^ Z ^ Z) + (I ^ Z ^ I ^ Z) + (Z ^ I ^ I ^ Z) + (I ^ Z ^ Z ^ I) x = ParameterVector("x", 2) ansatz = QuantumCircuit(4) # initial hadamard layer ansatz.h(ansatz.qubits) # e^{iZZ} layers def expiz(qubit0, qubit1): ansatz.cx(qubit0, qubit1) ansatz.rz(2 * x[0], qubit1) ansatz.cx(qubit0, qubit1) expiz(2, 1) expiz(3, 0) expiz(2, 0) expiz(1, 0) # mixer layer with RX gates for i in range(ansatz.num_qubits): ansatz.rx(2 * x[1], i) reference = np.array([[16.0, -5.551], [-5.551, 18.497]]) param = [0.4, 0.69] qgt = self.lcu_qgt if qgt_kind == "lcu" else self.reverse_qgt qfi = QFI(qgt) qfi_result = qfi.run([ansatz], [param]).result().qfis np.testing.assert_array_almost_equal(qfi_result[0], reference, decimal=3) def test_options(self): """Test QFI's options""" a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) qgt = LinCombQGT(estimator=self.estimator, options={"shots": 100}) with self.subTest("QGT"): qfi = QFI(qgt=qgt) options = qfi.options result = qfi.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("QFI init"): qfi = QFI(qgt=qgt, options={"shots": 200}) result = qfi.run([qc], [[1]]).result() options = qfi.options self.assertEqual(result.options.get("shots"), 200) self.assertEqual(options.get("shots"), 200) with self.subTest("QFI update"): qfi = QFI(qgt, options={"shots": 200}) qfi.update_default_options(shots=100) options = qfi.options result = qfi.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("QFI run"): qfi = QFI(qgt=qgt, options={"shots": 200}) result = qfi.run([qc], [[0]], shots=300).result() options = qfi.options self.assertEqual(result.options.get("shots"), 300) self.assertEqual(options.get("shots"), 200) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # ============================================================================= """Test QGT.""" import unittest from ddt import ddt, data import numpy as np from qiskit import QuantumCircuit from qiskit_algorithms.gradients import DerivativeType, LinCombQGT, ReverseQGT from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Estimator from qiskit.test import QiskitTestCase from .logging_primitives import LoggingEstimator @ddt class TestQGT(QiskitTestCase): """Test QGT""" def setUp(self): super().setUp() self.estimator = Estimator() @data(LinCombQGT, ReverseQGT) def test_qgt_derivative_type(self, qgt_type): """Test QGT derivative_type""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) a, b = Parameter("a"), Parameter("b") qc = QuantumCircuit(1) qc.h(0) qc.rz(a, 0) qc.rx(b, 0) param_list = [[np.pi / 4, 0], [np.pi / 2, np.pi / 4]] correct_values = [ np.array([[1, 0.707106781j], [-0.707106781j, 0.5]]) / 4, np.array([[1, 1j], [-1j, 1]]) / 4, ] # test real derivative with self.subTest("Test with DerivativeType.REAL"): qgt.derivative_type = DerivativeType.REAL for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].real, atol=1e-3) # test imaginary derivative with self.subTest("Test with DerivativeType.IMAG"): qgt.derivative_type = DerivativeType.IMAG for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].imag, atol=1e-3) # test real + imaginary derivative with self.subTest("Test with DerivativeType.COMPLEX"): qgt.derivative_type = DerivativeType.COMPLEX for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_phase_fix(self, qgt_type): """Test the phase-fix argument in a QGT calculation""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, phase_fix=False) # create the circuit a, b = Parameter("a"), Parameter("b") qc = QuantumCircuit(1) qc.h(0) qc.rz(a, 0) qc.rx(b, 0) param_list = [[np.pi / 4, 0], [np.pi / 2, np.pi / 4]] correct_values = [ np.array([[1, 0.707106781j], [-0.707106781j, 1]]) / 4, np.array([[1, 1j], [-1j, 1]]) / 4, ] # test real derivative with self.subTest("Test phase fix with DerivativeType.REAL"): qgt.derivative_type = DerivativeType.REAL for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].real, atol=1e-3) # test imaginary derivative with self.subTest("Test phase fix with DerivativeType.IMAG"): qgt.derivative_type = DerivativeType.IMAG for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].imag, atol=1e-3) # test real + imaginary derivative with self.subTest("Test phase fix with DerivativeType.COMPLEX"): qgt.derivative_type = DerivativeType.COMPLEX for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_coefficients(self, qgt_type): """Test the derivative option of QGT""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) qc = RealAmplitudes(num_qubits=2, reps=1) qc.rz(qc.parameters[0].exp() + 2 * qc.parameters[1], 0) qc.rx(3.0 * qc.parameters[2] + qc.parameters[3].sin(), 1) # test imaginary derivative param_list = [ [np.pi / 4 for param in qc.parameters], [np.pi / 2 for param in qc.parameters], ] correct_values = ( np.array( [ [ [5.707309, 4.2924833, 1.5295868, 0.1938604], [4.2924833, 4.9142136, 0.75, 0.8838835], [1.5295868, 0.75, 3.4430195, 0.0758252], [0.1938604, 0.8838835, 0.0758252, 1.1357233], ], [ [1.0, 0.0, 1.0, 0.0], [0.0, 1.0, 0.0, 0.0], [1.0, 0.0, 10.0, -0.0], [0.0, 0.0, -0.0, 1.0], ], ] ) / 4 ) for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_parameters(self, qgt_type): """Test the QGT with specified parameters""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.ry(b, 0) param_values = [np.pi / 4, np.pi / 4] qgt_result = qgt.run([qc], [param_values], [[a]]).result().qgts np.testing.assert_allclose(qgt_result[0], [[1 / 4]], atol=1e-3) with self.subTest("Test with different parameter orders"): c = Parameter("c") qc2 = QuantumCircuit(1) qc2.rx(a, 0) qc2.rz(b, 0) qc2.rx(c, 0) param_values = [np.pi / 4, np.pi / 4, np.pi / 4] params = [[a, b, c], [c, b, a], [a, c], [b, a]] expected = [ np.array( [ [0.25, 0.0, 0.1767767], [0.0, 0.125, -0.08838835], [0.1767767, -0.08838835, 0.1875], ] ), np.array( [ [0.1875, -0.08838835, 0.1767767], [-0.08838835, 0.125, 0.0], [0.1767767, 0.0, 0.25], ] ), np.array([[0.25, 0.1767767], [0.1767767, 0.1875]]), np.array([[0.125, 0.0], [0.0, 0.25]]), ] for i, param in enumerate(params): qgt_result = qgt.run([qc2], [param_values], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], expected[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_multi_arguments(self, qgt_type): """Test the QGT for multiple arguments""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.ry(b, 0) qc2 = QuantumCircuit(1) qc2.rx(a, 0) qc2.ry(b, 0) param_list = [[np.pi / 4], [np.pi / 2]] correct_values = [[[1 / 4]], [[1 / 4, 0], [0, 0]]] param_list = [[np.pi / 4, np.pi / 4], [np.pi / 2, np.pi / 2]] qgt_results = qgt.run([qc, qc2], param_list, [[a], None]).result().qgts for i, _ in enumerate(param_list): np.testing.assert_allclose(qgt_results[i], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_validation(self, qgt_type): """Test estimator QGT's validation""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args) a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) parameter_values = [[np.pi / 4]] with self.subTest("assert number of circuits does not match"): with self.assertRaises(ValueError): qgt.run([qc, qc], parameter_values) with self.subTest("assert number of parameter values does not match"): with self.assertRaises(ValueError): qgt.run([qc], [[np.pi / 4], [np.pi / 2]]) with self.subTest("assert number of parameters does not match"): with self.assertRaises(ValueError): qgt.run([qc], parameter_values, parameters=[[a], [a]]) def test_options(self): """Test QGT's options""" a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) estimator = Estimator(options={"shots": 100}) with self.subTest("estimator"): qgt = LinCombQGT(estimator) options = qgt.options result = qgt.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("QGT init"): qgt = LinCombQGT(estimator, options={"shots": 200}) result = qgt.run([qc], [[1]]).result() options = qgt.options self.assertEqual(result.options.get("shots"), 200) self.assertEqual(options.get("shots"), 200) with self.subTest("QGT update"): qgt = LinCombQGT(estimator, options={"shots": 200}) qgt.update_default_options(shots=100) options = qgt.options result = qgt.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("QGT run"): qgt = LinCombQGT(estimator, options={"shots": 200}) result = qgt.run([qc], [[0]], shots=300).result() options = qgt.options self.assertEqual(result.options.get("shots"), 300) self.assertEqual(options.get("shots"), 200) def test_operations_preserved(self): """Test non-parameterized instructions are preserved and not unrolled.""" x, y = Parameter("x"), Parameter("y") circuit = QuantumCircuit(2) circuit.initialize([0.5, 0.5, 0.5, 0.5]) # this should remain as initialize circuit.crx(x, 0, 1) # this should get unrolled circuit.ry(y, 0) values = [np.pi / 2, np.pi] expect = np.diag([0.25, 0.5]) / 4 ops = [] def operations_callback(op): ops.append(op) estimator = LoggingEstimator(operations_callback=operations_callback) qgt = LinCombQGT(estimator, derivative_type=DerivativeType.REAL) job = qgt.run([circuit], [values]) result = job.result() with self.subTest(msg="assert initialize is preserved"): self.assertTrue(all("initialize" in ops_i[0].keys() for ops_i in ops)) with self.subTest(msg="assert result is correct"): np.testing.assert_allclose(result.qgts[0], expect, atol=1e-5) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. # ============================================================================= """Test Sampler Gradients""" import unittest from typing import List import numpy as np from ddt import ddt, data from qiskit import QuantumCircuit from qiskit_algorithms.gradients import ( FiniteDiffSamplerGradient, LinCombSamplerGradient, ParamShiftSamplerGradient, SPSASamplerGradient, ) from qiskit.circuit import Parameter from qiskit.circuit.library import EfficientSU2, RealAmplitudes from qiskit.circuit.library.standard_gates import RXXGate from qiskit.primitives import Sampler from qiskit.result import QuasiDistribution from qiskit.test import QiskitTestCase from .logging_primitives import LoggingSampler gradient_factories = [ lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="central"), lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="forward"), lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="backward"), ParamShiftSamplerGradient, LinCombSamplerGradient, ] @ddt class TestSamplerGradient(QiskitTestCase): """Test Sampler Gradient""" @data(*gradient_factories) def test_single_circuit(self, grad): """Test the sampler gradient for a single circuit""" sampler = Sampler() a = Parameter("a") qc = QuantumCircuit(1) qc.h(0) qc.p(a, 0) qc.h(0) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4], [0], [np.pi / 2]] expected = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}], [{0: 0, 1: 0}], [{0: -0.499999, 1: 0.499999}], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(expected[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_p(self, grad): """Test the sampler gradient for p""" sampler = Sampler() a = Parameter("a") qc = QuantumCircuit(1) qc.h(0) qc.p(a, 0) qc.h(0) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4], [0], [np.pi / 2]] expected = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}], [{0: 0, 1: 0}], [{0: -0.499999, 1: 0.499999}], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(expected[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_u(self, grad): """Test the sampler gradient for u""" sampler = Sampler() a = Parameter("a") b = Parameter("b") c = Parameter("c") qc = QuantumCircuit(1) qc.h(0) qc.u(a, b, c, 0) qc.h(0) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4, 0, 0], [np.pi / 4, np.pi / 4, np.pi / 4]] expected = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}, {0: 0, 1: 0}, {0: 0, 1: 0}], [{0: -0.176777, 1: 0.176777}, {0: -0.426777, 1: 0.426777}, {0: -0.426777, 1: 0.426777}], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(expected[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_efficient_su2(self, grad): """Test the sampler gradient for EfficientSU2""" sampler = Sampler() qc = EfficientSU2(2, reps=1) qc.measure_all() gradient = grad(sampler) param_list = [ [np.pi / 4 for param in qc.parameters], [np.pi / 2 for param in qc.parameters], ] expected = [ [ { 0: -0.11963834764831836, 1: -0.05713834764831845, 2: -0.21875000000000003, 3: 0.39552669529663675, }, { 0: -0.32230339059327373, 1: -0.031250000000000014, 2: 0.2339150429449554, 3: 0.11963834764831843, }, { 0: 0.012944173824159189, 1: -0.01294417382415923, 2: 0.07544417382415919, 3: -0.07544417382415919, }, { 0: 0.2080266952966367, 1: -0.03125000000000002, 2: -0.11963834764831842, 3: -0.057138347648318405, }, { 0: -0.11963834764831838, 1: 0.11963834764831838, 2: -0.21875000000000003, 3: 0.21875, }, { 0: -0.2781092167691146, 1: -0.0754441738241592, 2: 0.27810921676911443, 3: 0.07544417382415924, }, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0}, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0}, ], [ { 0: -4.163336342344337e-17, 1: 2.7755575615628914e-17, 2: -4.163336342344337e-17, 3: 0.0, }, {0: 0.0, 1: -1.3877787807814457e-17, 2: 4.163336342344337e-17, 3: 0.0}, { 0: -0.24999999999999994, 1: 0.24999999999999994, 2: 0.24999999999999994, 3: -0.24999999999999994, }, { 0: 0.24999999999999994, 1: 0.24999999999999994, 2: -0.24999999999999994, 3: -0.24999999999999994, }, { 0: -4.163336342344337e-17, 1: 4.163336342344337e-17, 2: -4.163336342344337e-17, 3: 5.551115123125783e-17, }, { 0: -0.24999999999999994, 1: 0.24999999999999994, 2: 0.24999999999999994, 3: -0.24999999999999994, }, {0: 0.0, 1: 2.7755575615628914e-17, 2: 0.0, 3: 2.7755575615628914e-17}, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0}, ], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=2) array2 = _quasi2array(expected[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_2qubit_gate(self, grad): """Test the sampler gradient for 2 qubit gates""" sampler = Sampler() for gate in [RXXGate]: param_list = [[np.pi / 4], [np.pi / 2]] correct_results = [ [{0: -0.5 / np.sqrt(2), 1: 0, 2: 0, 3: 0.5 / np.sqrt(2)}], [{0: -0.5, 1: 0, 2: 0, 3: 0.5}], ] for i, param in enumerate(param_list): a = Parameter("a") qc = QuantumCircuit(2) qc.append(gate(a), [qc.qubits[0], qc.qubits[1]], []) qc.measure_all() gradient = grad(sampler) gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=2) array2 = _quasi2array(correct_results[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_parameter_coefficient(self, grad): """Test the sampler gradient for parameter variables with coefficients""" sampler = Sampler() qc = RealAmplitudes(num_qubits=2, reps=1) qc.rz(qc.parameters[0].exp() + 2 * qc.parameters[1], 0) qc.rx(3.0 * qc.parameters[0] + qc.parameters[1].sin(), 1) qc.u(qc.parameters[0], qc.parameters[1], qc.parameters[3], 1) qc.p(2 * qc.parameters[0] + 1, 0) qc.rxx(qc.parameters[0] + 2, 0, 1) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4 for _ in qc.parameters], [np.pi / 2 for _ in qc.parameters]] correct_results = [ [ { 0: 0.30014831912265927, 1: -0.6634809704357856, 2: 0.343589357193753, 3: 0.019743294119373426, }, { 0: 0.16470607453981906, 1: -0.40996282450610577, 2: 0.08791803062881773, 3: 0.15733871933746948, }, { 0: 0.27036068339663866, 1: -0.273790986018701, 2: 0.12752010079553433, 3: -0.12408979817347202, }, { 0: -0.2098616294167757, 1: -0.2515823946449894, 2: 0.21929102305386305, 3: 0.24215300100790207, }, ], [ { 0: -1.844810060881004, 1: 0.04620532700836027, 2: 1.6367366426074323, 3: 0.16186809126521057, }, { 0: 0.07296073407769421, 1: -0.021774869186331716, 2: 0.02177486918633173, 3: -0.07296073407769456, }, { 0: -0.07794369186049102, 1: -0.07794369186049122, 2: 0.07794369186049117, 3: 0.07794369186049112, }, { 0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, }, ], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=2) array2 = _quasi2array(correct_results[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_parameters(self, grad): """Test the sampler gradient for parameters""" sampler = Sampler() a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.rz(b, 0) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4, np.pi / 2]] expected = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param], parameters=[[a]]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(expected[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) # parameter order with self.subTest(msg="The order of gradients"): c = Parameter("c") qc = QuantumCircuit(1) qc.rx(a, 0) qc.rz(b, 0) qc.rx(c, 0) qc.measure_all() param_values = [[np.pi / 4, np.pi / 2, np.pi / 3]] params = [[a, b, c], [c, b, a], [a, c], [c, a]] expected = [ [ {0: -0.17677666583387008, 1: 0.17677666583378482}, {0: 0.3061861668168149, 1: -0.3061861668167012}, {0: -0.3061861668168149, 1: 0.30618616681678645}, ], [ {0: -0.3061861668168149, 1: 0.30618616681678645}, {0: 0.3061861668168149, 1: -0.3061861668167012}, {0: -0.17677666583387008, 1: 0.17677666583378482}, ], [ {0: -0.17677666583387008, 1: 0.17677666583378482}, {0: -0.3061861668168149, 1: 0.30618616681678645}, ], [ {0: -0.3061861668168149, 1: 0.30618616681678645}, {0: -0.17677666583387008, 1: 0.17677666583378482}, ], ] for i, p in enumerate(params): gradients = gradient.run([qc], param_values, parameters=[p]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(expected[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_multi_arguments(self, grad): """Test the sampler gradient for multiple arguments""" sampler = Sampler() a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.measure_all() qc2 = QuantumCircuit(1) qc2.rx(b, 0) qc2.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4], [np.pi / 2]] correct_results = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}], [{0: -0.499999, 1: 0.499999}], ] gradients = gradient.run([qc, qc2], param_list).result().gradients for i, q_dists in enumerate(gradients): array1 = _quasi2array(q_dists, num_qubits=1) array2 = _quasi2array(correct_results[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) # parameters with self.subTest(msg="Different parameters"): c = Parameter("c") qc3 = QuantumCircuit(1) qc3.rx(c, 0) qc3.ry(a, 0) qc3.measure_all() param_list2 = [[np.pi / 4], [np.pi / 4, np.pi / 4], [np.pi / 4, np.pi / 4]] gradients = ( gradient.run([qc, qc3, qc3], param_list2, parameters=[[a], [c], None]) .result() .gradients ) correct_results = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}], [{0: -0.25, 1: 0.25}], [{0: -0.25, 1: 0.25}, {0: -0.25, 1: 0.25}], ] for i, q_dists in enumerate(gradients): array1 = _quasi2array(q_dists, num_qubits=1) array2 = _quasi2array(correct_results[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_validation(self, grad): """Test sampler gradient's validation""" sampler = Sampler() a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4], [np.pi / 2]] with self.assertRaises(ValueError): gradient.run([qc], param_list) with self.assertRaises(ValueError): gradient.run([qc, qc], param_list, parameters=[[a]]) with self.assertRaises(ValueError): gradient.run([qc], [[np.pi / 4, np.pi / 4]]) def test_spsa_gradient(self): """Test the SPSA sampler gradient""" sampler = Sampler() with self.assertRaises(ValueError): _ = SPSASamplerGradient(sampler, epsilon=-0.1) a = Parameter("a") b = Parameter("b") c = Parameter("c") qc = QuantumCircuit(2) qc.rx(b, 0) qc.rx(a, 1) qc.measure_all() param_list = [[1, 2]] correct_results = [ [ {0: 0.2273244, 1: -0.6480598, 2: 0.2273244, 3: 0.1934111}, {0: -0.2273244, 1: 0.6480598, 2: -0.2273244, 3: -0.1934111}, ], ] gradient = SPSASamplerGradient(sampler, epsilon=1e-6, seed=123) for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=2) array2 = _quasi2array(correct_results[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) # multi parameters with self.subTest(msg="Multiple parameters"): param_list2 = [[1, 2], [1, 2], [3, 4]] correct_results2 = [ [ {0: 0.2273244, 1: -0.6480598, 2: 0.2273244, 3: 0.1934111}, {0: -0.2273244, 1: 0.6480598, 2: -0.2273244, 3: -0.1934111}, ], [ {0: -0.2273244, 1: 0.6480598, 2: -0.2273244, 3: -0.1934111}, ], [ {0: -0.0141129, 1: -0.0564471, 2: -0.3642884, 3: 0.4348484}, {0: 0.0141129, 1: 0.0564471, 2: 0.3642884, 3: -0.4348484}, ], ] gradient = SPSASamplerGradient(sampler, epsilon=1e-6, seed=123) gradients = ( gradient.run([qc] * 3, param_list2, parameters=[None, [b], None]).result().gradients ) for i, result in enumerate(gradients): array1 = _quasi2array(result, num_qubits=2) array2 = _quasi2array(correct_results2[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) # batch size with self.subTest(msg="Batch size"): param_list = [[1, 1]] gradient = SPSASamplerGradient(sampler, epsilon=1e-6, batch_size=4, seed=123) gradients = gradient.run([qc], param_list).result().gradients correct_results3 = [ [ { 0: -0.1620149622932887, 1: -0.25872053011771756, 2: 0.3723827084675668, 3: 0.04835278392088804, }, { 0: -0.1620149622932887, 1: 0.3723827084675668, 2: -0.25872053011771756, 3: 0.04835278392088804, }, ] ] for i, q_dists in enumerate(gradients): array1 = _quasi2array(q_dists, num_qubits=2) array2 = _quasi2array(correct_results3[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) # parameter order with self.subTest(msg="The order of gradients"): qc = QuantumCircuit(1) qc.rx(a, 0) qc.rz(b, 0) qc.rx(c, 0) qc.measure_all() param_list = [[np.pi / 4, np.pi / 2, np.pi / 3]] param = [[a, b, c], [c, b, a], [a, c], [c, a]] correct_results = [ [ {0: -0.17677624757590138, 1: 0.17677624757590138}, {0: 0.17677624757590138, 1: -0.17677624757590138}, {0: 0.17677624757590138, 1: -0.17677624757590138}, ], [ {0: 0.17677624757590138, 1: -0.17677624757590138}, {0: 0.17677624757590138, 1: -0.17677624757590138}, {0: -0.17677624757590138, 1: 0.17677624757590138}, ], [ {0: -0.17677624757590138, 1: 0.17677624757590138}, {0: 0.17677624757590138, 1: -0.17677624757590138}, ], [ {0: 0.17677624757590138, 1: -0.17677624757590138}, {0: -0.17677624757590138, 1: 0.17677624757590138}, ], ] for i, p in enumerate(param): gradient = SPSASamplerGradient(sampler, epsilon=1e-6, seed=123) gradients = gradient.run([qc], param_list, parameters=[p]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(correct_results[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(ParamShiftSamplerGradient, LinCombSamplerGradient) def test_gradient_random_parameters(self, grad): """Test param shift and lin comb w/ random parameters""" rng = np.random.default_rng(123) qc = RealAmplitudes(num_qubits=3, reps=1) params = qc.parameters qc.rx(3.0 * params[0] + params[1].sin(), 0) qc.ry(params[0].exp() + 2 * params[1], 1) qc.rz(params[0] * params[1] - params[2], 2) qc.p(2 * params[0] + 1, 0) qc.u(params[0].sin(), params[1] - 2, params[2] * params[3], 1) qc.sx(2) qc.rxx(params[0].sin(), 1, 2) qc.ryy(params[1].cos(), 2, 0) qc.rzz(params[2] * 2, 0, 1) qc.crx(params[0].exp(), 1, 2) qc.cry(params[1].arctan(), 2, 0) qc.crz(params[2] * -2, 0, 1) qc.dcx(0, 1) qc.csdg(0, 1) qc.toffoli(0, 1, 2) qc.iswap(0, 2) qc.swap(1, 2) qc.global_phase = params[0] * params[1] + params[2].cos().exp() qc.measure_all() sampler = Sampler() findiff = FiniteDiffSamplerGradient(sampler, 1e-6) gradient = grad(sampler) num_qubits = qc.num_qubits num_tries = 10 param_values = rng.normal(0, 2, (num_tries, qc.num_parameters)).tolist() result1 = findiff.run([qc] * num_tries, param_values).result().gradients result2 = gradient.run([qc] * num_tries, param_values).result().gradients self.assertEqual(len(result1), len(result2)) for res1, res2 in zip(result1, result2): array1 = _quasi2array(res1, num_qubits) array2 = _quasi2array(res2, num_qubits) np.testing.assert_allclose(array1, array2, rtol=1e-4) @data( FiniteDiffSamplerGradient, ParamShiftSamplerGradient, LinCombSamplerGradient, SPSASamplerGradient, ) def test_options(self, grad): """Test sampler gradient's run options""" a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) qc.measure_all() sampler = Sampler(options={"shots": 100}) with self.subTest("sampler"): if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient: gradient = grad(sampler, epsilon=1e-6) else: gradient = grad(sampler) options = gradient.options result = gradient.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("gradient init"): if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient: gradient = grad(sampler, epsilon=1e-6, options={"shots": 200}) else: gradient = grad(sampler, options={"shots": 200}) options = gradient.options result = gradient.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 200) self.assertEqual(options.get("shots"), 200) with self.subTest("gradient update"): if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient: gradient = grad(sampler, epsilon=1e-6, options={"shots": 200}) else: gradient = grad(sampler, options={"shots": 200}) gradient.update_default_options(shots=100) options = gradient.options result = gradient.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("gradient run"): if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient: gradient = grad(sampler, epsilon=1e-6, options={"shots": 200}) else: gradient = grad(sampler, options={"shots": 200}) options = gradient.options result = gradient.run([qc], [[1]], shots=300).result() self.assertEqual(result.options.get("shots"), 300) # Only default + sampler options. Not run. self.assertEqual(options.get("shots"), 200) @data( FiniteDiffSamplerGradient, ParamShiftSamplerGradient, LinCombSamplerGradient, SPSASamplerGradient, ) def test_operations_preserved(self, gradient_cls): """Test non-parameterized instructions are preserved and not unrolled.""" x = Parameter("x") circuit = QuantumCircuit(2) circuit.initialize(np.array([1, 1, 0, 0]) / np.sqrt(2)) # this should remain as initialize circuit.crx(x, 0, 1) # this should get unrolled circuit.measure_all() values = [np.pi / 2] expect = [{0: 0, 1: -0.25, 2: 0, 3: 0.25}] ops = [] def operations_callback(op): ops.append(op) sampler = LoggingSampler(operations_callback=operations_callback) if gradient_cls in [SPSASamplerGradient, FiniteDiffSamplerGradient]: gradient = gradient_cls(sampler, epsilon=0.01) else: gradient = gradient_cls(sampler) job = gradient.run([circuit], [values]) result = job.result() with self.subTest(msg="assert initialize is preserved"): self.assertTrue(all("initialize" in ops_i[0].keys() for ops_i in ops)) with self.subTest(msg="assert result is correct"): array1 = _quasi2array(result.gradients[0], num_qubits=2) array2 = _quasi2array(expect, num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-5) def _quasi2array(quasis: List[QuasiDistribution], num_qubits: int) -> np.ndarray: ret = np.zeros((len(quasis), 2**num_qubits)) for i, quasi in enumerate(quasis): ret[i, list(quasi.keys())] = list(quasi.values()) return ret if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the QAOA algorithm.""" import unittest from functools import partial from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np import rustworkx as rx from ddt import ddt, idata, unpack from scipy.optimize import minimize as scipy_minimize from qiskit import QuantumCircuit from qiskit_algorithms.minimum_eigensolvers import QAOA from qiskit_algorithms.optimizers import COBYLA, NELDER_MEAD from qiskit.circuit import Parameter from qiskit.primitives import Sampler from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.result import QuasiDistribution from qiskit.utils import algorithm_globals W1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) P1 = 1 M1 = SparsePauliOp.from_list( [ ("IIIX", 1), ("IIXI", 1), ("IXII", 1), ("XIII", 1), ] ) S1 = {"0101", "1010"} W2 = np.array( [ [0.0, 8.0, -9.0, 0.0], [8.0, 0.0, 7.0, 9.0], [-9.0, 7.0, 0.0, -8.0], [0.0, 9.0, -8.0, 0.0], ] ) P2 = 1 M2 = None S2 = {"1011", "0100"} CUSTOM_SUPERPOSITION = [1 / np.sqrt(15)] * 15 + [0] @ddt class TestQAOA(QiskitAlgorithmsTestCase): """Test QAOA with MaxCut.""" def setUp(self): super().setUp() self.seed = 10598 algorithm_globals.random_seed = self.seed self.sampler = Sampler() @idata( [ [W1, P1, M1, S1], [W2, P2, M2, S2], ] ) @unpack def test_qaoa(self, w, reps, mixer, solutions): """QAOA test""" self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", reps, w) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) @idata( [ [W1, P1, S1], [W2, P2, S2], ] ) @unpack def test_qaoa_qc_mixer(self, w, prob, solutions): """QAOA test with a mixer as a parameterized circuit""" self.log.debug( "Testing %s-step QAOA with MaxCut on graph with a mixer as a parameterized circuit\n%s", prob, w, ) optimizer = COBYLA() qubit_op, _ = self._get_operator(w) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) theta = Parameter("θ") mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) def test_qaoa_qc_mixer_many_parameters(self): """QAOA test with a mixer as a parameterized circuit with the num of parameters > 1.""" optimizer = COBYLA() qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) for i in range(num_qubits): theta = Parameter("θ" + str(i)) mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) self.log.debug(x) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, S1) def test_qaoa_qc_mixer_no_parameters(self): """QAOA test with a mixer as a parameterized circuit with zero parameters.""" qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) # just arbitrary circuit mixer.rx(np.pi / 2, range(num_qubits)) qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) # we just assert that we get a result, it is not meaningful. self.assertIsNotNone(result.eigenstate) def test_change_operator_size(self): """QAOA change operator size test""" qubit_op, _ = self._get_operator( np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) ) qaoa = QAOA(self.sampler, COBYLA(), reps=1) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 4x4"): self.assertIn(graph_solution, {"0101", "1010"}) qubit_op, _ = self._get_operator( np.array( [ [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], ] ) ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 6x6"): self.assertIn(graph_solution, {"010101", "101010"}) @idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]]) @unpack def test_qaoa_initial_point(self, w, solutions, init_pt): """Check first parameter value used is initial point as expected""" qubit_op, _ = self._get_operator(w) first_pt = [] def cb_callback(eval_count, parameters, mean, metadata): nonlocal first_pt if eval_count == 1: first_pt = list(parameters) qaoa = QAOA( self.sampler, COBYLA(), initial_point=init_pt, callback=cb_callback, ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest("Initial Point"): # If None the preferred random initial point of QAOA variational form if init_pt is None: self.assertLess(result.eigenvalue, -0.97) else: self.assertListEqual(init_pt, first_pt) with self.subTest("Solution"): self.assertIn(graph_solution, solutions) def test_qaoa_random_initial_point(self): """QAOA random initial point""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) self.assertLess(result.eigenvalue, -0.97) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA( self.sampler, partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}), ) result = qaoa.compute_minimum_eigenvalue(qubit_op) self.assertEqual(result.cost_function_evals, 5) def _get_operator(self, weight_matrix): """Generate Hamiltonian for the max-cut problem of a graph. Args: weight_matrix (numpy.ndarray) : adjacency matrix. Returns: PauliSumOp: operator for the Hamiltonian float: a constant shift for the obj function. """ num_nodes = weight_matrix.shape[0] pauli_list = [] shift = 0 for i in range(num_nodes): for j in range(i): if weight_matrix[i, j] != 0: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))]) shift -= 0.5 * weight_matrix[i, j] lst = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list] return SparsePauliOp.from_list(lst), shift def _get_graph_solution(self, x: np.ndarray) -> str: """Get graph solution from binary string. Args: x : binary string as numpy array. Returns: a graph solution as string. """ return "".join([str(int(i)) for i in 1 - x]) def _sample_most_likely(self, state_vector: QuasiDistribution) -> np.ndarray: """Compute the most likely binary string from state vector. Args: state_vector: Quasi-distribution. Returns: Binary string as numpy.ndarray of ints. """ values = list(state_vector.values()) n = int(np.log2(len(values))) k = np.argmax(np.abs(values)) x = np.zeros(n) for i in range(n): x[i] = k % 2 k >>= 1 return x if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the QAOA algorithm with opflow.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial import numpy as np from scipy.optimize import minimize as scipy_minimize from ddt import ddt, idata, unpack import rustworkx as rx from qiskit import QuantumCircuit from qiskit_algorithms.minimum_eigensolvers import QAOA from qiskit_algorithms.optimizers import COBYLA, NELDER_MEAD from qiskit.circuit import Parameter from qiskit.opflow import PauliSumOp from qiskit.quantum_info import Pauli from qiskit.result import QuasiDistribution from qiskit.primitives import Sampler from qiskit.utils import algorithm_globals I = PauliSumOp.from_list([("I", 1)]) X = PauliSumOp.from_list([("X", 1)]) W1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) P1 = 1 M1 = (I ^ I ^ I ^ X) + (I ^ I ^ X ^ I) + (I ^ X ^ I ^ I) + (X ^ I ^ I ^ I) S1 = {"0101", "1010"} W2 = np.array( [ [0.0, 8.0, -9.0, 0.0], [8.0, 0.0, 7.0, 9.0], [-9.0, 7.0, 0.0, -8.0], [0.0, 9.0, -8.0, 0.0], ] ) P2 = 1 M2 = None S2 = {"1011", "0100"} CUSTOM_SUPERPOSITION = [1 / np.sqrt(15)] * 15 + [0] @ddt class TestQAOA(QiskitAlgorithmsTestCase): """Test QAOA with MaxCut.""" def setUp(self): super().setUp() self.seed = 10598 algorithm_globals.random_seed = self.seed self.sampler = Sampler() @idata( [ [W1, P1, M1, S1], [W2, P2, M2, S2], ] ) @unpack def test_qaoa(self, w, reps, mixer, solutions): """QAOA test""" self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", reps, w) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) @idata( [ [W1, P1, S1], [W2, P2, S2], ] ) @unpack def test_qaoa_qc_mixer(self, w, prob, solutions): """QAOA test with a mixer as a parameterized circuit""" self.log.debug( "Testing %s-step QAOA with MaxCut on graph with a mixer as a parameterized circuit\n%s", prob, w, ) optimizer = COBYLA() qubit_op, _ = self._get_operator(w) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) theta = Parameter("θ") mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) def test_qaoa_qc_mixer_many_parameters(self): """QAOA test with a mixer as a parameterized circuit with the num of parameters > 1.""" optimizer = COBYLA() qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) for i in range(num_qubits): theta = Parameter("θ" + str(i)) mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) self.log.debug(x) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, S1) def test_qaoa_qc_mixer_no_parameters(self): """QAOA test with a mixer as a parameterized circuit with zero parameters.""" qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) # just arbitrary circuit mixer.rx(np.pi / 2, range(num_qubits)) qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) # we just assert that we get a result, it is not meaningful. self.assertIsNotNone(result.eigenstate) def test_change_operator_size(self): """QAOA change operator size test""" qubit_op, _ = self._get_operator( np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) ) qaoa = QAOA(self.sampler, COBYLA(), reps=1) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 4x4"): self.assertIn(graph_solution, {"0101", "1010"}) qubit_op, _ = self._get_operator( np.array( [ [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], ] ) ) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 6x6"): self.assertIn(graph_solution, {"010101", "101010"}) @idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]]) @unpack def test_qaoa_initial_point(self, w, solutions, init_pt): """Check first parameter value used is initial point as expected""" qubit_op, _ = self._get_operator(w) first_pt = [] def cb_callback(eval_count, parameters, mean, metadata): nonlocal first_pt if eval_count == 1: first_pt = list(parameters) qaoa = QAOA( self.sampler, COBYLA(), initial_point=init_pt, callback=cb_callback, ) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest("Initial Point"): # If None the preferred random initial point of QAOA variational form if init_pt is None: self.assertLess(result.eigenvalue, -0.97) else: self.assertListEqual(init_pt, first_pt) with self.subTest("Solution"): self.assertIn(graph_solution, solutions) def test_qaoa_random_initial_point(self): """QAOA random initial point""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) self.assertLess(result.eigenvalue, -0.97) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA( self.sampler, partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}), ) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(qubit_op) self.assertEqual(result.cost_function_evals, 5) def _get_operator(self, weight_matrix): """Generate Hamiltonian for the max-cut problem of a graph. Args: weight_matrix (numpy.ndarray) : adjacency matrix. Returns: PauliSumOp: operator for the Hamiltonian float: a constant shift for the obj function. """ num_nodes = weight_matrix.shape[0] pauli_list = [] shift = 0 for i in range(num_nodes): for j in range(i): if weight_matrix[i, j] != 0: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))]) shift -= 0.5 * weight_matrix[i, j] opflow_list = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list] with self.assertWarns(DeprecationWarning): return PauliSumOp.from_list(opflow_list), shift def _get_graph_solution(self, x: np.ndarray) -> str: """Get graph solution from binary string. Args: x : binary string as numpy array. Returns: a graph solution as string. """ return "".join([str(int(i)) for i in 1 - x]) def _sample_most_likely(self, state_vector: QuasiDistribution) -> np.ndarray: """Compute the most likely binary string from state vector. Args: state_vector: Quasi-distribution. Returns: Binary string as numpy.ndarray of ints. """ values = list(state_vector.values()) n = int(np.log2(len(values))) k = np.argmax(np.abs(values)) x = np.zeros(n) for i in range(n): x[i] = k % 2 k >>= 1 return x if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the variational quantum eigensolver algorithm.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial import numpy as np from scipy.optimize import minimize as scipy_minimize from ddt import data, ddt from qiskit import QuantumCircuit from qiskit_algorithms import AlgorithmError from qiskit_algorithms.gradients import ParamShiftEstimatorGradient from qiskit_algorithms.minimum_eigensolvers import VQE from qiskit_algorithms.optimizers import ( CG, COBYLA, GradientDescent, L_BFGS_B, OptimizerResult, P_BFGS, QNSPSA, SLSQP, SPSA, TNC, ) from qiskit_algorithms.state_fidelities import ComputeUncompute from qiskit.circuit.library import RealAmplitudes, TwoLocal from qiskit.opflow import PauliSumOp, TwoQubitReduction from qiskit.quantum_info import SparsePauliOp, Operator, Pauli from qiskit.primitives import Estimator, Sampler from qiskit.utils import algorithm_globals # pylint: disable=invalid-name def _mock_optimizer(fun, x0, jac=None, bounds=None, inputs=None) -> OptimizerResult: """A mock of a callable that can be used as minimizer in the VQE.""" result = OptimizerResult() result.x = np.zeros_like(x0) result.fun = fun(result.x) result.nit = 0 if inputs is not None: inputs.update({"fun": fun, "x0": x0, "jac": jac, "bounds": bounds}) return result @ddt class TestVQE(QiskitAlgorithmsTestCase): """Test VQE""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed self.h2_op = SparsePauliOp( ["II", "IZ", "ZI", "ZZ", "XX"], coeffs=[ -1.052373245772859, 0.39793742484318045, -0.39793742484318045, -0.01128010425623538, 0.18093119978423156, ], ) self.h2_energy = -1.85727503 self.ryrz_wavefunction = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") self.ry_wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") @data(L_BFGS_B(), COBYLA()) def test_basic_aer_statevector(self, estimator): """Test VQE using reference Estimator.""" vqe = VQE(Estimator(), self.ryrz_wavefunction, estimator) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) with self.subTest(msg="test eigenvalue"): self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) with self.subTest(msg="test optimal_value"): self.assertAlmostEqual(result.optimal_value, self.h2_energy) with self.subTest(msg="test dimension of optimal point"): self.assertEqual(len(result.optimal_point), 16) with self.subTest(msg="assert cost_function_evals is set"): self.assertIsNotNone(result.cost_function_evals) with self.subTest(msg="assert optimizer_time is set"): self.assertIsNotNone(result.optimizer_time) with self.subTest(msg="assert optimizer_result is set"): self.assertIsNotNone(result.optimizer_result) with self.subTest(msg="assert optimizer_result."): self.assertAlmostEqual(result.optimizer_result.fun, self.h2_energy, places=5) with self.subTest(msg="assert return ansatz is set"): estimator = Estimator() job = estimator.run(result.optimal_circuit, self.h2_op, result.optimal_point) np.testing.assert_array_almost_equal(job.result().values, result.eigenvalue, 6) def test_invalid_initial_point(self): """Test the proper error is raised when the initial point has the wrong size.""" ansatz = self.ryrz_wavefunction initial_point = np.array([1]) vqe = VQE( Estimator(), ansatz, SLSQP(), initial_point=initial_point, ) with self.assertRaises(ValueError): _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_ansatz_resize(self): """Test the ansatz is properly resized if it's a blueprint circuit.""" ansatz = RealAmplitudes(1, reps=1) vqe = VQE(Estimator(), ansatz, SLSQP()) result = vqe.compute_minimum_eigenvalue(self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_invalid_ansatz_size(self): """Test an error is raised if the ansatz has the wrong number of qubits.""" ansatz = QuantumCircuit(1) ansatz.compose(RealAmplitudes(1, reps=2)) vqe = VQE(Estimator(), ansatz, SLSQP()) with self.assertRaises(AlgorithmError): _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_missing_ansatz_params(self): """Test specifying an ansatz with no parameters raises an error.""" ansatz = QuantumCircuit(self.h2_op.num_qubits) vqe = VQE(Estimator(), ansatz, SLSQP()) with self.assertRaises(AlgorithmError): vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_max_evals_grouped(self): """Test with SLSQP with max_evals_grouped.""" optimizer = SLSQP(maxiter=50, max_evals_grouped=5) vqe = VQE( Estimator(), self.ryrz_wavefunction, optimizer, ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) @data( CG(), L_BFGS_B(), P_BFGS(), SLSQP(), TNC(), ) def test_with_gradient(self, optimizer): """Test VQE using gradient primitive.""" estimator = Estimator() vqe = VQE( estimator, self.ry_wavefunction, optimizer, gradient=ParamShiftEstimatorGradient(estimator), ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_gradient_passed(self): """Test the gradient is properly passed into the optimizer.""" inputs = {} estimator = Estimator() vqe = VQE( estimator, RealAmplitudes(), partial(_mock_optimizer, inputs=inputs), gradient=ParamShiftEstimatorGradient(estimator), ) _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertIsNotNone(inputs["jac"]) def test_gradient_run(self): """Test using the gradient to calculate the minimum.""" estimator = Estimator() vqe = VQE( estimator, RealAmplitudes(), GradientDescent(maxiter=200, learning_rate=0.1), gradient=ParamShiftEstimatorGradient(estimator), ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_with_two_qubit_reduction(self): """Test the VQE using TwoQubitReduction.""" with self.assertWarns(DeprecationWarning): qubit_op = PauliSumOp.from_list( [ ("IIII", -0.8105479805373266), ("IIIZ", 0.17218393261915552), ("IIZZ", -0.22575349222402472), ("IZZI", 0.1721839326191556), ("ZZII", -0.22575349222402466), ("IIZI", 0.1209126326177663), ("IZZZ", 0.16892753870087912), ("IXZX", -0.045232799946057854), ("ZXIX", 0.045232799946057854), ("IXIX", 0.045232799946057854), ("ZXZX", -0.045232799946057854), ("ZZIZ", 0.16614543256382414), ("IZIZ", 0.16614543256382414), ("ZZZZ", 0.17464343068300453), ("ZIZI", 0.1209126326177663), ] ) tapered_qubit_op = TwoQubitReduction(num_particles=2).convert(qubit_op) vqe = VQE( Estimator(), self.ry_wavefunction, SPSA(maxiter=300, last_avg=5), ) result = vqe.compute_minimum_eigenvalue(tapered_qubit_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=2) def test_callback(self): """Test the callback on VQE.""" history = {"eval_count": [], "parameters": [], "mean": [], "metadata": []} def store_intermediate_result(eval_count, parameters, mean, metadata): history["eval_count"].append(eval_count) history["parameters"].append(parameters) history["mean"].append(mean) history["metadata"].append(metadata) optimizer = COBYLA(maxiter=3) wavefunction = self.ry_wavefunction estimator = Estimator() vqe = VQE( estimator, wavefunction, optimizer, callback=store_intermediate_result, ) vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertTrue(all(isinstance(count, int) for count in history["eval_count"])) self.assertTrue(all(isinstance(mean, float) for mean in history["mean"])) self.assertTrue(all(isinstance(metadata, dict) for metadata in history["metadata"])) for params in history["parameters"]: self.assertTrue(all(isinstance(param, float) for param in params)) def test_reuse(self): """Test re-using a VQE algorithm instance.""" ansatz = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") vqe = VQE(Estimator(), ansatz, SLSQP(maxiter=300)) with self.subTest(msg="assert VQE works once all info is available"): result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) operator = Operator(np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]])) with self.subTest(msg="assert vqe works on re-use."): result = vqe.compute_minimum_eigenvalue(operator=operator) self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5) def test_vqe_optimizer_reuse(self): """Test running same VQE twice to re-use optimizer, then switch optimizer""" vqe = VQE( Estimator(), self.ryrz_wavefunction, SLSQP(), ) def run_check(): result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) run_check() with self.subTest("Optimizer re-use."): run_check() with self.subTest("Optimizer replace."): vqe.optimizer = L_BFGS_B() run_check() def test_default_batch_evaluation_on_spsa(self): """Test the default batching works.""" ansatz = TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz") wrapped_estimator = Estimator() inner_estimator = Estimator() callcount = {"estimator": 0} def wrapped_estimator_run(*args, **kwargs): kwargs["callcount"]["estimator"] += 1 return inner_estimator.run(*args, **kwargs) wrapped_estimator.run = partial(wrapped_estimator_run, callcount=callcount) spsa = SPSA(maxiter=5) vqe = VQE(wrapped_estimator, ansatz, spsa) _ = vqe.compute_minimum_eigenvalue(Pauli("ZZ")) # 1 calibration + 5 loss + 1 return loss expected_estimator_runs = 1 + 5 + 1 with self.subTest(msg="check callcount"): self.assertEqual(callcount["estimator"], expected_estimator_runs) with self.subTest(msg="check reset to original max evals grouped"): self.assertIsNone(spsa._max_evals_grouped) def test_batch_evaluate_with_qnspsa(self): """Test batch evaluating with QNSPSA works.""" ansatz = TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz") wrapped_sampler = Sampler() inner_sampler = Sampler() wrapped_estimator = Estimator() inner_estimator = Estimator() callcount = {"sampler": 0, "estimator": 0} def wrapped_estimator_run(*args, **kwargs): kwargs["callcount"]["estimator"] += 1 return inner_estimator.run(*args, **kwargs) def wrapped_sampler_run(*args, **kwargs): kwargs["callcount"]["sampler"] += 1 return inner_sampler.run(*args, **kwargs) wrapped_estimator.run = partial(wrapped_estimator_run, callcount=callcount) wrapped_sampler.run = partial(wrapped_sampler_run, callcount=callcount) fidelity = ComputeUncompute(wrapped_sampler) def fidelity_callable(left, right): batchsize = np.asarray(left).shape[0] job = fidelity.run(batchsize * [ansatz], batchsize * [ansatz], left, right) return job.result().fidelities qnspsa = QNSPSA(fidelity_callable, maxiter=5) qnspsa.set_max_evals_grouped(100) vqe = VQE( wrapped_estimator, ansatz, qnspsa, ) _ = vqe.compute_minimum_eigenvalue(Pauli("ZZ")) # 5 (fidelity) expected_sampler_runs = 5 # 1 calibration + 1 stddev estimation + 1 initial blocking # + 5 (1 loss + 1 blocking) + 1 return loss expected_estimator_runs = 1 + 1 + 1 + 5 * 2 + 1 self.assertEqual(callcount["sampler"], expected_sampler_runs) self.assertEqual(callcount["estimator"], expected_estimator_runs) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" vqe = VQE( Estimator(), self.ryrz_wavefunction, partial(scipy_minimize, method="L-BFGS-B", options={"maxiter": 10}), ) result = vqe.compute_minimum_eigenvalue(self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=2) def test_optimizer_callable(self): """Test passing a optimizer directly as callable.""" ansatz = RealAmplitudes(1, reps=1) vqe = VQE(Estimator(), ansatz, _mock_optimizer) result = vqe.compute_minimum_eigenvalue(SparsePauliOp("Z")) self.assertTrue(np.all(result.optimal_point == np.zeros(ansatz.num_parameters))) def test_aux_operators_list(self): """Test list-based aux_operators.""" vqe = VQE(Estimator(), self.ry_wavefunction, SLSQP(maxiter=300)) with self.subTest("Test with an empty list."): result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=[]) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertIsInstance(result.aux_operators_evaluated, list) self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): with self.assertWarns(DeprecationWarning): aux_op1 = PauliSumOp.from_list([("II", 2.0)]) aux_op2 = PauliSumOp.from_list( [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] ) aux_ops = [aux_op1, aux_op2] result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0], 2.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[1][0], 0.0, places=6) # metadata self.assertIsInstance(result.aux_operators_evaluated[0][1], dict) self.assertIsInstance(result.aux_operators_evaluated[1][1], dict) with self.subTest("Test with additional zero operator."): extra_ops = [*aux_ops, 0] result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0], 2.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[1][0], 0.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[2][0], 0.0) # metadata self.assertIsInstance(result.aux_operators_evaluated[0][1], dict) self.assertIsInstance(result.aux_operators_evaluated[1][1], dict) self.assertIsInstance(result.aux_operators_evaluated[2][1], dict) def test_aux_operators_dict(self): """Test dictionary compatibility of aux_operators""" vqe = VQE(Estimator(), self.ry_wavefunction, SLSQP(maxiter=300)) with self.subTest("Test with an empty dictionary."): result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators={}) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertIsInstance(result.aux_operators_evaluated, dict) self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): with self.assertWarns(DeprecationWarning): aux_op1 = PauliSumOp.from_list([("II", 2.0)]) aux_op2 = PauliSumOp.from_list( [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] ) aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated["aux_op1"][0], 2.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["aux_op2"][0], 0.0, places=5) # metadata self.assertIsInstance(result.aux_operators_evaluated["aux_op1"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["aux_op2"][1], dict) with self.subTest("Test with additional zero operator."): extra_ops = {**aux_ops, "zero_operator": 0} result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated["aux_op1"][0], 2.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["aux_op2"][0], 0.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["zero_operator"][0], 0.0) # metadata self.assertIsInstance(result.aux_operators_evaluated["aux_op1"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["aux_op2"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["zero_operator"][1], dict) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test of scikit-quant optimizers.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy from qiskit import BasicAer from qiskit.circuit.library import RealAmplitudes from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.exceptions import MissingOptionalLibraryError from qiskit.opflow import PauliSumOp from qiskit_algorithms import VQE from qiskit_algorithms.optimizers import BOBYQA, SNOBFIT, IMFIL @ddt class TestOptimizers(QiskitAlgorithmsTestCase): """Test scikit-quant optimizers.""" def setUp(self): """Set the problem.""" super().setUp() algorithm_globals.random_seed = 50 with self.assertWarns(DeprecationWarning): self.qubit_op = PauliSumOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) def _optimize(self, optimizer): """launch vqe""" with self.assertWarns(DeprecationWarning): qe = QuantumInstance( BasicAer.get_backend("statevector_simulator"), seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) with self.assertWarns(DeprecationWarning): vqe = VQE(ansatz=RealAmplitudes(), optimizer=optimizer, quantum_instance=qe) result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op) self.assertAlmostEqual(result.eigenvalue.real, -1.857, places=1) def test_bobyqa(self): """BOBYQA optimizer test.""" try: optimizer = BOBYQA(maxiter=150) self._optimize(optimizer) except MissingOptionalLibraryError as ex: self.skipTest(str(ex)) @unittest.skipIf( tuple(map(int, numpy.__version__.split("."))) >= (1, 24, 0), "scikit's SnobFit currently incompatible with NumPy 1.24.0.", ) def test_snobfit(self): """SNOBFIT optimizer test.""" try: optimizer = SNOBFIT(maxiter=100, maxfail=100, maxmp=20) self._optimize(optimizer) except MissingOptionalLibraryError as ex: self.skipTest(str(ex)) @unittest.skipIf( tuple(map(int, numpy.__version__.split("."))) >= (1, 24, 0), "scikit's SnobFit currently incompatible with NumPy 1.24.0.", ) @data((None,), ([(-1, 1), (None, None)],)) @unpack def test_snobfit_missing_bounds(self, bounds): """SNOBFIT optimizer test with missing bounds.""" try: optimizer = SNOBFIT() with self.assertRaises(ValueError): optimizer.minimize( fun=lambda _: 1, # using dummy function (never called) x0=[0.1, 0.1], # dummy initial point bounds=bounds, ) except MissingOptionalLibraryError as ex: self.skipTest(str(ex)) def test_imfil(self): """IMFIL test.""" try: optimizer = IMFIL(maxiter=100) self._optimize(optimizer) except MissingOptionalLibraryError as ex: self.skipTest(str(ex)) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test of NFT optimizer""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from qiskit import BasicAer from qiskit.circuit.library import RealAmplitudes from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.opflow import PauliSumOp from qiskit_algorithms.optimizers import NFT from qiskit_algorithms import VQE class TestOptimizerNFT(QiskitAlgorithmsTestCase): """Test NFT optimizer using RY with VQE""" def setUp(self): super().setUp() algorithm_globals.random_seed = 50 with self.assertWarns(DeprecationWarning): self.qubit_op = PauliSumOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) def test_nft(self): """Test NFT optimizer by using it""" with self.assertWarns(DeprecationWarning): vqe = VQE( ansatz=RealAmplitudes(), optimizer=NFT(), quantum_instance=QuantumInstance( BasicAer.get_backend("statevector_simulator"), seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ), ) result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op) self.assertAlmostEqual(result.eigenvalue.real, -1.857275, places=6) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for PVQD.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial import numpy as np from ddt import data, ddt, unpack from qiskit import QiskitError from qiskit_algorithms.time_evolvers import TimeEvolutionProblem from qiskit_algorithms.optimizers import L_BFGS_B, SPSA, GradientDescent, OptimizerResult from qiskit_algorithms.state_fidelities import ComputeUncompute from qiskit_algorithms.time_evolvers.pvqd import PVQD from qiskit.circuit import Gate, Parameter, QuantumCircuit from qiskit.circuit.library import EfficientSU2 from qiskit.opflow import PauliSumOp from qiskit.primitives import Estimator, Sampler from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.test import QiskitTestCase from qiskit.utils import algorithm_globals # pylint: disable=unused-argument, invalid-name def gradient_supplied(fun, x0, jac, info): """A mock optimizer that checks whether the gradient is supported or not.""" result = OptimizerResult() result.x = x0 result.fun = 0 info["has_gradient"] = jac is not None return result class WhatAmI(Gate): """A custom opaque gate that can be inverted but not decomposed.""" def __init__(self, angle): super().__init__(name="whatami", num_qubits=2, params=[angle]) def inverse(self): return WhatAmI(-self.params[0]) @ddt class TestPVQD(QiskitAlgorithmsTestCase): """Tests for the pVQD algorithm.""" def setUp(self): super().setUp() self.hamiltonian = 0.1 * SparsePauliOp([Pauli("ZZ"), Pauli("IX"), Pauli("XI")]) self.observable = Pauli("ZZ") self.ansatz = EfficientSU2(2, reps=1) self.initial_parameters = np.zeros(self.ansatz.num_parameters) algorithm_globals.random_seed = 123 @data(("ising", True, 2), ("pauli", False, None), ("pauli_sum_op", True, 2)) @unpack def test_pvqd(self, hamiltonian_type, gradient, num_timesteps): """Test a simple evolution.""" time = 0.02 if hamiltonian_type == "ising": hamiltonian = self.hamiltonian elif hamiltonian_type == "pauli_sum_op": with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp(self.hamiltonian) else: # hamiltonian_type == "pauli": hamiltonian = Pauli("XX") # parse input arguments if gradient: optimizer = GradientDescent(maxiter=1) else: optimizer = L_BFGS_B(maxiter=1) sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) # run pVQD keeping track of the energy and the magnetization pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, estimator, optimizer=optimizer, num_timesteps=num_timesteps, ) problem = TimeEvolutionProblem( hamiltonian, time, aux_operators=[hamiltonian, self.observable] ) result = pvqd.evolve(problem) self.assertTrue(len(result.fidelities) == 3) self.assertTrue(np.all(result.times == [0.0, 0.01, 0.02])) self.assertTrue(np.asarray(result.observables).shape == (3, 2)) num_parameters = self.ansatz.num_parameters self.assertTrue( len(result.parameters) == 3 and np.all([len(params) == num_parameters for params in result.parameters]) ) def test_step(self): """Test calling the step method directly.""" sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, estimator, optimizer=L_BFGS_B(maxiter=100), ) # perform optimization for a timestep of 0, then the optimal parameters are the current # ones and the fidelity is 1 theta_next, fidelity = pvqd.step( self.hamiltonian, self.ansatz, self.initial_parameters, dt=0.0, initial_guess=np.zeros_like(self.initial_parameters), ) self.assertTrue(np.allclose(theta_next, self.initial_parameters)) self.assertAlmostEqual(fidelity, 1) def test_get_loss(self): """Test getting the loss function directly.""" sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, estimator, use_parameter_shift=False, ) theta = np.ones(self.ansatz.num_parameters) loss, gradient = pvqd.get_loss( self.hamiltonian, self.ansatz, dt=0.0, current_parameters=theta ) displacement = np.arange(self.ansatz.num_parameters) with self.subTest(msg="check gradient is None"): self.assertIsNone(gradient) with self.subTest(msg="check loss works"): self.assertGreater(loss(displacement), 0) self.assertAlmostEqual(loss(np.zeros_like(theta)), 0) def test_invalid_num_timestep(self): """Test raises if the num_timestep is not positive.""" sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, estimator, optimizer=L_BFGS_B(), num_timesteps=0, ) problem = TimeEvolutionProblem( self.hamiltonian, time=0.01, aux_operators=[self.hamiltonian, self.observable] ) with self.assertRaises(ValueError): _ = pvqd.evolve(problem) def test_initial_guess_and_observables(self): """Test doing no optimizations stays at initial guess.""" initial_guess = np.zeros(self.ansatz.num_parameters) sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, estimator, optimizer=SPSA(maxiter=0, learning_rate=0.1, perturbation=0.01), num_timesteps=10, initial_guess=initial_guess, ) problem = TimeEvolutionProblem( self.hamiltonian, time=0.1, aux_operators=[self.hamiltonian, self.observable] ) result = pvqd.evolve(problem) observables = result.aux_ops_evaluated self.assertEqual(observables[0], 0.1) # expected energy self.assertEqual(observables[1], 1) # expected magnetization def test_zero_parameters(self): """Test passing an ansatz with zero parameters raises an error.""" problem = TimeEvolutionProblem(self.hamiltonian, time=0.02) sampler = Sampler() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, QuantumCircuit(2), np.array([]), optimizer=SPSA(maxiter=10, learning_rate=0.1, perturbation=0.01), ) with self.assertRaises(QiskitError): _ = pvqd.evolve(problem) def test_initial_state_raises(self): """Test passing an initial state raises an error for now.""" initial_state = QuantumCircuit(2) initial_state.x(0) problem = TimeEvolutionProblem( self.hamiltonian, time=0.02, initial_state=initial_state, ) sampler = Sampler() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, optimizer=SPSA(maxiter=0, learning_rate=0.1, perturbation=0.01), ) with self.assertRaises(NotImplementedError): _ = pvqd.evolve(problem) def test_aux_ops_raises(self): """Test passing auxiliary operators with no estimator raises an error.""" problem = TimeEvolutionProblem( self.hamiltonian, time=0.02, aux_operators=[self.hamiltonian, self.observable] ) sampler = Sampler() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, optimizer=SPSA(maxiter=0, learning_rate=0.1, perturbation=0.01), ) with self.assertRaises(ValueError): _ = pvqd.evolve(problem) class TestPVQDUtils(QiskitTestCase): """Test some utility functions for PVQD.""" def setUp(self): super().setUp() self.hamiltonian = 0.1 * SparsePauliOp([Pauli("ZZ"), Pauli("IX"), Pauli("XI")]) self.ansatz = EfficientSU2(2, reps=1) def test_gradient_supported(self): """Test the gradient support is correctly determined.""" # gradient supported here wrapped = EfficientSU2(2) # a circuit wrapped into a big instruction plain = wrapped.decompose() # a plain circuit with already supported instructions # gradients not supported on the following circuits x = Parameter("x") duplicated = QuantumCircuit(2) duplicated.rx(x, 0) duplicated.rx(x, 1) needs_chainrule = QuantumCircuit(2) needs_chainrule.rx(2 * x, 0) custom_gate = WhatAmI(x) unsupported = QuantumCircuit(2) unsupported.append(custom_gate, [0, 1]) tests = [ (wrapped, True), # tuple: (circuit, gradient support) (plain, True), (duplicated, False), (needs_chainrule, False), (unsupported, False), ] # used to store the info if a gradient callable is passed into the # optimizer of not info = {"has_gradient": None} optimizer = partial(gradient_supplied, info=info) sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity=fidelity_primitive, ansatz=None, initial_parameters=np.array([]), estimator=estimator, optimizer=optimizer, ) problem = TimeEvolutionProblem(self.hamiltonian, time=0.01) for circuit, expected_support in tests: with self.subTest(circuit=circuit, expected_support=expected_support): pvqd.ansatz = circuit pvqd.initial_parameters = np.zeros(circuit.num_parameters) _ = pvqd.evolve(problem) self.assertEqual(info["has_gradient"], expected_support) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test evolver problem class.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import data, ddt from numpy.testing import assert_raises from qiskit import QuantumCircuit from qiskit_algorithms import TimeEvolutionProblem from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector from qiskit.circuit import Parameter from qiskit.opflow import Y, Z, One, X, Zero, PauliSumOp @ddt class TestTimeEvolutionProblem(QiskitAlgorithmsTestCase): """Test evolver problem class.""" def test_init_default(self): """Tests that all default fields are initialized correctly.""" hamiltonian = Y time = 2.5 initial_state = One evo_problem = TimeEvolutionProblem(hamiltonian, time, initial_state) expected_hamiltonian = Y expected_time = 2.5 expected_initial_state = One expected_aux_operators = None expected_t_param = None expected_param_value_dict = None self.assertEqual(evo_problem.hamiltonian, expected_hamiltonian) self.assertEqual(evo_problem.time, expected_time) self.assertEqual(evo_problem.initial_state, expected_initial_state) self.assertEqual(evo_problem.aux_operators, expected_aux_operators) self.assertEqual(evo_problem.t_param, expected_t_param) self.assertEqual(evo_problem.param_value_map, expected_param_value_dict) @data(QuantumCircuit(1), Statevector([1, 0])) def test_init_all(self, initial_state): """Tests that all fields are initialized correctly.""" t_parameter = Parameter("t") with self.assertWarns(DeprecationWarning): hamiltonian = t_parameter * Z + Y time = 2 aux_operators = [X, Y] param_value_dict = {t_parameter: 3.2} evo_problem = TimeEvolutionProblem( hamiltonian, time, initial_state, aux_operators, t_param=t_parameter, param_value_map=param_value_dict, ) with self.assertWarns(DeprecationWarning): expected_hamiltonian = Y + t_parameter * Z expected_time = 2 expected_type = QuantumCircuit expected_aux_operators = [X, Y] expected_t_param = t_parameter expected_param_value_dict = {t_parameter: 3.2} with self.assertWarns(DeprecationWarning): self.assertEqual(evo_problem.hamiltonian, expected_hamiltonian) self.assertEqual(evo_problem.time, expected_time) self.assertEqual(type(evo_problem.initial_state), expected_type) self.assertEqual(evo_problem.aux_operators, expected_aux_operators) self.assertEqual(evo_problem.t_param, expected_t_param) self.assertEqual(evo_problem.param_value_map, expected_param_value_dict) def test_validate_params(self): """Tests expected errors are thrown on parameters mismatch.""" param_x = Parameter("x") with self.subTest(msg="Parameter missing in dict."): with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Y")]), param_x) evolution_problem = TimeEvolutionProblem(hamiltonian, 2, Zero) with assert_raises(ValueError): evolution_problem.validate_params() if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test TrotterQRTE.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy as np from scipy.linalg import expm from numpy.testing import assert_raises from qiskit_algorithms.time_evolvers import TimeEvolutionProblem, TrotterQRTE from qiskit.primitives import Estimator from qiskit import QuantumCircuit from qiskit.circuit.library import ZGate from qiskit.quantum_info import Statevector, Pauli, SparsePauliOp from qiskit.utils import algorithm_globals from qiskit.circuit import Parameter from qiskit.opflow import PauliSumOp, X, MatrixOp from qiskit.synthesis import SuzukiTrotter, QDrift @ddt class TestTrotterQRTE(QiskitAlgorithmsTestCase): """TrotterQRTE tests.""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed @data( ( None, Statevector([0.29192658 - 0.45464871j, 0.70807342 - 0.45464871j]), ), ( SuzukiTrotter(), Statevector([0.29192658 - 0.84147098j, 0.0 - 0.45464871j]), ), ) @unpack def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state): """Test for default TrotterQRTE on a single qubit.""" with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) initial_state = QuantumCircuit(1) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) trotter_qrte = TrotterQRTE(product_formula=product_formula) evolution_result_state_circuit = trotter_qrte.evolve(evolution_problem).evolved_state np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result_state_circuit).data, expected_state.data ) @data((SparsePauliOp(["X", "Z"]), None), (SparsePauliOp(["X", "Z"]), Parameter("t"))) @unpack def test_trotter_qrte_trotter(self, operator, t_param): """Test for default TrotterQRTE on a single qubit with auxiliary operators.""" if not t_param is None: operator = SparsePauliOp(operator.paulis, np.array([t_param, 1])) # LieTrotter with 1 rep aux_ops = [Pauli("X"), Pauli("Y")] initial_state = QuantumCircuit(1) time = 3 num_timesteps = 2 evolution_problem = TimeEvolutionProblem( operator, time, initial_state, aux_ops, t_param=t_param ) estimator = Estimator() expected_psi, expected_observables_result = self._get_expected_trotter_qrte( operator, time, num_timesteps, initial_state, aux_ops, t_param, ) expected_evolved_state = Statevector(expected_psi) algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator, num_timesteps=num_timesteps) evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, expected_evolved_state.data, ) aux_ops_result = evolution_result.aux_ops_evaluated expected_aux_ops_result = [ (expected_observables_result[-1][0], {"variance": 0, "shots": 0}), (expected_observables_result[-1][1], {"variance": 0, "shots": 0}), ] means = [element[0] for element in aux_ops_result] expected_means = [element[0] for element in expected_aux_ops_result] np.testing.assert_array_almost_equal(means, expected_means) vars_and_shots = [element[1] for element in aux_ops_result] expected_vars_and_shots = [element[1] for element in expected_aux_ops_result] observables_result = evolution_result.observables expected_observables_result = [ [(o, {"variance": 0, "shots": 0}) for o in eor] for eor in expected_observables_result ] means = [sub_element[0] for element in observables_result for sub_element in element] expected_means = [ sub_element[0] for element in expected_observables_result for sub_element in element ] np.testing.assert_array_almost_equal(means, expected_means) for computed, expected in zip(vars_and_shots, expected_vars_and_shots): self.assertAlmostEqual(computed.pop("variance", 0), expected["variance"], 2) self.assertEqual(computed.pop("shots", 0), expected["shots"]) @data( ( PauliSumOp(SparsePauliOp([Pauli("XY"), Pauli("YX")])), Statevector([-0.41614684 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.90929743 + 0.0j]), ), ( PauliSumOp(SparsePauliOp([Pauli("ZZ"), Pauli("ZI"), Pauli("IZ")])), Statevector([-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j]), ), ( Pauli("YY"), Statevector([0.54030231 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.84147098j]), ), ) @unpack def test_trotter_qrte_trotter_two_qubits(self, operator, expected_state): """Test for TrotterQRTE on two qubits with various types of a Hamiltonian.""" # LieTrotter with 1 rep initial_state = QuantumCircuit(2) evolution_problem = TimeEvolutionProblem(operator, 1, initial_state) trotter_qrte = TrotterQRTE() evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, expected_state.data ) @data( (QuantumCircuit(1), Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j])), ( QuantumCircuit(1).compose(ZGate(), [0]), Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j]), ), ) @unpack def test_trotter_qrte_qdrift(self, initial_state, expected_state): """Test for TrotterQRTE with QDrift.""" with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(product_formula=QDrift()) evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, expected_state.data, ) @data((Parameter("t"), {}), (None, {Parameter("x"): 2}), (None, None)) @unpack def test_trotter_qrte_trotter_param_errors(self, t_param, param_value_dict): """Test TrotterQRTE with raising errors for parameters.""" with self.assertWarns(DeprecationWarning): operator = Parameter("t") * PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( SparsePauliOp([Pauli("Z")]) ) initial_state = QuantumCircuit(1) self._run_error_test(initial_state, operator, None, None, t_param, param_value_dict) @data(([Pauli("X"), Pauli("Y")], None)) @unpack def test_trotter_qrte_trotter_aux_ops_errors(self, aux_ops, estimator): """Test TrotterQRTE with raising errors.""" with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( SparsePauliOp([Pauli("Z")]) ) initial_state = QuantumCircuit(1) self._run_error_test(initial_state, operator, aux_ops, estimator, None, None) @data( (X, QuantumCircuit(1)), (MatrixOp([[1, 1], [0, 1]]), QuantumCircuit(1)), (PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp(SparsePauliOp([Pauli("Z")])), None), ( SparsePauliOp([Pauli("X"), Pauli("Z")], np.array([Parameter("a"), Parameter("b")])), QuantumCircuit(1), ), ) @unpack def test_trotter_qrte_trotter_hamiltonian_errors(self, operator, initial_state): """Test TrotterQRTE with raising errors for evolution problem content.""" self._run_error_test(initial_state, operator, None, None, None, None) @staticmethod def _run_error_test(initial_state, operator, aux_ops, estimator, t_param, param_value_dict): time = 1 algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator) with assert_raises(ValueError): evolution_problem = TimeEvolutionProblem( operator, time, initial_state, aux_ops, t_param=t_param, param_value_map=param_value_dict, ) _ = trotter_qrte.evolve(evolution_problem) @staticmethod def _get_expected_trotter_qrte(operator, time, num_timesteps, init_state, observables, t_param): """Compute reference values for Trotter evolution via exact matrix exponentiation.""" dt = time / num_timesteps observables = [obs.to_matrix() for obs in observables] psi = Statevector(init_state).data if t_param is None: ops = [Pauli(op).to_matrix() * np.real(coeff) for op, coeff in operator.to_list()] observable_results = [] observable_results.append([np.real(np.conj(psi).dot(obs).dot(psi)) for obs in observables]) for n in range(num_timesteps): if t_param is not None: time_value = (n + 1) * dt bound = operator.assign_parameters([time_value]) ops = [Pauli(op).to_matrix() * np.real(coeff) for op, coeff in bound.to_list()] for op in ops: psi = expm(-1j * op * dt).dot(psi) observable_results.append( [np.real(np.conj(psi).dot(obs).dot(psi)) for obs in observables] ) return psi, observable_results if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Classical Imaginary Evolver.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import data, ddt, unpack import numpy as np from qiskit_algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem from qiskit.quantum_info.states.statevector import Statevector from qiskit.quantum_info import SparsePauliOp from qiskit import QuantumCircuit from qiskit_algorithms import SciPyImaginaryEvolver from qiskit.opflow import PauliSumOp @ddt class TestSciPyImaginaryEvolver(QiskitAlgorithmsTestCase): """Test SciPy Imaginary Evolver.""" def create_hamiltonian_lattice(self, num_sites: int) -> SparsePauliOp: """Creates an Ising Hamiltonian on a lattice.""" j_const = 0.1 g_const = -1.0 zz_op = ["I" * i + "ZZ" + "I" * (num_sites - i - 2) for i in range(num_sites - 1)] x_op = ["I" * i + "X" + "I" * (num_sites - i - 1) for i in range(num_sites)] return SparsePauliOp(zz_op) * j_const + SparsePauliOp(x_op) * g_const @data( (Statevector.from_label("0"), 100, SparsePauliOp("X"), Statevector.from_label("-")), (Statevector.from_label("0"), 100, SparsePauliOp("-X"), Statevector.from_label("+")), ) @unpack def test_evolve( self, initial_state: Statevector, tau: float, hamiltonian: SparsePauliOp, expected_state: Statevector, ): """Initializes a classical imaginary evolver and evolves a state to find the ground state. It compares the solution with the first eigenstate of the hamiltonian. """ expected_state_matrix = expected_state.data evolution_problem = TimeEvolutionProblem(hamiltonian, tau, initial_state) classic_evolver = SciPyImaginaryEvolver(num_timesteps=300) result = classic_evolver.evolve(evolution_problem) with self.subTest("Amplitudes"): np.testing.assert_allclose( np.absolute(result.evolved_state.data), np.absolute(expected_state_matrix), atol=1e-10, rtol=0, ) with self.subTest("Phases"): np.testing.assert_allclose( np.angle(result.evolved_state.data), np.angle(expected_state_matrix), atol=1e-10, rtol=0, ) @data( ( Statevector.from_label("0" * 5), SparsePauliOp.from_sparse_list([("X", [i], 1) for i in range(5)], num_qubits=5), 5, ), (Statevector.from_label("0"), SparsePauliOp("X"), 1), ) @unpack def test_observables( self, initial_state: Statevector, hamiltonian: SparsePauliOp, nqubits: int ): """Tests if the observables are properly evaluated at each timestep.""" time_ev = 5.0 observables = {"Energy": hamiltonian, "Z": SparsePauliOp("Z" * nqubits)} evolution_problem = TimeEvolutionProblem( hamiltonian, time_ev, initial_state, aux_operators=observables ) classic_evolver = SciPyImaginaryEvolver(num_timesteps=300) result = classic_evolver.evolve(evolution_problem) z_mean, z_std = result.observables["Z"] time_vector = result.times expected_z = 1 / (np.cosh(time_vector) ** 2 + np.sinh(time_vector) ** 2) expected_z_std = np.zeros_like(expected_z) np.testing.assert_allclose(z_mean, expected_z**nqubits, atol=1e-10, rtol=0) np.testing.assert_allclose(z_std, expected_z_std, atol=1e-10, rtol=0) def test_quantum_circuit_initial_state(self): """Tests if the system can be evolved with a quantum circuit as an initial state.""" qc = QuantumCircuit(3) qc.h(0) qc.cx(0, range(1, 3)) evolution_problem = TimeEvolutionProblem( hamiltonian=SparsePauliOp("X" * 3), time=1.0, initial_state=qc ) classic_evolver = SciPyImaginaryEvolver(num_timesteps=5) result = classic_evolver.evolve(evolution_problem) self.assertEqual(result.evolved_state, Statevector(qc)) def test_paulisumop_hamiltonian(self): """Tests if the hamiltonian can be a PauliSumOp""" with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp.from_list( [ ("XI", 1), ("IX", 1), ] ) observable = PauliSumOp.from_list([("ZZ", 1)]) evolution_problem = TimeEvolutionProblem( hamiltonian=hamiltonian, time=1.0, initial_state=Statevector.from_label("00"), aux_operators={"ZZ": observable}, ) classic_evolver = SciPyImaginaryEvolver(num_timesteps=5) result = classic_evolver.evolve(evolution_problem) expected = 1 / (np.cosh(1.0) ** 2 + np.sinh(1.0) ** 2) np.testing.assert_almost_equal(result.aux_ops_evaluated["ZZ"][0], expected**2) def test_error_time_dependency(self): """Tests if an error is raised for a time dependent Hamiltonian.""" evolution_problem = TimeEvolutionProblem( hamiltonian=SparsePauliOp("X" * 3), time=1.0, initial_state=Statevector.from_label("0" * 3), t_param=0, ) classic_evolver = SciPyImaginaryEvolver(num_timesteps=5) with self.assertRaises(ValueError): classic_evolver.evolve(evolution_problem) def test_no_time_steps(self): """Tests if the evolver handles some edge cases related to the number of timesteps.""" evolution_problem = TimeEvolutionProblem( hamiltonian=SparsePauliOp("X"), time=1.0, initial_state=Statevector.from_label("0"), aux_operators={"Energy": SparsePauliOp("X")}, ) with self.subTest("0 timesteps"): with self.assertRaises(ValueError): classic_evolver = SciPyImaginaryEvolver(num_timesteps=0) classic_evolver.evolve(evolution_problem) with self.subTest("1 timestep"): classic_evolver = SciPyImaginaryEvolver(num_timesteps=1) result = classic_evolver.evolve(evolution_problem) np.testing.assert_equal(result.times, np.array([0.0, 1.0])) with self.subTest("Negative timesteps"): with self.assertRaises(ValueError): classic_evolver = SciPyImaginaryEvolver(num_timesteps=-5) classic_evolver.evolve(evolution_problem) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Classical Real Evolver.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import data, ddt, unpack import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit_algorithms import SciPyRealEvolver, TimeEvolutionProblem from qiskit.quantum_info import Statevector, SparsePauliOp def zero(n): """Auxiliary function to create an initial state on n qubits.""" qr = QuantumRegister(n) qc = QuantumCircuit(qr) return Statevector(qc) def one(n): """Auxiliary function to create an initial state on n qubits.""" qr = QuantumRegister(n) qc = QuantumCircuit(qr) qc.x(qr) return Statevector(qc) @ddt class TestClassicalRealEvolver(QiskitAlgorithmsTestCase): """Test Classical Real Evolver.""" @data( (one(1), np.pi / 2, SparsePauliOp("X"), -1.0j * zero(1)), ( one(1).expand(zero(1)), np.pi / 2, SparsePauliOp(["XX", "YY"], [0.5, 0.5]), -1.0j * zero(1).expand(one(1)), ), ( one(1).expand(zero(1)), np.pi / 4, SparsePauliOp(["XX", "YY"], [0.5, 0.5]), ((one(1).expand(zero(1)) - 1.0j * zero(1).expand(one(1)))) / np.sqrt(2), ), (zero(12), np.pi / 2, SparsePauliOp("X" * 12), -1.0j * (one(12))), ) @unpack def test_evolve( self, initial_state: Statevector, time_ev: float, hamiltonian: SparsePauliOp, expected_state: Statevector, ): """Initializes a classical real evolver and evolves a state.""" evolution_problem = TimeEvolutionProblem(hamiltonian, time_ev, initial_state) classic_evolver = SciPyRealEvolver(num_timesteps=1) result = classic_evolver.evolve(evolution_problem) np.testing.assert_allclose( result.evolved_state.data, expected_state.data, atol=1e-10, rtol=0, ) def test_observables(self): """Tests if the observables are properly evaluated at each timestep.""" initial_state = zero(1) time_ev = 10.0 hamiltonian = SparsePauliOp("X") observables = {"Energy": SparsePauliOp("X"), "Z": SparsePauliOp("Z")} evolution_problem = TimeEvolutionProblem( hamiltonian, time_ev, initial_state, aux_operators=observables ) classic_evolver = SciPyRealEvolver(num_timesteps=10) result = classic_evolver.evolve(evolution_problem) z_mean, z_std = result.observables["Z"] timesteps = z_mean.shape[0] time_vector = np.linspace(0, time_ev, timesteps) expected_z = 1 - 2 * (np.sin(time_vector)) ** 2 expected_z_std = np.zeros_like(expected_z) np.testing.assert_allclose(z_mean, expected_z, atol=1e-10, rtol=0) np.testing.assert_allclose(z_std, expected_z_std, atol=1e-10, rtol=0) np.testing.assert_equal(time_vector, result.times) def test_quantum_circuit_initial_state(self): """Tests if the system can be evolved with a quantum circuit as an initial state.""" qc = QuantumCircuit(3) qc.h(0) qc.cx(0, range(1, 3)) evolution_problem = TimeEvolutionProblem( hamiltonian=SparsePauliOp("X" * 3), time=2 * np.pi, initial_state=qc ) classic_evolver = SciPyRealEvolver(num_timesteps=500) result = classic_evolver.evolve(evolution_problem) np.testing.assert_almost_equal( result.evolved_state.data, np.array([1, 0, 0, 0, 0, 0, 0, 1]) / np.sqrt(2), decimal=10, ) def test_error_time_dependency(self): """Tests if an error is raised for time dependent hamiltonian.""" evolution_problem = TimeEvolutionProblem( hamiltonian=SparsePauliOp("X" * 3), time=1.0, initial_state=zero(3), t_param=0 ) classic_evolver = SciPyRealEvolver(num_timesteps=5) with self.assertRaises(ValueError): classic_evolver.evolve(evolution_problem) def test_no_time_steps(self): """Tests if the evolver handles some edge cases related to the number of timesteps.""" evolution_problem = TimeEvolutionProblem( hamiltonian=SparsePauliOp("X"), time=1.0, initial_state=zero(1), aux_operators={"Energy": SparsePauliOp("X")}, ) with self.subTest("0 timesteps"): with self.assertRaises(ValueError): classic_evolver = SciPyRealEvolver(num_timesteps=0) classic_evolver.evolve(evolution_problem) with self.subTest("1 timestep"): classic_evolver = SciPyRealEvolver(num_timesteps=1) result = classic_evolver.evolve(evolution_problem) np.testing.assert_equal(result.times, np.array([0.0, 1.0])) with self.subTest("Negative timesteps"): with self.assertRaises(ValueError): classic_evolver = SciPyRealEvolver(num_timesteps=-5) classic_evolver.evolve(evolution_problem) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Variational Quantum Imaginary Time Evolution algorithm.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit_algorithms.gradients import LinCombQGT, LinCombEstimatorGradient from qiskit.primitives import Estimator from qiskit.quantum_info import SparsePauliOp, Pauli from qiskit.utils import algorithm_globals from qiskit_algorithms import TimeEvolutionProblem, VarQITE from qiskit_algorithms.time_evolvers.variational import ( ImaginaryMcLachlanPrinciple, ) from qiskit.circuit.library import EfficientSU2 from qiskit.quantum_info import Statevector @ddt class TestVarQITE(QiskitAlgorithmsTestCase): """Test Variational Quantum Imaginary Time Evolution algorithm.""" def setUp(self): super().setUp() self.seed = 11 np.random.seed(self.seed) def test_run_d_1_with_aux_ops(self): """Test VarQITE for d = 1 and t = 1 with evaluating auxiliary operator and the Forward Euler solver..""" observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) aux_ops = [Pauli("XX"), Pauli("YZ")] d = 1 ansatz = EfficientSU2(observable.num_qubits, reps=d) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) for i in range(len(parameters)): init_param_values[i] = np.pi / 2 init_param_values[0] = 1 time = 1 evolution_problem = TimeEvolutionProblem(observable, time, aux_operators=aux_ops) thetas_expected = [ 0.87984606025879, 2.04681975664763, 2.68980594039104, 2.75915988512186, 2.38796546567171, 1.78144857115127, 2.13109162826101, 1.9259609596416, ] thetas_expected_shots = [ 0.9392668013702317, 1.8756706968454864, 2.6915067128662398, 2.655420131540562, 2.174687086978046, 1.6997059390911056, 1.8056912289547045, 1.939353810908912, ] with self.subTest(msg="Test exact backend."): algorithm_globals.random_seed = self.seed estimator = Estimator() qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator) var_principle = ImaginaryMcLachlanPrinciple(qgt, gradient) var_qite = VarQITE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) evolution_result = var_qite.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] expected_aux_ops = (-0.2177982985749799, 0.2556790598588627) for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected[i], decimal=2 ) np.testing.assert_array_almost_equal( [result[0] for result in aux_ops], expected_aux_ops ) with self.subTest(msg="Test shot-based backend."): algorithm_globals.random_seed = self.seed estimator = Estimator(options={"shots": 4096, "seed": self.seed}) qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator) var_principle = ImaginaryMcLachlanPrinciple(qgt, gradient) var_qite = VarQITE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) evolution_result = var_qite.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] expected_aux_ops = (-0.24629853310903974, 0.2518122871921184) for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected_shots[i], decimal=2 ) np.testing.assert_array_almost_equal( [result[0] for result in aux_ops], expected_aux_ops ) def test_run_d_1_t_7(self): """Test VarQITE for d = 1 and t = 7 with RK45 ODE solver.""" observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) d = 1 ansatz = EfficientSU2(observable.num_qubits, reps=d) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) for i in range(len(parameters)): init_param_values[i] = np.pi / 2 init_param_values[0] = 1 var_principle = ImaginaryMcLachlanPrinciple() time = 7 var_qite = VarQITE( ansatz, init_param_values, var_principle, ode_solver="RK45", num_timesteps=25 ) thetas_expected = [ 0.828917365718767, 1.88481074798033, 3.14111335991238, 3.14125849601269, 2.33768562678401, 1.78670990729437, 2.04214275514208, 2.04009918594422, ] self._test_helper(observable, thetas_expected, time, var_qite, 2) def test_run_d_2(self): """Test VarQITE for d = 2 and t = 1 with RK45 ODE solver.""" observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) d = 2 ansatz = EfficientSU2(observable.num_qubits, reps=d) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) for i in range(len(parameters)): init_param_values[i] = np.pi / 4 var_principle = ImaginaryMcLachlanPrinciple() time = 1 var_qite = VarQITE( ansatz, init_param_values, var_principle, ode_solver="RK45", num_timesteps=25 ) thetas_expected = [ 1.29495364023786, 1.08970061333559, 0.667488228710748, 0.500122687902944, 1.4377736672043, 1.22881086103085, 0.729773048146251, 1.01698854755226, 0.050807780587492, 0.294828474947149, 0.839305697704923, 0.663689581255428, ] self._test_helper(observable, thetas_expected, time, var_qite, 4) def test_run_d_1_time_dependent(self): """Test VarQITE for d = 1 and a time-dependent Hamiltonian with the Forward Euler solver.""" t_param = Parameter("t") time = 1 observable = SparsePauliOp(["I", "Z"], np.array([0, t_param])) x, y, z = [Parameter(s) for s in "xyz"] ansatz = QuantumCircuit(1) ansatz.rz(x, 0) ansatz.ry(y, 0) ansatz.rz(z, 0) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) x_val = 0 y_val = np.pi / 2 z_val = 0 init_param_values[0] = x_val init_param_values[1] = y_val init_param_values[2] = z_val evolution_problem = TimeEvolutionProblem(observable, time, t_param=t_param) thetas_expected = [1.83881002737137e-18, 2.43224994794434, -3.05311331771918e-18] thetas_expected_shots = [1.83881002737137e-18, 2.43224994794434, -3.05311331771918e-18] state_expected = Statevector([0.34849948 + 0.0j, 0.93730897 + 0.0j]).to_dict() # the expected final state is Statevector([0.34849948+0.j, 0.93730897+0.j]) with self.subTest(msg="Test exact backend."): algorithm_globals.random_seed = self.seed estimator = Estimator() var_principle = ImaginaryMcLachlanPrinciple() var_qite = VarQITE( ansatz, init_param_values, var_principle, estimator, num_timesteps=100 ) evolution_result = var_qite.evolve(evolution_problem) evolved_state = evolution_result.evolved_state parameter_values = evolution_result.parameter_values[-1] for key, evolved_value in Statevector(evolved_state).to_dict().items(): # np.allclose works with complex numbers self.assertTrue(np.allclose(evolved_value, state_expected[key], 1e-02)) for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected[i], decimal=2 ) with self.subTest(msg="Test shot-based backend."): algorithm_globals.random_seed = self.seed estimator = Estimator(options={"shots": 4 * 4096, "seed": self.seed}) var_principle = ImaginaryMcLachlanPrinciple() var_qite = VarQITE( ansatz, init_param_values, var_principle, estimator, num_timesteps=100 ) evolution_result = var_qite.evolve(evolution_problem) evolved_state = evolution_result.evolved_state parameter_values = evolution_result.parameter_values[-1] for key, evolved_value in Statevector(evolved_state).to_dict().items(): # np.allclose works with complex numbers self.assertTrue(np.allclose(evolved_value, state_expected[key], 1e-02)) for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected_shots[i], decimal=2 ) def _test_helper(self, observable, thetas_expected, time, var_qite, decimal): evolution_problem = TimeEvolutionProblem(observable, time) evolution_result = var_qite.evolve(evolution_problem) parameter_values = evolution_result.parameter_values[-1] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected[i], decimal=decimal ) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Variational Quantum Real Time Evolution algorithm.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter, ParameterVector from qiskit_algorithms.gradients import LinCombQGT, DerivativeType, LinCombEstimatorGradient from qiskit.primitives import Estimator from qiskit.utils import algorithm_globals from qiskit.quantum_info import SparsePauliOp, Pauli, Statevector from qiskit_algorithms import TimeEvolutionProblem, VarQRTE from qiskit_algorithms.time_evolvers.variational import ( RealMcLachlanPrinciple, ) from qiskit.circuit.library import EfficientSU2 @ddt class TestVarQRTE(QiskitAlgorithmsTestCase): """Test Variational Quantum Real Time Evolution algorithm.""" def setUp(self): super().setUp() self.seed = 11 np.random.seed(self.seed) def test_time_dependent_hamiltonian(self): """Simple test case with a time dependent Hamiltonian.""" t_param = Parameter("t") hamiltonian = SparsePauliOp(["Z"], np.array(t_param)) x = ParameterVector("x", 3) circuit = QuantumCircuit(1) circuit.rz(x[0], 0) circuit.ry(x[1], 0) circuit.rz(x[2], 0) initial_parameters = np.array([0, np.pi / 2, 0]) def expected_state(time): # possible with pen and paper as the Hamiltonian is diagonal return 1 / np.sqrt(2) * np.array([np.exp(-0.5j * time**2), np.exp(0.5j * time**2)]) final_time = 0.75 evolution_problem = TimeEvolutionProblem(hamiltonian, t_param=t_param, time=final_time) estimator = Estimator() varqrte = VarQRTE(circuit, initial_parameters, estimator=estimator) result = varqrte.evolve(evolution_problem) final_parameters = result.parameter_values[-1] final_state = Statevector(circuit.bind_parameters(final_parameters)).to_dict() final_expected_state = expected_state(final_time) for key, expected_value in final_state.items(): self.assertTrue(np.allclose(final_expected_state[int(key)], expected_value, 1e-02)) def test_run_d_1_with_aux_ops(self): """Test VarQRTE for d = 1 and t = 0.1 with evaluating auxiliary operators and the Forward Euler solver.""" observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) aux_ops = [Pauli("XX"), Pauli("YZ")] d = 1 ansatz = EfficientSU2(observable.num_qubits, reps=d) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) for i in range(len(parameters)): init_param_values[i] = np.pi / 2 init_param_values[0] = 1 time = 0.1 evolution_problem = TimeEvolutionProblem(observable, time, aux_operators=aux_ops) thetas_expected = [ 0.886841151529636, 1.53852629218265, 1.57099556659882, 1.5889216657174, 1.5996487153364, 1.57018939515742, 1.63950719260698, 1.53853696496673, ] thetas_expected_shots = [ 0.886975892820015, 1.53822607733397, 1.57058096749141, 1.59023223608564, 1.60105707043745, 1.57018042397236, 1.64010900210835, 1.53959523034133, ] with self.subTest(msg="Test exact backend."): algorithm_globals.random_seed = self.seed estimator = Estimator() qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) evolution_result = var_qrte.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] expected_aux_ops = [0.06836996703935797, 0.7711574493422457] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected[i], decimal=2 ) np.testing.assert_array_almost_equal( [result[0] for result in aux_ops], expected_aux_ops ) with self.subTest(msg="Test shot-based backend."): algorithm_globals.random_seed = self.seed estimator = Estimator(options={"shots": 4 * 4096, "seed": self.seed}) qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) evolution_result = var_qrte.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] expected_aux_ops = [ 0.070436, 0.777938, ] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected_shots[i], decimal=2 ) np.testing.assert_array_almost_equal( [result[0] for result in aux_ops], expected_aux_ops, decimal=2 ) def test_run_d_2(self): """Test VarQRTE for d = 2 and t = 1 with RK45 ODE solver.""" observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) d = 2 ansatz = EfficientSU2(observable.num_qubits, reps=d) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) for i in range(len(parameters)): init_param_values[i] = np.pi / 4 estimator = Estimator() qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) param_dict = dict(zip(parameters, init_param_values)) time = 1 var_qrte = VarQRTE(ansatz, param_dict, var_principle, ode_solver="RK45", num_timesteps=25) thetas_expected = [ 0.348407744196573, 0.919404626262464, 1.18189219371626, 0.771011177789998, 0.734384256533924, 0.965289520781899, 1.14441687204195, 1.17231927568571, 1.03014771379412, 0.867266309056347, 0.699606368428206, 0.610788576398685, ] self._test_helper(observable, thetas_expected, time, var_qrte) def test_run_d_1_time_dependent(self): """Test VarQRTE for d = 1 and a time-dependent Hamiltonian with the Forward Euler solver.""" t_param = Parameter("t") time = 1 observable = SparsePauliOp(["I", "Z"], np.array([0, t_param])) x, y, z = [Parameter(s) for s in "xyz"] ansatz = QuantumCircuit(1) ansatz.rz(x, 0) ansatz.ry(y, 0) ansatz.rz(z, 0) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) x_val = 0 y_val = np.pi / 2 z_val = 0 init_param_values[0] = x_val init_param_values[1] = y_val init_param_values[2] = z_val evolution_problem = TimeEvolutionProblem(observable, time, t_param=t_param) thetas_expected = [1.27675647831902e-18, 1.5707963267949, 0.990000000000001] thetas_expected_shots = [0.00534345821469238, 1.56260960200375, 0.990017403734316] # the expected final state is Statevector([0.62289306-0.33467034j, 0.62289306+0.33467034j]) with self.subTest(msg="Test exact backend."): algorithm_globals.random_seed = self.seed estimator = Estimator() qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=100 ) evolution_result = var_qrte.evolve(evolution_problem) parameter_values = evolution_result.parameter_values[-1] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected[i], decimal=2 ) with self.subTest(msg="Test shot-based backend."): algorithm_globals.random_seed = self.seed estimator = Estimator(options={"shots": 4 * 4096, "seed": self.seed}) qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=100 ) evolution_result = var_qrte.evolve(evolution_problem) parameter_values = evolution_result.parameter_values[-1] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected_shots[i], decimal=2 ) def _test_helper(self, observable, thetas_expected, time, var_qrte): evolution_problem = TimeEvolutionProblem(observable, time) evolution_result = var_qrte.evolve(evolution_problem) parameter_values = evolution_result.parameter_values[-1] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal(float(parameter_value), thetas_expected[i], decimal=4) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """BasicAer Backends Test.""" from qiskit import BasicAer from qiskit.providers.basicaer import BasicAerProvider from qiskit.providers.exceptions import QiskitBackendNotFoundError from qiskit.test import providers class TestBasicAerBackends(providers.ProviderTestCase): """Qiskit BasicAer Backends (Object) Tests.""" provider_cls = BasicAerProvider backend_name = "qasm_simulator" def test_deprecated(self): """Test that deprecated names map the same backends as the new names.""" def _get_first_available_backend(provider, backend_names): """Gets the first available backend.""" if isinstance(backend_names, str): backend_names = [backend_names] for backend_name in backend_names: try: return provider.get_backend(backend_name).name() except QiskitBackendNotFoundError: pass return None deprecated_names = BasicAer._deprecated_backend_names() for oldname, newname in deprecated_names.items(): expected = ( "WARNING:qiskit.providers.providerutils:Backend '%s' is deprecated. " "Use '%s'." % (oldname, newname) ) with self.subTest(oldname=oldname, newname=newname): with self.assertLogs("qiskit.providers.providerutils", level="WARNING") as context: resolved_newname = _get_first_available_backend(BasicAer, newname) real_backend = BasicAer.get_backend(resolved_newname) self.assertEqual(BasicAer.backends(oldname)[0], real_backend) self.assertEqual(context.output, [expected]) def test_aliases_fail(self): """Test a failing backend lookup.""" self.assertRaises(QiskitBackendNotFoundError, BasicAer.get_backend, "bad_name") def test_aliases_return_empty_list(self): """Test backends() return an empty list if name is unknown.""" self.assertEqual(BasicAer.backends("bad_name"), [])
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """BasicAer provider integration tests.""" import unittest from qiskit import BasicAer from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import execute from qiskit.result import Result from qiskit.providers.basicaer import BasicAerError from qiskit.test import QiskitTestCase class TestBasicAerIntegration(QiskitTestCase): """Qiskit BasicAer simulator integration tests.""" def setUp(self): super().setUp() qr = QuantumRegister(1) cr = ClassicalRegister(1) self._qc1 = QuantumCircuit(qr, cr, name="qc1") self._qc2 = QuantumCircuit(qr, cr, name="qc2") self._qc1.measure(qr[0], cr[0]) self.backend = BasicAer.get_backend("qasm_simulator") self._result1 = execute(self._qc1, self.backend).result() def test_builtin_simulator_result_fields(self): """Test components of a result from a local simulator.""" self.assertEqual("qasm_simulator", self._result1.backend_name) self.assertIsInstance(self._result1.job_id, str) self.assertEqual(self._result1.status, "COMPLETED") self.assertEqual(self._result1.results[0].status, "DONE") def test_basicaer_execute(self): """Test Compiler and run.""" qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) job = execute(qc, self.backend) result = job.result() self.assertIsInstance(result, Result) def test_basicaer_execute_two(self): """Test Compiler and run.""" qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qc_extra = QuantumCircuit(qubit_reg, clbit_reg, name="extra") qc_extra.measure(qubit_reg, clbit_reg) job = execute([qc, qc_extra], self.backend) result = job.result() self.assertIsInstance(result, Result) def test_basicaer_num_qubits(self): """Test BasicAerError is raised if num_qubits too large to simulate.""" qc = QuantumCircuit(50, 1) qc.x(0) qc.measure(0, 0) with self.assertRaises(BasicAerError): execute(qc, self.backend) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for all BasicAer simulators.""" import io from logging import StreamHandler, getLogger import sys from qiskit import BasicAer from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.compiler import transpile from qiskit.compiler import assemble from qiskit.qobj import QobjHeader from qiskit.test import QiskitTestCase class StreamHandlerRaiseException(StreamHandler): """Handler class that will raise an exception on formatting errors.""" def handleError(self, record): raise sys.exc_info() class TestBasicAerQobj(QiskitTestCase): """Tests for all the Terra simulators.""" def setUp(self): super().setUp() logger = getLogger() self.addCleanup(logger.setLevel, logger.level) logger.setLevel("DEBUG") self.output = io.StringIO() logger.addHandler(StreamHandlerRaiseException(self.output)) qr = QuantumRegister(1) cr = ClassicalRegister(1) self.qc1 = QuantumCircuit(qr, cr, name="circuit0") self.qc1.h(qr[0]) def test_qobj_headers_in_result(self): """Test that the qobj headers are passed onto the results.""" custom_qobj_header = {"x": 1, "y": [1, 2, 3], "z": {"a": 4}} for backend in BasicAer.backends(): with self.subTest(backend=backend): new_circ = transpile(self.qc1, backend=backend) qobj = assemble(new_circ, shots=1024) # Update the Qobj header. qobj.header = QobjHeader.from_dict(custom_qobj_header) # Update the Qobj.experiment header. qobj.experiments[0].header.some_field = "extra info" result = backend.run(qobj).result() self.assertEqual(result.header.to_dict(), custom_qobj_header) self.assertEqual(result.results[0].header.some_field, "extra info")
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test executing multiple-register circuits on BasicAer.""" from qiskit import BasicAer, execute from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.quantum_info import Operator, Statevector, process_fidelity, state_fidelity from qiskit.test import QiskitTestCase class TestCircuitMultiRegs(QiskitTestCase): """QuantumCircuit Qasm tests.""" def test_circuit_multi(self): """Test circuit multi regs declared at start.""" qreg0 = QuantumRegister(2, "q0") creg0 = ClassicalRegister(2, "c0") qreg1 = QuantumRegister(2, "q1") creg1 = ClassicalRegister(2, "c1") circ = QuantumCircuit(qreg0, qreg1, creg0, creg1) circ.x(qreg0[1]) circ.x(qreg1[0]) meas = QuantumCircuit(qreg0, qreg1, creg0, creg1) meas.measure(qreg0, creg0) meas.measure(qreg1, creg1) qc = circ.compose(meas) backend_sim = BasicAer.get_backend("qasm_simulator") result = execute(qc, backend_sim, seed_transpiler=34342).result() counts = result.get_counts(qc) target = {"01 10": 1024} backend_sim = BasicAer.get_backend("statevector_simulator") result = execute(circ, backend_sim, seed_transpiler=3438).result() state = result.get_statevector(circ) backend_sim = BasicAer.get_backend("unitary_simulator") result = execute(circ, backend_sim, seed_transpiler=3438).result() unitary = Operator(result.get_unitary(circ)) self.assertEqual(counts, target) self.assertAlmostEqual(state_fidelity(Statevector.from_label("0110"), state), 1.0, places=7) self.assertAlmostEqual( process_fidelity(Operator.from_label("IXXI"), unitary), 1.0, places=7 )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test QASM simulator.""" import os import unittest import io from logging import StreamHandler, getLogger import sys import numpy as np from qiskit import execute from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.compiler import transpile, assemble from qiskit.providers.basicaer import QasmSimulatorPy from qiskit.test import providers class StreamHandlerRaiseException(StreamHandler): """Handler class that will raise an exception on formatting errors.""" def handleError(self, record): raise sys.exc_info() class TestBasicAerQasmSimulator(providers.BackendTestCase): """Test the Basic qasm_simulator.""" backend_cls = QasmSimulatorPy def setUp(self): super().setUp() self.seed = 88 qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") qasm_filename = os.path.join(qasm_dir, "example.qasm") transpiled_circuit = QuantumCircuit.from_qasm_file(qasm_filename) transpiled_circuit.name = "test" transpiled_circuit = transpile(transpiled_circuit, backend=self.backend) self.qobj = assemble(transpiled_circuit, shots=1000, seed_simulator=self.seed) logger = getLogger() self.addCleanup(logger.setLevel, logger.level) logger.setLevel("DEBUG") self.log_output = io.StringIO() logger.addHandler(StreamHandlerRaiseException(self.log_output)) def assertExecuteLog(self, log_msg): """Runs execute and check for logs containing specified message""" shots = 100 qr = QuantumRegister(2, "qr") cr = ClassicalRegister(4, "cr") circuit = QuantumCircuit(qr, cr) execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed) self.log_output.seek(0) # Filter unrelated log lines output_lines = self.log_output.readlines() execute_log_lines = [x for x in output_lines if log_msg in x] self.assertTrue(len(execute_log_lines) > 0) def test_submission_log_time(self): """Check Total Job Submission Time is logged""" self.assertExecuteLog("Total Job Submission Time") def test_qasm_simulator_single_shot(self): """Test single shot run.""" shots = 1 self.qobj.config.shots = shots result = self.backend.run(self.qobj).result() self.assertEqual(result.success, True) def test_measure_sampler_repeated_qubits(self): """Test measure sampler if qubits measured more than once.""" shots = 100 qr = QuantumRegister(2, "qr") cr = ClassicalRegister(4, "cr") circuit = QuantumCircuit(qr, cr) circuit.x(qr[1]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) circuit.measure(qr[1], cr[2]) circuit.measure(qr[0], cr[3]) target = {"0110": shots} job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed) result = job.result() counts = result.get_counts(0) self.assertEqual(counts, target) def test_measure_sampler_single_qubit(self): """Test measure sampler if single-qubit is measured.""" shots = 100 num_qubits = 5 qr = QuantumRegister(num_qubits, "qr") cr = ClassicalRegister(1, "cr") for qubit in range(num_qubits): circuit = QuantumCircuit(qr, cr) circuit.x(qr[qubit]) circuit.measure(qr[qubit], cr[0]) target = {"1": shots} job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed) result = job.result() counts = result.get_counts(0) self.assertEqual(counts, target) def test_measure_sampler_partial_qubit(self): """Test measure sampler if single-qubit is measured.""" shots = 100 num_qubits = 5 qr = QuantumRegister(num_qubits, "qr") cr = ClassicalRegister(4, "cr") # ░ ░ ░ ┌─┐ ░ # qr_0: ──────░─────░─────░─┤M├─░──── # ┌───┐ ░ ░ ┌─┐ ░ └╥┘ ░ # qr_1: ┤ X ├─░─────░─┤M├─░──╫──░──── # └───┘ ░ ░ └╥┘ ░ ║ ░ # qr_2: ──────░─────░──╫──░──╫──░──── # ┌───┐ ░ ┌─┐ ░ ║ ░ ║ ░ ┌─┐ # qr_3: ┤ X ├─░─┤M├─░──╫──░──╫──░─┤M├ # └───┘ ░ └╥┘ ░ ║ ░ ║ ░ └╥┘ # qr_4: ──────░──╫──░──╫──░──╫──░──╫─ # ░ ║ ░ ║ ░ ║ ░ ║ # cr: 4/═════════╩═════╩═════╩═════╩═ # 1 0 2 3 circuit = QuantumCircuit(qr, cr) circuit.x(qr[3]) circuit.x(qr[1]) circuit.barrier(qr) circuit.measure(qr[3], cr[1]) circuit.barrier(qr) circuit.measure(qr[1], cr[0]) circuit.barrier(qr) circuit.measure(qr[0], cr[2]) circuit.barrier(qr) circuit.measure(qr[3], cr[3]) target = {"1011": shots} job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed) result = job.result() counts = result.get_counts(0) self.assertEqual(counts, target) def test_qasm_simulator(self): """Test data counts output for single circuit run against reference.""" result = self.backend.run(self.qobj).result() shots = 1024 threshold = 0.04 * shots counts = result.get_counts("test") target = { "100 100": shots / 8, "011 011": shots / 8, "101 101": shots / 8, "111 111": shots / 8, "000 000": shots / 8, "010 010": shots / 8, "110 110": shots / 8, "001 001": shots / 8, } self.assertDictAlmostEqual(counts, target, threshold) def test_if_statement(self): """Test if statements.""" shots = 100 qr = QuantumRegister(3, "qr") cr = ClassicalRegister(3, "cr") # ┌───┐┌─┐ ┌─┐ # qr_0: ┤ X ├┤M├──────────┤M├────── # ├───┤└╥┘┌─┐ └╥┘┌─┐ # qr_1: ┤ X ├─╫─┤M├────────╫─┤M├─── # └───┘ ║ └╥┘ ┌───┐ ║ └╥┘┌─┐ # qr_2: ──────╫──╫──┤ X ├──╫──╫─┤M├ # ║ ║ └─╥─┘ ║ ║ └╥┘ # ║ ║ ┌──╨──┐ ║ ║ ║ # cr: 3/══════╩══╩═╡ 0x3 ╞═╩══╩══╩═ # 0 1 └─────┘ 0 1 2 circuit_if_true = QuantumCircuit(qr, cr) circuit_if_true.x(qr[0]) circuit_if_true.x(qr[1]) circuit_if_true.measure(qr[0], cr[0]) circuit_if_true.measure(qr[1], cr[1]) circuit_if_true.x(qr[2]).c_if(cr, 0x3) circuit_if_true.measure(qr[0], cr[0]) circuit_if_true.measure(qr[1], cr[1]) circuit_if_true.measure(qr[2], cr[2]) # ┌───┐┌─┐ ┌─┐ # qr_0: ┤ X ├┤M├───────┤M├────── # └┬─┬┘└╥┘ └╥┘┌─┐ # qr_1: ─┤M├──╫─────────╫─┤M├─── # └╥┘ ║ ┌───┐ ║ └╥┘┌─┐ # qr_2: ──╫───╫──┤ X ├──╫──╫─┤M├ # ║ ║ └─╥─┘ ║ ║ └╥┘ # ║ ║ ┌──╨──┐ ║ ║ ║ # cr: 3/══╩═══╩═╡ 0x3 ╞═╩══╩══╩═ # 1 0 └─────┘ 0 1 2 circuit_if_false = QuantumCircuit(qr, cr) circuit_if_false.x(qr[0]) circuit_if_false.measure(qr[0], cr[0]) circuit_if_false.measure(qr[1], cr[1]) circuit_if_false.x(qr[2]).c_if(cr, 0x3) circuit_if_false.measure(qr[0], cr[0]) circuit_if_false.measure(qr[1], cr[1]) circuit_if_false.measure(qr[2], cr[2]) job = execute( [circuit_if_true, circuit_if_false], backend=self.backend, shots=shots, seed_simulator=self.seed, ) result = job.result() counts_if_true = result.get_counts(circuit_if_true) counts_if_false = result.get_counts(circuit_if_false) self.assertEqual(counts_if_true, {"111": 100}) self.assertEqual(counts_if_false, {"001": 100}) def test_bit_cif_crossaffect(self): """Test if bits in a classical register other than the single conditional bit affect the conditioned operation.""" # ┌───┐ ┌─┐ # q0_0: ────────┤ H ├──────────┤M├ # ┌───┐ └─╥─┘ ┌─┐ └╥┘ # q0_1: ┤ X ├─────╫──────┤M├────╫─ # ├───┤ ║ └╥┘┌─┐ ║ # q0_2: ┤ X ├─────╫───────╫─┤M├─╫─ # └───┘┌────╨─────┐ ║ └╥┘ ║ # c0: 3/═════╡ c0_0=0x1 ╞═╩══╩══╬═ # └──────────┘ 1 2 ║ # c1: 1/════════════════════════╩═ # 0 shots = 100 qr = QuantumRegister(3) cr = ClassicalRegister(3) cr1 = ClassicalRegister(1) circuit = QuantumCircuit(qr, cr, cr1) circuit.x([qr[1], qr[2]]) circuit.measure(qr[1], cr[1]) circuit.measure(qr[2], cr[2]) circuit.h(qr[0]).c_if(cr[0], True) circuit.measure(qr[0], cr1[0]) job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed) result = job.result().get_counts() target = {"0 110": 100} self.assertEqual(result, target) def test_teleport(self): """Test teleportation as in tutorials""" # ┌─────────┐ ┌───┐ ░ ┌─┐ # qr_0: ┤ Ry(π/4) ├───────■──┤ H ├─░─┤M├──────────────────── # └──┬───┬──┘ ┌─┴─┐└───┘ ░ └╥┘┌─┐ # qr_1: ───┤ H ├─────■──┤ X ├──────░──╫─┤M├───────────────── # └───┘ ┌─┴─┐└───┘ ░ ║ └╥┘ ┌───┐ ┌───┐ ┌─┐ # qr_2: ───────────┤ X ├───────────░──╫──╫──┤ Z ├──┤ X ├─┤M├ # └───┘ ░ ║ ║ └─╥─┘ └─╥─┘ └╥┘ # ║ ║ ┌──╨──┐ ║ ║ # cr0: 1/═════════════════════════════╩══╬═╡ 0x1 ╞═══╬════╬═ # 0 ║ └─────┘┌──╨──┐ ║ # cr1: 1/════════════════════════════════╩════════╡ 0x1 ╞═╬═ # 0 └─────┘ ║ # cr2: 1/═════════════════════════════════════════════════╩═ # 0 self.log.info("test_teleport") pi = np.pi shots = 2000 qr = QuantumRegister(3, "qr") cr0 = ClassicalRegister(1, "cr0") cr1 = ClassicalRegister(1, "cr1") cr2 = ClassicalRegister(1, "cr2") circuit = QuantumCircuit(qr, cr0, cr1, cr2, name="teleport") circuit.h(qr[1]) circuit.cx(qr[1], qr[2]) circuit.ry(pi / 4, qr[0]) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.barrier(qr) circuit.measure(qr[0], cr0[0]) circuit.measure(qr[1], cr1[0]) circuit.z(qr[2]).c_if(cr0, 1) circuit.x(qr[2]).c_if(cr1, 1) circuit.measure(qr[2], cr2[0]) job = execute(circuit, backend=self.backend, shots=shots, seed_simulator=self.seed) results = job.result() data = results.get_counts("teleport") alice = { "00": data["0 0 0"] + data["1 0 0"], "01": data["0 1 0"] + data["1 1 0"], "10": data["0 0 1"] + data["1 0 1"], "11": data["0 1 1"] + data["1 1 1"], } bob = { "0": data["0 0 0"] + data["0 1 0"] + data["0 0 1"] + data["0 1 1"], "1": data["1 0 0"] + data["1 1 0"] + data["1 0 1"] + data["1 1 1"], } self.log.info("test_teleport: circuit:") self.log.info(circuit.qasm()) self.log.info("test_teleport: data %s", data) self.log.info("test_teleport: alice %s", alice) self.log.info("test_teleport: bob %s", bob) alice_ratio = 1 / np.tan(pi / 8) ** 2 bob_ratio = bob["0"] / float(bob["1"]) error = abs(alice_ratio - bob_ratio) / alice_ratio self.log.info("test_teleport: relative error = %s", error) self.assertLess(error, 0.05) def test_memory(self): """Test memory.""" # ┌───┐ ┌─┐ # qr_0: ┤ H ├──■─────┤M├─── # └───┘┌─┴─┐ └╥┘┌─┐ # qr_1: ─────┤ X ├────╫─┤M├ # └┬─┬┘ ║ └╥┘ # qr_2: ──────┤M├─────╫──╫─ # ┌───┐ └╥┘ ┌─┐ ║ ║ # qr_3: ┤ X ├──╫──┤M├─╫──╫─ # └───┘ ║ └╥┘ ║ ║ # cr0: 2/══════╬═══╬══╩══╩═ # ║ ║ 0 1 # ║ ║ # cr1: 2/══════╩═══╩═══════ # 0 1 qr = QuantumRegister(4, "qr") cr0 = ClassicalRegister(2, "cr0") cr1 = ClassicalRegister(2, "cr1") circ = QuantumCircuit(qr, cr0, cr1) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.x(qr[3]) circ.measure(qr[0], cr0[0]) circ.measure(qr[1], cr0[1]) circ.measure(qr[2], cr1[0]) circ.measure(qr[3], cr1[1]) shots = 50 job = execute(circ, backend=self.backend, shots=shots, memory=True) result = job.result() memory = result.get_memory() self.assertEqual(len(memory), shots) for mem in memory: self.assertIn(mem, ["10 00", "10 11"]) def test_unitary(self): """Test unitary gate instruction""" max_qubits = 4 x_mat = np.array([[0, 1], [1, 0]]) # Test 1 to max_qubits for random n-qubit unitary gate for i in range(max_qubits): num_qubits = i + 1 # Apply X gate to all qubits multi_x = x_mat for _ in range(i): multi_x = np.kron(multi_x, x_mat) # Target counts shots = 1024 target_counts = {num_qubits * "1": shots} # Test circuit qr = QuantumRegister(num_qubits, "qr") cr = ClassicalRegister(num_qubits, "cr") circuit = QuantumCircuit(qr, cr) circuit.unitary(multi_x, qr) circuit.measure(qr, cr) job = execute(circuit, self.backend, shots=shots) result = job.result() counts = result.get_counts(0) self.assertEqual(counts, target_counts) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test StateVectorSimulatorPy.""" import unittest import numpy as np from qiskit.providers.basicaer import StatevectorSimulatorPy from qiskit.test import ReferenceCircuits from qiskit.test import providers from qiskit import QuantumRegister, QuantumCircuit, execute from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info import state_fidelity class StatevectorSimulatorTest(providers.BackendTestCase): """Test BasicAer statevector simulator.""" backend_cls = StatevectorSimulatorPy circuit = None def test_run_circuit(self): """Test final state vector for single circuit run.""" # Set test circuit self.circuit = ReferenceCircuits.bell_no_measure() # Execute result = super().test_run_circuit() actual = result.get_statevector(self.circuit) # state is 1/sqrt(2)|00> + 1/sqrt(2)|11>, up to a global phase self.assertAlmostEqual((abs(actual[0])) ** 2, 1 / 2) self.assertEqual(actual[1], 0) self.assertEqual(actual[2], 0) self.assertAlmostEqual((abs(actual[3])) ** 2, 1 / 2) def test_measure_collapse(self): """Test final measurement collapses statevector""" # Set test circuit self.circuit = ReferenceCircuits.bell() # Execute result = super().test_run_circuit() actual = result.get_statevector(self.circuit) # The final state should be EITHER |00> OR |11> diff_00 = np.linalg.norm(np.array([1, 0, 0, 0]) - actual) ** 2 diff_11 = np.linalg.norm(np.array([0, 0, 0, 1]) - actual) ** 2 success = np.allclose([diff_00, diff_11], [0, 2]) or np.allclose([diff_00, diff_11], [2, 0]) # state is 1/sqrt(2)|00> + 1/sqrt(2)|11>, up to a global phase self.assertTrue(success) def test_unitary(self): """Test unitary gate instruction""" num_trials = 10 max_qubits = 3 # Test 1 to max_qubits for random n-qubit unitary gate for i in range(max_qubits): num_qubits = i + 1 psi_init = np.zeros(2**num_qubits) psi_init[0] = 1.0 qr = QuantumRegister(num_qubits, "qr") for _ in range(num_trials): # Create random unitary unitary = random_unitary(2**num_qubits) # Compute expected output state psi_target = unitary.data.dot(psi_init) # Simulate output on circuit circuit = QuantumCircuit(qr) circuit.unitary(unitary, qr) job = execute(circuit, self.backend) result = job.result() psi_out = result.get_statevector(0) fidelity = state_fidelity(psi_target, psi_out) self.assertGreater(fidelity, 0.999) def test_global_phase(self): """Test global_phase""" n_qubits = 4 qr = QuantumRegister(n_qubits) circ = QuantumCircuit(qr) circ.x(qr) circ.global_phase = 0.5 self.circuit = circ result = super().test_run_circuit() actual = result.get_statevector(self.circuit) expected = np.exp(1j * circ.global_phase) * np.repeat([[0], [1]], [n_qubits**2 - 1, 1]) self.assertTrue(np.allclose(actual, expected)) def test_global_phase_composite(self): """Test global_phase""" n_qubits = 4 qr = QuantumRegister(n_qubits) circ = QuantumCircuit(qr) circ.x(qr) circ.global_phase = 0.5 gate = circ.to_gate() comp = QuantumCircuit(qr) comp.append(gate, qr) comp.global_phase = 0.1 self.circuit = comp result = super().test_run_circuit() actual = result.get_statevector(self.circuit) expected = np.exp(1j * 0.6) * np.repeat([[0], [1]], [n_qubits**2 - 1, 1]) self.assertTrue(np.allclose(actual, expected)) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for unitary simulator.""" import unittest import numpy as np from qiskit import execute from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.providers.basicaer import UnitarySimulatorPy from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.test import ReferenceCircuits from qiskit.test import providers from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info import process_fidelity, Operator class BasicAerUnitarySimulatorPyTest(providers.BackendTestCase): """Test BasicAer unitary simulator.""" backend_cls = UnitarySimulatorPy circuit = ReferenceCircuits.bell_no_measure() def test_basicaer_unitary_simulator_py(self): """Test unitary simulator.""" circuits = self._test_circuits() job = execute(circuits, backend=self.backend) sim_unitaries = [job.result().get_unitary(circ) for circ in circuits] reference_unitaries = self._reference_unitaries() for u_sim, u_ref in zip(sim_unitaries, reference_unitaries): self.assertTrue(matrix_equal(u_sim, u_ref, ignore_phase=True)) def _test_circuits(self): """Return test circuits for unitary simulator""" qr = QuantumRegister(3) cr = ClassicalRegister(3) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc3 = QuantumCircuit(qr, cr) qc4 = QuantumCircuit(qr, cr) qc5 = QuantumCircuit(qr, cr) # Test circuit 1: HxHxH qc1.h(qr) # Test circuit 2: IxCX qc2.cx(qr[0], qr[1]) # Test circuit 3: CXxY qc3.y(qr[0]) qc3.cx(qr[1], qr[2]) # Test circuit 4: (CX.I).(IxCX).(IxIxX) qc4.h(qr[0]) qc4.cx(qr[0], qr[1]) qc4.cx(qr[1], qr[2]) # Test circuit 5 (X.Z)x(Z.Y)x(Y.X) qc5.x(qr[0]) qc5.y(qr[0]) qc5.y(qr[1]) qc5.z(qr[1]) qc5.z(qr[2]) qc5.x(qr[2]) return [qc1, qc2, qc3, qc4, qc5] def _reference_unitaries(self): """Return reference unitaries for test circuits""" # Gate matrices gate_h = np.array([[1, 1], [1, -1]]) / np.sqrt(2) gate_x = np.array([[0, 1], [1, 0]]) gate_y = np.array([[0, -1j], [1j, 0]]) gate_z = np.array([[1, 0], [0, -1]]) gate_cx = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0.0, 0, 1, 0], [0, 1, 0, 0]]) # Unitary matrices target_unitary1 = np.kron(np.kron(gate_h, gate_h), gate_h) target_unitary2 = np.kron(np.eye(2), gate_cx) target_unitary3 = np.kron(gate_cx, gate_y) target_unitary4 = np.dot( np.kron(gate_cx, np.eye(2)), np.dot(np.kron(np.eye(2), gate_cx), np.kron(np.eye(4), gate_h)), ) target_unitary5 = np.kron( np.kron(np.dot(gate_x, gate_z), np.dot(gate_z, gate_y)), np.dot(gate_y, gate_x) ) return [target_unitary1, target_unitary2, target_unitary3, target_unitary4, target_unitary5] def test_unitary(self): """Test unitary gate instruction""" num_trials = 10 max_qubits = 3 # Test 1 to max_qubits for random n-qubit unitary gate for i in range(max_qubits): num_qubits = i + 1 unitary_init = Operator(np.eye(2**num_qubits)) qr = QuantumRegister(num_qubits, "qr") for _ in range(num_trials): # Create random unitary unitary = random_unitary(2**num_qubits) # Compute expected output state unitary_target = unitary.dot(unitary_init) # Simulate output on circuit circuit = QuantumCircuit(qr) circuit.unitary(unitary, qr) job = execute(circuit, self.backend) result = job.result() unitary_out = Operator(result.get_unitary(0)) fidelity = process_fidelity(unitary_target, unitary_out) self.assertGreater(fidelity, 0.999) def test_global_phase(self): """Test global phase for XZH See https://github.com/Qiskit/qiskit-terra/issues/3083""" q = QuantumRegister(1) circuit = QuantumCircuit(q) circuit.h(q[0]) circuit.z(q[0]) circuit.x(q[0]) job = execute(circuit, self.backend) result = job.result() unitary_out = result.get_unitary(circuit) unitary_target = np.array( [[-1 / np.sqrt(2), 1 / np.sqrt(2)], [1 / np.sqrt(2), 1 / np.sqrt(2)]] ) self.assertTrue(np.allclose(unitary_out, unitary_target)) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test QuantumCircuit.find_bit.""" from ddt import ddt, data, unpack from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit, AncillaRegister from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase @ddt class TestQuantumCircuitFindBit(QiskitTestCase): """Test cases for QuantumCircuit.find_bit.""" @data(Qubit, Clbit) def test_bit_not_in_circuit(self, bit_type): """Verify we raise if the bit has not been attached to the circuit.""" qc = QuantumCircuit() bit = bit_type() with self.assertRaisesRegex(CircuitError, r"Could not locate provided bit"): qc.find_bit(bit) @data(Qubit, Clbit) def test_registerless_bit_constructor(self, bit_type): """Verify we find individual bits added via QuantumCircuit constructor.""" bits = [bit_type() for _ in range(5)] qc = QuantumCircuit(bits) for idx, bit in enumerate(bits): self.assertEqual(qc.find_bit(bit), (idx, [])) @data(Qubit, Clbit) def test_registerless_add_bits(self, bit_type): """Verify we find individual bits added via QuantumCircuit.add_bits.""" bits = [bit_type() for _ in range(5)] qc = QuantumCircuit() qc.add_bits(bits) for idx, bit in enumerate(bits): self.assertEqual(qc.find_bit(bit), (idx, [])) def test_registerless_add_int(self): """Verify we find bits and implicit registers added via QuantumCircuit(int, int).""" qc = QuantumCircuit(5, 2) qubits = qc.qubits clbits = qc.clbits # N.B. After deprecation of implicit register creation via # QuantumCircuit(int, int) in PR#6582 and subsequent removal, this test # should be updated to verify no registers are found. qr = qc.qregs[0] cr = qc.cregs[0] for idx, bit in enumerate(qubits): self.assertEqual(qc.find_bit(bit), (idx, [(qr, idx)])) for idx, bit in enumerate(clbits): self.assertEqual(qc.find_bit(bit), (idx, [(cr, idx)])) @data(QuantumRegister, ClassicalRegister) def test_register_bit_reg_constructor(self, reg_type): """Verify we find register bits added via QuantumCicrcuit(reg).""" reg = reg_type(5, "reg") qc = QuantumCircuit(reg) for idx, bit in enumerate(reg): self.assertEqual(qc.find_bit(bit), (idx, [(reg, idx)])) @data(QuantumRegister, ClassicalRegister) def test_register_bit_add_reg(self, reg_type): """Verify we find register bits added QuantumCircuit.add_register.""" reg = reg_type(5, "reg") qc = QuantumCircuit() qc.add_register(reg) for idx, bit in enumerate(reg): self.assertEqual(qc.find_bit(bit), (idx, [(reg, idx)])) def test_ancilla_register_add_register(self): """Verify AncillaRegisters are found by find_bit by their locations in qubits/qregs.""" qreg = QuantumRegister(3, "qr") areg = AncillaRegister(5, "ar") qc = QuantumCircuit() qc.add_register(qreg) qc.add_register(areg) for idx, bit in enumerate(areg): self.assertEqual(qc.find_bit(bit), (idx + len(qreg), [(areg, idx)])) @data([Qubit, QuantumRegister], [Clbit, ClassicalRegister]) @unpack def test_multiple_register_from_bit(self, bit_type, reg_type): """Verify we find individual bits in multiple registers.""" bits = [bit_type() for _ in range(10)] even_reg = reg_type(bits=bits[::2]) odd_reg = reg_type(bits=bits[1::2]) fwd_reg = reg_type(bits=bits) rev_reg = reg_type(bits=bits[::-1]) qc = QuantumCircuit() qc.add_bits(bits) qc.add_register(even_reg, odd_reg, fwd_reg, rev_reg) for idx, bit in enumerate(bits): if idx % 2: self.assertEqual( qc.find_bit(bit), (idx, [(odd_reg, idx // 2), (fwd_reg, idx), (rev_reg, 9 - idx)]), ) else: self.assertEqual( qc.find_bit(bit), (idx, [(even_reg, idx // 2), (fwd_reg, idx), (rev_reg, 9 - idx)]), ) @data(QuantumRegister, ClassicalRegister) def test_multiple_register_from_reg(self, reg_type): """Verify we find register bits in multiple registers.""" reg1 = reg_type(6, "reg1") reg2 = reg_type(4, "reg2") even_reg = reg_type(bits=(reg1[:] + reg2[:])[::2]) odd_reg = reg_type(bits=(reg1[:] + reg2[:])[1::2]) qc = QuantumCircuit(reg1, reg2, even_reg, odd_reg) for idx, bit in enumerate(reg1): if idx % 2: self.assertEqual(qc.find_bit(bit), (idx, [(reg1, idx), (odd_reg, idx // 2)])) else: self.assertEqual(qc.find_bit(bit), (idx, [(reg1, idx), (even_reg, idx // 2)])) for idx, bit in enumerate(reg2): circ_idx = len(reg1) + idx if idx % 2: self.assertEqual( qc.find_bit(bit), (circ_idx, [(reg2, idx), (odd_reg, circ_idx // 2)]) ) else: self.assertEqual( qc.find_bit(bit), (circ_idx, [(reg2, idx), (even_reg, circ_idx // 2)]) )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test cases for the circuit qasm_file and qasm_string method.""" import io import json import random import ddt import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, pulse from qiskit.circuit import CASE_DEFAULT from qiskit.circuit.classical import expr, types from qiskit.circuit.classicalregister import Clbit from qiskit.circuit.quantumregister import Qubit from qiskit.circuit.random import random_circuit from qiskit.circuit.gate import Gate from qiskit.circuit.library import ( XGate, QFT, QAOAAnsatz, PauliEvolutionGate, DCXGate, MCU1Gate, MCXGate, MCXGrayCode, MCXRecursive, MCXVChain, ) from qiskit.circuit.instruction import Instruction from qiskit.circuit.parameter import Parameter from qiskit.circuit.parametervector import ParameterVector from qiskit.synthesis import LieTrotter, SuzukiTrotter from qiskit.extensions import UnitaryGate from qiskit.test import QiskitTestCase from qiskit.qpy import dump, load from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.quantum_info.random import random_unitary from qiskit.circuit.controlledgate import ControlledGate @ddt.ddt class TestLoadFromQPY(QiskitTestCase): """Test circuit.from_qasm_* set of methods.""" def assertDeprecatedBitProperties(self, original, roundtripped): """Test that deprecated bit attributes are equal if they are set in the original circuit.""" owned_qubits = [ (a, b) for a, b in zip(original.qubits, roundtripped.qubits) if a._register is not None ] if owned_qubits: original_qubits, roundtripped_qubits = zip(*owned_qubits) self.assertEqual(original_qubits, roundtripped_qubits) owned_clbits = [ (a, b) for a, b in zip(original.clbits, roundtripped.clbits) if a._register is not None ] if owned_clbits: original_clbits, roundtripped_clbits = zip(*owned_clbits) self.assertEqual(original_clbits, roundtripped_clbits) def test_qpy_full_path(self): """Test full path qpy serialization for basic circuit.""" qr_a = QuantumRegister(4, "a") qr_b = QuantumRegister(4, "b") cr_c = ClassicalRegister(4, "c") cr_d = ClassicalRegister(4, "d") q_circuit = QuantumCircuit( qr_a, qr_b, cr_c, cr_d, name="MyCircuit", metadata={"test": 1, "a": 2}, global_phase=3.14159, ) q_circuit.h(qr_a) q_circuit.cx(qr_a, qr_b) q_circuit.barrier(qr_a) q_circuit.barrier(qr_b) q_circuit.measure(qr_a, cr_c) q_circuit.measure(qr_b, cr_d) qpy_file = io.BytesIO() dump(q_circuit, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(q_circuit, new_circ) self.assertEqual(q_circuit.global_phase, new_circ.global_phase) self.assertEqual(q_circuit.metadata, new_circ.metadata) self.assertEqual(q_circuit.name, new_circ.name) self.assertDeprecatedBitProperties(q_circuit, new_circ) def test_circuit_with_conditional(self): """Test that instructions with conditions are correctly serialized.""" qc = QuantumCircuit(1, 1) qc.x(0).c_if(qc.cregs[0], 1) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_int_parameter(self): """Test that integer parameters are correctly serialized.""" qc = QuantumCircuit(1) qc.rx(3, 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_float_parameter(self): """Test that float parameters are correctly serialized.""" qc = QuantumCircuit(1) qc.rx(3.14, 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_numpy_float_parameter(self): """Test that numpy float parameters are correctly serialized.""" qc = QuantumCircuit(1) qc.rx(np.float32(3.14), 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_numpy_int_parameter(self): """Test that numpy integer parameters are correctly serialized.""" qc = QuantumCircuit(1) qc.rx(np.int16(3), 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_unitary_gate(self): """Test that numpy array parameters are correctly serialized""" qc = QuantumCircuit(1) unitary = np.array([[0, 1], [1, 0]]) qc.unitary(unitary, 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_opaque_gate(self): """Test that custom opaque gate is correctly serialized""" custom_gate = Gate("black_box", 1, []) qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_opaque_instruction(self): """Test that custom opaque instruction is correctly serialized""" custom_gate = Instruction("black_box", 1, 0, []) qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_custom_gate(self): """Test that custom gate is correctly serialized""" custom_gate = Gate("black_box", 1, []) custom_definition = QuantumCircuit(1) custom_definition.h(0) custom_definition.rz(1.5, 0) custom_definition.sdg(0) custom_gate.definition = custom_definition qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertDeprecatedBitProperties(qc, new_circ) def test_custom_instruction(self): """Test that custom instruction is correctly serialized""" custom_gate = Instruction("black_box", 1, 0, []) custom_definition = QuantumCircuit(1) custom_definition.h(0) custom_definition.rz(1.5, 0) custom_definition.sdg(0) custom_gate.definition = custom_definition qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertDeprecatedBitProperties(qc, new_circ) def test_parameter(self): """Test that a circuit with a parameter is correctly serialized.""" theta = Parameter("theta") qc = QuantumCircuit(5, 1) qc.h(0) for i in range(4): qc.cx(i, i + 1) qc.barrier() qc.rz(theta, range(5)) qc.barrier() for i in reversed(range(4)): qc.cx(i, i + 1) qc.h(0) qc.measure(0, 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.bind_parameters({theta: 3.14}), new_circ.bind_parameters({theta: 3.14})) self.assertDeprecatedBitProperties(qc, new_circ) def test_bound_parameter(self): """Test a circuit with a bound parameter is correctly serialized.""" theta = Parameter("theta") qc = QuantumCircuit(5, 1) qc.h(0) for i in range(4): qc.cx(i, i + 1) qc.barrier() qc.rz(theta, range(5)) qc.barrier() for i in reversed(range(4)): qc.cx(i, i + 1) qc.h(0) qc.measure(0, 0) qc.assign_parameters({theta: 3.14}) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_bound_calibration_parameter(self): """Test a circuit with a bound calibration parameter is correctly serialized. In particular, this test ensures that parameters on a circuit instruction are consistent with the circuit's calibrations dictionary after serialization. """ amp = Parameter("amp") with pulse.builder.build() as sched: pulse.builder.play(pulse.Constant(100, amp), pulse.DriveChannel(0)) gate = Gate("custom", 1, [amp]) qc = QuantumCircuit(1) qc.append(gate, (0,)) qc.add_calibration(gate, (0,), sched) qc.assign_parameters({amp: 1 / 3}, inplace=True) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) instruction = new_circ.data[0] cal_key = ( tuple(new_circ.find_bit(q).index for q in instruction.qubits), tuple(instruction.operation.params), ) # Make sure that looking for a calibration based on the instruction's # parameters succeeds self.assertIn(cal_key, new_circ.calibrations[gate.name]) def test_parameter_expression(self): """Test a circuit with a parameter expression.""" theta = Parameter("theta") phi = Parameter("phi") sum_param = theta + phi qc = QuantumCircuit(5, 1) qc.h(0) for i in range(4): qc.cx(i, i + 1) qc.barrier() qc.rz(sum_param, range(3)) qc.rz(phi, 3) qc.rz(theta, 4) qc.barrier() for i in reversed(range(4)): qc.cx(i, i + 1) qc.h(0) qc.measure(0, 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_string_parameter(self): """Test a PauliGate instruction that has string parameters.""" circ = QuantumCircuit(3) circ.z(0) circ.y(1) circ.x(2) qpy_file = io.BytesIO() dump(circ, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(circ, new_circuit) self.assertDeprecatedBitProperties(circ, new_circuit) def test_multiple_circuits(self): """Test multiple circuits can be serialized together.""" circuits = [] for i in range(10): circuits.append( random_circuit(10, 10, measure=True, conditional=True, reset=True, seed=42 + i) ) qpy_file = io.BytesIO() dump(circuits, qpy_file) qpy_file.seek(0) new_circs = load(qpy_file) self.assertEqual(circuits, new_circs) for old, new in zip(circuits, new_circs): self.assertDeprecatedBitProperties(old, new) def test_shared_bit_register(self): """Test a circuit with shared bit registers.""" qubits = [Qubit() for _ in range(5)] qc = QuantumCircuit() qc.add_bits(qubits) qr = QuantumRegister(bits=qubits) qc.add_register(qr) qc.h(qr) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.measure_all() qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_qc = load(qpy_file)[0] self.assertEqual(qc, new_qc) self.assertDeprecatedBitProperties(qc, new_qc) def test_hybrid_standalone_register(self): """Test qpy serialization with registers that mix bit types""" qr = QuantumRegister(5, "foo") qr = QuantumRegister(name="bar", bits=qr[:3] + [Qubit(), Qubit()]) cr = ClassicalRegister(5, "foo") cr = ClassicalRegister(name="classical_bar", bits=cr[:3] + [Clbit(), Clbit()]) qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.measure(qr, cr) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_mixed_registers(self): """Test circuit with mix of standalone and shared registers.""" qubits = [Qubit() for _ in range(5)] clbits = [Clbit() for _ in range(5)] qc = QuantumCircuit() qc.add_bits(qubits) qc.add_bits(clbits) qr = QuantumRegister(bits=qubits) cr = ClassicalRegister(bits=clbits) qc.add_register(qr) qc.add_register(cr) qr_standalone = QuantumRegister(2, "standalone") qc.add_register(qr_standalone) cr_standalone = ClassicalRegister(2, "classical_standalone") qc.add_register(cr_standalone) qc.unitary(random_unitary(32, seed=42), qr) qc.unitary(random_unitary(4, seed=100), qr_standalone) qc.measure(qr, cr) qc.measure(qr_standalone, cr_standalone) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_standalone_and_shared_out_of_order(self): """Test circuit with register bits inserted out of order.""" qr_standalone = QuantumRegister(2, "standalone") qubits = [Qubit() for _ in range(5)] clbits = [Clbit() for _ in range(5)] qc = QuantumCircuit() qc.add_bits(qubits) qc.add_bits(clbits) random.shuffle(qubits) random.shuffle(clbits) qr = QuantumRegister(bits=qubits) cr = ClassicalRegister(bits=clbits) qc.add_register(qr) qc.add_register(cr) qr_standalone = QuantumRegister(2, "standalone") cr_standalone = ClassicalRegister(2, "classical_standalone") qc.add_bits([qr_standalone[1], qr_standalone[0]]) qc.add_bits([cr_standalone[1], cr_standalone[0]]) qc.add_register(qr_standalone) qc.add_register(cr_standalone) qc.unitary(random_unitary(32, seed=42), qr) qc.unitary(random_unitary(4, seed=100), qr_standalone) qc.measure(qr, cr) qc.measure(qr_standalone, cr_standalone) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_unitary_gate_with_label(self): """Test that numpy array parameters are correctly serialized with a label""" qc = QuantumCircuit(1) unitary = np.array([[0, 1], [1, 0]]) unitary_gate = UnitaryGate(unitary, "My Special unitary") qc.append(unitary_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_opaque_gate_with_label(self): """Test that custom opaque gate is correctly serialized with a label""" custom_gate = Gate("black_box", 1, []) custom_gate.label = "My Special Black Box" qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_opaque_instruction_with_label(self): """Test that custom opaque instruction is correctly serialized with a label""" custom_gate = Instruction("black_box", 1, 0, []) custom_gate.label = "My Special Black Box Instruction" qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_custom_gate_with_label(self): """Test that custom gate is correctly serialized with a label""" custom_gate = Gate("black_box", 1, []) custom_definition = QuantumCircuit(1) custom_definition.h(0) custom_definition.rz(1.5, 0) custom_definition.sdg(0) custom_gate.definition = custom_definition custom_gate.label = "My special black box with a definition" qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_custom_instruction_with_label(self): """Test that custom instruction is correctly serialized with a label""" custom_gate = Instruction("black_box", 1, 0, []) custom_definition = QuantumCircuit(1) custom_definition.h(0) custom_definition.rz(1.5, 0) custom_definition.sdg(0) custom_gate.definition = custom_definition custom_gate.label = "My Special Black Box Instruction with a definition" qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_custom_gate_with_noop_definition(self): """Test that a custom gate whose definition contains no elements is serialized with a proper definition. Regression test of gh-7429.""" empty = QuantumCircuit(1, name="empty").to_gate() opaque = Gate("opaque", 1, []) qc = QuantumCircuit(2) qc.append(empty, [0], []) qc.append(opaque, [1], []) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertEqual(len(new_circ), 2) self.assertIsInstance(new_circ.data[0].operation.definition, QuantumCircuit) self.assertIs(new_circ.data[1].operation.definition, None) self.assertDeprecatedBitProperties(qc, new_circ) def test_custom_instruction_with_noop_definition(self): """Test that a custom instruction whose definition contains no elements is serialized with a proper definition. Regression test of gh-7429.""" empty = QuantumCircuit(1, name="empty").to_instruction() opaque = Instruction("opaque", 1, 0, []) qc = QuantumCircuit(2) qc.append(empty, [0], []) qc.append(opaque, [1], []) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertEqual(len(new_circ), 2) self.assertIsInstance(new_circ.data[0].operation.definition, QuantumCircuit) self.assertIs(new_circ.data[1].operation.definition, None) self.assertDeprecatedBitProperties(qc, new_circ) def test_standard_gate_with_label(self): """Test a standard gate with a label.""" qc = QuantumCircuit(1) gate = XGate() gate.label = "My special X gate" qc.append(gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_circuit_with_conditional_with_label(self): """Test that instructions with conditions are correctly serialized.""" qc = QuantumCircuit(1, 1) gate = XGate(label="My conditional x gate") gate.c_if(qc.cregs[0], 1) qc.append(gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_initialize_qft(self): """Test that initialize with a complex statevector and qft work.""" k = 5 state = (1 / np.sqrt(8)) * np.array( [ np.exp(-1j * 2 * np.pi * k * (0) / 8), np.exp(-1j * 2 * np.pi * k * (1) / 8), np.exp(-1j * 2 * np.pi * k * (2) / 8), np.exp(-1j * 2 * np.pi * k * 3 / 8), np.exp(-1j * 2 * np.pi * k * 4 / 8), np.exp(-1j * 2 * np.pi * k * 5 / 8), np.exp(-1j * 2 * np.pi * k * 6 / 8), np.exp(-1j * 2 * np.pi * k * 7 / 8), ] ) qubits = 3 qc = QuantumCircuit(qubits, qubits) qc.initialize(state) qc.append(QFT(qubits), range(qubits)) qc.measure(range(qubits), range(qubits)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_statepreparation(self): """Test that state preparation with a complex statevector and qft work.""" k = 5 state = (1 / np.sqrt(8)) * np.array( [ np.exp(-1j * 2 * np.pi * k * (0) / 8), np.exp(-1j * 2 * np.pi * k * (1) / 8), np.exp(-1j * 2 * np.pi * k * (2) / 8), np.exp(-1j * 2 * np.pi * k * 3 / 8), np.exp(-1j * 2 * np.pi * k * 4 / 8), np.exp(-1j * 2 * np.pi * k * 5 / 8), np.exp(-1j * 2 * np.pi * k * 6 / 8), np.exp(-1j * 2 * np.pi * k * 7 / 8), ] ) qubits = 3 qc = QuantumCircuit(qubits, qubits) qc.prepare_state(state) qc.append(QFT(qubits), range(qubits)) qc.measure(range(qubits), range(qubits)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_single_bit_teleportation(self): """Test a teleportation circuit with single bit conditions.""" qr = QuantumRegister(1) cr = ClassicalRegister(2, name="name") qc = QuantumCircuit(qr, cr, name="Reset Test") qc.x(0) qc.measure(0, cr[0]) qc.x(0).c_if(cr[0], 1) qc.measure(0, cr[1]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_qaoa(self): """Test loading a QAOA circuit works.""" cost_operator = Pauli("ZIIZ") qaoa = QAOAAnsatz(cost_operator, reps=2) qpy_file = io.BytesIO() dump(qaoa, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qaoa, new_circ) self.assertEqual( [x.operation.label for x in qaoa.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qaoa, new_circ) def test_evolutiongate(self): """Test loading a circuit with evolution gate works.""" synthesis = LieTrotter(reps=2) evo = PauliEvolutionGate( SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=2, synthesis=synthesis ) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) new_evo = new_circ.data[0].operation self.assertIsInstance(new_evo, PauliEvolutionGate) self.assertDeprecatedBitProperties(qc, new_circ) def test_evolutiongate_param_time(self): """Test loading a circuit with an evolution gate that has a parameter for time.""" synthesis = LieTrotter(reps=2) time = Parameter("t") evo = PauliEvolutionGate( SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=time, synthesis=synthesis ) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) new_evo = new_circ.data[0].operation self.assertIsInstance(new_evo, PauliEvolutionGate) self.assertDeprecatedBitProperties(qc, new_circ) def test_evolutiongate_param_expr_time(self): """Test loading a circuit with an evolution gate that has a parameter for time.""" synthesis = LieTrotter(reps=2) time = Parameter("t") evo = PauliEvolutionGate( SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=time * time, synthesis=synthesis ) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) new_evo = new_circ.data[0].operation self.assertIsInstance(new_evo, PauliEvolutionGate) self.assertDeprecatedBitProperties(qc, new_circ) def test_evolutiongate_param_vec_time(self): """Test loading a an evolution gate that has a param vector element for time.""" synthesis = LieTrotter(reps=2) time = ParameterVector("TimeVec", 1) evo = PauliEvolutionGate( SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=time[0], synthesis=synthesis ) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) new_evo = new_circ.data[0].operation self.assertIsInstance(new_evo, PauliEvolutionGate) self.assertDeprecatedBitProperties(qc, new_circ) def test_op_list_evolutiongate(self): """Test loading a circuit with evolution gate works.""" evo = PauliEvolutionGate( [SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)])] * 5, time=0.2, synthesis=None ) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) new_evo = new_circ.data[0].operation self.assertIsInstance(new_evo, PauliEvolutionGate) self.assertDeprecatedBitProperties(qc, new_circ) def test_op_evolution_gate_suzuki_trotter(self): """Test qpy path with a suzuki trotter synthesis method on an evolution gate.""" synthesis = SuzukiTrotter() evo = PauliEvolutionGate( SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=0.2, synthesis=synthesis ) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) new_evo = new_circ.data[0].operation self.assertIsInstance(new_evo, PauliEvolutionGate) self.assertDeprecatedBitProperties(qc, new_circ) def test_parameter_expression_global_phase(self): """Test a circuit with a parameter expression global_phase.""" theta = Parameter("theta") phi = Parameter("phi") sum_param = theta + phi qc = QuantumCircuit(5, 1, global_phase=sum_param) qc.h(0) for i in range(4): qc.cx(i, i + 1) qc.barrier() qc.rz(sum_param, range(3)) qc.rz(phi, 3) qc.rz(theta, 4) qc.barrier() for i in reversed(range(4)): qc.cx(i, i + 1) qc.h(0) qc.measure(0, 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_parameter_global_phase(self): """Test a circuit with a parameter expression global_phase.""" theta = Parameter("theta") qc = QuantumCircuit(2, global_phase=theta) qc.h(0) qc.cx(0, 1) qc.measure_all() qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) def test_parameter_vector(self): """Test a circuit with a parameter vector for gate parameters.""" qc = QuantumCircuit(11) input_params = ParameterVector("x_par", 11) user_params = ParameterVector("θ_par", 11) for i, param in enumerate(user_params): qc.ry(param, i) for i, param in enumerate(input_params): qc.rz(param, i) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] expected_params = [x.name for x in qc.parameters] self.assertEqual([x.name for x in new_circuit.parameters], expected_params) self.assertDeprecatedBitProperties(qc, new_circuit) def test_parameter_vector_element_in_expression(self): """Test a circuit with a parameter vector used in a parameter expression.""" qc = QuantumCircuit(7) entanglement = [[i, i + 1] for i in range(7 - 1)] input_params = ParameterVector("x_par", 14) user_params = ParameterVector("\u03B8_par", 1) for i in range(qc.num_qubits): qc.ry(user_params[0], qc.qubits[i]) for source, target in entanglement: qc.cz(qc.qubits[source], qc.qubits[target]) for i in range(qc.num_qubits): qc.rz(-2 * input_params[2 * i + 1], qc.qubits[i]) qc.rx(-2 * input_params[2 * i], qc.qubits[i]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] expected_params = [x.name for x in qc.parameters] self.assertEqual([x.name for x in new_circuit.parameters], expected_params) self.assertDeprecatedBitProperties(qc, new_circuit) def test_parameter_vector_incomplete_warns(self): """Test that qpy's deserialization warns if a ParameterVector isn't fully identical.""" vec = ParameterVector("test", 3) qc = QuantumCircuit(1, name="fun") qc.rx(vec[1], 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) with self.assertWarnsRegex(UserWarning, r"^The ParameterVector.*Elements 0, 2.*fun$"): new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_parameter_vector_global_phase(self): """Test that a circuit with a standalone ParameterVectorElement phase works.""" vec = ParameterVector("phase", 1) qc = QuantumCircuit(1, global_phase=vec[0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_custom_metadata_serializer_full_path(self): """Test that running with custom metadata serialization works.""" class CustomObject: """Custom string container object.""" def __init__(self, string): self.string = string def __eq__(self, other): return self.string == other.string class CustomSerializer(json.JSONEncoder): """Custom json encoder to handle CustomObject.""" def default(self, o): if isinstance(o, CustomObject): return {"__type__": "Custom", "value": o.string} return json.JSONEncoder.default(self, o) class CustomDeserializer(json.JSONDecoder): """Custom json decoder to handle CustomObject.""" def object_hook(self, o): # pylint: disable=invalid-name,method-hidden """Hook to override default decoder. Normally specified as a kwarg on load() that overloads the default decoder. Done here to avoid reimplementing the decode method. """ if "__type__" in o: obj_type = o["__type__"] if obj_type == "Custom": return CustomObject(o["value"]) return o theta = Parameter("theta") qc = QuantumCircuit(2, global_phase=theta) qc.h(0) qc.cx(0, 1) qc.measure_all() circuits = [qc, qc.copy()] circuits[0].metadata = {"key": CustomObject("Circuit 1")} circuits[1].metadata = {"key": CustomObject("Circuit 2")} qpy_file = io.BytesIO() dump(circuits, qpy_file, metadata_serializer=CustomSerializer) qpy_file.seek(0) new_circuits = load(qpy_file, metadata_deserializer=CustomDeserializer) self.assertEqual(qc, new_circuits[0]) self.assertEqual(circuits[0].metadata["key"], CustomObject("Circuit 1")) self.assertEqual(qc, new_circuits[1]) self.assertEqual(circuits[1].metadata["key"], CustomObject("Circuit 2")) self.assertDeprecatedBitProperties(qc, new_circuits[0]) self.assertDeprecatedBitProperties(qc, new_circuits[1]) def test_qpy_with_ifelseop(self): """Test qpy serialization with an if block.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.measure(0, 0) with qc.if_test((qc.clbits[0], True)): qc.x(1) qc.measure(1, 1) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_qpy_with_ifelseop_with_else(self): """Test qpy serialization with an else block.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.measure(0, 0) with qc.if_test((qc.clbits[0], True)) as else_: qc.x(1) with else_: qc.y(1) qc.measure(1, 1) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_qpy_with_while_loop(self): """Test qpy serialization with a for loop.""" qc = QuantumCircuit(2, 1) with qc.while_loop((qc.clbits[0], 0)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_qpy_with_for_loop(self): """Test qpy serialization with a for loop.""" qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_qpy_with_for_loop_iterator(self): """Test qpy serialization with a for loop.""" qc = QuantumCircuit(2, 1) with qc.for_loop(iter(range(5))): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_qpy_clbit_switch(self): """Test QPY serialisation for a switch statement with a Clbit target.""" case_t = QuantumCircuit(2, 1) case_t.x(0) case_f = QuantumCircuit(2, 1) case_f.z(0) qc = QuantumCircuit(2, 1) qc.switch(0, [(True, case_t), (False, case_f)], qc.qubits, qc.clbits) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_qpy_register_switch(self): """Test QPY serialisation for a switch statement with a ClassicalRegister target.""" qreg = QuantumRegister(2, "q") creg = ClassicalRegister(3, "c") case_0 = QuantumCircuit(qreg, creg) case_0.x(0) case_1 = QuantumCircuit(qreg, creg) case_1.z(1) case_2 = QuantumCircuit(qreg, creg) case_2.x(1) qc = QuantumCircuit(qreg, creg) qc.switch(creg, [(0, case_0), ((1, 2), case_1), ((3, 4, CASE_DEFAULT), case_2)], qreg, creg) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_standalone_register_partial_bit_in_circuit(self): """Test qpy with only some bits from standalone register.""" qr = QuantumRegister(2) qc = QuantumCircuit([qr[0]]) qc.x(0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_nested_tuple_param(self): """Test qpy with an instruction that contains nested tuples.""" inst = Instruction("tuple_test", 1, 0, [((((0, 1), (0, 1)), 2, 3), ("A", "B", "C"))]) qc = QuantumCircuit(1) qc.append(inst, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_empty_tuple_param(self): """Test qpy with an instruction that contains an empty tuple.""" inst = Instruction("empty_tuple_test", 1, 0, [()]) qc = QuantumCircuit(1) qc.append(inst, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_ucr_gates(self): """Test qpy with UCRX, UCRY, and UCRZ gates.""" qc = QuantumCircuit(3) qc.ucrz([0, 0, 0, -np.pi], [0, 1], 2) qc.ucry([0, 0, 0, -np.pi], [0, 2], 1) qc.ucrx([0, 0, 0, -np.pi], [2, 1], 0) qc.measure_all() qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc.decompose().decompose(), new_circuit.decompose().decompose()) self.assertDeprecatedBitProperties(qc, new_circuit) def test_controlled_gate(self): """Test a custom controlled gate.""" qc = QuantumCircuit(3) controlled_gate = DCXGate().control(1) qc.append(controlled_gate, [0, 1, 2]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_controlled_gate_open_controls(self): """Test a controlled gate with open controls round-trips exactly.""" qc = QuantumCircuit(3) controlled_gate = DCXGate().control(1, ctrl_state=0) qc.append(controlled_gate, [0, 1, 2]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_nested_controlled_gate(self): """Test a custom nested controlled gate.""" custom_gate = Gate("black_box", 1, []) custom_definition = QuantumCircuit(1) custom_definition.h(0) custom_definition.rz(1.5, 0) custom_definition.sdg(0) custom_gate.definition = custom_definition qc = QuantumCircuit(3) qc.append(custom_gate, [0]) controlled_gate = custom_gate.control(2) qc.append(controlled_gate, [0, 1, 2]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertDeprecatedBitProperties(qc, new_circ) def test_open_controlled_gate(self): """Test an open control is preserved across serialization.""" qc = QuantumCircuit(2) qc.cx(0, 1, ctrl_state=0) with io.BytesIO() as fd: dump(qc, fd) fd.seek(0) new_circ = load(fd)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.data[0].operation.ctrl_state, new_circ.data[0].operation.ctrl_state) self.assertDeprecatedBitProperties(qc, new_circ) def test_standard_control_gates(self): """Test standard library controlled gates.""" qc = QuantumCircuit(6) mcu1_gate = MCU1Gate(np.pi, 2) mcx_gate = MCXGate(5) mcx_gray_gate = MCXGrayCode(5) mcx_recursive_gate = MCXRecursive(4) mcx_vchain_gate = MCXVChain(3) qc.append(mcu1_gate, [0, 2, 1]) qc.append(mcx_gate, list(range(0, 6))) qc.append(mcx_gray_gate, list(range(0, 6))) qc.append(mcx_recursive_gate, list(range(0, 5))) qc.append(mcx_vchain_gate, list(range(0, 5))) qc.mcp(np.pi, [0, 2], 1) qc.mct([0, 2], 1) qc.mcx([0, 2], 1) qc.measure_all() qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_controlled_gate_subclass_custom_definition(self): """Test controlled gate with overloaded definition. Reproduce from: https://github.com/Qiskit/qiskit-terra/issues/8794 """ class CustomCXGate(ControlledGate): """Custom CX with overloaded _define.""" def __init__(self, label=None, ctrl_state=None): super().__init__( "cx", 2, [], label, num_ctrl_qubits=1, ctrl_state=ctrl_state, base_gate=XGate() ) def _define(self) -> None: qc = QuantumCircuit(2, name=self.name) qc.cx(0, 1) self.definition = qc qc = QuantumCircuit(2) qc.append(CustomCXGate(), [0, 1]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertDeprecatedBitProperties(qc, new_circ) def test_load_with_loose_bits(self): """Test that loading from a circuit with loose bits works.""" qc = QuantumCircuit([Qubit(), Qubit(), Clbit()]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(tuple(new_circuit.qregs), ()) self.assertEqual(tuple(new_circuit.cregs), ()) self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_load_with_loose_bits_and_registers(self): """Test that loading from a circuit with loose bits and registers works.""" qc = QuantumCircuit(QuantumRegister(3), ClassicalRegister(1), [Clbit()]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_registers_after_loose_bits(self): """Test that a circuit whose registers appear after some loose bits roundtrips. Regression test of gh-9094.""" qc = QuantumCircuit() qc.add_bits([Qubit(), Clbit()]) qc.add_register(QuantumRegister(2, name="q1")) qc.add_register(ClassicalRegister(2, name="c1")) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_roundtrip_empty_register(self): """Test that empty registers round-trip correctly.""" qc = QuantumCircuit(QuantumRegister(0), ClassicalRegister(0)) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_roundtrip_several_empty_registers(self): """Test that several empty registers round-trip correctly.""" qc = QuantumCircuit( QuantumRegister(0, "a"), QuantumRegister(0, "b"), ClassicalRegister(0, "c"), ClassicalRegister(0, "d"), ) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_roundtrip_empty_registers_with_loose_bits(self): """Test that empty registers still round-trip correctly in the presence of loose bits.""" loose = [Qubit(), Clbit()] qc = QuantumCircuit(loose, QuantumRegister(0), ClassicalRegister(0)) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) qc = QuantumCircuit(QuantumRegister(0), ClassicalRegister(0), loose) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_incomplete_owned_bits(self): """Test that a circuit that contains only some bits that are owned by a register are correctly roundtripped.""" reg = QuantumRegister(5, "q") qc = QuantumCircuit(reg[:3]) qc.ccx(0, 1, 2) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_diagonal_gate(self): """Test that a `DiagonalGate` successfully roundtrips.""" qc = QuantumCircuit(2) qc.diagonal([1, -1, -1, 1], [0, 1]) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] # DiagonalGate (and a bunch of the qiskit.extensions gates) have non-deterministic # definitions with regard to internal instruction names, so cannot be directly compared for # equality. self.assertIs(type(qc.data[0].operation), type(new_circuit.data[0].operation)) self.assertEqual(qc.data[0].operation.params, new_circuit.data[0].operation.params) self.assertDeprecatedBitProperties(qc, new_circuit) @ddt.data(QuantumCircuit.if_test, QuantumCircuit.while_loop) def test_if_else_while_expr_simple(self, control_flow): """Test that `IfElseOp` and `WhileLoopOp` can have an `Expr` node as their `condition`, and that this round-trips through QPY.""" body = QuantumCircuit(1) qr = QuantumRegister(2, "q1") cr = ClassicalRegister(2, "c1") qc = QuantumCircuit(qr, cr) control_flow(qc, expr.equal(cr, 3), body.copy(), [0], []) control_flow(qc, expr.lift(qc.clbits[0]), body.copy(), [0], []) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) @ddt.data(QuantumCircuit.if_test, QuantumCircuit.while_loop) def test_if_else_while_expr_nested(self, control_flow): """Test that `IfElseOp` and `WhileLoopOp` can have an `Expr` node as their `condition`, and that this round-trips through QPY.""" inner = QuantumCircuit(1) outer = QuantumCircuit(1, 1) control_flow(outer, expr.lift(outer.clbits[0]), inner.copy(), [0], []) qr = QuantumRegister(2, "q1") cr = ClassicalRegister(2, "c1") qc = QuantumCircuit(qr, cr) control_flow(qc, expr.equal(cr, 3), outer.copy(), [1], [1]) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_if_else_expr_stress(self): """Stress-test the `Expr` handling in the condition of an `IfElseOp`. This should hit on every aspect of the `Expr` tree.""" inner = QuantumCircuit(1) inner.x(0) outer = QuantumCircuit(1, 1) outer.if_test(expr.cast(outer.clbits[0], types.Bool()), inner.copy(), [0], []) # Register whose size is deliberately larger that one byte. cr1 = ClassicalRegister(256, "c1") cr2 = ClassicalRegister(4, "c2") loose = Clbit() qc = QuantumCircuit([Qubit(), Qubit(), loose], cr1, cr2) qc.rz(1.0, 0) qc.if_test( expr.logic_and( expr.logic_and( expr.logic_or( expr.cast( expr.less(expr.bit_and(cr1, 0x0F), expr.bit_not(cr1)), types.Bool(), ), expr.cast( expr.less_equal(expr.bit_or(cr2, 7), expr.bit_xor(cr2, 7)), types.Bool(), ), ), expr.logic_and( expr.logic_or(expr.equal(cr2, 2), expr.logic_not(expr.not_equal(cr2, 3))), expr.logic_or( expr.greater(cr2, 3), expr.greater_equal(cr2, 3), ), ), ), expr.logic_not(loose), ), outer.copy(), [1], [0], ) qc.rz(1.0, 0) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_switch_expr_simple(self): """Test that `SwitchCaseOp` can have an `Expr` node as its `target`, and that this round-trips through QPY.""" body = QuantumCircuit(1) qr = QuantumRegister(2, "q1") cr = ClassicalRegister(2, "c1") qc = QuantumCircuit(qr, cr) qc.switch(expr.bit_and(cr, 3), [(1, body.copy())], [0], []) qc.switch(expr.logic_not(qc.clbits[0]), [(False, body.copy())], [0], []) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_switch_expr_nested(self): """Test that `SwitchCaseOp` can have an `Expr` node as its `target`, and that this round-trips through QPY.""" inner = QuantumCircuit(1) outer = QuantumCircuit(1, 1) outer.switch(expr.lift(outer.clbits[0]), [(False, inner.copy())], [0], []) qr = QuantumRegister(2, "q1") cr = ClassicalRegister(2, "c1") qc = QuantumCircuit(qr, cr) qc.switch(expr.lift(cr), [(3, outer.copy())], [1], [1]) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_switch_expr_stress(self): """Stress-test the `Expr` handling in the target of a `SwitchCaseOp`. This should hit on every aspect of the `Expr` tree.""" inner = QuantumCircuit(1) inner.x(0) outer = QuantumCircuit(1, 1) outer.switch(expr.cast(outer.clbits[0], types.Bool()), [(True, inner.copy())], [0], []) # Register whose size is deliberately larger that one byte. cr1 = ClassicalRegister(256, "c1") cr2 = ClassicalRegister(4, "c2") loose = Clbit() qc = QuantumCircuit([Qubit(), Qubit(), loose], cr1, cr2) qc.rz(1.0, 0) qc.switch( expr.logic_and( expr.logic_and( expr.logic_or( expr.cast( expr.less(expr.bit_and(cr1, 0x0F), expr.bit_not(cr1)), types.Bool(), ), expr.cast( expr.less_equal(expr.bit_or(cr2, 7), expr.bit_xor(cr2, 7)), types.Bool(), ), ), expr.logic_and( expr.logic_or(expr.equal(cr2, 2), expr.logic_not(expr.not_equal(cr2, 3))), expr.logic_or( expr.greater(cr2, 3), expr.greater_equal(cr2, 3), ), ), ), expr.logic_not(loose), ), [(False, outer.copy())], [1], [0], ) qc.rz(1.0, 0) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_multiple_nested_control_custom_definitions(self): """Test that circuits with multiple controlled custom gates that in turn depend on custom gates can be exported successfully when there are several such gates in the outer circuit. See gh-9746""" inner_1 = QuantumCircuit(1, name="inner_1") inner_1.x(0) inner_2 = QuantumCircuit(1, name="inner_2") inner_2.y(0) outer_1 = QuantumCircuit(1, name="outer_1") outer_1.append(inner_1.to_gate(), [0], []) outer_2 = QuantumCircuit(1, name="outer_2") outer_2.append(inner_2.to_gate(), [0], []) qc = QuantumCircuit(2) qc.append(outer_1.to_gate().control(1), [0, 1], []) qc.append(outer_2.to_gate().control(1), [0, 1], []) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_qpy_deprecation(self): """Test the old import path's deprecations fire.""" with self.assertWarnsRegex(DeprecationWarning, "is deprecated"): # pylint: disable=no-name-in-module, unused-import, redefined-outer-name, reimported from qiskit.circuit.qpy_serialization import dump, load
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's QuantumCircuit class for multiple registers.""" from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.circuit.exceptions import CircuitError class TestCircuitMultiRegs(QiskitTestCase): """QuantumCircuit Qasm tests.""" def test_circuit_multi(self): """Test circuit multi regs declared at start.""" qreg0 = QuantumRegister(2, "q0") creg0 = ClassicalRegister(2, "c0") qreg1 = QuantumRegister(2, "q1") creg1 = ClassicalRegister(2, "c1") circ = QuantumCircuit(qreg0, qreg1, creg0, creg1) circ.x(qreg0[1]) circ.x(qreg1[0]) meas = QuantumCircuit(qreg0, qreg1, creg0, creg1) meas.measure(qreg0, creg0) meas.measure(qreg1, creg1) qc = circ.compose(meas) circ2 = QuantumCircuit() circ2.add_register(qreg0) circ2.add_register(qreg1) circ2.add_register(creg0) circ2.add_register(creg1) circ2.x(qreg0[1]) circ2.x(qreg1[0]) meas2 = QuantumCircuit() meas2.add_register(qreg0) meas2.add_register(qreg1) meas2.add_register(creg0) meas2.add_register(creg1) meas2.measure(qreg0, creg0) meas2.measure(qreg1, creg1) qc2 = circ2.compose(meas2) dag_qc = circuit_to_dag(qc) dag_qc2 = circuit_to_dag(qc2) dag_circ2 = circuit_to_dag(circ2) dag_circ = circuit_to_dag(circ) self.assertEqual(dag_qc, dag_qc2) self.assertEqual(dag_circ, dag_circ2) def test_circuit_multi_name_collision(self): """Test circuit multi regs, with name collision.""" qreg0 = QuantumRegister(2, "q") qreg1 = QuantumRegister(3, "q") self.assertRaises(CircuitError, QuantumCircuit, qreg0, qreg1)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's QuantumCircuit class.""" import numpy as np from ddt import data, ddt from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute from qiskit.circuit import Gate, Instruction, Measure, Parameter from qiskit.circuit.bit import Bit from qiskit.circuit.classicalregister import Clbit from qiskit.circuit.exceptions import CircuitError from qiskit.circuit.controlflow import IfElseOp from qiskit.circuit.library import CXGate, HGate from qiskit.circuit.library.standard_gates import SGate from qiskit.circuit.quantumcircuit import BitLocations from qiskit.circuit.quantumcircuitdata import CircuitInstruction from qiskit.circuit.quantumregister import AncillaQubit, AncillaRegister, Qubit from qiskit.pulse import DriveChannel, Gaussian, Play, Schedule from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase @ddt class TestCircuitOperations(QiskitTestCase): """QuantumCircuit Operations tests.""" @data(0, 1, -1, -2) def test_append_resolves_integers(self, index): """Test that integer arguments to append are correctly resolved.""" # We need to assume that appending ``Bit`` instances will always work, so we have something # to test against. qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] test = QuantumCircuit(qubits, clbits) test.append(Measure(), [index], [index]) expected = QuantumCircuit(qubits, clbits) expected.append(Measure(), [qubits[index]], [clbits[index]]) self.assertEqual(test, expected) @data(np.int32(0), np.int8(-1), np.uint64(1)) def test_append_resolves_numpy_integers(self, index): """Test that Numpy's integers can be used to reference qubits and clbits.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] test = QuantumCircuit(qubits, clbits) test.append(Measure(), [index], [index]) expected = QuantumCircuit(qubits, clbits) expected.append(Measure(), [qubits[int(index)]], [clbits[int(index)]]) self.assertEqual(test, expected) @data( slice(0, 2), slice(None, 1), slice(1, None), slice(None, None), slice(0, 2, 2), slice(2, -1, -1), slice(1000, 1003), ) def test_append_resolves_slices(self, index): """Test that slices can be used to reference qubits and clbits with the same semantics that they have on lists.""" qregs = [QuantumRegister(2), QuantumRegister(1)] cregs = [ClassicalRegister(1), ClassicalRegister(2)] test = QuantumCircuit(*qregs, *cregs) test.append(Measure(), [index], [index]) expected = QuantumCircuit(*qregs, *cregs) for qubit, clbit in zip(expected.qubits[index], expected.clbits[index]): expected.append(Measure(), [qubit], [clbit]) self.assertEqual(test, expected) def test_append_resolves_scalar_numpy_array(self): """Test that size-1 Numpy arrays can be used to index arguments. These arrays can be passed to ``int``, which means they sometimes might be involved in spurious casts.""" test = QuantumCircuit(1, 1) test.append(Measure(), [np.array([0])], [np.array([0])]) expected = QuantumCircuit(1, 1) expected.measure(0, 0) self.assertEqual(test, expected) @data([3], [-3], [0, 1, 3]) def test_append_rejects_out_of_range_input(self, specifier): """Test that append rejects an integer that's out of range.""" test = QuantumCircuit(2, 2) with self.subTest("qubit"), self.assertRaisesRegex(CircuitError, "out of range"): opaque = Instruction("opaque", len(specifier), 1, []) test.append(opaque, specifier, [0]) with self.subTest("clbit"), self.assertRaisesRegex(CircuitError, "out of range"): opaque = Instruction("opaque", 1, len(specifier), []) test.append(opaque, [0], specifier) def test_append_rejects_bits_not_in_circuit(self): """Test that append rejects bits that are not in the circuit.""" test = QuantumCircuit(2, 2) with self.subTest("qubit"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [Qubit()], [test.clbits[0]]) with self.subTest("clbit"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [test.qubits[0]], [Clbit()]) with self.subTest("qubit list"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [[test.qubits[0], Qubit()]], [test.clbits]) with self.subTest("clbit list"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [test.qubits], [[test.clbits[0], Clbit()]]) def test_append_rejects_bit_of_wrong_type(self): """Test that append rejects bits of the wrong type in an argument list.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] test = QuantumCircuit(qubits, clbits) with self.subTest("c to q"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [clbits[0]], [clbits[1]]) with self.subTest("q to c"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [qubits[0]], [qubits[1]]) with self.subTest("none to q"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [Bit()], [clbits[0]]) with self.subTest("none to c"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [qubits[0]], [Bit()]) with self.subTest("none list"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [[qubits[0], Bit()]], [[clbits[0], Bit()]]) @data(0.0, 1.0, 1.0 + 0.0j, "0") def test_append_rejects_wrong_types(self, specifier): """Test that various bad inputs are rejected, both given loose or in sublists.""" test = QuantumCircuit(2, 2) # Use a default Instruction to be sure that there's not overridden broadcasting. opaque = Instruction("opaque", 1, 1, []) with self.subTest("q"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [specifier], [0]) with self.subTest("c"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [0], [specifier]) with self.subTest("q list"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [[specifier]], [[0]]) with self.subTest("c list"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [[0]], [[specifier]]) @data([], [0], [0, 1, 2]) def test_append_rejects_bad_arguments_opaque(self, bad_arg): """Test that a suitable exception is raised when there is an argument mismatch.""" inst = QuantumCircuit(2, 2).to_instruction() qc = QuantumCircuit(3, 3) with self.assertRaisesRegex(CircuitError, "The amount of qubit arguments"): qc.append(inst, bad_arg, [0, 1]) with self.assertRaisesRegex(CircuitError, "The amount of clbit arguments"): qc.append(inst, [0, 1], bad_arg) def test_anding_self(self): """Test that qc &= qc finishes, which can be prone to infinite while-loops. This can occur e.g. when a user tries >>> other_qc = qc >>> other_qc &= qc # or qc2.compose(qc) """ qc = QuantumCircuit(1) qc.x(0) # must contain at least one operation to end up in a infinite while-loop # attempt addition, times out if qc is added via reference qc &= qc # finally, qc should contain two X gates self.assertEqual(["x", "x"], [x.operation.name for x in qc.data]) def test_compose_circuit(self): """Test composing two circuits""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr[0]) qc1.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc3 = qc1.compose(qc2) backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_compose_circuit_and(self): """Test composing two circuits using & operator""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr[0]) qc1.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc3 = qc1 & qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_compose_circuit_iand(self): """Test composing circuits using &= operator (in place)""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr[0]) qc1.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc1 &= qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc1, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 2}) # changes "in-place" self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_compose_circuit_fail_circ_size(self): """Test composing circuit fails when number of wires in circuit is not enough""" qr1 = QuantumRegister(2) qr2 = QuantumRegister(4) # Creating our circuits qc1 = QuantumCircuit(qr1) qc1.x(0) qc1.h(1) qc2 = QuantumCircuit(qr2) qc2.h([1, 2]) qc2.cx(2, 3) # Composing will fail because qc2 requires 4 wires self.assertRaises(CircuitError, qc1.compose, qc2) def test_compose_circuit_fail_arg_size(self): """Test composing circuit fails when arg size does not match number of wires""" qr1 = QuantumRegister(2) qr2 = QuantumRegister(2) qc1 = QuantumCircuit(qr1) qc1.h(0) qc2 = QuantumCircuit(qr2) qc2.cx(0, 1) self.assertRaises(CircuitError, qc1.compose, qc2, qubits=[0]) def test_tensor_circuit(self): """Test tensoring two circuits""" qc1 = QuantumCircuit(1, 1) qc2 = QuantumCircuit(1, 1) qc2.h(0) qc2.measure(0, 0) qc1.measure(0, 0) qc3 = qc1.tensor(qc2) backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc1.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_tensor_circuit_xor(self): """Test tensoring two circuits using ^ operator""" qc1 = QuantumCircuit(1, 1) qc2 = QuantumCircuit(1, 1) qc2.h(0) qc2.measure(0, 0) qc1.measure(0, 0) qc3 = qc1 ^ qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc1.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_tensor_circuit_ixor(self): """Test tensoring two circuits using ^= operator""" qc1 = QuantumCircuit(1, 1) qc2 = QuantumCircuit(1, 1) qc2.h(0) qc2.measure(0, 0) qc1.measure(0, 0) qc1 ^= qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc1, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 2}) # changes "in-place" self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_measure_args_type_cohesion(self): """Test for proper args types for measure function.""" quantum_reg = QuantumRegister(3) classical_reg_0 = ClassicalRegister(1) classical_reg_1 = ClassicalRegister(2) quantum_circuit = QuantumCircuit(quantum_reg, classical_reg_0, classical_reg_1) quantum_circuit.h(quantum_reg) with self.assertRaises(CircuitError) as ctx: quantum_circuit.measure(quantum_reg, classical_reg_1) self.assertEqual(ctx.exception.message, "register size error") def test_copy_circuit(self): """Test copy method makes a copy""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) self.assertEqual(qc, qc.copy()) def test_copy_copies_registers(self): """Test copy copies the registers not via reference.""" qc = QuantumCircuit(1, 1) copied = qc.copy() copied.add_register(QuantumRegister(1, "additional_q")) copied.add_register(ClassicalRegister(1, "additional_c")) self.assertEqual(len(qc.qregs), 1) self.assertEqual(len(copied.qregs), 2) self.assertEqual(len(qc.cregs), 1) self.assertEqual(len(copied.cregs), 2) def test_copy_empty_like_circuit(self): """Test copy_empty_like method makes a clear copy.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr, global_phase=1.0, name="qc", metadata={"key": "value"}) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) sched = Schedule(Play(Gaussian(160, 0.1, 40), DriveChannel(0))) qc.add_calibration("h", [0, 1], sched) copied = qc.copy_empty_like() qc.clear() self.assertEqual(qc, copied) self.assertEqual(qc.global_phase, copied.global_phase) self.assertEqual(qc.name, copied.name) self.assertEqual(qc.metadata, copied.metadata) self.assertEqual(qc.calibrations, copied.calibrations) copied = qc.copy_empty_like("copy") self.assertEqual(copied.name, "copy") def test_circuit_copy_rejects_invalid_types(self): """Test copy method rejects argument with type other than 'string' and 'None' type.""" qc = QuantumCircuit(1, 1) qc.h(0) with self.assertRaises(TypeError): qc.copy([1, "2", 3]) def test_circuit_copy_empty_like_rejects_invalid_types(self): """Test copy_empty_like method rejects argument with type other than 'string' and 'None' type.""" qc = QuantumCircuit(1, 1) qc.h(0) with self.assertRaises(TypeError): qc.copy_empty_like(123) def test_clear_circuit(self): """Test clear method deletes instructions in circuit.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.clear() self.assertEqual(len(qc.data), 0) self.assertEqual(len(qc._parameter_table), 0) def test_measure_active(self): """Test measure_active Applies measurements only to non-idle qubits. Creates a ClassicalRegister of size equal to the amount of non-idle qubits to store the measured values. """ qr = QuantumRegister(4) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[2]) circuit.measure_active() expected = QuantumCircuit(qr) expected.h(qr[0]) expected.h(qr[2]) expected.add_register(cr) expected.barrier() expected.measure([qr[0], qr[2]], [cr[0], cr[1]]) self.assertEqual(expected, circuit) def test_measure_active_copy(self): """Test measure_active copy Applies measurements only to non-idle qubits. Creates a ClassicalRegister of size equal to the amount of non-idle qubits to store the measured values. """ qr = QuantumRegister(4) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[2]) new_circuit = circuit.measure_active(inplace=False) expected = QuantumCircuit(qr) expected.h(qr[0]) expected.h(qr[2]) expected.add_register(cr) expected.barrier() expected.measure([qr[0], qr[2]], [cr[0], cr[1]]) self.assertEqual(expected, new_circuit) self.assertFalse("measure" in circuit.count_ops().keys()) def test_measure_active_repetition(self): """Test measure_active in a circuit with a 'measure' creg. measure_active should be aware that the creg 'measure' might exists. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.measure_active() self.assertEqual(len(circuit.cregs), 2) # Two cregs self.assertEqual(len(circuit.cregs[0]), 2) # Both length 2 self.assertEqual(len(circuit.cregs[1]), 2) def test_measure_all(self): """Test measure_all applies measurements to all qubits. Creates a ClassicalRegister of size equal to the total amount of qubits to store those measured values. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr) circuit.measure_all() expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr) self.assertEqual(expected, circuit) def test_measure_all_not_add_bits_equal(self): """Test measure_all applies measurements to all qubits. Does not create a new ClassicalRegister if the existing one is big enough. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure_all(add_bits=False) expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr) self.assertEqual(expected, circuit) def test_measure_all_not_add_bits_bigger(self): """Test measure_all applies measurements to all qubits. Does not create a new ClassicalRegister if the existing one is big enough. """ qr = QuantumRegister(2) cr = ClassicalRegister(3, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure_all(add_bits=False) expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr[0:2]) self.assertEqual(expected, circuit) def test_measure_all_not_add_bits_smaller(self): """Test measure_all applies measurements to all qubits. Raises an error if there are not enough classical bits to store the measurements. """ qr = QuantumRegister(3) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) with self.assertRaisesRegex(CircuitError, "The number of classical bits"): circuit.measure_all(add_bits=False) def test_measure_all_copy(self): """Test measure_all with inplace=False""" qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr) new_circuit = circuit.measure_all(inplace=False) expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr) self.assertEqual(expected, new_circuit) self.assertFalse("measure" in circuit.count_ops().keys()) def test_measure_all_repetition(self): """Test measure_all in a circuit with a 'measure' creg. measure_all should be aware that the creg 'measure' might exists. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr, cr) circuit.measure_all() self.assertEqual(len(circuit.cregs), 2) # Two cregs self.assertEqual(len(circuit.cregs[0]), 2) # Both length 2 self.assertEqual(len(circuit.cregs[1]), 2) def test_remove_final_measurements(self): """Test remove_final_measurements Removes all measurements at end of circuit. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) circuit.remove_final_measurements() expected = QuantumCircuit(qr) self.assertEqual(expected, circuit) def test_remove_final_measurements_copy(self): """Test remove_final_measurements on copy Removes all measurements at end of circuit. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) new_circuit = circuit.remove_final_measurements(inplace=False) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) self.assertTrue("measure" in circuit.count_ops().keys()) def test_remove_final_measurements_copy_with_parameters(self): """Test remove_final_measurements doesn't corrupt ParameterTable See https://github.com/Qiskit/qiskit-terra/issues/6108 for more details """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") theta = Parameter("theta") circuit = QuantumCircuit(qr, cr) circuit.rz(theta, qr) circuit.measure(qr, cr) circuit.remove_final_measurements() copy = circuit.copy() self.assertEqual(copy, circuit) def test_remove_final_measurements_multiple_measures(self): """Test remove_final_measurements only removes measurements at the end of the circuit remove_final_measurements should not remove measurements in the beginning or middle of the circuit. """ qr = QuantumRegister(2) cr = ClassicalRegister(1) circuit = QuantumCircuit(qr, cr) circuit.measure(qr[0], cr) circuit.h(0) circuit.measure(qr[0], cr) circuit.h(0) circuit.measure(qr[0], cr) circuit.remove_final_measurements() expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr) expected.h(0) expected.measure(qr[0], cr) expected.h(0) self.assertEqual(expected, circuit) def test_remove_final_measurements_5802(self): """Test remove_final_measurements removes classical bits https://github.com/Qiskit/qiskit-terra/issues/5802. """ qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) circuit.remove_final_measurements() self.assertEqual(circuit.cregs, []) self.assertEqual(circuit.clbits, []) def test_remove_final_measurements_7089(self): """Test remove_final_measurements removes resulting unused registers even if not all bits were measured into. https://github.com/Qiskit/qiskit-terra/issues/7089. """ circuit = QuantumCircuit(2, 5) circuit.measure(0, 0) circuit.measure(1, 1) circuit.remove_final_measurements(inplace=True) self.assertEqual(circuit.cregs, []) self.assertEqual(circuit.clbits, []) def test_remove_final_measurements_bit_locations(self): """Test remove_final_measurements properly recalculates clbit indicies and preserves order of remaining cregs and clbits. """ c0 = ClassicalRegister(1) c1_0 = Clbit() c2 = ClassicalRegister(1) c3 = ClassicalRegister(1) # add an individual bit that's not in any register of this circuit circuit = QuantumCircuit(QuantumRegister(1), c0, [c1_0], c2, c3) circuit.measure(0, c1_0) circuit.measure(0, c2[0]) # assert cregs and clbits before measure removal self.assertEqual(circuit.cregs, [c0, c2, c3]) self.assertEqual(circuit.clbits, [c0[0], c1_0, c2[0], c3[0]]) # assert clbit indices prior to measure removal self.assertEqual(circuit.find_bit(c0[0]), BitLocations(0, [(c0, 0)])) self.assertEqual(circuit.find_bit(c1_0), BitLocations(1, [])) self.assertEqual(circuit.find_bit(c2[0]), BitLocations(2, [(c2, 0)])) self.assertEqual(circuit.find_bit(c3[0]), BitLocations(3, [(c3, 0)])) circuit.remove_final_measurements() # after measure removal, creg c2 should be gone, as should lone bit c1_0 # and c0 should still come before c3 self.assertEqual(circuit.cregs, [c0, c3]) self.assertEqual(circuit.clbits, [c0[0], c3[0]]) # there should be no gaps in clbit indices # e.g. c3[0] is now the second clbit self.assertEqual(circuit.find_bit(c0[0]), BitLocations(0, [(c0, 0)])) self.assertEqual(circuit.find_bit(c3[0]), BitLocations(1, [(c3, 0)])) def test_reverse(self): """Test reverse method reverses but does not invert.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.s(1) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) qc.x(0) qc.y(1) expected = QuantumCircuit(2, 2) expected.y(1) expected.x(0) expected.measure([0, 1], [0, 1]) expected.cx(0, 1) expected.s(1) expected.h(0) self.assertEqual(qc.reverse_ops(), expected) def test_repeat(self): """Test repeating the circuit works.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.h(0).c_if(cr, 1) with self.subTest("repeat 0 times"): rep = qc.repeat(0) self.assertEqual(rep, QuantumCircuit(qr, cr)) with self.subTest("repeat 3 times"): inst = qc.to_instruction() ref = QuantumCircuit(qr, cr) for _ in range(3): ref.append(inst, ref.qubits, ref.clbits) rep = qc.repeat(3) self.assertEqual(rep, ref) @data(0, 1, 4) def test_repeat_global_phase(self, num): """Test the global phase is properly handled upon repeat.""" phase = 0.123 qc = QuantumCircuit(1, global_phase=phase) expected = np.exp(1j * phase * num) * np.identity(2) np.testing.assert_array_almost_equal(Operator(qc.repeat(num)).data, expected) def test_bind_global_phase(self): """Test binding global phase.""" x = Parameter("x") circuit = QuantumCircuit(1, global_phase=x) self.assertEqual(circuit.parameters, {x}) bound = circuit.bind_parameters({x: 2}) self.assertEqual(bound.global_phase, 2) self.assertEqual(bound.parameters, set()) def test_bind_parameter_in_phase_and_gate(self): """Test binding a parameter present in the global phase and the gates.""" x = Parameter("x") circuit = QuantumCircuit(1, global_phase=x) circuit.rx(x, 0) self.assertEqual(circuit.parameters, {x}) ref = QuantumCircuit(1, global_phase=2) ref.rx(2, 0) bound = circuit.bind_parameters({x: 2}) self.assertEqual(bound, ref) self.assertEqual(bound.parameters, set()) def test_power(self): """Test taking the circuit to a power works.""" qc = QuantumCircuit(2) qc.cx(0, 1) qc.rx(0.2, 1) gate = qc.to_gate() with self.subTest("power(int >= 0) equals repeat"): self.assertEqual(qc.power(4), qc.repeat(4)) with self.subTest("explicit matrix power"): self.assertEqual(qc.power(4, matrix_power=True).data[0].operation, gate.power(4)) with self.subTest("float power"): self.assertEqual(qc.power(1.23).data[0].operation, gate.power(1.23)) with self.subTest("negative power"): self.assertEqual(qc.power(-2).data[0].operation, gate.power(-2)) def test_power_parameterized_circuit(self): """Test taking a parameterized circuit to a power.""" theta = Parameter("th") qc = QuantumCircuit(2) qc.cx(0, 1) qc.rx(theta, 1) with self.subTest("power(int >= 0) equals repeat"): self.assertEqual(qc.power(4), qc.repeat(4)) with self.subTest("cannot to matrix power if parameterized"): with self.assertRaises(CircuitError): _ = qc.power(0.5) def test_control(self): """Test controlling the circuit.""" qc = QuantumCircuit(2, name="my_qc") qc.cry(0.2, 0, 1) c_qc = qc.control() with self.subTest("return type is circuit"): self.assertIsInstance(c_qc, QuantumCircuit) with self.subTest("test name"): self.assertEqual(c_qc.name, "c_my_qc") with self.subTest("repeated control"): cc_qc = c_qc.control() self.assertEqual(cc_qc.num_qubits, c_qc.num_qubits + 1) with self.subTest("controlled circuit has same parameter"): param = Parameter("p") qc.rx(param, 0) c_qc = qc.control() self.assertEqual(qc.parameters, c_qc.parameters) with self.subTest("non-unitary operation raises"): qc.reset(0) with self.assertRaises(CircuitError): _ = qc.control() def test_control_implementation(self): """Run a test case for controlling the circuit, which should use ``Gate.control``.""" qc = QuantumCircuit(3) qc.cx(0, 1) qc.cry(0.2, 0, 1) qc.t(0) qc.append(SGate().control(2), [0, 1, 2]) qc.iswap(2, 0) c_qc = qc.control(2, ctrl_state="10") cgate = qc.to_gate().control(2, ctrl_state="10") ref = QuantumCircuit(*c_qc.qregs) ref.append(cgate, ref.qubits) self.assertEqual(ref, c_qc) @data("gate", "instruction") def test_repeat_appended_type(self, subtype): """Test repeat appends Gate if circuit contains only gates and Instructions otherwise.""" sub = QuantumCircuit(2) sub.x(0) if subtype == "gate": sub = sub.to_gate() else: sub = sub.to_instruction() qc = QuantumCircuit(2) qc.append(sub, [0, 1]) rep = qc.repeat(3) if subtype == "gate": self.assertTrue(all(isinstance(op.operation, Gate) for op in rep.data)) else: self.assertTrue(all(isinstance(op.operation, Instruction) for op in rep.data)) def test_reverse_bits(self): """Test reversing order of bits.""" qc = QuantumCircuit(3, 2) qc.h(0) qc.s(1) qc.cx(0, 1) qc.measure(0, 1) qc.x(0) qc.y(1) qc.global_phase = -1 expected = QuantumCircuit(3, 2) expected.h(2) expected.s(1) expected.cx(2, 1) expected.measure(2, 0) expected.x(2) expected.y(1) expected.global_phase = -1 self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_boxed(self): """Test reversing order of bits in a hierarchical circuit.""" wide_cx = QuantumCircuit(3) wide_cx.cx(0, 1) wide_cx.cx(1, 2) wide_cxg = wide_cx.to_gate() cx_box = QuantumCircuit(3) cx_box.append(wide_cxg, [0, 1, 2]) expected = QuantumCircuit(3) expected.cx(2, 1) expected.cx(1, 0) self.assertEqual(cx_box.reverse_bits().decompose(), expected) self.assertEqual(cx_box.decompose().reverse_bits(), expected) # box one more layer to be safe. cx_box_g = cx_box.to_gate() cx_box_box = QuantumCircuit(4) cx_box_box.append(cx_box_g, [0, 1, 2]) cx_box_box.cx(0, 3) expected2 = QuantumCircuit(4) expected2.cx(3, 2) expected2.cx(2, 1) expected2.cx(3, 0) self.assertEqual(cx_box_box.reverse_bits().decompose().decompose(), expected2) def test_reverse_bits_with_registers(self): """Test reversing order of bits when registers are present.""" qr1 = QuantumRegister(3, "a") qr2 = QuantumRegister(2, "b") qc = QuantumCircuit(qr1, qr2) qc.h(qr1[0]) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr1[2]) qc.cx(qr1[2], qr2[0]) qc.cx(qr2[0], qr2[1]) expected = QuantumCircuit(qr2, qr1) expected.h(qr1[2]) expected.cx(qr1[2], qr1[1]) expected.cx(qr1[1], qr1[0]) expected.cx(qr1[0], qr2[1]) expected.cx(qr2[1], qr2[0]) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_overlapped_registers(self): """Test reversing order of bits when registers are overlapped.""" qr1 = QuantumRegister(2, "a") qr2 = QuantumRegister(bits=[qr1[0], qr1[1], Qubit()], name="b") qc = QuantumCircuit(qr1, qr2) qc.h(qr1[0]) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr2[2]) qr2 = QuantumRegister(bits=[Qubit(), qr1[0], qr1[1]], name="b") expected = QuantumCircuit(qr2, qr1) expected.h(qr1[1]) expected.cx(qr1[1], qr1[0]) expected.cx(qr1[0], qr2[0]) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_registerless_bits(self): """Test reversing order of registerless bits.""" q0 = Qubit() q1 = Qubit() c0 = Clbit() c1 = Clbit() qc = QuantumCircuit([q0, q1], [c0, c1]) qc.h(0) qc.cx(0, 1) qc.x(0).c_if(1, True) qc.measure(0, 0) expected = QuantumCircuit([c1, c0], [q1, q0]) expected.h(1) expected.cx(1, 0) expected.x(1).c_if(0, True) expected.measure(1, 1) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_registers_and_bits(self): """Test reversing order of bits with registers and registerless bits.""" qr = QuantumRegister(2, "a") q = Qubit() qc = QuantumCircuit(qr, [q]) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.cx(qr[1], q) expected = QuantumCircuit([q], qr) expected.h(qr[1]) expected.cx(qr[1], qr[0]) expected.cx(qr[0], q) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_mixed_overlapped_registers(self): """Test reversing order of bits with overlapped registers and registerless bits.""" q = Qubit() qr1 = QuantumRegister(bits=[q, Qubit()], name="qr1") qr2 = QuantumRegister(bits=[qr1[1], Qubit()], name="qr2") qc = QuantumCircuit(qr1, qr2, [Qubit()]) qc.h(q) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr2[1]) qc.cx(2, 3) qr2 = QuantumRegister(2, "qr2") qr1 = QuantumRegister(bits=[qr2[1], q], name="qr1") expected = QuantumCircuit([Qubit()], qr2, qr1) expected.h(qr1[1]) expected.cx(qr1[1], qr1[0]) expected.cx(qr1[0], qr2[0]) expected.cx(1, 0) self.assertEqual(qc.reverse_bits(), expected) def test_cnot_alias(self): """Test that the cnot method alias adds a cx gate.""" qc = QuantumCircuit(2) qc.cnot(0, 1) expected = QuantumCircuit(2) expected.cx(0, 1) self.assertEqual(qc, expected) def test_inverse(self): """Test inverse circuit.""" qr = QuantumRegister(2) qc = QuantumCircuit(qr, global_phase=0.5) qc.h(0) qc.barrier(qr) qc.t(1) expected = QuantumCircuit(qr) expected.tdg(1) expected.barrier(qr) expected.h(0) expected.global_phase = -0.5 self.assertEqual(qc.inverse(), expected) def test_compare_two_equal_circuits(self): """Test to compare that 2 circuits are equal.""" qc1 = QuantumCircuit(2, 2) qc1.h(0) qc2 = QuantumCircuit(2, 2) qc2.h(0) self.assertTrue(qc1 == qc2) def test_compare_two_different_circuits(self): """Test to compare that 2 circuits are different.""" qc1 = QuantumCircuit(2, 2) qc1.h(0) qc2 = QuantumCircuit(2, 2) qc2.x(0) self.assertFalse(qc1 == qc2) def test_compare_circuits_with_single_bit_conditions(self): """Test that circuits with single-bit conditions can be compared correctly.""" qreg = QuantumRegister(1, name="q") creg = ClassicalRegister(1, name="c") qc1 = QuantumCircuit(qreg, creg, [Clbit()]) qc1.x(0).c_if(qc1.cregs[0], 1) qc1.x(0).c_if(qc1.clbits[-1], True) qc2 = QuantumCircuit(qreg, creg, [Clbit()]) qc2.x(0).c_if(qc2.cregs[0], 1) qc2.x(0).c_if(qc2.clbits[-1], True) self.assertEqual(qc1, qc2) # Order of operations transposed. qc1 = QuantumCircuit(qreg, creg, [Clbit()]) qc1.x(0).c_if(qc1.cregs[0], 1) qc1.x(0).c_if(qc1.clbits[-1], True) qc2 = QuantumCircuit(qreg, creg, [Clbit()]) qc2.x(0).c_if(qc2.clbits[-1], True) qc2.x(0).c_if(qc2.cregs[0], 1) self.assertNotEqual(qc1, qc2) # Single-bit condition values not the same. qc1 = QuantumCircuit(qreg, creg, [Clbit()]) qc1.x(0).c_if(qc1.cregs[0], 1) qc1.x(0).c_if(qc1.clbits[-1], True) qc2 = QuantumCircuit(qreg, creg, [Clbit()]) qc2.x(0).c_if(qc2.cregs[0], 1) qc2.x(0).c_if(qc2.clbits[-1], False) self.assertNotEqual(qc1, qc2) def test_compare_a_circuit_with_none(self): """Test to compare that a circuit is different to None.""" qc1 = QuantumCircuit(2, 2) qc1.h(0) qc2 = None self.assertFalse(qc1 == qc2) def test_overlapped_add_bits_and_add_register(self): """Test add registers whose bits have already been added by add_bits.""" qc = QuantumCircuit() for bit_type, reg_type in ( [Qubit, QuantumRegister], [Clbit, ClassicalRegister], [AncillaQubit, AncillaRegister], ): bits = [bit_type() for _ in range(10)] reg = reg_type(bits=bits) qc.add_bits(bits) qc.add_register(reg) self.assertEqual(qc.num_qubits, 20) self.assertEqual(qc.num_clbits, 10) self.assertEqual(qc.num_ancillas, 10) def test_overlapped_add_register_and_add_register(self): """Test add registers whose bits have already been added by add_register.""" qc = QuantumCircuit() for bit_type, reg_type in ( [Qubit, QuantumRegister], [Clbit, ClassicalRegister], [AncillaQubit, AncillaRegister], ): bits = [bit_type() for _ in range(10)] reg1 = reg_type(bits=bits) reg2 = reg_type(bits=bits) qc.add_register(reg1) qc.add_register(reg2) self.assertEqual(qc.num_qubits, 20) self.assertEqual(qc.num_clbits, 10) self.assertEqual(qc.num_ancillas, 10) def test_from_instructions(self): """Test from_instructions method.""" qreg = QuantumRegister(4) creg = ClassicalRegister(3) a, b, c, d = qreg x, y, z = creg circuit_1 = QuantumCircuit(2, 1) circuit_1.x(0) circuit_2 = QuantumCircuit(2, 1) circuit_2.y(0) def instructions(): yield CircuitInstruction(HGate(), [a], []) yield CircuitInstruction(CXGate(), [a, b], []) yield CircuitInstruction(Measure(), [a], [x]) yield CircuitInstruction(Measure(), [b], [y]) yield CircuitInstruction(IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z]) def instruction_tuples(): yield HGate(), [a], [] yield CXGate(), [a, b], [] yield CircuitInstruction(Measure(), [a], [x]) yield Measure(), [b], [y] yield IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z] def instruction_tuples_partial(): yield HGate(), [a] yield CXGate(), [a, b], [] yield CircuitInstruction(Measure(), [a], [x]) yield Measure(), [b], [y] yield IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z] circuit = QuantumCircuit.from_instructions(instructions()) circuit_tuples = QuantumCircuit.from_instructions(instruction_tuples()) circuit_tuples_partial = QuantumCircuit.from_instructions(instruction_tuples_partial()) expected = QuantumCircuit([a, b, c, d], [x, y, z]) for instruction in instructions(): expected.append(instruction.operation, instruction.qubits, instruction.clbits) self.assertEqual(circuit, expected) self.assertEqual(circuit_tuples, expected) self.assertEqual(circuit_tuples_partial, expected) def test_from_instructions_bit_order(self): """Test from_instructions method bit order.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) a, b = qreg c, d = creg def instructions(): yield CircuitInstruction(HGate(), [b], []) yield CircuitInstruction(CXGate(), [a, b], []) yield CircuitInstruction(Measure(), [b], [d]) yield CircuitInstruction(Measure(), [a], [c]) circuit = QuantumCircuit.from_instructions(instructions()) self.assertEqual(circuit.qubits, [b, a]) self.assertEqual(circuit.clbits, [d, c]) circuit = QuantumCircuit.from_instructions(instructions(), qubits=qreg) self.assertEqual(circuit.qubits, [a, b]) self.assertEqual(circuit.clbits, [d, c]) circuit = QuantumCircuit.from_instructions(instructions(), clbits=creg) self.assertEqual(circuit.qubits, [b, a]) self.assertEqual(circuit.clbits, [c, d]) circuit = QuantumCircuit.from_instructions( instructions(), qubits=iter([a, b]), clbits=[c, d] ) self.assertEqual(circuit.qubits, [a, b]) self.assertEqual(circuit.clbits, [c, d]) def test_from_instructions_metadata(self): """Test from_instructions method passes metadata.""" qreg = QuantumRegister(2) a, b = qreg def instructions(): yield CircuitInstruction(HGate(), [a], []) yield CircuitInstruction(CXGate(), [a, b], []) circuit = QuantumCircuit.from_instructions(instructions(), name="test", global_phase=0.1) expected = QuantumCircuit([a, b], global_phase=0.1) for instruction in instructions(): expected.append(instruction.operation, instruction.qubits, instruction.clbits) self.assertEqual(circuit, expected) self.assertEqual(circuit.name, "test") class TestCircuitPrivateOperations(QiskitTestCase): """Direct tests of some of the private methods of QuantumCircuit. These do not represent functionality that we want to expose to users, but there are some cases where private methods are used internally (similar to "protected" access in .NET or "friend" access in C++), and we want to make sure they work in those cases.""" def test_previous_instruction_in_scope_failures(self): """Test the failure paths of the peek and pop methods for retrieving the most recent instruction in a scope.""" test = QuantumCircuit(1, 1) with self.assertRaisesRegex(CircuitError, r"This circuit contains no instructions\."): test._peek_previous_instruction_in_scope() with self.assertRaisesRegex(CircuitError, r"This circuit contains no instructions\."): test._pop_previous_instruction_in_scope() with test.for_loop(range(2)): with self.assertRaisesRegex(CircuitError, r"This scope contains no instructions\."): test._peek_previous_instruction_in_scope() with self.assertRaisesRegex(CircuitError, r"This scope contains no instructions\."): test._pop_previous_instruction_in_scope() def test_pop_previous_instruction_removes_parameters(self): """Test that the private "pop instruction" method removes parameters from the parameter table if that instruction is the only instance.""" x, y = Parameter("x"), Parameter("y") test = QuantumCircuit(1, 1) test.rx(y, 0) last_instructions = test.u(x, y, 0, 0) self.assertEqual({x, y}, set(test.parameters)) instruction = test._pop_previous_instruction_in_scope() self.assertEqual(list(last_instructions), [instruction]) self.assertEqual({y}, set(test.parameters)) def test_decompose_gate_type(self): """Test decompose specifying gate type.""" circuit = QuantumCircuit(1) circuit.append(SGate(label="s_gate"), [0]) decomposed = circuit.decompose(gates_to_decompose=SGate) self.assertNotIn("s", decomposed.count_ops())
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's inverse gate operation.""" import unittest import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, pulse from qiskit.circuit import Clbit from qiskit.circuit.library import RXGate, RYGate from qiskit.test import QiskitTestCase from qiskit.circuit.exceptions import CircuitError from qiskit.extensions.simulator import Snapshot class TestCircuitProperties(QiskitTestCase): """QuantumCircuit properties tests.""" def test_qarg_numpy_int(self): """Test castable to integer args for QuantumCircuit.""" n = np.int64(12) qc1 = QuantumCircuit(n) self.assertEqual(qc1.num_qubits, 12) self.assertEqual(type(qc1), QuantumCircuit) def test_carg_numpy_int(self): """Test castable to integer cargs for QuantumCircuit.""" n = np.int64(12) c1 = ClassicalRegister(n) qc1 = QuantumCircuit(c1) c_regs = qc1.cregs self.assertEqual(c_regs[0], c1) self.assertEqual(type(qc1), QuantumCircuit) def test_carg_numpy_int_2(self): """Test castable to integer cargs for QuantumCircuit.""" qc1 = QuantumCircuit(12, np.int64(12)) self.assertEqual(len(qc1.clbits), 12) self.assertTrue(all(isinstance(bit, Clbit) for bit in qc1.clbits)) self.assertEqual(type(qc1), QuantumCircuit) def test_qarg_numpy_int_exception(self): """Test attempt to pass non-castable arg to QuantumCircuit.""" self.assertRaises(CircuitError, QuantumCircuit, "string") def test_warning_on_noninteger_float(self): """Test warning when passing non-integer float to QuantumCircuit""" self.assertRaises(CircuitError, QuantumCircuit, 2.2) # but an integer float should pass qc = QuantumCircuit(2.0) self.assertEqual(qc.num_qubits, 2) def test_circuit_depth_empty(self): """Test depth of empty circuity""" q = QuantumRegister(5, "q") qc = QuantumCircuit(q) self.assertEqual(qc.depth(), 0) def test_circuit_depth_no_reg(self): """Test depth of no register circuits""" qc = QuantumCircuit() self.assertEqual(qc.depth(), 0) def test_circuit_depth_meas_only(self): """Test depth of measurement only""" q = QuantumRegister(1, "q") c = ClassicalRegister(1, "c") qc = QuantumCircuit(q, c) qc.measure(q, c) self.assertEqual(qc.depth(), 1) def test_circuit_depth_barrier(self): """Make sure barriers do not add to depth""" # ┌───┐ ░ ┌─┐ # q_0: ┤ H ├──■──────────────────░─┤M├──────────── # ├───┤┌─┴─┐ ░ └╥┘┌─┐ # q_1: ┤ H ├┤ X ├──■─────────────░──╫─┤M├───────── # ├───┤└───┘ │ ┌───┐ ░ ║ └╥┘┌─┐ # q_2: ┤ H ├───────┼──┤ X ├──■───░──╫──╫─┤M├────── # ├───┤ │ └─┬─┘┌─┴─┐ ░ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├───────┼────┼──┤ X ├─░──╫──╫──╫─┤M├─── # ├───┤ ┌─┴─┐ │ └───┘ ░ ║ ║ ║ └╥┘┌─┐ # q_4: ┤ H ├─────┤ X ├──■────────░──╫──╫──╫──╫─┤M├ # └───┘ └───┘ ░ ║ ║ ║ ║ └╥┘ # c: 5/═════════════════════════════╩══╩══╩══╩══╩═ # 0 1 2 3 4 q = QuantumRegister(5, "q") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[4]) qc.cx(q[0], q[1]) qc.cx(q[1], q[4]) qc.cx(q[4], q[2]) qc.cx(q[2], q[3]) qc.barrier(q) qc.measure(q, c) self.assertEqual(qc.depth(), 6) def test_circuit_depth_simple(self): """Test depth for simple circuit""" # ┌───┐ # q_0: ┤ H ├──■──────────────────── # └───┘ │ ┌───┐┌─┐ # q_1: ───────┼────────────┤ X ├┤M├ # ┌───┐ │ ┌───┐┌───┐└─┬─┘└╥┘ # q_2: ┤ X ├──┼──┤ X ├┤ X ├──┼───╫─ # └───┘ │ └───┘└───┘ │ ║ # q_3: ───────┼──────────────┼───╫─ # ┌─┴─┐┌───┐ │ ║ # q_4: ─────┤ X ├┤ X ├───────■───╫─ # └───┘└───┘ ║ # c: 1/══════════════════════════╩═ # 0 q = QuantumRegister(5, "q") c = ClassicalRegister(1, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[4]) qc.x(q[2]) qc.x(q[2]) qc.x(q[2]) qc.x(q[4]) qc.cx(q[4], q[1]) qc.measure(q[1], c[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_multi_reg(self): """Test depth for multiple registers""" # ┌───┐ # q1_0: ┤ H ├──■───────────────── # ├───┤┌─┴─┐ # q1_1: ┤ H ├┤ X ├──■──────────── # ├───┤└───┘ │ ┌───┐ # q1_2: ┤ H ├───────┼──┤ X ├──■── # ├───┤ │ └─┬─┘┌─┴─┐ # q2_0: ┤ H ├───────┼────┼──┤ X ├ # ├───┤ ┌─┴─┐ │ └───┘ # q2_1: ┤ H ├─────┤ X ├──■─────── # └───┘ └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q1, q2, c) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_3q_gate(self): """Test depth for 3q gate""" # ┌───┐ # q1_0: ┤ H ├──■────■───────────────── # ├───┤ │ ┌─┴─┐ # q1_1: ┤ H ├──┼──┤ X ├──■──────────── # ├───┤ │ └───┘ │ ┌───┐ # q1_2: ┤ H ├──┼─────────┼──┤ X ├──■── # ├───┤┌─┴─┐ │ └─┬─┘┌─┴─┐ # q2_0: ┤ H ├┤ X ├───────┼────┼──┤ X ├ # ├───┤└─┬─┘ ┌─┴─┐ │ └───┘ # q2_1: ┤ H ├──■───────┤ X ├──■─────── # └───┘ └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q1, q2, c) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.ccx(q2[1], q1[0], q2[0]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.depth(), 6) def test_circuit_depth_conditionals1(self): """Test circuit depth for conditional gates #1.""" # ┌───┐ ┌─┐ # q_0: ┤ H ├──■──┤M├───────────────── # ├───┤┌─┴─┐└╥┘┌─┐ # q_1: ┤ H ├┤ X ├─╫─┤M├────────────── # ├───┤└───┘ ║ └╥┘ ┌───┐ # q_2: ┤ H ├──■───╫──╫──┤ H ├──────── # ├───┤┌─┴─┐ ║ ║ └─╥─┘ ┌───┐ # q_3: ┤ H ├┤ X ├─╫──╫────╫────┤ H ├─ # └───┘└───┘ ║ ║ ║ └─╥─┘ # ║ ║ ┌──╨──┐┌──╨──┐ # c: 4/═══════════╩══╩═╡ 0x2 ╞╡ 0x4 ╞ # 0 1 └─────┘└─────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[0], q[1]) qc.cx(q[2], q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.h(q[2]).c_if(c, 2) qc.h(q[3]).c_if(c, 4) self.assertEqual(qc.depth(), 5) def test_circuit_depth_conditionals2(self): """Test circuit depth for conditional gates #2.""" # ┌───┐ ┌─┐┌─┐ # q_0: ┤ H ├──■──┤M├┤M├────────────── # ├───┤┌─┴─┐└╥┘└╥┘ # q_1: ┤ H ├┤ X ├─╫──╫─────────────── # ├───┤└───┘ ║ ║ ┌───┐ # q_2: ┤ H ├──■───╫──╫──┤ H ├──────── # ├───┤┌─┴─┐ ║ ║ └─╥─┘ ┌───┐ # q_3: ┤ H ├┤ X ├─╫──╫────╫────┤ H ├─ # └───┘└───┘ ║ ║ ║ └─╥─┘ # ║ ║ ┌──╨──┐┌──╨──┐ # c: 4/═══════════╩══╩═╡ 0x2 ╞╡ 0x4 ╞ # 0 0 └─────┘└─────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[0], q[1]) qc.cx(q[2], q[3]) qc.measure(q[0], c[0]) qc.measure(q[0], c[0]) qc.h(q[2]).c_if(c, 2) qc.h(q[3]).c_if(c, 4) self.assertEqual(qc.depth(), 6) def test_circuit_depth_conditionals3(self): """Test circuit depth for conditional gates #3.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───■──────────── # ├───┤└╥┘ │ ┌─┐ # q_1: ┤ H ├─╫────┼───┤M├────── # ├───┤ ║ │ └╥┘┌─┐ # q_2: ┤ H ├─╫────┼────╫─┤M├─── # ├───┤ ║ ┌─┴─┐ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──┤ X ├──╫──╫─┤M├ # └───┘ ║ └─╥─┘ ║ ║ └╥┘ # ║ ┌──╨──┐ ║ ║ ║ # c: 4/══════╩═╡ 0x2 ╞═╩══╩══╩═ # 0 └─────┘ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c, 2) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 4) def test_circuit_depth_bit_conditionals1(self): """Test circuit depth for single bit conditional gates #1.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────────────────────── # ├───┤└╥┘ ┌───┐ # q_1: ┤ H ├─╫───────┤ H ├────────────── # ├───┤ ║ ┌─┐ └─╥─┘ # q_2: ┤ H ├─╫─┤M├─────╫──────────────── # ├───┤ ║ └╥┘ ║ ┌───┐ # q_3: ┤ H ├─╫──╫──────╫────────┤ H ├─── # └───┘ ║ ║ ║ └─╥─┘ # ║ ║ ┌────╨────┐┌────╨────┐ # c: 4/══════╩══╩═╡ c_0=0x1 ╞╡ c_2=0x0 ╞ # 0 2 └─────────┘└─────────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[2], c[2]) qc.h(q[1]).c_if(c[0], True) qc.h(q[3]).c_if(c[2], False) self.assertEqual(qc.depth(), 3) def test_circuit_depth_bit_conditionals2(self): """Test circuit depth for single bit conditional gates #2.""" # ┌───┐┌─┐ » # q_0: ┤ H ├┤M├──────────────────────────────■─────────────────────■─────» # ├───┤└╥┘ ┌───┐ ┌─┴─┐ │ » # q_1: ┤ H ├─╫───────┤ H ├─────────────────┤ X ├───────────────────┼─────» # ├───┤ ║ ┌─┐ └─╥─┘ └─╥─┘ ┌─┴─┐ » # q_2: ┤ H ├─╫─┤M├─────╫─────────────────────╫──────────■────────┤ H ├───» # ├───┤ ║ └╥┘ ║ ┌───┐ ║ ┌─┴─┐ └─╥─┘ » # q_3: ┤ H ├─╫──╫──────╫────────┤ H ├────────╫────────┤ X ├────────╫─────» # └───┘ ║ ║ ║ └─╥─┘ ║ └─╥─┘ ║ » # ║ ║ ┌────╨────┐┌────╨────┐┌────╨────┐┌────╨────┐┌────╨────┐» # c: 4/══════╩══╩═╡ c_1=0x1 ╞╡ c_3=0x1 ╞╡ c_0=0x0 ╞╡ c_2=0x0 ╞╡ c_1=0x1 ╞» # 0 2 └─────────┘└─────────┘└─────────┘└─────────┘└─────────┘» # « # «q_0: ─────────── # « # «q_1: ─────■───── # « │ # «q_2: ─────┼───── # « ┌─┴─┐ # «q_3: ───┤ H ├─── # « └─╥─┘ # « ┌────╨────┐ # «c: 4/╡ c_3=0x1 ╞ # « └─────────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[2], c[2]) qc.h(q[1]).c_if(c[1], True) qc.h(q[3]).c_if(c[3], True) qc.cx(0, 1).c_if(c[0], False) qc.cx(2, 3).c_if(c[2], False) qc.ch(0, 2).c_if(c[1], True) qc.ch(1, 3).c_if(c[3], True) self.assertEqual(qc.depth(), 4) def test_circuit_depth_bit_conditionals3(self): """Test circuit depth for single bit conditional gates #3.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├────────────────────────────────────── # ├───┤└╥┘ ┌───┐ ┌─┐ # q_1: ┤ H ├─╫────┤ H ├─────────────────────┤M├────── # ├───┤ ║ └─╥─┘ ┌───┐ └╥┘┌─┐ # q_2: ┤ H ├─╫──────╫──────┤ H ├─────────────╫─┤M├─── # ├───┤ ║ ║ └─╥─┘ ┌───┐ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──────╫────────╫──────┤ H ├────╫──╫─┤M├ # └───┘ ║ ║ ║ └─╥─┘ ║ ║ └╥┘ # ║ ┌────╨────┐┌──╨──┐┌────╨────┐ ║ ║ ║ # c: 4/══════╩═╡ c_0=0x1 ╞╡ 0x2 ╞╡ c_3=0x1 ╞═╩══╩══╩═ # 0 └─────────┘└─────┘└─────────┘ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.h(1).c_if(c[0], True) qc.h(q[2]).c_if(c, 2) qc.h(3).c_if(c[3], True) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 6) def test_circuit_depth_measurements1(self): """Test circuit depth for measurements #1.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 2) def test_circuit_depth_measurements2(self): """Test circuit depth for measurements #2.""" # ┌───┐┌─┐┌─┐┌─┐┌─┐ # q_0: ┤ H ├┤M├┤M├┤M├┤M├ # ├───┤└╥┘└╥┘└╥┘└╥┘ # q_1: ┤ H ├─╫──╫──╫──╫─ # ├───┤ ║ ║ ║ ║ # q_2: ┤ H ├─╫──╫──╫──╫─ # ├───┤ ║ ║ ║ ║ # q_3: ┤ H ├─╫──╫──╫──╫─ # └───┘ ║ ║ ║ ║ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[0], c[1]) qc.measure(q[0], c[2]) qc.measure(q[0], c[3]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_measurements3(self): """Test circuit depth for measurements #3.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # c: 4/══════╩══╩══╩══╩═ # 0 0 0 0 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[0]) qc.measure(q[2], c[0]) qc.measure(q[3], c[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_barriers1(self): """Test circuit depth for barriers #1.""" # ┌───┐ ░ # q_0: ┤ H ├──■───░─────────── # └───┘┌─┴─┐ ░ # q_1: ─────┤ X ├─░─────────── # └───┘ ░ ┌───┐ # q_2: ───────────░─┤ H ├──■── # ░ └───┘┌─┴─┐ # q_3: ───────────░──────┤ X ├ # ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.barrier(q) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_barriers2(self): """Test circuit depth for barriers #2.""" # ┌───┐ ░ ░ ░ # q_0: ┤ H ├─░───■───░───────░────── # └───┘ ░ ┌─┴─┐ ░ ░ # q_1: ──────░─┤ X ├─░───────░────── # ░ └───┘ ░ ┌───┐ ░ # q_2: ──────░───────░─┤ H ├─░───■── # ░ ░ └───┘ ░ ┌─┴─┐ # q_3: ──────░───────░───────░─┤ X ├ # ░ ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.barrier(q) circ.cx(0, 1) circ.barrier(q) circ.h(2) circ.barrier(q) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_barriers3(self): """Test circuit depth for barriers #3.""" # ┌───┐ ░ ░ ░ ░ ░ # q_0: ┤ H ├─░───■───░──░──░───────░────── # └───┘ ░ ┌─┴─┐ ░ ░ ░ ░ # q_1: ──────░─┤ X ├─░──░──░───────░────── # ░ └───┘ ░ ░ ░ ┌───┐ ░ # q_2: ──────░───────░──░──░─┤ H ├─░───■── # ░ ░ ░ ░ └───┘ ░ ┌─┴─┐ # q_3: ──────░───────░──░──░───────░─┤ X ├ # ░ ░ ░ ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.barrier(q) circ.cx(0, 1) circ.barrier(q) circ.barrier(q) circ.barrier(q) circ.h(2) circ.barrier(q) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap1(self): """Test circuit depth for snapshots #1.""" # ┌───┐ ░ # q_0: ┤ H ├──■───░─────────── # └───┘┌─┴─┐ ░ # q_1: ─────┤ X ├─░─────────── # └───┘ ░ ┌───┐ # q_2: ───────────░─┤ H ├──■── # ░ └───┘┌─┴─┐ # q_3: ───────────░──────┤ X ├ # ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.append(Snapshot("snap", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap2(self): """Test circuit depth for snapshots #2.""" # ┌───┐ ░ ░ ░ # q_0: ┤ H ├─░───■───░───────░────── # └───┘ ░ ┌─┴─┐ ░ ░ # q_1: ──────░─┤ X ├─░───────░────── # ░ └───┘ ░ ┌───┐ ░ # q_2: ──────░───────░─┤ H ├─░───■── # ░ ░ └───┘ ░ ┌─┴─┐ # q_3: ──────░───────░───────░─┤ X ├ # ░ ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.append(Snapshot("snap0", num_qubits=4), [0, 1, 2, 3]) circ.cx(0, 1) circ.append(Snapshot("snap1", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.append(Snapshot("snap2", num_qubits=4), [0, 1, 2, 3]) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap3(self): """Test circuit depth for snapshots #3.""" # ┌───┐ ░ ░ # q_0: ┤ H ├──■───░──░─────────── # └───┘┌─┴─┐ ░ ░ # q_1: ─────┤ X ├─░──░─────────── # └───┘ ░ ░ ┌───┐ # q_2: ───────────░──░─┤ H ├──■── # ░ ░ └───┘┌─┴─┐ # q_3: ───────────░──░──────┤ X ├ # ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.append(Snapshot("snap0", num_qubits=4), [0, 1, 2, 3]) circ.append(Snapshot("snap1", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_2qubit(self): """Test finding depth of two-qubit gates only.""" # ┌───┐ # q_0: ┤ H ├──■─────────────────── # └───┘┌─┴─┐┌─────────┐ ┌─┐ # q_1: ─────┤ X ├┤ Rz(0.1) ├─■─┤M├ # ┌───┐└───┘└─────────┘ │ └╥┘ # q_2: ┤ H ├──■──────────────┼──╫─ # └───┘┌─┴─┐ │ ║ # q_3: ─────┤ X ├────────────■──╫─ # └───┘ ║ # c: 1/═════════════════════════╩═ # 0 circ = QuantumCircuit(4, 1) circ.h(0) circ.cx(0, 1) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) self.assertEqual(circ.depth(lambda x: x.operation.num_qubits == 2), 2) def test_circuit_depth_multiqubit_or_conditional(self): """Test finding depth of multi-qubit or conditional gates.""" # ┌───┐ ┌───┐ # q_0: ┤ H ├──■───────────────────────────┤ X ├─── # └───┘ │ ┌─────────┐ ┌─┐ └─╥─┘ # q_1: ───────■──┤ Rz(0.1) ├──────■─┤M├─────╫───── # ┌─┴─┐└──┬───┬──┘ │ └╥┘ ║ # q_2: ─────┤ X ├───┤ H ├─────■───┼──╫──────╫───── # └───┘ └───┘ ┌─┴─┐ │ ║ ║ # q_3: ─────────────────────┤ X ├─■──╫──────╫───── # └───┘ ║ ┌────╨────┐ # c: 1/══════════════════════════════╩═╡ c_0 = T ╞ # 0 └─────────┘ circ = QuantumCircuit(4, 1) circ.h(0) circ.ccx(0, 1, 2) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) circ.x(0).c_if(0, 1) self.assertEqual( circ.depth(lambda x: x.operation.num_qubits >= 2 or x.operation.condition is not None), 4, ) def test_circuit_depth_first_qubit(self): """Test finding depth of gates touching q0 only.""" # ┌───┐ ┌───┐ # q_0: ┤ H ├──■─────┤ T ├───────── # └───┘┌─┴─┐┌──┴───┴──┐ ┌─┐ # q_1: ─────┤ X ├┤ Rz(0.1) ├─■─┤M├ # ┌───┐└───┘└─────────┘ │ └╥┘ # q_2: ┤ H ├──■──────────────┼──╫─ # └───┘┌─┴─┐ │ ║ # q_3: ─────┤ X ├────────────■──╫─ # └───┘ ║ # c: 1/═════════════════════════╩═ # 0 circ = QuantumCircuit(4, 1) circ.h(0) circ.cx(0, 1) circ.t(0) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) self.assertEqual(circ.depth(lambda x: circ.qubits[0] in x.qubits), 3) def test_circuit_size_empty(self): """Circuit.size should return 0 for an empty circuit.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) self.assertEqual(qc.size(), 0) def test_circuit_size_single_qubit_gates(self): """Circuit.size should increment for each added single qubit gate.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) self.assertEqual(qc.size(), 1) qc.h(q[1]) self.assertEqual(qc.size(), 2) def test_circuit_size_2qubit(self): """Circuit.size of only 2-qubit gates.""" size = 3 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.rz(0.1, q[1]) qc.rzz(0.1, q[1], q[2]) self.assertEqual(qc.size(lambda x: x.operation.num_qubits == 2), 2) def test_circuit_size_ignores_barriers_snapshots(self): """Circuit.size should not count barriers or snapshots.""" q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) self.assertEqual(qc.size(), 2) qc.barrier(q) self.assertEqual(qc.size(), 2) qc.append(Snapshot("snapshot_label", num_qubits=4), [0, 1, 2, 3]) self.assertEqual(qc.size(), 2) def test_circuit_count_ops(self): """Test circuit count ops.""" q = QuantumRegister(6, "q") qc = QuantumCircuit(q) qc.h(q) qc.x(q[1]) qc.y(q[2:4]) qc.z(q[3:]) result = qc.count_ops() expected = {"h": 6, "z": 3, "y": 2, "x": 1} self.assertIsInstance(result, dict) self.assertEqual(expected, result) def test_circuit_nonlocal_gates(self): """Test num_nonlocal_gates.""" # ┌───┐ ┌────────┐ # q_0: ┤ H ├───────────────────┤0 ├ # ├───┤ ┌───┐ │ │ # q_1: ┤ H ├───┤ X ├─────────■─┤ ├ # ├───┤ └───┘ │ │ │ # q_2: ┤ H ├─────■───────────X─┤ Iswap ├ # ├───┤ │ ┌───┐ │ │ │ # q_3: ┤ H ├─────┼─────┤ Z ├─X─┤ ├ # ├───┤┌────┴────┐├───┤ │ │ # q_4: ┤ H ├┤ Ry(0.1) ├┤ Z ├───┤1 ├ # ├───┤└──┬───┬──┘└───┘ └───╥────┘ # q_5: ┤ H ├───┤ Z ├───────────────╫───── # └───┘ └───┘ ┌──╨──┐ # c: 2/═════════════════════════╡ 0x2 ╞══ # └─────┘ q = QuantumRegister(6, "q") c = ClassicalRegister(2, "c") qc = QuantumCircuit(q, c) qc.h(q) qc.x(q[1]) qc.cry(0.1, q[2], q[4]) qc.z(q[3:]) qc.cswap(q[1], q[2], q[3]) qc.iswap(q[0], q[4]).c_if(c, 2) result = qc.num_nonlocal_gates() expected = 3 self.assertEqual(expected, result) def test_circuit_nonlocal_gates_no_instruction(self): """Verify num_nunlocal_gates does not include barriers.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/4500 n = 3 qc = QuantumCircuit(n) qc.h(range(n)) qc.barrier() self.assertEqual(qc.num_nonlocal_gates(), 0) def test_circuit_connected_components_empty(self): """Verify num_connected_components is width for empty""" q = QuantumRegister(7, "q") qc = QuantumCircuit(q) self.assertEqual(7, qc.num_connected_components()) def test_circuit_connected_components_multi_reg(self): """Test tensor factors works over multi registers""" # ┌───┐ # q1_0: ┤ H ├──■───────────────── # ├───┤┌─┴─┐ # q1_1: ┤ H ├┤ X ├──■──────────── # ├───┤└───┘ │ ┌───┐ # q1_2: ┤ H ├───────┼──┤ X ├──■── # ├───┤ │ └─┬─┘┌─┴─┐ # q2_0: ┤ H ├───────┼────┼──┤ X ├ # ├───┤ ┌─┴─┐ │ └───┘ # q2_1: ┤ H ├─────┤ X ├──■─────── # └───┘ └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_multi_reg2(self): """Test tensor factors works over multi registers #2.""" # q1_0: ──■──────────── # │ # q1_1: ──┼─────────■── # │ ┌───┐ │ # q1_2: ──┼──┤ X ├──┼── # │ └─┬─┘┌─┴─┐ # q2_0: ──┼────■──┤ X ├ # ┌─┴─┐ └───┘ # q2_1: ┤ X ├────────── # └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[1]) qc.cx(q2[0], q1[2]) qc.cx(q1[1], q2[0]) self.assertEqual(qc.num_connected_components(), 2) def test_circuit_connected_components_disconnected(self): """Test tensor factors works with 2q subspaces.""" # q1_0: ──■────────────────────── # │ # q1_1: ──┼────■───────────────── # │ │ # q1_2: ──┼────┼────■──────────── # │ │ │ # q1_3: ──┼────┼────┼────■─────── # │ │ │ │ # q1_4: ──┼────┼────┼────┼────■── # │ │ │ │ ┌─┴─┐ # q2_0: ──┼────┼────┼────┼──┤ X ├ # │ │ │ ┌─┴─┐└───┘ # q2_1: ──┼────┼────┼──┤ X ├───── # │ │ ┌─┴─┐└───┘ # q2_2: ──┼────┼──┤ X ├────────── # │ ┌─┴─┐└───┘ # q2_3: ──┼──┤ X ├─────────────── # ┌─┴─┐└───┘ # q2_4: ┤ X ├──────────────────── # └───┘ q1 = QuantumRegister(5, "q1") q2 = QuantumRegister(5, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[4]) qc.cx(q1[1], q2[3]) qc.cx(q1[2], q2[2]) qc.cx(q1[3], q2[1]) qc.cx(q1[4], q2[0]) self.assertEqual(qc.num_connected_components(), 5) def test_circuit_connected_components_with_clbits(self): """Test tensor components with classical register.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 4) def test_circuit_connected_components_with_cond(self): """Test tensor components with one conditional gate.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───■──────────── # ├───┤└╥┘ │ ┌─┐ # q_1: ┤ H ├─╫────┼───┤M├────── # ├───┤ ║ │ └╥┘┌─┐ # q_2: ┤ H ├─╫────┼────╫─┤M├─── # ├───┤ ║ ┌─┴─┐ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──┤ X ├──╫──╫─┤M├ # └───┘ ║ └─╥─┘ ║ ║ └╥┘ # ║ ┌──╨──┐ ║ ║ ║ # c: 4/══════╩═╡ 0x2 ╞═╩══╩══╩═ # 0 └─────┘ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c, 2) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_with_cond2(self): """Test tensor components with two conditional gates.""" # ┌───┐ ┌───┐ # q_0: ┤ H ├─┤ H ├──────── # ├───┤ └─╥─┘ # q_1: ┤ H ├───╫──────■─── # ├───┤ ║ ┌─┴─┐ # q_2: ┤ H ├───╫────┤ X ├─ # ├───┤ ║ └─╥─┘ # q_3: ┤ H ├───╫──────╫─── # └───┘┌──╨──┐┌──╨──┐ # c: 8/═════╡ 0x0 ╞╡ 0x4 ╞ # └─────┘└─────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(2 * size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(0).c_if(c, 0) qc.cx(1, 2).c_if(c, 4) self.assertEqual(qc.num_connected_components(), 2) def test_circuit_connected_components_with_cond3(self): """Test tensor components with three conditional gates and measurements.""" # ┌───┐┌─┐ ┌───┐ # q0_0: ┤ H ├┤M├─┤ H ├────────────────── # ├───┤└╥┘ └─╥─┘ # q0_1: ┤ H ├─╫────╫──────■───────────── # ├───┤ ║ ║ ┌─┴─┐ ┌─┐ # q0_2: ┤ H ├─╫────╫────┤ X ├─┤M├─────── # ├───┤ ║ ║ └─╥─┘ └╥┘ ┌───┐ # q0_3: ┤ H ├─╫────╫──────╫────╫──┤ X ├─ # └───┘ ║ ║ ║ ║ └─╥─┘ # ║ ┌──╨──┐┌──╨──┐ ║ ┌──╨──┐ # c0: 4/══════╩═╡ 0x0 ╞╡ 0x1 ╞═╩═╡ 0x2 ╞ # 0 └─────┘└─────┘ 2 └─────┘ size = 4 q = QuantumRegister(size) c = ClassicalRegister(size) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.h(q[0]).c_if(c, 0) qc.cx(q[1], q[2]).c_if(c, 1) qc.measure(q[2], c[2]) qc.x(q[3]).c_if(c, 2) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_with_bit_cond(self): """Test tensor components with one single bit conditional gate.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────────■──────── # ├───┤└╥┘┌─┐ │ # q_1: ┤ H ├─╫─┤M├────────┼──────── # ├───┤ ║ └╥┘┌─┐ │ # q_2: ┤ H ├─╫──╫─┤M├─────┼──────── # ├───┤ ║ ║ └╥┘ ┌─┴─┐ ┌─┐ # q_3: ┤ H ├─╫──╫──╫────┤ X ├───┤M├ # └───┘ ║ ║ ║ └─╥─┘ └╥┘ # ║ ║ ║ ┌────╨────┐ ║ # c: 4/══════╩══╩══╩═╡ c_0=0x1 ╞═╩═ # 0 1 2 └─────────┘ 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c[0], True) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 3) def test_circuit_connected_components_with_bit_cond2(self): """Test tensor components with two bit conditional gates.""" # ┌───┐ ┌───┐ ┌───┐ # q_0: ┤ H ├───┤ H ├─────────────────┤ X ├─── # ├───┤ └─╥─┘ └─┬─┘ # q_1: ┤ H ├─────╫─────────────────────■───── # ├───┤ ║ ║ # q_2: ┤ H ├─────╫──────────■──────────╫───── # ├───┤ ║ │ ║ # q_3: ┤ H ├─────╫──────────■──────────╫───── # └───┘┌────╨────┐┌────╨────┐┌────╨────┐ # c: 6/═════╡ c_1=0x1 ╞╡ c_0=0x1 ╞╡ c_4=0x0 ╞ # └─────────┘└─────────┘└─────────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size + 2, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(0).c_if(c[1], True) qc.cx(1, 0).c_if(c[4], False) qc.cz(2, 3).c_if(c[0], True) self.assertEqual(qc.num_connected_components(), 5) def test_circuit_connected_components_with_bit_cond3(self): """Test tensor components with register and bit conditional gates.""" # ┌───┐ ┌───┐ # q0_0: ┤ H ├───┤ H ├─────────────────────── # ├───┤ └─╥─┘ # q0_1: ┤ H ├─────╫─────────■─────────────── # ├───┤ ║ ┌─┴─┐ # q0_2: ┤ H ├─────╫───────┤ X ├───────────── # ├───┤ ║ └─╥─┘ ┌───┐ # q0_3: ┤ H ├─────╫─────────╫──────┤ X ├──── # └───┘ ║ ║ └─╥─┘ # ┌────╨─────┐┌──╨──┐┌────╨─────┐ # c0: 4/═════╡ c0_0=0x1 ╞╡ 0x1 ╞╡ c0_2=0x1 ╞ # └──────────┘└─────┘└──────────┘ size = 4 q = QuantumRegister(size) c = ClassicalRegister(size) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[0]).c_if(c[0], True) qc.cx(q[1], q[2]).c_if(c, 1) qc.x(q[3]).c_if(c[2], True) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_unitary_factors1(self): """Test unitary factors empty circuit.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) self.assertEqual(qc.num_unitary_factors(), 4) def test_circuit_unitary_factors2(self): """Test unitary factors multi qregs""" q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q1, q2, c) self.assertEqual(qc.num_unitary_factors(), 4) def test_circuit_unitary_factors3(self): """Test unitary factors measurements and conditionals.""" # ┌───┐ ┌─┐ # q_0: ┤ H ├────────■──────────■────■──────────■──┤M├─── # ├───┤ │ │ │ ┌─┐ │ └╥┘ # q_1: ┤ H ├──■─────┼─────■────┼────┼──┤M├─────┼───╫──── # ├───┤┌─┴─┐ │ ┌─┴─┐ │ │ └╥┘┌─┐ │ ║ # q_2: ┤ H ├┤ X ├───┼───┤ X ├──┼────┼───╫─┤M├──┼───╫──── # ├───┤└───┘ ┌─┴─┐ └───┘┌─┴─┐┌─┴─┐ ║ └╥┘┌─┴─┐ ║ ┌─┐ # q_3: ┤ H ├──────┤ X ├──────┤ X ├┤ X ├─╫──╫─┤ X ├─╫─┤M├ # └───┘ └─╥─┘ └───┘└───┘ ║ ║ └───┘ ║ └╥┘ # ┌──╨──┐ ║ ║ ║ ║ # c: 4/══════════╡ 0x2 ╞════════════════╩══╩═══════╩══╩═ # └─────┘ 1 2 0 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[1], q[2]) qc.cx(q[1], q[2]) qc.cx(q[0], q[3]).c_if(c, 2) qc.cx(q[0], q[3]) qc.cx(q[0], q[3]) qc.cx(q[0], q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_unitary_factors(), 2) def test_circuit_unitary_factors4(self): """Test unitary factors measurements go to same cbit.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # q_4: ──────╫──╫──╫──╫─ # ║ ║ ║ ║ # c: 5/══════╩══╩══╩══╩═ # 0 0 0 0 size = 5 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[0]) qc.measure(q[2], c[0]) qc.measure(q[3], c[0]) self.assertEqual(qc.num_unitary_factors(), 5) def test_num_qubits_qubitless_circuit(self): """Check output in absence of qubits.""" c_reg = ClassicalRegister(3) circ = QuantumCircuit(c_reg) self.assertEqual(circ.num_qubits, 0) def test_num_qubits_qubitfull_circuit(self): """Check output in presence of qubits""" q_reg = QuantumRegister(4) c_reg = ClassicalRegister(3) circ = QuantumCircuit(q_reg, c_reg) self.assertEqual(circ.num_qubits, 4) def test_num_qubits_registerless_circuit(self): """Check output for circuits with direct argument for qubits.""" circ = QuantumCircuit(5) self.assertEqual(circ.num_qubits, 5) def test_num_qubits_multiple_register_circuit(self): """Check output for circuits with multiple quantum registers.""" q_reg1 = QuantumRegister(5) q_reg2 = QuantumRegister(6) q_reg3 = QuantumRegister(7) circ = QuantumCircuit(q_reg1, q_reg2, q_reg3) self.assertEqual(circ.num_qubits, 18) def test_calibrations_basis_gates(self): """Check if the calibrations for basis gates provided are added correctly.""" circ = QuantumCircuit(2) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) with pulse.build() as q1_y90: pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), pulse.DriveChannel(1)) # Add calibration circ.add_calibration(RXGate(3.14), [0], q0_x180) circ.add_calibration(RYGate(1.57), [1], q1_y90) self.assertEqual(set(circ.calibrations.keys()), {"rx", "ry"}) self.assertEqual(set(circ.calibrations["rx"].keys()), {((0,), (3.14,))}) self.assertEqual(set(circ.calibrations["ry"].keys()), {((1,), (1.57,))}) self.assertEqual( circ.calibrations["rx"][((0,), (3.14,))].instructions, q0_x180.instructions ) self.assertEqual(circ.calibrations["ry"][((1,), (1.57,))].instructions, q1_y90.instructions) def test_calibrations_custom_gates(self): """Check if the calibrations for custom gates with params provided are added correctly.""" circ = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibrations with a custom gate 'rxt' circ.add_calibration("rxt", [0], q0_x180, params=[1.57, 3.14, 4.71]) self.assertEqual(set(circ.calibrations.keys()), {"rxt"}) self.assertEqual(set(circ.calibrations["rxt"].keys()), {((0,), (1.57, 3.14, 4.71))}) self.assertEqual( circ.calibrations["rxt"][((0,), (1.57, 3.14, 4.71))].instructions, q0_x180.instructions ) def test_calibrations_no_params(self): """Check calibrations if the no params is provided with just gate name.""" circ = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) circ.add_calibration("h", [0], q0_x180) self.assertEqual(set(circ.calibrations.keys()), {"h"}) self.assertEqual(set(circ.calibrations["h"].keys()), {((0,), ())}) self.assertEqual(circ.calibrations["h"][((0,), ())].instructions, q0_x180.instructions) def test_has_calibration_for(self): """Test that `has_calibration_for` returns a correct answer.""" qc = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("h", [0], q0_x180) qc.h(0) qc.h(1) self.assertTrue(qc.has_calibration_for(qc.data[0])) self.assertFalse(qc.has_calibration_for(qc.data[1])) def test_has_calibration_for_legacy(self): """Test that `has_calibration_for` returns a correct answer when presented with a legacy 3 tuple.""" qc = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("h", [0], q0_x180) qc.h(0) qc.h(1) self.assertTrue( qc.has_calibration_for( (qc.data[0].operation, list(qc.data[0].qubits), list(qc.data[0].clbits)) ) ) self.assertFalse( qc.has_calibration_for( (qc.data[1].operation, list(qc.data[1].qubits), list(qc.data[1].clbits)) ) ) def test_metadata_copy_does_not_share_state(self): """Verify mutating the metadata of a circuit copy does not impact original.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/6057 qc1 = QuantumCircuit(1) qc1.metadata = {"a": 0} qc2 = qc1.copy() qc2.metadata["a"] = 1000 self.assertEqual(qc1.metadata["a"], 0) def test_metadata_is_dict(self): """Verify setting metadata to None in the constructor results in an empty dict.""" qc = QuantumCircuit(1) metadata1 = qc.metadata self.assertEqual(metadata1, {}) def test_metadata_raises(self): """Test that we must set metadata to a dict.""" qc = QuantumCircuit(1) with self.assertRaises(TypeError): qc.metadata = 1 def test_metdata_deprectation(self): """Test that setting metadata to None emits a deprecation warning.""" qc = QuantumCircuit(1) with self.assertWarns(DeprecationWarning): qc.metadata = None self.assertEqual(qc.metadata, {}) def test_scheduling(self): """Test cannot return schedule information without scheduling.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) with self.assertRaises(AttributeError): # pylint: disable=pointless-statement qc.op_start_times if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's gates in QASM2.""" import unittest from math import pi import re from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.circuit import Parameter, Qubit, Clbit, Gate from qiskit.circuit.library import C3SXGate, CCZGate, CSGate, CSdgGate, PermutationGate from qiskit.qasm.exceptions import QasmError # Regex pattern to match valid OpenQASM identifiers VALID_QASM2_IDENTIFIER = re.compile("[a-z][a-zA-Z_0-9]*") class TestCircuitQasm(QiskitTestCase): """QuantumCircuit QASM2 tests.""" def test_circuit_qasm(self): """Test circuit qasm() method.""" qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") cr = ClassicalRegister(3, "cr") qc = QuantumCircuit(qr1, qr2, cr) qc.p(0.3, qr1[0]) qc.u(0.3, 0.2, 0.1, qr2[1]) qc.s(qr2[1]) qc.sdg(qr2[1]) qc.cx(qr1[0], qr2[1]) qc.barrier(qr2) qc.cx(qr2[1], qr1[0]) qc.h(qr2[1]) qc.x(qr2[1]).c_if(cr, 0) qc.y(qr1[0]).c_if(cr, 1) qc.z(qr1[0]).c_if(cr, 2) qc.barrier(qr1, qr2) qc.measure(qr1[0], cr[0]) qc.measure(qr2[0], cr[1]) qc.measure(qr2[1], cr[2]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg qr1[1]; qreg qr2[2]; creg cr[3]; p(0.3) qr1[0]; u(0.3,0.2,0.1) qr2[1]; s qr2[1]; sdg qr2[1]; cx qr1[0],qr2[1]; barrier qr2[0],qr2[1]; cx qr2[1],qr1[0]; h qr2[1]; if(cr==0) x qr2[1]; if(cr==1) y qr1[0]; if(cr==2) z qr1[0]; barrier qr1[0],qr2[0],qr2[1]; measure qr1[0] -> cr[0]; measure qr2[0] -> cr[1]; measure qr2[1] -> cr[2];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_composite_circuit(self): """Test circuit qasm() method when a composite circuit instruction is included within circuit. """ composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_instruction() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate composite_circ q0,q1 { h q0; x q1; cx q0,q1; } qreg qr[2]; creg cr[2]; h qr[0]; cx qr[0],qr[1]; barrier qr[0],qr[1]; composite_circ qr[0],qr[1]; measure qr[0] -> cr[0]; measure qr[1] -> cr[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_multiple_same_composite_circuits(self): """Test circuit qasm() method when a composite circuit is added to the circuit multiple times """ composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_instruction() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate composite_circ q0,q1 { h q0; x q1; cx q0,q1; } qreg qr[2]; creg cr[2]; h qr[0]; cx qr[0],qr[1]; barrier qr[0],qr[1]; composite_circ qr[0],qr[1]; composite_circ qr[0],qr[1]; measure qr[0] -> cr[0]; measure qr[1] -> cr[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_multiple_composite_circuits_with_same_name(self): """Test circuit qasm() method when multiple composite circuit instructions with the same circuit name are added to the circuit """ my_gate = QuantumCircuit(1, name="my_gate") my_gate.h(0) my_gate_inst1 = my_gate.to_instruction() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst2 = my_gate.to_instruction() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst3 = my_gate.to_instruction() qr = QuantumRegister(1, name="qr") circuit = QuantumCircuit(qr, name="circuit") circuit.append(my_gate_inst1, [qr[0]]) circuit.append(my_gate_inst2, [qr[0]]) my_gate_inst2_id = id(circuit.data[-1].operation) circuit.append(my_gate_inst3, [qr[0]]) my_gate_inst3_id = id(circuit.data[-1].operation) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate q0 {{ h q0; }} gate my_gate_{1} q0 {{ x q0; }} gate my_gate_{0} q0 {{ x q0; }} qreg qr[1]; my_gate qr[0]; my_gate_{1} qr[0]; my_gate_{0} qr[0];\n""".format( my_gate_inst3_id, my_gate_inst2_id ) self.assertEqual(circuit.qasm(), expected_qasm) def test_circuit_qasm_with_composite_circuit_with_children_composite_circuit(self): """Test circuit qasm() method when composite circuits with children composite circuits in the definitions are added to the circuit""" child_circ = QuantumCircuit(2, name="child_circ") child_circ.h(0) child_circ.cx(0, 1) parent_circ = QuantumCircuit(3, name="parent_circ") parent_circ.append(child_circ, range(2)) parent_circ.h(2) grandparent_circ = QuantumCircuit(4, name="grandparent_circ") grandparent_circ.append(parent_circ, range(3)) grandparent_circ.x(3) qc = QuantumCircuit(4) qc.append(grandparent_circ, range(4)) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate child_circ q0,q1 { h q0; cx q0,q1; } gate parent_circ q0,q1,q2 { child_circ q0,q1; h q2; } gate grandparent_circ q0,q1,q2,q3 { parent_circ q0,q1,q2; x q3; } qreg q[4]; grandparent_circ q[0],q[1],q[2],q[3];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_pi(self): """Test circuit qasm() method with pi params.""" circuit = QuantumCircuit(2) circuit.cz(0, 1) circuit.u(2 * pi, 3 * pi, -5 * pi, 0) qasm_str = circuit.qasm() circuit2 = QuantumCircuit.from_qasm_str(qasm_str) self.assertEqual(circuit, circuit2) def test_circuit_qasm_with_composite_circuit_with_one_param(self): """Test circuit qasm() method when a composite circuit instruction has one param """ original_str = """OPENQASM 2.0; include "qelib1.inc"; gate nG0(param0) q0 { h q0; } qreg q[3]; creg c[3]; nG0(pi) q[0];\n""" qc = QuantumCircuit.from_qasm_str(original_str) self.assertEqual(original_str, qc.qasm()) def test_circuit_qasm_with_composite_circuit_with_many_params_and_qubits(self): """Test circuit qasm() method when a composite circuit instruction has many params and qubits """ original_str = """OPENQASM 2.0; include "qelib1.inc"; gate nG0(param0,param1) q0,q1 { h q0; h q1; } qreg q[3]; qreg r[3]; creg c[3]; creg d[3]; nG0(pi,pi/2) q[0],r[0];\n""" qc = QuantumCircuit.from_qasm_str(original_str) self.assertEqual(original_str, qc.qasm()) def test_c3sxgate_roundtrips(self): """Test that C3SXGate correctly round trips. Qiskit gives this gate a different name ('c3sx') to the name in Qiskit's version of qelib1.inc ('c3sqrtx') gate, which can lead to resolution issues.""" qc = QuantumCircuit(4) qc.append(C3SXGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; c3sqrtx q[0],q[1],q[2],q[3]; """ self.assertEqual(qasm, expected) parsed = QuantumCircuit.from_qasm_str(qasm) self.assertIsInstance(parsed.data[0].operation, C3SXGate) def test_c3sxgate_qasm_deprecation_warning(self): """Test deprecation warning for C3SXGate.""" with self.assertWarnsRegex(DeprecationWarning, r"Correct exporting to OpenQASM 2"): C3SXGate().qasm() def test_cczgate_qasm(self): """Test that CCZ dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(3) qc.append(CCZGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate ccz q0,q1,q2 { h q2; ccx q0,q1,q2; h q2; } qreg q[3]; ccz q[0],q[1],q[2]; """ self.assertEqual(qasm, expected) def test_csgate_qasm(self): """Test that CS dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.append(CSGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate cs q0,q1 { p(pi/4) q0; cx q0,q1; p(-pi/4) q1; cx q0,q1; p(pi/4) q1; } qreg q[2]; cs q[0],q[1]; """ self.assertEqual(qasm, expected) def test_csdggate_qasm(self): """Test that CSdg dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.append(CSdgGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate csdg q0,q1 { p(-pi/4) q0; cx q0,q1; p(pi/4) q1; cx q0,q1; p(-pi/4) q1; } qreg q[2]; csdg q[0],q[1]; """ self.assertEqual(qasm, expected) def test_rzxgate_qasm(self): """Test that RZX dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.rzx(0, 0, 1) qc.rzx(pi / 2, 1, 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate rzx(param0) q0,q1 { h q1; cx q0,q1; rz(param0) q1; cx q0,q1; h q1; } qreg q[2]; rzx(0) q[0],q[1]; rzx(pi/2) q[1],q[0]; """ self.assertEqual(qasm, expected) def test_ecrgate_qasm(self): """Test that ECR dumps its definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.ecr(0, 1) qc.ecr(1, 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate rzx(param0) q0,q1 { h q1; cx q0,q1; rz(param0) q1; cx q0,q1; h q1; } gate ecr q0,q1 { rzx(pi/4) q0,q1; x q0; rzx(-pi/4) q0,q1; } qreg q[2]; ecr q[0],q[1]; ecr q[1],q[0]; """ self.assertEqual(qasm, expected) def test_unitary_qasm(self): """Test that UnitaryGate can be dumped to OQ2 correctly.""" qc = QuantumCircuit(1) qc.unitary([[1, 0], [0, 1]], 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate unitary q0 { u(0,0,0) q0; } qreg q[1]; unitary q[0]; """ self.assertEqual(qasm, expected) def test_multiple_unitary_qasm(self): """Test that multiple UnitaryGate instances can all dump successfully.""" custom = QuantumCircuit(1, name="custom") custom.unitary([[1, 0], [0, -1]], 0) qc = QuantumCircuit(2) qc.unitary([[1, 0], [0, 1]], 0) qc.unitary([[0, 1], [1, 0]], 1) qc.append(custom.to_gate(), [0], []) qasm = qc.qasm() expected = re.compile( r"""OPENQASM 2.0; include "qelib1.inc"; gate unitary q0 { u\(0,0,0\) q0; } gate (?P<u1>unitary_[0-9]*) q0 { u\(pi,-pi/2,pi/2\) q0; } gate (?P<u2>unitary_[0-9]*) q0 { u\(0,pi/2,pi/2\) q0; } gate custom q0 { (?P=u2) q0; } qreg q\[2\]; unitary q\[0\]; (?P=u1) q\[1\]; custom q\[0\]; """, re.MULTILINE, ) self.assertRegex(qasm, expected) def test_unbound_circuit_raises(self): """Test circuits with unbound parameters raises.""" qc = QuantumCircuit(1) theta = Parameter("θ") qc.rz(theta, 0) with self.assertRaises(QasmError): qc.qasm() def test_gate_qasm_with_ctrl_state(self): """Test gate qasm() with controlled gate that has ctrl_state setting.""" from qiskit.quantum_info import Operator qc = QuantumCircuit(2) qc.ch(0, 1, ctrl_state=0) qasm_str = qc.qasm() self.assertEqual(Operator(qc), Operator(QuantumCircuit.from_qasm_str(qasm_str))) def test_circuit_qasm_with_mcx_gate(self): """Test circuit qasm() method with MCXGate See https://github.com/Qiskit/qiskit-terra/issues/4943 """ qc = QuantumCircuit(4) qc.mcx([0, 1, 2], 3) # qasm output doesn't support parameterized gate yet. # param0 for "gate mcuq(param0) is not used inside the definition expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate mcx q0,q1,q2,q3 { h q3; p(pi/8) q0; p(pi/8) q1; p(pi/8) q2; p(pi/8) q3; cx q0,q1; p(-pi/8) q1; cx q0,q1; cx q1,q2; p(-pi/8) q2; cx q0,q2; p(pi/8) q2; cx q1,q2; p(-pi/8) q2; cx q0,q2; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; h q3; } qreg q[4]; mcx q[0],q[1],q[2],q[3];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_mcx_gate_variants(self): """Test circuit qasm() method with MCXGrayCode, MCXRecursive, MCXVChain""" import qiskit.circuit.library as cl n = 5 qc = QuantumCircuit(2 * n - 1) qc.append(cl.MCXGrayCode(n), range(n + 1)) qc.append(cl.MCXRecursive(n), range(n + 2)) qc.append(cl.MCXVChain(n), range(2 * n - 1)) # qasm output doesn't support parameterized gate yet. # param0 for "gate mcuq(param0) is not used inside the definition expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate mcu1(param0) q0,q1,q2,q3,q4,q5 { cu1(pi/16) q4,q5; cx q4,q3; cu1(-pi/16) q3,q5; cx q4,q3; cu1(pi/16) q3,q5; cx q3,q2; cu1(-pi/16) q2,q5; cx q4,q2; cu1(pi/16) q2,q5; cx q3,q2; cu1(-pi/16) q2,q5; cx q4,q2; cu1(pi/16) q2,q5; cx q2,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q3,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q2,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q3,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q1,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q2,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q1,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q2,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; } gate mcx_gray q0,q1,q2,q3,q4,q5 { h q5; mcu1(pi) q0,q1,q2,q3,q4,q5; h q5; } gate mcx q0,q1,q2,q3 { h q3; p(pi/8) q0; p(pi/8) q1; p(pi/8) q2; p(pi/8) q3; cx q0,q1; p(-pi/8) q1; cx q0,q1; cx q1,q2; p(-pi/8) q2; cx q0,q2; p(pi/8) q2; cx q1,q2; p(-pi/8) q2; cx q0,q2; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; h q3; } gate mcx_recursive q0,q1,q2,q3,q4,q5,q6 { mcx q0,q1,q2,q6; mcx q3,q4,q6,q5; mcx q0,q1,q2,q6; mcx q3,q4,q6,q5; } gate mcx_vchain q0,q1,q2,q3,q4,q5,q6,q7,q8 { rccx q0,q1,q6; rccx q2,q6,q7; rccx q3,q7,q8; ccx q4,q8,q5; rccx q3,q7,q8; rccx q2,q6,q7; rccx q0,q1,q6; } qreg q[9]; mcx_gray q[0],q[1],q[2],q[3],q[4],q[5]; mcx_recursive q[0],q[1],q[2],q[3],q[4],q[5],q[6]; mcx_vchain q[0],q[1],q[2],q[3],q[4],q[5],q[6],q[7],q[8];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_registerless_bits(self): """Test that registerless bits do not have naming collisions in their registers.""" initial_registers = [QuantumRegister(2), ClassicalRegister(2)] qc = QuantumCircuit(*initial_registers, [Qubit(), Clbit()]) # Match a 'qreg identifier[3];'-like QASM register declaration. register_regex = re.compile(r"\s*[cq]reg\s+(\w+)\s*\[\d+\]\s*", re.M) qasm_register_names = set() for statement in qc.qasm().split(";"): match = register_regex.match(statement) if match: qasm_register_names.add(match.group(1)) self.assertEqual(len(qasm_register_names), 4) # Check that no additional registers were added to the circuit. self.assertEqual(len(qc.qregs), 1) self.assertEqual(len(qc.cregs), 1) # Check that the registerless-register names are recalculated after adding more registers, # to avoid naming clashes in this case. generated_names = qasm_register_names - {register.name for register in initial_registers} for generated_name in generated_names: qc.add_register(QuantumRegister(1, name=generated_name)) qasm_register_names = set() for statement in qc.qasm().split(";"): match = register_regex.match(statement) if match: qasm_register_names.add(match.group(1)) self.assertEqual(len(qasm_register_names), 6) def test_circuit_qasm_with_repeated_instruction_names(self): """Test that qasm() doesn't change the name of the instructions that live in circuit.data, but a copy of them when there are repeated names.""" qc = QuantumCircuit(2) qc.h(0) qc.x(1) # Create some random custom gate and name it "custom" custom = QuantumCircuit(1) custom.h(0) custom.y(0) gate = custom.to_gate() gate.name = "custom" # Another random custom gate named "custom" as well custom2 = QuantumCircuit(2) custom2.x(0) custom2.z(1) gate2 = custom2.to_gate() gate2.name = "custom" # Append custom gates with same name to original circuit qc.append(gate, [0]) qc.append(gate2, [1, 0]) # Expected qasm string will append the id to the second gate with repeated name expected_qasm = f"""OPENQASM 2.0; include "qelib1.inc"; gate custom q0 {{ h q0; y q0; }} gate custom_{id(gate2)} q0,q1 {{ x q0; z q1; }} qreg q[2]; h q[0]; x q[1]; custom q[0]; custom_{id(gate2)} q[1],q[0];\n""" # Check qasm() produced the correct string self.assertEqual(expected_qasm, qc.qasm()) # Check instruction names were not changed by qasm() names = ["h", "x", "custom", "custom"] for idx, instruction in enumerate(qc._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_with_invalid_identifiers(self): """Test that qasm() detects and corrects invalid OpenQASM gate identifiers, while not changing the instructions on the original circuit""" qc = QuantumCircuit(2) # Create some gate and give it an invalid name custom = QuantumCircuit(1) custom.x(0) custom.u(0, 0, pi, 0) gate = custom.to_gate() gate.name = "A[$]" # Another gate also with invalid name custom2 = QuantumCircuit(2) custom2.x(0) custom2.append(gate, [1]) gate2 = custom2.to_gate() gate2.name = "invalid[name]" # Append gates qc.append(gate, [0]) qc.append(gate2, [1, 0]) # Expected qasm with valid identifiers expected_qasm = "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "gate gate_A___ q0 { x q0; u(0,0,pi) q0; }", "gate invalid_name_ q0,q1 { x q0; gate_A___ q1; }", "qreg q[2];", "gate_A___ q[0];", "invalid_name_ q[1],q[0];", "", ] ) # Check qasm() produces the correct string self.assertEqual(expected_qasm, qc.qasm()) # Check instruction names were not changed by qasm() names = ["A[$]", "invalid[name]"] for idx, instruction in enumerate(qc._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_with_duplicate_invalid_identifiers(self): """Test that qasm() corrects invalid identifiers and the de-duplication code runs correctly, without altering original instructions""" base = QuantumCircuit(1) # First gate with invalid name, escapes to "invalid__" clash1 = QuantumCircuit(1, name="invalid??") clash1.x(0) base.append(clash1, [0]) # Second gate with invalid name that also escapes to "invalid__" clash2 = QuantumCircuit(1, name="invalid[]") clash2.z(0) base.append(clash2, [0]) # Check qasm is correctly produced names = set() for match in re.findall(r"gate (\S+)", base.qasm()): self.assertTrue(VALID_QASM2_IDENTIFIER.fullmatch(match)) names.add(match) self.assertEqual(len(names), 2) # Check instruction names were not changed by qasm() names = ["invalid??", "invalid[]"] for idx, instruction in enumerate(base._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_escapes_register_names(self): """Test that registers that have invalid OpenQASM 2 names get correctly escaped, even when they would escape to the same value.""" qc = QuantumCircuit(QuantumRegister(2, "?invalid"), QuantumRegister(2, "!invalid")) qc.cx(0, 1) qc.cx(2, 3) qasm = qc.qasm() match = re.fullmatch( rf"""OPENQASM 2.0; include "qelib1.inc"; qreg ({VALID_QASM2_IDENTIFIER.pattern})\[2\]; qreg ({VALID_QASM2_IDENTIFIER.pattern})\[2\]; cx \1\[0\],\1\[1\]; cx \2\[0\],\2\[1\]; """, qasm, ) self.assertTrue(match) self.assertNotEqual(match.group(1), match.group(2)) def test_circuit_qasm_escapes_reserved(self): """Test that the OpenQASM 2 exporter won't export reserved names.""" qc = QuantumCircuit(QuantumRegister(1, "qreg")) gate = Gate("gate", 1, []) gate.definition = QuantumCircuit(1) qc.append(gate, [qc.qubits[0]]) qasm = qc.qasm() match = re.fullmatch( rf"""OPENQASM 2.0; include "qelib1.inc"; gate ({VALID_QASM2_IDENTIFIER.pattern}) q0 {{ }} qreg ({VALID_QASM2_IDENTIFIER.pattern})\[1\]; \1 \2\[0\]; """, qasm, ) self.assertTrue(match) self.assertNotEqual(match.group(1), "gate") self.assertNotEqual(match.group(1), "qreg") def test_circuit_qasm_with_double_precision_rotation_angle(self): """Test that qasm() emits high precision rotation angles per default.""" from qiskit.circuit.tools.pi_check import MAX_FRAC qc = QuantumCircuit(1) qc.p(0.123456789, 0) qc.p(pi * pi, 0) qc.p(MAX_FRAC * pi + 1, 0) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; p(0.123456789) q[0]; p(9.869604401089358) q[0]; p(51.26548245743669) q[0];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_rotation_angles_close_to_pi(self): """Test that qasm() properly rounds values closer than 1e-12 to pi.""" qc = QuantumCircuit(1) qc.p(pi + 1e-11, 0) qc.p(pi + 1e-12, 0) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; p(3.141592653599793) q[0]; p(pi) q[0];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_raises_on_single_bit_condition(self): """OpenQASM 2 can't represent single-bit conditions, so test that a suitable error is printed if this is attempted.""" qc = QuantumCircuit(1, 1) qc.x(0).c_if(0, True) with self.assertRaisesRegex(QasmError, "OpenQASM 2 can only condition on registers"): qc.qasm() def test_circuit_raises_invalid_custom_gate_no_qubits(self): """OpenQASM 2 exporter of custom gates with no qubits. See: https://github.com/Qiskit/qiskit-terra/issues/10435""" legit_circuit = QuantumCircuit(5, name="legit_circuit") empty_circuit = QuantumCircuit(name="empty_circuit") legit_circuit.append(empty_circuit) with self.assertRaisesRegex(QasmError, "acts on zero qubits"): legit_circuit.qasm() def test_circuit_raises_invalid_custom_gate_clbits(self): """OpenQASM 2 exporter of custom instruction. See: https://github.com/Qiskit/qiskit-terra/issues/7351""" instruction = QuantumCircuit(2, 2, name="inst") instruction.cx(0, 1) instruction.measure([0, 1], [0, 1]) custom_instruction = instruction.to_instruction() qc = QuantumCircuit(2, 2) qc.append(custom_instruction, [0, 1], [0, 1]) with self.assertRaisesRegex(QasmError, "acts on 2 classical bits"): qc.qasm() def test_circuit_qasm_with_permutations(self): """Test circuit qasm() method with Permutation gates.""" qc = QuantumCircuit(4) qc.append(PermutationGate([2, 1, 0]), [0, 1, 2]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate permutation__2_1_0_ q0,q1,q2 { swap q0,q2; } qreg q[4]; permutation__2_1_0_ q[0],q[1],q[2];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_multiple_permutation(self): """Test that multiple PermutationGates can be added to a circuit.""" custom = QuantumCircuit(3, name="custom") custom.append(PermutationGate([2, 1, 0]), [0, 1, 2]) custom.append(PermutationGate([0, 1, 2]), [0, 1, 2]) qc = QuantumCircuit(4) qc.append(PermutationGate([2, 1, 0]), [0, 1, 2], []) qc.append(PermutationGate([1, 2, 0]), [0, 1, 2], []) qc.append(custom.to_gate(), [1, 3, 2], []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate permutation__2_1_0_ q0,q1,q2 { swap q0,q2; } gate permutation__1_2_0_ q0,q1,q2 { swap q1,q2; swap q0,q2; } gate permutation__0_1_2_ q0,q1,q2 { } gate custom q0,q1,q2 { permutation__2_1_0_ q0,q1,q2; permutation__0_1_2_ q0,q1,q2; } qreg q[4]; permutation__2_1_0_ q[0],q[1],q[2]; permutation__1_2_0_ q[0],q[1],q[2]; custom q[1],q[3],q[2]; """ self.assertEqual(qasm, expected) def test_circuit_qasm_with_reset(self): """Test circuit qasm() method with Reset.""" qc = QuantumCircuit(2) qc.reset([0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; reset q[0]; reset q[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_nested_gate_naming_clashes(self): """Test that gates that have naming clashes but only appear in the body of another gate still get exported correctly.""" # pylint: disable=missing-class-docstring class Inner(Gate): def __init__(self, param): super().__init__("inner", 1, [param]) def _define(self): self._definition = QuantumCircuit(1) self._definition.rx(self.params[0], 0) class Outer(Gate): def __init__(self, param): super().__init__("outer", 1, [param]) def _define(self): self._definition = QuantumCircuit(1) self._definition.append(Inner(self.params[0]), [0], []) qc = QuantumCircuit(1) qc.append(Outer(1.0), [0], []) qc.append(Outer(2.0), [0], []) qasm = qc.qasm() expected = re.compile( r"""OPENQASM 2\.0; include "qelib1\.inc"; gate inner\(param0\) q0 { rx\(1\.0\) q0; } gate outer\(param0\) q0 { inner\(1\.0\) q0; } gate (?P<inner1>inner_[0-9]*)\(param0\) q0 { rx\(2\.0\) q0; } gate (?P<outer1>outer_[0-9]*)\(param0\) q0 { (?P=inner1)\(2\.0\) q0; } qreg q\[1\]; outer\(1\.0\) q\[0\]; (?P=outer1)\(2\.0\) q\[0\]; """, re.MULTILINE, ) self.assertRegex(qasm, expected) def test_opaque_output(self): """Test that gates with no definition are exported as `opaque`.""" custom = QuantumCircuit(1, name="custom") custom.append(Gate("my_c", 1, []), [0]) qc = QuantumCircuit(2) qc.append(Gate("my_a", 1, []), [0]) qc.append(Gate("my_a", 1, []), [1]) qc.append(Gate("my_b", 2, [1.0]), [1, 0]) qc.append(custom.to_gate(), [0], []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; opaque my_a q0; opaque my_b(param0) q0,q1; opaque my_c q0; gate custom q0 { my_c q0; } qreg q[2]; my_a q[0]; my_a q[1]; my_b(1.0) q[1],q[0]; custom q[0]; """ self.assertEqual(qasm, expected) def test_sequencial_inner_gates_with_same_name(self): """Test if inner gates sequentially added with the same name result in the correct qasm""" qubits_range = range(3) gate_a = QuantumCircuit(3, name="a") gate_a.h(qubits_range) gate_a = gate_a.to_instruction() gate_b = QuantumCircuit(3, name="a") gate_b.append(gate_a, qubits_range) gate_b.x(qubits_range) gate_b = gate_b.to_instruction() qc = QuantumCircuit(3) qc.append(gate_b, qubits_range) qc.z(qubits_range) gate_a_id = id(qc.data[0].operation) expected_output = f"""OPENQASM 2.0; include "qelib1.inc"; gate a q0,q1,q2 {{ h q0; h q1; h q2; }} gate a_{gate_a_id} q0,q1,q2 {{ a q0,q1,q2; x q0; x q1; x q2; }} qreg q[3]; a_{gate_a_id} q[0],q[1],q[2]; z q[0]; z q[1]; z q[2]; """ self.assertEqual(qc.qasm(), expected_output) def test_empty_barrier(self): """Test that a blank barrier statement in _Qiskit_ acts over all qubits, while an explicitly no-op barrier (assuming Qiskit continues to allow this) is not output to OQ2 at all, since the statement requires an argument in the spec.""" qc = QuantumCircuit(QuantumRegister(2, "qr1"), QuantumRegister(3, "qr2")) qc.barrier() # In Qiskit land, this affects _all_ qubits. qc.barrier([]) # This explicitly affects _no_ qubits (so is totally meaningless). expected = """\ OPENQASM 2.0; include "qelib1.inc"; qreg qr1[2]; qreg qr2[3]; barrier qr1[0],qr1[1],qr2[0],qr2[1],qr2[2]; """ self.assertEqual(qc.qasm(), expected) def test_small_angle_valid(self): """Test that small angles do not get converted to invalid OQ2 floating-point values.""" # OQ2 _technically_ requires a decimal point in all floating-point values, even ones that # are followed by an exponent. qc = QuantumCircuit(1) qc.rx(0.000001, 0) expected = """\ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; rx(1.e-06) q[0]; """ self.assertEqual(qc.qasm(), expected) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test commutation checker class .""" import unittest import numpy as np from qiskit import ClassicalRegister from qiskit.test import QiskitTestCase from qiskit.circuit import QuantumRegister, Parameter, Qubit from qiskit.circuit import CommutationChecker from qiskit.circuit.library import ( ZGate, XGate, CXGate, CCXGate, MCXGate, RZGate, Measure, Barrier, Reset, LinearFunction, ) class TestCommutationChecker(QiskitTestCase): """Test CommutationChecker class.""" def test_simple_gates(self): """Check simple commutation relations between gates, experimenting with different orders of gates, different orders of qubits, different sets of qubits over which gates are defined, and so on.""" comm_checker = CommutationChecker() # should commute res = comm_checker.commute(ZGate(), [0], [], CXGate(), [0, 1], []) self.assertTrue(res) # should not commute res = comm_checker.commute(ZGate(), [1], [], CXGate(), [0, 1], []) self.assertFalse(res) # should not commute res = comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], []) self.assertFalse(res) # should commute res = comm_checker.commute(XGate(), [1], [], CXGate(), [0, 1], []) self.assertTrue(res) # should not commute res = comm_checker.commute(XGate(), [1], [], CXGate(), [1, 0], []) self.assertFalse(res) # should commute res = comm_checker.commute(XGate(), [0], [], CXGate(), [1, 0], []) self.assertTrue(res) # should commute res = comm_checker.commute(CXGate(), [1, 0], [], XGate(), [0], []) self.assertTrue(res) # should not commute res = comm_checker.commute(CXGate(), [1, 0], [], XGate(), [1], []) self.assertFalse(res) # should commute res = comm_checker.commute( CXGate(), [1, 0], [], CXGate(), [1, 0], [], ) self.assertTrue(res) # should not commute res = comm_checker.commute( CXGate(), [1, 0], [], CXGate(), [0, 1], [], ) self.assertFalse(res) # should commute res = comm_checker.commute( CXGate(), [1, 0], [], CXGate(), [1, 2], [], ) self.assertTrue(res) # should not commute res = comm_checker.commute( CXGate(), [1, 0], [], CXGate(), [2, 1], [], ) self.assertFalse(res) # should commute res = comm_checker.commute( CXGate(), [1, 0], [], CXGate(), [2, 3], [], ) self.assertTrue(res) res = comm_checker.commute(XGate(), [2], [], CCXGate(), [0, 1, 2], []) self.assertTrue(res) res = comm_checker.commute(CCXGate(), [0, 1, 2], [], CCXGate(), [0, 2, 1], []) self.assertFalse(res) def test_passing_quantum_registers(self): """Check that passing QuantumRegisters works correctly.""" comm_checker = CommutationChecker() qr = QuantumRegister(4) # should commute res = comm_checker.commute(CXGate(), [qr[1], qr[0]], [], CXGate(), [qr[1], qr[2]], []) self.assertTrue(res) # should not commute res = comm_checker.commute(CXGate(), [qr[0], qr[1]], [], CXGate(), [qr[1], qr[2]], []) self.assertFalse(res) def test_caching_positive_results(self): """Check that hashing positive results in commutativity checker works as expected.""" comm_checker = CommutationChecker() res = comm_checker.commute(ZGate(), [0], [], CXGate(), [0, 1], []) self.assertTrue(res) self.assertGreater(len(comm_checker.cache), 0) def test_caching_negative_results(self): """Check that hashing negative results in commutativity checker works as expected.""" comm_checker = CommutationChecker() res = comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], []) self.assertFalse(res) self.assertGreater(len(comm_checker.cache), 0) def test_caching_different_qubit_sets(self): """Check that hashing same commutativity results over different qubit sets works as expected.""" comm_checker = CommutationChecker() # All the following should be cached in the same way # though each relation gets cached twice: (A, B) and (B, A) comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], []) comm_checker.commute(XGate(), [10], [], CXGate(), [10, 20], []) comm_checker.commute(XGate(), [10], [], CXGate(), [10, 5], []) comm_checker.commute(XGate(), [5], [], CXGate(), [5, 7], []) self.assertEqual(len(comm_checker.cache), 2) def test_gates_with_parameters(self): """Check commutativity between (non-parameterized) gates with parameters.""" comm_checker = CommutationChecker() res = comm_checker.commute(RZGate(0), [0], [], XGate(), [0], []) self.assertTrue(res) res = comm_checker.commute(RZGate(np.pi / 2), [0], [], XGate(), [0], []) self.assertFalse(res) res = comm_checker.commute(RZGate(np.pi / 2), [0], [], RZGate(0), [0], []) self.assertTrue(res) def test_parameterized_gates(self): """Check commutativity between parameterized gates, both with free and with bound parameters.""" comm_checker = CommutationChecker() # gate that has parameters but is not considered parameterized rz_gate = RZGate(np.pi / 2) self.assertEqual(len(rz_gate.params), 1) self.assertFalse(rz_gate.is_parameterized()) # gate that has parameters and is considered parameterized rz_gate_theta = RZGate(Parameter("Theta")) rz_gate_phi = RZGate(Parameter("Phi")) self.assertEqual(len(rz_gate_theta.params), 1) self.assertTrue(rz_gate_theta.is_parameterized()) # gate that has no parameters and is not considered parameterized cx_gate = CXGate() self.assertEqual(len(cx_gate.params), 0) self.assertFalse(cx_gate.is_parameterized()) # We should detect that these gates commute res = comm_checker.commute(rz_gate, [0], [], cx_gate, [0, 1], []) self.assertTrue(res) # We should detect that these gates commute res = comm_checker.commute(rz_gate, [0], [], rz_gate, [0], []) self.assertTrue(res) # We should detect that parameterized gates over disjoint qubit subsets commute res = comm_checker.commute(rz_gate_theta, [0], [], rz_gate_theta, [1], []) self.assertTrue(res) # We should detect that parameterized gates over disjoint qubit subsets commute res = comm_checker.commute(rz_gate_theta, [0], [], rz_gate_phi, [1], []) self.assertTrue(res) # We should detect that parameterized gates over disjoint qubit subsets commute res = comm_checker.commute(rz_gate_theta, [2], [], cx_gate, [1, 3], []) self.assertTrue(res) # However, for now commutativity checker should return False when checking # commutativity between a parameterized gate and some other gate, when # the two gates are over intersecting qubit subsets. # This check should be changed if commutativity checker is extended to # handle parameterized gates better. res = comm_checker.commute(rz_gate_theta, [0], [], cx_gate, [0, 1], []) self.assertFalse(res) res = comm_checker.commute(rz_gate_theta, [0], [], rz_gate, [0], []) self.assertFalse(res) def test_measure(self): """Check commutativity involving measures.""" comm_checker = CommutationChecker() # Measure is over qubit 0, while gate is over a disjoint subset of qubits # We should be able to swap these. res = comm_checker.commute(Measure(), [0], [0], CXGate(), [1, 2], []) self.assertTrue(res) # Measure and gate have intersecting set of qubits # We should not be able to swap these. res = comm_checker.commute(Measure(), [0], [0], CXGate(), [0, 2], []) self.assertFalse(res) # Measures over different qubits and clbits res = comm_checker.commute(Measure(), [0], [0], Measure(), [1], [1]) self.assertTrue(res) # Measures over different qubits but same classical bit # We should not be able to swap these. res = comm_checker.commute(Measure(), [0], [0], Measure(), [1], [0]) self.assertFalse(res) # Measures over same qubits but different classical bit # ToDo: can we swap these? # Currently checker takes the safe approach and returns False. res = comm_checker.commute(Measure(), [0], [0], Measure(), [0], [1]) self.assertFalse(res) def test_barrier(self): """Check commutativity involving barriers.""" comm_checker = CommutationChecker() # A gate should not commute with a barrier # (at least if these are over intersecting qubit sets). res = comm_checker.commute(Barrier(4), [0, 1, 2, 3], [], CXGate(), [1, 2], []) self.assertFalse(res) # Does it even make sense to have a barrier over a subset of qubits? # Though in this case, it probably makes sense to say that barrier and gate can be swapped. res = comm_checker.commute(Barrier(4), [0, 1, 2, 3], [], CXGate(), [5, 6], []) self.assertTrue(res) def test_reset(self): """Check commutativity involving resets.""" comm_checker = CommutationChecker() # A gate should not commute with reset when the qubits intersect. res = comm_checker.commute(Reset(), [0], [], CXGate(), [0, 2], []) self.assertFalse(res) # A gate should commute with reset when the qubits are disjoint. res = comm_checker.commute(Reset(), [0], [], CXGate(), [1, 2], []) self.assertTrue(res) def test_conditional_gates(self): """Check commutativity involving conditional gates.""" comm_checker = CommutationChecker() qr = QuantumRegister(3) cr = ClassicalRegister(2) # Currently, in all cases commutativity checker should returns False. # This is definitely suboptimal. res = comm_checker.commute( CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [], XGate(), [qr[2]], [] ) self.assertFalse(res) res = comm_checker.commute( CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [], XGate(), [qr[1]], [] ) self.assertFalse(res) res = comm_checker.commute( CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [], CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [] ) self.assertFalse(res) res = comm_checker.commute( XGate().c_if(cr[0], 0), [qr[0]], [], XGate().c_if(cr[0], 1), [qr[0]], [] ) self.assertFalse(res) res = comm_checker.commute(XGate().c_if(cr[0], 0), [qr[0]], [], XGate(), [qr[0]], []) self.assertFalse(res) def test_complex_gates(self): """Check commutativity involving more complex gates.""" comm_checker = CommutationChecker() lf1 = LinearFunction([[0, 1, 0], [1, 0, 0], [0, 0, 1]]) lf2 = LinearFunction([[1, 0, 0], [0, 0, 1], [0, 1, 0]]) # lf1 is equivalent to swap(0, 1), and lf2 to swap(1, 2). # These do not commute. res = comm_checker.commute(lf1, [0, 1, 2], [], lf2, [0, 1, 2], []) self.assertFalse(res) lf3 = LinearFunction([[0, 1, 0], [0, 0, 1], [1, 0, 0]]) lf4 = LinearFunction([[0, 0, 1], [1, 0, 0], [0, 1, 0]]) # lf3 is permutation 1->2, 2->3, 3->1. # lf3 is the inverse permutation 1->3, 2->1, 3->2. # These commute. res = comm_checker.commute(lf3, [0, 1, 2], [], lf4, [0, 1, 2], []) self.assertTrue(res) def test_c7x_gate(self): """Test wide gate works correctly.""" qargs = [Qubit() for _ in [None] * 8] res = CommutationChecker().commute(XGate(), qargs[:1], [], XGate().control(7), qargs, []) self.assertFalse(res) def test_wide_gates_over_nondisjoint_qubits(self): """Test that checking wide gates does not lead to memory problems.""" res = CommutationChecker().commute(MCXGate(29), list(range(30)), [], XGate(), [0], []) self.assertFalse(res) res = CommutationChecker().commute(XGate(), [0], [], MCXGate(29), list(range(30)), []) self.assertFalse(res) def test_wide_gates_over_disjoint_qubits(self): """Test that wide gates still commute when they are over disjoint sets of qubits.""" res = CommutationChecker().commute(MCXGate(29), list(range(30)), [], XGate(), [30], []) self.assertTrue(res) res = CommutationChecker().commute(XGate(), [30], [], MCXGate(29), list(range(30)), []) self.assertTrue(res) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """Test QuantumCircuit.compose().""" import unittest import numpy as np from qiskit import transpile from qiskit.pulse import Schedule from qiskit.circuit import ( QuantumRegister, ClassicalRegister, Clbit, QuantumCircuit, Qubit, Parameter, Gate, Instruction, CASE_DEFAULT, SwitchCaseOp, ) from qiskit.circuit.library import HGate, RZGate, CXGate, CCXGate, TwoLocal from qiskit.circuit.classical import expr from qiskit.test import QiskitTestCase class TestCircuitCompose(QiskitTestCase): """Test composition of two circuits.""" def setUp(self): super().setUp() qreg1 = QuantumRegister(3, "lqr_1") qreg2 = QuantumRegister(2, "lqr_2") creg = ClassicalRegister(2, "lcr") self.circuit_left = QuantumCircuit(qreg1, qreg2, creg) self.circuit_left.h(qreg1[0]) self.circuit_left.x(qreg1[1]) self.circuit_left.p(0.1, qreg1[2]) self.circuit_left.cx(qreg2[0], qreg2[1]) self.left_qubit0 = qreg1[0] self.left_qubit1 = qreg1[1] self.left_qubit2 = qreg1[2] self.left_qubit3 = qreg2[0] self.left_qubit4 = qreg2[1] self.left_clbit0 = creg[0] self.left_clbit1 = creg[1] self.condition = (creg, 3) def test_compose_inorder(self): """Composing two circuits of the same width, default order. ┌───┐ lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■─────── ├───┤ │ ┌───┐ lqr_1_1: |0>──┤ X ├─── rqr_1: |0>──┼──┤ X ├ ┌─┴───┴──┐ │ ├───┤ lqr_1_2: |0>┤ P(0.1) ├ + rqr_2: |0>──┼──┤ Y ├ = └────────┘ ┌─┴─┐└───┘ lqr_2_0: |0>────■───── rqr_3: |0>┤ X ├───── ┌─┴─┐ └───┘┌───┐ lqr_2_1: |0>──┤ X ├─── rqr_4: |0>─────┤ Z ├ └───┘ └───┘ lcr_0: 0 ═══════════ lcr_1: 0 ═══════════ ┌───┐ lqr_1_0: |0>──┤ H ├─────■─────── ├───┤ │ ┌───┐ lqr_1_1: |0>──┤ X ├─────┼──┤ X ├ ┌─┴───┴──┐ │ ├───┤ lqr_1_2: |0>┤ P(0.1) ├──┼──┤ Y ├ └────────┘┌─┴─┐└───┘ lqr_2_0: |0>────■─────┤ X ├───── ┌─┴─┐ └───┘┌───┐ lqr_2_1: |0>──┤ X ├────────┤ Z ├ └───┘ └───┘ lcr_0: 0 ═══════════════════════ lcr_1: 0 ═══════════════════════ """ qreg = QuantumRegister(5, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit3) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.z(self.left_qubit4) circuit_composed = self.circuit_left.compose(circuit_right, inplace=False) self.assertEqual(circuit_composed, circuit_expected) def test_compose_inorder_unusual_types(self): """Test that composition works in order, using Numpy integer types as well as regular integer types. In general, it should be permissible to use any of the same `QubitSpecifier` types (or similar for `Clbit`) that `QuantumCircuit.append` uses.""" qreg = QuantumRegister(5, "rqr") creg = ClassicalRegister(2, "rcr") circuit_right = QuantumCircuit(qreg, creg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_right.measure([0, 1], [0, 1]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit3) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.z(self.left_qubit4) circuit_expected.measure(self.left_qubit0, self.left_clbit0) circuit_expected.measure(self.left_qubit1, self.left_clbit1) circuit_composed = self.circuit_left.compose(circuit_right, np.arange(5), slice(0, 2)) self.assertEqual(circuit_composed, circuit_expected) def test_compose_inorder_inplace(self): """Composing two circuits of the same width, default order, inplace. ┌───┐ lqr_1_0: |0>───┤ H ├─── rqr_0: |0>──■─────── ├───┤ │ ┌───┐ lqr_1_1: |0>───┤ X ├─── rqr_1: |0>──┼──┤ X ├ ┌──┴───┴──┐ │ ├───┤ lqr_1_2: |0>┤ U1(0.1) ├ + rqr_2: |0>──┼──┤ Y ├ = └─────────┘ ┌─┴─┐└───┘ lqr_2_0: |0>─────■───── rqr_3: |0>┤ X ├───── ┌─┴─┐ └───┘┌───┐ lqr_2_1: |0>───┤ X ├─── rqr_4: |0>─────┤ Z ├ └───┘ └───┘ lcr_0: 0 ═══════════ lcr_1: 0 ═══════════ ┌───┐ lqr_1_0: |0>───┤ H ├─────■─────── ├───┤ │ ┌───┐ lqr_1_1: |0>───┤ X ├─────┼──┤ X ├ ┌──┴───┴──┐ │ ├───┤ lqr_1_2: |0>┤ U1(0.1) ├──┼──┤ Y ├ └─────────┘┌─┴─┐└───┘ lqr_2_0: |0>─────■─────┤ X ├───── ┌─┴─┐ └───┘┌───┐ lqr_2_1: |0>───┤ X ├────────┤ Z ├ └───┘ └───┘ lcr_0: 0 ════════════════════════ lcr_1: 0 ════════════════════════ """ qreg = QuantumRegister(5, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit3) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.z(self.left_qubit4) # inplace circuit_left = self.circuit_left.copy() circuit_left.compose(circuit_right, inplace=True) self.assertEqual(circuit_left, circuit_expected) def test_compose_inorder_smaller(self): """Composing with a smaller RHS dag, default order. ┌───┐ ┌─────┐ lqr_1_0: |0>───┤ H ├─── rqr_0: |0>──■──┤ Tdg ├ ├───┤ ┌─┴─┐└─────┘ lqr_1_1: |0>───┤ X ├─── rqr_1: |0>┤ X ├─────── ┌──┴───┴──┐ └───┘ lqr_1_2: |0>┤ U1(0.1) ├ + = └─────────┘ lqr_2_0: |0>─────■───── ┌─┴─┐ lqr_2_1: |0>───┤ X ├─── └───┘ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ ┌───┐ ┌─────┐ lqr_1_0: |0>───┤ H ├─────■──┤ Tdg ├ ├───┤ ┌─┴─┐└─────┘ lqr_1_1: |0>───┤ X ├───┤ X ├─────── ┌──┴───┴──┐└───┘ lqr_1_2: |0>┤ U1(0.1) ├──────────── └─────────┘ lqr_2_0: |0>─────■───────────────── ┌─┴─┐ lqr_2_1: |0>───┤ X ├─────────────── └───┘ lcr_0: 0 ══════════════════════════ lcr_1: 0 ══════════════════════════ """ qreg = QuantumRegister(2, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[1]) circuit_right.tdg(qreg[0]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit1) circuit_expected.tdg(self.left_qubit0) circuit_composed = self.circuit_left.compose(circuit_right) self.assertEqual(circuit_composed, circuit_expected) def test_compose_permuted(self): """Composing two dags of the same width, permuted wires. ┌───┐ lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■─────── ├───┤ │ ┌───┐ lqr_1_1: |0>──┤ X ├─── rqr_1: |0>──┼──┤ X ├ ┌─┴───┴──┐ │ ├───┤ lqr_1_2: |0>┤ P(0.1) ├ rqr_2: |0>──┼──┤ Y ├ └────────┘ ┌─┴─┐└───┘ lqr_2_0: |0>────■───── + rqr_3: |0>┤ X ├───── = ┌─┴─┐ └───┘┌───┐ lqr_2_1: |0>──┤ X ├─── rqr_4: |0>─────┤ Z ├ └───┘ └───┘ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ ┌───┐ ┌───┐ lqr_1_0: |0>──┤ H ├───┤ Z ├ ├───┤ ├───┤ lqr_1_1: |0>──┤ X ├───┤ X ├ ┌─┴───┴──┐├───┤ lqr_1_2: |0>┤ P(0.1) ├┤ Y ├ └────────┘└───┘ lqr_2_0: |0>────■───────■── ┌─┴─┐ ┌─┴─┐ lqr_2_1: |0>──┤ X ├───┤ X ├ └───┘ └───┘ lcr_0: 0 ══════════════════ lcr_1: 0 ══════════════════ """ qreg = QuantumRegister(5, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_expected = self.circuit_left.copy() circuit_expected.z(self.left_qubit0) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.cx(self.left_qubit3, self.left_qubit4) # permuted wiring circuit_composed = self.circuit_left.compose( circuit_right, qubits=[ self.left_qubit3, self.left_qubit1, self.left_qubit2, self.left_qubit4, self.left_qubit0, ], inplace=False, ) self.assertEqual(circuit_composed, circuit_expected) def test_compose_permuted_smaller(self): """Composing with a smaller RHS dag, and permuted wires. Compose using indices. ┌───┐ ┌─────┐ lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■──┤ Tdg ├ ├───┤ ┌─┴─┐└─────┘ lqr_1_1: |0>──┤ X ├─── rqr_1: |0>┤ X ├─────── ┌─┴───┴──┐ └───┘ lqr_1_2: |0>┤ P(0.1) ├ + = └────────┘ lqr_2_0: |0>────■───── ┌─┴─┐ lqr_2_1: |0>──┤ X ├─── └───┘ lcr_0: 0 ═════════════ lcr_1: 0 ═════════════ ┌───┐ lqr_1_0: |0>──┤ H ├─────────────── ├───┤ lqr_1_1: |0>──┤ X ├─────────────── ┌─┴───┴──┐┌───┐ lqr_1_2: |0>┤ P(0.1) ├┤ X ├─────── └────────┘└─┬─┘┌─────┐ lqr_2_0: |0>────■───────■──┤ Tdg ├ ┌─┴─┐ └─────┘ lqr_2_1: |0>──┤ X ├─────────────── └───┘ lcr_0: 0 ═════════════════════════ lcr_1: 0 ═════════════════════════ """ qreg = QuantumRegister(2, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[1]) circuit_right.tdg(qreg[0]) # permuted wiring of subset circuit_composed = self.circuit_left.compose(circuit_right, qubits=[3, 2]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit3, self.left_qubit2) circuit_expected.tdg(self.left_qubit3) self.assertEqual(circuit_composed, circuit_expected) def test_compose_classical(self): """Composing on classical bits. ┌───┐ ┌─────┐┌─┐ lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■──┤ Tdg ├┤M├ ├───┤ ┌─┴─┐└─┬─┬─┘└╥┘ lqr_1_1: |0>──┤ X ├─── rqr_1: |0>┤ X ├──┤M├───╫─ ┌─┴───┴──┐ └───┘ └╥┘ ║ lqr_1_2: |0>┤ P(0.1) ├ + rcr_0: 0 ════════╬════╩═ = └────────┘ ║ lqr_2_0: |0>────■───── rcr_1: 0 ════════╩══════ ┌─┴─┐ lqr_2_1: |0>──┤ X ├─── └───┘ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ ┌───┐ lqr_1_0: |0>──┤ H ├────────────────── ├───┤ ┌─────┐┌─┐ lqr_1_1: |0>──┤ X ├─────■──┤ Tdg ├┤M├ ┌─┴───┴──┐ │ └─────┘└╥┘ lqr_1_2: |0>┤ P(0.1) ├──┼──────────╫─ └────────┘ │ ║ lqr_2_0: |0>────■───────┼──────────╫─ ┌─┴─┐ ┌─┴─┐ ┌─┐ ║ lqr_2_1: |0>──┤ X ├───┤ X ├──┤M├───╫─ └───┘ └───┘ └╥┘ ║ lcr_0: 0 ══════════════════╩════╬═ ║ lcr_1: 0 ═══════════════════════╩═ """ qreg = QuantumRegister(2, "rqr") creg = ClassicalRegister(2, "rcr") circuit_right = QuantumCircuit(qreg, creg) circuit_right.cx(qreg[0], qreg[1]) circuit_right.tdg(qreg[0]) circuit_right.measure(qreg, creg) # permuted subset of qubits and clbits circuit_composed = self.circuit_left.compose(circuit_right, qubits=[1, 4], clbits=[1, 0]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit1, self.left_qubit4) circuit_expected.tdg(self.left_qubit1) circuit_expected.measure(self.left_qubit4, self.left_clbit0) circuit_expected.measure(self.left_qubit1, self.left_clbit1) self.assertEqual(circuit_composed, circuit_expected) def test_compose_conditional(self): """Composing on classical bits. ┌───┐ ┌───┐ ┌─┐ lqr_1_0: |0>──┤ H ├─── rqr_0: ────────┤ H ├─┤M├─── ├───┤ ┌───┐ └─┬─┘ └╥┘┌─┐ lqr_1_1: |0>──┤ X ├─── rqr_1: ─┤ X ├────┼────╫─┤M├ ┌─┴───┴──┐ └─┬─┘ │ ║ └╥┘ lqr_1_2: |0>┤ P(0.1) ├ + ┌──┴──┐┌──┴──┐ ║ ║ └────────┘ rcr_0: ╡ ╞╡ ╞═╩══╬═ lqr_2_0: |0>────■───── │ = 3 ││ = 3 │ ║ ┌─┴─┐ rcr_1: ╡ ╞╡ ╞════╩═ lqr_2_1: |0>──┤ X ├─── └─────┘└─────┘ └───┘ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ ┌───┐ lqr_1_0: ──┤ H ├─────────────────────── ├───┤ ┌───┐ ┌─┐ lqr_1_1: ──┤ X ├───────────┤ H ├────┤M├ ┌─┴───┴──┐ └─┬─┘ └╥┘ lqr_1_2: ┤ P(0.1) ├──────────┼───────╫─ └────────┘ │ ║ lqr_2_0: ────■───────────────┼───────╫─ ┌─┴─┐ ┌───┐ │ ┌─┐ ║ lqr_2_1: ──┤ X ├────┤ X ├────┼───┤M├─╫─ └───┘ └─┬─┘ │ └╥┘ ║ ┌──┴──┐┌──┴──┐ ║ ║ lcr_0: ════════════╡ ╞╡ ╞═╬══╩═ │ = 3 ││ = 3 │ ║ lcr_1: ════════════╡ ╞╡ ╞═╩════ └─────┘└─────┘ """ qreg = QuantumRegister(2, "rqr") creg = ClassicalRegister(2, "rcr") circuit_right = QuantumCircuit(qreg, creg) circuit_right.x(qreg[1]).c_if(creg, 3) circuit_right.h(qreg[0]).c_if(creg, 3) circuit_right.measure(qreg, creg) # permuted subset of qubits and clbits circuit_composed = self.circuit_left.compose(circuit_right, qubits=[1, 4], clbits=[0, 1]) circuit_expected = self.circuit_left.copy() circuit_expected.x(self.left_qubit4).c_if(*self.condition) circuit_expected.h(self.left_qubit1).c_if(*self.condition) circuit_expected.measure(self.left_qubit1, self.left_clbit0) circuit_expected.measure(self.left_qubit4, self.left_clbit1) self.assertEqual(circuit_composed, circuit_expected) def test_compose_conditional_no_match(self): """Test that compose correctly maps registers in conditions to the new circuit, even when there are no matching registers in the destination circuit. Regression test of gh-6583 and gh-6584.""" right = QuantumCircuit(QuantumRegister(3), ClassicalRegister(1), ClassicalRegister(1)) right.h(1) right.cx(1, 2) right.cx(0, 1) right.h(0) right.measure([0, 1], [0, 1]) right.z(2).c_if(right.cregs[0], 1) right.x(2).c_if(right.cregs[1], 1) test = QuantumCircuit(3, 3).compose(right, range(3), range(2)) z = next(ins.operation for ins in test.data[::-1] if ins.operation.name == "z") x = next(ins.operation for ins in test.data[::-1] if ins.operation.name == "x") # The registers should have been mapped, including the bits inside them. Unlike the # previous test, there are no matching registers in the destination circuit, so the # composition needs to add new registers (bit groupings) over the existing mapped bits. self.assertIsNot(z.condition, None) self.assertIsInstance(z.condition[0], ClassicalRegister) self.assertEqual(len(z.condition[0]), len(right.cregs[0])) self.assertIs(z.condition[0][0], test.clbits[0]) self.assertEqual(z.condition[1], 1) self.assertIsNot(x.condition, None) self.assertIsInstance(x.condition[0], ClassicalRegister) self.assertEqual(len(x.condition[0]), len(right.cregs[1])) self.assertEqual(z.condition[1], 1) self.assertIs(x.condition[0][0], test.clbits[1]) def test_compose_switch_match(self): """Test that composition containing a `switch` with a register that matches proceeds correctly.""" case_0 = QuantumCircuit(1, 2) case_0.x(0) case_1 = QuantumCircuit(1, 2) case_1.z(0) case_default = QuantumCircuit(1, 2) cr = ClassicalRegister(2, "target") right = QuantumCircuit(QuantumRegister(1), cr) right.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [0], [0, 1]) test = QuantumCircuit(QuantumRegister(3), cr, ClassicalRegister(2)).compose( right, [1], [0, 1] ) expected = test.copy_empty_like() expected.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [1], [0, 1]) self.assertEqual(test, expected) def test_compose_switch_no_match(self): """Test that composition containing a `switch` with a register that matches proceeds correctly.""" case_0 = QuantumCircuit(1, 2) case_0.x(0) case_1 = QuantumCircuit(1, 2) case_1.z(0) case_default = QuantumCircuit(1, 2) cr = ClassicalRegister(2, "target") right = QuantumCircuit(QuantumRegister(1), cr) right.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [0], [0, 1]) test = QuantumCircuit(3, 3).compose(right, [1], [0, 1]) self.assertEqual(len(test.data), 1) self.assertIsInstance(test.data[0].operation, SwitchCaseOp) target = test.data[0].operation.target self.assertIn(target, test.cregs) self.assertEqual(list(target), test.clbits[0:2]) def test_compose_gate(self): """Composing with a gate. ┌───┐ ┌───┐ ┌───┐ lqr_1_0: ──┤ H ├─── lqr_1_0: ──┤ H ├────┤ X ├ ├───┤ ├───┤ └─┬─┘ lqr_1_1: ──┤ X ├─── lqr_1_1: ──┤ X ├──────┼─── ┌─┴───┴──┐ ───■─── ┌─┴───┴──┐ │ lqr_1_2: ┤ P(0.1) ├ + ┌─┴─┐ = lqr_1_2: ┤ P(0.1) ├───┼─── └────────┘ ─┤ X ├─ └────────┘ │ lqr_2_0: ────■───── └───┘ lqr_2_0: ────■────────┼── ┌─┴─┐ ┌─┴─┐ │ lqr_2_1: ──┤ X ├─── lqr_2_1: ──┤ X ├──────■─── └───┘ └───┘ lcr_0: 0 ══════════ lcr_0: 0 ═════════════════ lcr_1: 0 ══════════ lcr_1: 0 ═════════════════ """ circuit_composed = self.circuit_left.compose(CXGate(), qubits=[4, 0]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit4, self.left_qubit0) self.assertEqual(circuit_composed, circuit_expected) def test_compose_calibrations(self): """Test that composing two circuits updates calibrations.""" circ_left = QuantumCircuit(1) circ_left.add_calibration("h", [0], None) circ_right = QuantumCircuit(1) circ_right.add_calibration("rx", [0], None) circ = circ_left.compose(circ_right) self.assertEqual(len(circ.calibrations), 2) self.assertEqual(len(circ_left.calibrations), 1) circ_left = QuantumCircuit(1) circ_left.add_calibration("h", [0], None) circ_right = QuantumCircuit(1) circ_right.add_calibration("h", [1], None) circ = circ_left.compose(circ_right) self.assertEqual(len(circ.calibrations), 1) self.assertEqual(len(circ.calibrations["h"]), 2) self.assertEqual(len(circ_left.calibrations), 1) # Ensure that transpiled _calibration is defaultdict qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc = transpile(qc, None, basis_gates=["h", "cx"], coupling_map=[[0, 1], [1, 0]]) qc.add_calibration("cx", [0, 1], Schedule()) def test_compose_one_liner(self): """Test building a circuit in one line, for fun.""" circ = QuantumCircuit(3) h = HGate() rz = RZGate(0.1) cx = CXGate() ccx = CCXGate() circ = circ.compose(h, [0]).compose(cx, [0, 2]).compose(ccx, [2, 1, 0]).compose(rz, [1]) expected = QuantumCircuit(3) expected.h(0) expected.cx(0, 2) expected.ccx(2, 1, 0) expected.rz(0.1, 1) self.assertEqual(circ, expected) def test_compose_global_phase(self): """Composing with global phase.""" circ1 = QuantumCircuit(1, global_phase=1) circ1.rz(0.5, 0) circ2 = QuantumCircuit(1, global_phase=2) circ3 = QuantumCircuit(1, global_phase=3) circ4 = circ1.compose(circ2).compose(circ3) self.assertEqual( circ4.global_phase, circ1.global_phase + circ2.global_phase + circ3.global_phase ) def test_compose_front_circuit(self): """Test composing a circuit at the front of a circuit.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) other = QuantumCircuit(2) other.cz(1, 0) other.z(1) output = qc.compose(other, front=True) expected = QuantumCircuit(2) expected.cz(1, 0) expected.z(1) expected.h(0) expected.cx(0, 1) self.assertEqual(output, expected) def test_compose_front_gate(self): """Test composing a gate at the front of a circuit.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) output = qc.compose(CXGate(), [1, 0], front=True) expected = QuantumCircuit(2) expected.cx(1, 0) expected.h(0) expected.cx(0, 1) self.assertEqual(output, expected) def test_compose_adds_parameters(self): """Test the composed circuit contains all parameters.""" a, b = Parameter("a"), Parameter("b") qc_a = QuantumCircuit(1) qc_a.rx(a, 0) qc_b = QuantumCircuit(1) qc_b.rx(b, 0) with self.subTest("compose with other circuit out-of-place"): qc_1 = qc_a.compose(qc_b) self.assertEqual(qc_1.parameters, {a, b}) with self.subTest("compose with other instruction out-of-place"): instr_b = qc_b.to_instruction() qc_2 = qc_a.compose(instr_b, [0]) self.assertEqual(qc_2.parameters, {a, b}) with self.subTest("compose with other circuit in-place"): qc_a.compose(qc_b, inplace=True) self.assertEqual(qc_a.parameters, {a, b}) def test_wrapped_compose(self): """Test wrapping the circuit upon composition works.""" qc_a = QuantumCircuit(1) qc_a.x(0) qc_b = QuantumCircuit(1, name="B") qc_b.h(0) qc_a.compose(qc_b, wrap=True, inplace=True) self.assertDictEqual(qc_a.count_ops(), {"B": 1, "x": 1}) self.assertDictEqual(qc_a.decompose().count_ops(), {"h": 1, "u3": 1}) def test_wrapping_unitary_circuit(self): """Test a unitary circuit will be wrapped as Gate, else as Instruction.""" qc_init = QuantumCircuit(1) qc_init.x(0) qc_unitary = QuantumCircuit(1, name="a") qc_unitary.ry(0.23, 0) qc_nonunitary = QuantumCircuit(1) qc_nonunitary.reset(0) with self.subTest("wrapping a unitary circuit"): qc = qc_init.compose(qc_unitary, wrap=True) self.assertIsInstance(qc.data[1].operation, Gate) with self.subTest("wrapping a non-unitary circuit"): qc = qc_init.compose(qc_nonunitary, wrap=True) self.assertIsInstance(qc.data[1].operation, Instruction) def test_single_bit_condition(self): """Test that compose can correctly handle circuits that contain conditions on single bits. This is a regression test of the bug that broke qiskit-experiments in gh-7653.""" base = QuantumCircuit(1, 1) base.x(0).c_if(0, True) test = QuantumCircuit(1, 1).compose(base) self.assertIsNot(base.clbits[0], test.clbits[0]) self.assertEqual(base, test) self.assertIs(test.data[0].operation.condition[0], test.clbits[0]) def test_condition_mapping_ifelseop(self): """Test that the condition in an `IfElseOp` is correctly mapped to a new set of bits and registers.""" base_loose = Clbit() base_creg = ClassicalRegister(2) base_qreg = QuantumRegister(1) base = QuantumCircuit(base_qreg, [base_loose], base_creg) with base.if_test((base_loose, True)): base.x(0) with base.if_test((base_creg, 3)): base.x(0) test_loose = Clbit() test_creg = ClassicalRegister(2) test_qreg = QuantumRegister(1) test = QuantumCircuit(test_qreg, [test_loose], test_creg).compose(base) bit_instruction = test.data[0].operation reg_instruction = test.data[1].operation self.assertIs(bit_instruction.condition[0], test_loose) self.assertEqual(bit_instruction.condition, (test_loose, True)) self.assertIs(reg_instruction.condition[0], test_creg) self.assertEqual(reg_instruction.condition, (test_creg, 3)) def test_condition_mapping_whileloopop(self): """Test that the condition in a `WhileLoopOp` is correctly mapped to a new set of bits and registers.""" base_loose = Clbit() base_creg = ClassicalRegister(2) base_qreg = QuantumRegister(1) base = QuantumCircuit(base_qreg, [base_loose], base_creg) with base.while_loop((base_loose, True)): base.x(0) with base.while_loop((base_creg, 3)): base.x(0) test_loose = Clbit() test_creg = ClassicalRegister(2) test_qreg = QuantumRegister(1) test = QuantumCircuit(test_qreg, [test_loose], test_creg).compose(base) bit_instruction = test.data[0].operation reg_instruction = test.data[1].operation self.assertIs(bit_instruction.condition[0], test_loose) self.assertEqual(bit_instruction.condition, (test_loose, True)) self.assertIs(reg_instruction.condition[0], test_creg) self.assertEqual(reg_instruction.condition, (test_creg, 3)) def test_compose_no_clbits_in_one(self): """Test combining a circuit with cregs to one without""" ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx") qc = QuantumCircuit(2) qc.measure_all() out = ansatz.compose(qc) self.assertEqual(out.clbits, qc.clbits) def test_compose_no_clbits_in_one_inplace(self): """Test combining a circuit with cregs to one without inplace""" ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx") qc = QuantumCircuit(2) qc.measure_all() ansatz.compose(qc, inplace=True) self.assertEqual(ansatz.clbits, qc.clbits) def test_compose_no_clbits_in_one_multireg(self): """Test combining a circuit with cregs to one without, multi cregs""" ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx") qa = QuantumRegister(2, "q") ca = ClassicalRegister(2, "a") cb = ClassicalRegister(2, "b") qc = QuantumCircuit(qa, ca, cb) qc.measure(0, cb[1]) out = ansatz.compose(qc) self.assertEqual(out.clbits, qc.clbits) self.assertEqual(out.cregs, qc.cregs) def test_compose_noclbits_registerless(self): """Combining a circuit with cregs to one without, registerless case""" inner = QuantumCircuit([Qubit(), Qubit()], [Clbit(), Clbit()]) inner.measure([0, 1], [0, 1]) outer = QuantumCircuit(2) outer.compose(inner, inplace=True) self.assertEqual(outer.clbits, inner.clbits) self.assertEqual(outer.cregs, []) def test_expr_condition_is_mapped(self): """Test that an expression in a condition involving several registers is mapped correctly to the destination circuit.""" inner = QuantumCircuit(1) inner.x(0) a_src = ClassicalRegister(2, "a_src") b_src = ClassicalRegister(2, "b_src") c_src = ClassicalRegister(name="c_src", bits=list(a_src) + list(b_src)) source = QuantumCircuit(QuantumRegister(1), a_src, b_src, c_src) test_1 = lambda: expr.lift(a_src[0]) test_2 = lambda: expr.logic_not(b_src[1]) test_3 = lambda: expr.logic_and(expr.bit_and(b_src, 2), expr.less(c_src, 7)) source.if_test(test_1(), inner.copy(), [0], []) source.if_else(test_2(), inner.copy(), inner.copy(), [0], []) source.while_loop(test_3(), inner.copy(), [0], []) a_dest = ClassicalRegister(2, "a_dest") b_dest = ClassicalRegister(2, "b_dest") dest = QuantumCircuit(QuantumRegister(1), a_dest, b_dest).compose(source) # Check that the input conditions weren't mutated. for in_condition, instruction in zip((test_1, test_2, test_3), source.data): self.assertEqual(in_condition(), instruction.operation.condition) # Should be `a_dest`, `b_dest` and an added one to account for `c_src`. self.assertEqual(len(dest.cregs), 3) mapped_reg = dest.cregs[-1] expected = QuantumCircuit(dest.qregs[0], a_dest, b_dest, mapped_reg) expected.if_test(expr.lift(a_dest[0]), inner.copy(), [0], []) expected.if_else(expr.logic_not(b_dest[1]), inner.copy(), inner.copy(), [0], []) expected.while_loop( expr.logic_and(expr.bit_and(b_dest, 2), expr.less(mapped_reg, 7)), inner.copy(), [0], [] ) self.assertEqual(dest, expected) def test_expr_target_is_mapped(self): """Test that an expression in a switch statement's target is mapping correctly to the destination circuit.""" inner1 = QuantumCircuit(1) inner1.x(0) inner2 = QuantumCircuit(1) inner2.z(0) a_src = ClassicalRegister(2, "a_src") b_src = ClassicalRegister(2, "b_src") c_src = ClassicalRegister(name="c_src", bits=list(a_src) + list(b_src)) source = QuantumCircuit(QuantumRegister(1), a_src, b_src, c_src) test_1 = lambda: expr.lift(a_src[0]) test_2 = lambda: expr.logic_not(b_src[1]) test_3 = lambda: expr.lift(b_src) test_4 = lambda: expr.bit_and(c_src, 7) source.switch(test_1(), [(False, inner1.copy()), (True, inner2.copy())], [0], []) source.switch(test_2(), [(False, inner1.copy()), (True, inner2.copy())], [0], []) source.switch(test_3(), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], []) source.switch(test_4(), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], []) a_dest = ClassicalRegister(2, "a_dest") b_dest = ClassicalRegister(2, "b_dest") dest = QuantumCircuit(QuantumRegister(1), a_dest, b_dest).compose(source) # Check that the input expressions weren't mutated. for in_target, instruction in zip((test_1, test_2, test_3, test_4), source.data): self.assertEqual(in_target(), instruction.operation.target) # Should be `a_dest`, `b_dest` and an added one to account for `c_src`. self.assertEqual(len(dest.cregs), 3) mapped_reg = dest.cregs[-1] expected = QuantumCircuit(dest.qregs[0], a_dest, b_dest, mapped_reg) expected.switch( expr.lift(a_dest[0]), [(False, inner1.copy()), (True, inner2.copy())], [0], [] ) expected.switch( expr.logic_not(b_dest[1]), [(False, inner1.copy()), (True, inner2.copy())], [0], [] ) expected.switch( expr.lift(b_dest), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], [] ) expected.switch( expr.bit_and(mapped_reg, 7), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], [], ) self.assertEqual(dest, expected) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Test Qiskit's controlled gate operation.""" import unittest from test import combine import numpy as np from numpy import pi from ddt import ddt, data, unpack from qiskit import QuantumRegister, QuantumCircuit, execute, BasicAer, QiskitError from qiskit.test import QiskitTestCase from qiskit.circuit import ControlledGate, Parameter, Gate from qiskit.circuit.exceptions import CircuitError from qiskit.quantum_info.operators.predicates import matrix_equal, is_unitary_matrix from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.states import Statevector import qiskit.circuit.add_control as ac from qiskit.transpiler.passes import Unroller from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_circuit import dag_to_circuit from qiskit.quantum_info import Operator from qiskit.circuit.library import ( CXGate, XGate, YGate, ZGate, U1Gate, CYGate, CZGate, CU1Gate, SwapGate, PhaseGate, CCXGate, HGate, RZGate, RXGate, CPhaseGate, RYGate, CRYGate, CRXGate, CSwapGate, UGate, U3Gate, CHGate, CRZGate, CU3Gate, CUGate, SXGate, CSXGate, MSGate, Barrier, RCCXGate, RC3XGate, MCU1Gate, MCXGate, MCXGrayCode, MCXRecursive, MCXVChain, C3XGate, C3SXGate, C4XGate, MCPhaseGate, GlobalPhaseGate, ) from qiskit.circuit._utils import _compute_control_matrix import qiskit.circuit.library.standard_gates as allGates from qiskit.extensions import UnitaryGate from qiskit.circuit.library.standard_gates.multi_control_rotation_gates import _mcsu2_real_diagonal from .gate_utils import _get_free_params @ddt class TestControlledGate(QiskitTestCase): """Tests for controlled gates and the ControlledGate class.""" def test_controlled_x(self): """Test creation of controlled x gate""" self.assertEqual(XGate().control(), CXGate()) def test_controlled_y(self): """Test creation of controlled y gate""" self.assertEqual(YGate().control(), CYGate()) def test_controlled_z(self): """Test creation of controlled z gate""" self.assertEqual(ZGate().control(), CZGate()) def test_controlled_h(self): """Test the creation of a controlled H gate.""" self.assertEqual(HGate().control(), CHGate()) def test_controlled_phase(self): """Test the creation of a controlled U1 gate.""" theta = 0.5 self.assertEqual(PhaseGate(theta).control(), CPhaseGate(theta)) def test_double_controlled_phase(self): """Test the creation of a controlled phase gate.""" theta = 0.5 self.assertEqual(PhaseGate(theta).control(2), MCPhaseGate(theta, 2)) def test_controlled_u1(self): """Test the creation of a controlled U1 gate.""" theta = 0.5 self.assertEqual(U1Gate(theta).control(), CU1Gate(theta)) circ = QuantumCircuit(1) circ.append(U1Gate(theta), circ.qregs[0]) unroller = Unroller(["cx", "u", "p"]) ctrl_circ_gate = dag_to_circuit(unroller.run(circuit_to_dag(circ))).control() ctrl_circ = QuantumCircuit(2) ctrl_circ.append(ctrl_circ_gate, ctrl_circ.qregs[0]) ctrl_circ = ctrl_circ.decompose().decompose() self.assertEqual(ctrl_circ.size(), 1) def test_controlled_rz(self): """Test the creation of a controlled RZ gate.""" theta = 0.5 self.assertEqual(RZGate(theta).control(), CRZGate(theta)) def test_control_parameters(self): """Test different ctrl_state formats for control function.""" theta = 0.5 self.assertEqual( CRYGate(theta).control(2, ctrl_state="01"), CRYGate(theta).control(2, ctrl_state=1) ) self.assertEqual( CRYGate(theta).control(2, ctrl_state=None), CRYGate(theta).control(2, ctrl_state=3) ) self.assertEqual(CCXGate().control(2, ctrl_state="01"), CCXGate().control(2, ctrl_state=1)) self.assertEqual(CCXGate().control(2, ctrl_state=None), CCXGate().control(2, ctrl_state=3)) def test_controlled_ry(self): """Test the creation of a controlled RY gate.""" theta = 0.5 self.assertEqual(RYGate(theta).control(), CRYGate(theta)) def test_controlled_rx(self): """Test the creation of a controlled RX gate.""" theta = 0.5 self.assertEqual(RXGate(theta).control(), CRXGate(theta)) def test_controlled_u(self): """Test the creation of a controlled U gate.""" theta, phi, lamb = 0.1, 0.2, 0.3 self.assertEqual(UGate(theta, phi, lamb).control(), CUGate(theta, phi, lamb, 0)) def test_controlled_u3(self): """Test the creation of a controlled U3 gate.""" theta, phi, lamb = 0.1, 0.2, 0.3 self.assertEqual(U3Gate(theta, phi, lamb).control(), CU3Gate(theta, phi, lamb)) circ = QuantumCircuit(1) circ.append(U3Gate(theta, phi, lamb), circ.qregs[0]) unroller = Unroller(["cx", "u", "p"]) ctrl_circ_gate = dag_to_circuit(unroller.run(circuit_to_dag(circ))).control() ctrl_circ = QuantumCircuit(2) ctrl_circ.append(ctrl_circ_gate, ctrl_circ.qregs[0]) ctrl_circ = ctrl_circ.decompose().decompose() self.assertEqual(ctrl_circ.size(), 1) def test_controlled_cx(self): """Test creation of controlled cx gate""" self.assertEqual(CXGate().control(), CCXGate()) def test_controlled_swap(self): """Test creation of controlled swap gate""" self.assertEqual(SwapGate().control(), CSwapGate()) def test_special_cases_equivalent_to_controlled_base_gate(self): """Test that ``ControlledGate`` subclasses for more efficient representations give equivalent matrices and definitions to the naive ``base_gate.control(n)``.""" # Angles used here are not important, we just pick slightly strange values to ensure that # there are no coincidental equivalences. tests = [ (CXGate(), 1), (CCXGate(), 2), (C3XGate(), 3), (C4XGate(), 4), (MCXGate(5), 5), (CYGate(), 1), (CZGate(), 1), (CPhaseGate(np.pi / 7), 1), (MCPhaseGate(np.pi / 7, 2), 2), (CSwapGate(), 1), (CSXGate(), 1), (C3SXGate(), 3), (CHGate(), 1), (CU1Gate(np.pi / 7), 1), (MCU1Gate(np.pi / 7, 2), 2), # `CUGate` takes an extra "global" phase parameter compared to `UGate`, and consequently # is only equal to `base_gate.control()` when this extra phase is 0. (CUGate(np.pi / 7, np.pi / 5, np.pi / 3, 0), 1), (CU3Gate(np.pi / 7, np.pi / 5, np.pi / 3), 1), (CRXGate(np.pi / 7), 1), (CRYGate(np.pi / 7), 1), (CRZGate(np.pi / 7), 1), ] for special_case_gate, n_controls in tests: with self.subTest(gate=special_case_gate.name): naive_operator = Operator(special_case_gate.base_gate.control(n_controls)) # Ensure that both the array form (if the gate overrides `__array__`) and the # circuit-definition form are tested. self.assertTrue(Operator(special_case_gate).equiv(naive_operator)) if not isinstance(special_case_gate, CXGate): # CX is treated like a primitive within Terra, and doesn't have a definition. self.assertTrue(Operator(special_case_gate.definition).equiv(naive_operator)) def test_global_phase_control(self): """Test creation of a GlobalPhaseGate.""" base = GlobalPhaseGate(np.pi / 7) expected_1q = PhaseGate(np.pi / 7) self.assertEqual(Operator(base.control()), Operator(expected_1q)) expected_2q = PhaseGate(np.pi / 7).control() self.assertEqual(Operator(base.control(2)), Operator(expected_2q)) expected_open = QuantumCircuit(1) expected_open.x(0) expected_open.p(np.pi / 7, 0) expected_open.x(0) self.assertEqual(Operator(base.control(ctrl_state=0)), Operator(expected_open)) def test_circuit_append(self): """Test appending a controlled gate to a quantum circuit.""" circ = QuantumCircuit(5) inst = CXGate() circ.append(inst.control(), qargs=[0, 2, 1]) circ.append(inst.control(2), qargs=[0, 3, 1, 2]) circ.append(inst.control().control(), qargs=[0, 3, 1, 2]) # should be same as above self.assertEqual(circ[1].operation, circ[2].operation) self.assertEqual(circ.depth(), 3) self.assertEqual(circ[0].operation.num_ctrl_qubits, 2) self.assertEqual(circ[1].operation.num_ctrl_qubits, 3) self.assertEqual(circ[2].operation.num_ctrl_qubits, 3) self.assertEqual(circ[0].operation.num_qubits, 3) self.assertEqual(circ[1].operation.num_qubits, 4) self.assertEqual(circ[2].operation.num_qubits, 4) for instr in circ: self.assertTrue(isinstance(instr.operation, ControlledGate)) def test_swap_definition_specification(self): """Test the instantiation of a controlled swap gate with explicit definition.""" swap = SwapGate() cswap = ControlledGate( "cswap", 3, [], num_ctrl_qubits=1, definition=swap.definition, base_gate=swap ) self.assertEqual(swap.definition, cswap.definition) def test_multi_controlled_composite_gate(self): """Test a multi controlled composite gate.""" num_ctrl = 3 # create composite gate sub_q = QuantumRegister(2) cgate = QuantumCircuit(sub_q, name="cgate") cgate.h(sub_q[0]) cgate.crz(pi / 2, sub_q[0], sub_q[1]) cgate.swap(sub_q[0], sub_q[1]) cgate.u(0.1, 0.2, 0.3, sub_q[1]) cgate.t(sub_q[0]) num_target = cgate.width() gate = cgate.to_gate() cont_gate = gate.control(num_ctrl_qubits=num_ctrl) control = QuantumRegister(num_ctrl) target = QuantumRegister(num_target) qc = QuantumCircuit(control, target) qc.append(cont_gate, control[:] + target[:]) op_mat = Operator(cgate).data cop_mat = _compute_control_matrix(op_mat, num_ctrl) ref_mat = Operator(qc).data self.assertTrue(matrix_equal(cop_mat, ref_mat)) def test_single_controlled_composite_gate(self): """Test a singly controlled composite gate.""" num_ctrl = 1 # create composite gate sub_q = QuantumRegister(2) cgate = QuantumCircuit(sub_q, name="cgate") cgate.h(sub_q[0]) cgate.cx(sub_q[0], sub_q[1]) num_target = cgate.width() gate = cgate.to_gate() cont_gate = gate.control(num_ctrl_qubits=num_ctrl) control = QuantumRegister(num_ctrl, "control") target = QuantumRegister(num_target, "target") qc = QuantumCircuit(control, target) qc.append(cont_gate, control[:] + target[:]) op_mat = Operator(cgate).data cop_mat = _compute_control_matrix(op_mat, num_ctrl) ref_mat = Operator(qc).data self.assertTrue(matrix_equal(cop_mat, ref_mat)) def test_control_open_controlled_gate(self): """Test control(2) vs control.control where inner gate has open controls.""" gate1pre = ZGate().control(1, ctrl_state=0) gate1 = gate1pre.control(1, ctrl_state=1) gate2 = ZGate().control(2, ctrl_state=1) expected = Operator(_compute_control_matrix(ZGate().to_matrix(), 2, ctrl_state=1)) self.assertEqual(expected, Operator(gate1)) self.assertEqual(expected, Operator(gate2)) def test_multi_control_z(self): """Test a multi controlled Z gate.""" qc = QuantumCircuit(1) qc.z(0) ctr_gate = qc.to_gate().control(2) ctr_circ = QuantumCircuit(3) ctr_circ.append(ctr_gate, range(3)) ref_circ = QuantumCircuit(3) ref_circ.h(2) ref_circ.ccx(0, 1, 2) ref_circ.h(2) self.assertEqual(ctr_circ.decompose(), ref_circ) def test_multi_control_u3(self): """Test the matrix representation of the controlled and controlled-controlled U3 gate.""" from qiskit.circuit.library.standard_gates import u3 num_ctrl = 3 # U3 gate params alpha, beta, gamma = 0.2, 0.3, 0.4 u3gate = u3.U3Gate(alpha, beta, gamma) cu3gate = u3.CU3Gate(alpha, beta, gamma) # cnu3 gate cnu3 = u3gate.control(num_ctrl) width = cnu3.num_qubits qr = QuantumRegister(width) qcnu3 = QuantumCircuit(qr) qcnu3.append(cnu3, qr, []) # U3 gate qu3 = QuantumCircuit(1) qu3.append(u3gate, [0]) # CU3 gate qcu3 = QuantumCircuit(2) qcu3.append(cu3gate, [0, 1]) # c-cu3 gate width = 3 qr = QuantumRegister(width) qc_cu3 = QuantumCircuit(qr) c_cu3 = cu3gate.control(1) qc_cu3.append(c_cu3, qr, []) # Circuit unitaries mat_cnu3 = Operator(qcnu3).data mat_u3 = Operator(qu3).data mat_cu3 = Operator(qcu3).data mat_c_cu3 = Operator(qc_cu3).data # Target Controlled-U3 unitary target_cnu3 = _compute_control_matrix(mat_u3, num_ctrl) target_cu3 = np.kron(mat_u3, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0])) target_c_cu3 = np.kron(mat_cu3, np.diag([0, 1])) + np.kron(np.eye(4), np.diag([1, 0])) tests = [ ("check unitary of u3.control against tensored unitary of u3", target_cu3, mat_cu3), ( "check unitary of cu3.control against tensored unitary of cu3", target_c_cu3, mat_c_cu3, ), ("check unitary of cnu3 against tensored unitary of u3", target_cnu3, mat_cnu3), ] for itest in tests: info, target, decomp = itest[0], itest[1], itest[2] with self.subTest(i=info): self.assertTrue(matrix_equal(target, decomp, atol=1e-8, rtol=1e-5)) def test_multi_control_u1(self): """Test the matrix representation of the controlled and controlled-controlled U1 gate.""" from qiskit.circuit.library.standard_gates import u1 num_ctrl = 3 # U1 gate params theta = 0.2 u1gate = u1.U1Gate(theta) cu1gate = u1.CU1Gate(theta) # cnu1 gate cnu1 = u1gate.control(num_ctrl) width = cnu1.num_qubits qr = QuantumRegister(width) qcnu1 = QuantumCircuit(qr) qcnu1.append(cnu1, qr, []) # U1 gate qu1 = QuantumCircuit(1) qu1.append(u1gate, [0]) # CU1 gate qcu1 = QuantumCircuit(2) qcu1.append(cu1gate, [0, 1]) # c-cu1 gate width = 3 qr = QuantumRegister(width) qc_cu1 = QuantumCircuit(qr) c_cu1 = cu1gate.control(1) qc_cu1.append(c_cu1, qr, []) job = execute( [qcnu1, qu1, qcu1, qc_cu1], BasicAer.get_backend("unitary_simulator"), basis_gates=["u1", "u2", "u3", "id", "cx"], ) result = job.result() # Circuit unitaries mat_cnu1 = result.get_unitary(0) # trace out ancillae mat_u1 = result.get_unitary(1) mat_cu1 = result.get_unitary(2) mat_c_cu1 = result.get_unitary(3) # Target Controlled-U1 unitary target_cnu1 = _compute_control_matrix(mat_u1, num_ctrl) target_cu1 = np.kron(mat_u1, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0])) target_c_cu1 = np.kron(mat_cu1, np.diag([0, 1])) + np.kron(np.eye(4), np.diag([1, 0])) tests = [ ("check unitary of u1.control against tensored unitary of u1", target_cu1, mat_cu1), ( "check unitary of cu1.control against tensored unitary of cu1", target_c_cu1, mat_c_cu1, ), ("check unitary of cnu1 against tensored unitary of u1", target_cnu1, mat_cnu1), ] for itest in tests: info, target, decomp = itest[0], itest[1], itest[2] with self.subTest(i=info): self.log.info(info) self.assertTrue(matrix_equal(target, decomp)) @data(1, 2, 3, 4) def test_multi_controlled_u1_matrix(self, num_controls): """Test the matrix representation of the multi-controlled CU1 gate. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcu1.py """ # registers for the circuit q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) # iterate over all possible combinations of control qubits for ctrl_state in range(2**num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] lam = 0.3165354 * pi qc = QuantumCircuit(q_controls, q_target) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) qc.mcp(lam, q_controls, q_target[0]) # for idx in subset: for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) base = PhaseGate(lam).to_matrix() expected = _compute_control_matrix(base, num_controls, ctrl_state=ctrl_state) with self.subTest(msg=f"control state = {ctrl_state}"): self.assertTrue(matrix_equal(simulated, expected)) @data(1, 2, 3, 4) def test_multi_control_toffoli_matrix_clean_ancillas(self, num_controls): """Test the multi-control Toffoli gate with clean ancillas. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ # set up circuit q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) if num_controls > 2: num_ancillas = num_controls - 2 q_ancillas = QuantumRegister(num_controls) qc.add_register(q_ancillas) else: num_ancillas = 0 q_ancillas = None # apply hadamard on control qubits and toffoli gate qc.mct(q_controls, q_target[0], q_ancillas, mode="basic") # execute the circuit and obtain statevector result backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) # compare to expectation if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected)) @data(1, 2, 3, 4, 5) def test_multi_control_toffoli_matrix_basic_dirty_ancillas(self, num_controls): """Test the multi-control Toffoli gate with dirty ancillas (basic-dirty-ancilla). Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) q_ancillas = None if num_controls <= 2: num_ancillas = 0 else: num_ancillas = num_controls - 2 q_ancillas = QuantumRegister(num_ancillas) qc.add_register(q_ancillas) qc.mct(q_controls, q_target[0], q_ancillas, mode="basic-dirty-ancilla") simulated = execute(qc, BasicAer.get_backend("unitary_simulator")).result().get_unitary(qc) if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected, atol=1e-8)) @data(1, 2, 3, 4, 5) def test_multi_control_toffoli_matrix_advanced_dirty_ancillas(self, num_controls): """Test the multi-control Toffoli gate with dirty ancillas (advanced). Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) q_ancillas = None if num_controls <= 4: num_ancillas = 0 else: num_ancillas = 1 q_ancillas = QuantumRegister(num_ancillas) qc.add_register(q_ancillas) qc.mct(q_controls, q_target[0], q_ancillas, mode="advanced") simulated = execute(qc, BasicAer.get_backend("unitary_simulator")).result().get_unitary(qc) if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected, atol=1e-8)) @data(1, 2, 3) def test_multi_control_toffoli_matrix_noancilla_dirty_ancillas(self, num_controls): """Test the multi-control Toffoli gate with dirty ancillas (noancilla). Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) qc.mct(q_controls, q_target[0], None, mode="noancilla") simulated = execute(qc, BasicAer.get_backend("unitary_simulator")).result().get_unitary(qc) base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected, atol=1e-8)) def test_mcsu2_real_diagonal(self): """Test mcsu2_real_diagonal""" num_ctrls = 6 theta = 0.3 ry_matrix = RYGate(theta).to_matrix() qc = _mcsu2_real_diagonal(ry_matrix, num_ctrls) mcry_matrix = _compute_control_matrix(ry_matrix, 6) self.assertTrue(np.allclose(mcry_matrix, Operator(qc).to_matrix())) @combine(num_controls=[1, 2, 4], base_gate_name=["x", "y", "z"], use_basis_gates=[True, False]) def test_multi_controlled_rotation_gate_matrices( self, num_controls, base_gate_name, use_basis_gates ): """Test the multi controlled rotation gates without ancillas. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcr.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) # iterate over all possible combinations of control qubits for ctrl_state in range(2**num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] theta = 0.871236 * pi qc = QuantumCircuit(q_controls, q_target) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) # call mcrx/mcry/mcrz if base_gate_name == "y": qc.mcry( theta, q_controls, q_target[0], None, mode="noancilla", use_basis_gates=use_basis_gates, ) else: # case 'x' or 'z' only support the noancilla mode and do not have this keyword getattr(qc, "mcr" + base_gate_name)( theta, q_controls, q_target[0], use_basis_gates=use_basis_gates ) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) if use_basis_gates: with self.subTest(msg="check only basis gates used"): gates_used = set(qc.count_ops().keys()) self.assertTrue(gates_used.issubset({"x", "u", "p", "cx"})) backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) if base_gate_name == "x": rot_mat = RXGate(theta).to_matrix() elif base_gate_name == "y": rot_mat = RYGate(theta).to_matrix() else: # case 'z' rot_mat = RZGate(theta).to_matrix() expected = _compute_control_matrix(rot_mat, num_controls, ctrl_state=ctrl_state) with self.subTest(msg=f"control state = {ctrl_state}"): self.assertTrue(matrix_equal(simulated, expected)) @combine(num_controls=[1, 2, 4], use_basis_gates=[True, False]) def test_multi_controlled_y_rotation_matrix_basic_mode(self, num_controls, use_basis_gates): """Test the multi controlled Y rotation using the mode 'basic'. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcr.py """ # get the number of required ancilla qubits if num_controls <= 2: num_ancillas = 0 else: num_ancillas = num_controls - 2 q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) for ctrl_state in range(2**num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] theta = 0.871236 * pi if num_ancillas > 0: q_ancillas = QuantumRegister(num_ancillas) qc = QuantumCircuit(q_controls, q_target, q_ancillas) else: qc = QuantumCircuit(q_controls, q_target) q_ancillas = None for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) qc.mcry( theta, q_controls, q_target[0], q_ancillas, mode="basic", use_basis_gates=use_basis_gates, ) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) rot_mat = RYGate(theta).to_matrix() backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] expected = _compute_control_matrix(rot_mat, num_controls, ctrl_state=ctrl_state) with self.subTest(msg=f"control state = {ctrl_state}"): self.assertTrue(matrix_equal(simulated, expected)) def test_mcry_defaults_to_vchain(self): """Test mcry defaults to the v-chain mode if sufficient work qubits are provided.""" circuit = QuantumCircuit(5) control_qubits = circuit.qubits[:3] target_qubit = circuit.qubits[3] additional_qubits = circuit.qubits[4:] circuit.mcry(0.2, control_qubits, target_qubit, additional_qubits) # If the v-chain mode is selected, all qubits are used. If the noancilla mode would be # selected, the bottom qubit would remain unused. dag = circuit_to_dag(circuit) self.assertEqual(len(list(dag.idle_wires())), 0) @data(1, 2) def test_mcx_gates_yield_explicit_gates(self, num_ctrl_qubits): """Test the creating a MCX gate yields the explicit definition if we know it.""" cls = MCXGate(num_ctrl_qubits).__class__ explicit = {1: CXGate, 2: CCXGate} self.assertEqual(cls, explicit[num_ctrl_qubits]) @data(1, 2, 3, 4) def test_mcxgraycode_gates_yield_explicit_gates(self, num_ctrl_qubits): """Test creating an mcx gate calls MCXGrayCode and yeilds explicit definition.""" qc = QuantumCircuit(num_ctrl_qubits + 1) qc.mcx(list(range(num_ctrl_qubits)), [num_ctrl_qubits]) explicit = {1: CXGate, 2: CCXGate, 3: C3XGate, 4: C4XGate} self.assertEqual(type(qc[0].operation), explicit[num_ctrl_qubits]) @data(3, 4, 5, 8) def test_mcx_gates(self, num_ctrl_qubits): """Test the mcx gates.""" backend = BasicAer.get_backend("statevector_simulator") reference = np.zeros(2 ** (num_ctrl_qubits + 1)) reference[-1] = 1 for gate in [ MCXGrayCode(num_ctrl_qubits), MCXRecursive(num_ctrl_qubits), MCXVChain(num_ctrl_qubits, False), MCXVChain(num_ctrl_qubits, True), ]: with self.subTest(gate=gate): circuit = QuantumCircuit(gate.num_qubits) if num_ctrl_qubits > 0: circuit.x(list(range(num_ctrl_qubits))) circuit.append(gate, list(range(gate.num_qubits)), []) statevector = execute(circuit, backend).result().get_statevector() # account for ancillas if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0: corrected = np.zeros(2 ** (num_ctrl_qubits + 1), dtype=complex) for i, statevector_amplitude in enumerate(statevector): i = int(bin(i)[2:].zfill(circuit.num_qubits)[gate.num_ancilla_qubits :], 2) corrected[i] += statevector_amplitude statevector = corrected np.testing.assert_array_almost_equal(statevector.real, reference) @data(1, 2, 3, 4) def test_inverse_x(self, num_ctrl_qubits): """Test inverting the controlled X gate.""" cnx = XGate().control(num_ctrl_qubits) inv_cnx = cnx.inverse() result = Operator(cnx).compose(Operator(inv_cnx)) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0])) @data(1, 2, 3) def test_inverse_gate(self, num_ctrl_qubits): """Test inverting a controlled gate based on a circuit definition.""" qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cx(1, 2) qc.rx(np.pi / 4, [0, 1, 2]) gate = qc.to_gate() cgate = gate.control(num_ctrl_qubits) inv_cgate = cgate.inverse() result = Operator(cgate).compose(Operator(inv_cgate)) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0])) @data(1, 2, 3) def test_inverse_circuit(self, num_ctrl_qubits): """Test inverting a controlled gate based on a circuit definition.""" qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cx(1, 2) qc.rx(np.pi / 4, [0, 1, 2]) cqc = qc.control(num_ctrl_qubits) cqc_inv = cqc.inverse() result = Operator(cqc).compose(Operator(cqc_inv)) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0])) @data(1, 2, 3, 4, 5) def test_controlled_unitary(self, num_ctrl_qubits): """Test the matrix data of an Operator, which is based on a controlled gate.""" num_target = 1 q_target = QuantumRegister(num_target) qc1 = QuantumCircuit(q_target) # for h-rx(pi/2) theta, phi, lamb = 1.57079632679490, 0.0, 4.71238898038469 qc1.u(theta, phi, lamb, q_target[0]) base_gate = qc1.to_gate() # get UnitaryGate version of circuit base_op = Operator(qc1) base_mat = base_op.data cgate = base_gate.control(num_ctrl_qubits) test_op = Operator(cgate) cop_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertTrue(is_unitary_matrix(base_mat)) self.assertTrue(matrix_equal(cop_mat, test_op.data)) @data(1, 2, 3, 4, 5) def test_controlled_random_unitary(self, num_ctrl_qubits): """Test the matrix data of an Operator based on a random UnitaryGate.""" num_target = 2 base_gate = random_unitary(2**num_target).to_instruction() base_mat = base_gate.to_matrix() cgate = base_gate.control(num_ctrl_qubits) test_op = Operator(cgate) cop_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertTrue(matrix_equal(cop_mat, test_op.data)) @combine(num_ctrl_qubits=[1, 2, 3], ctrl_state=[0, None]) def test_open_controlled_unitary_z(self, num_ctrl_qubits, ctrl_state): """Test that UnitaryGate with control returns params.""" umat = np.array([[1, 0], [0, -1]]) ugate = UnitaryGate(umat) cugate = ugate.control(num_ctrl_qubits, ctrl_state=ctrl_state) ref_mat = _compute_control_matrix(umat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cugate), Operator(ref_mat)) def test_controlled_controlled_rz(self): """Test that UnitaryGate with control returns params.""" qc = QuantumCircuit(1) qc.rz(0.2, 0) controlled = QuantumCircuit(2) controlled.compose(qc.control(), inplace=True) self.assertEqual(Operator(controlled), Operator(CRZGate(0.2))) self.assertEqual(Operator(controlled), Operator(RZGate(0.2).control())) def test_controlled_controlled_unitary(self): """Test that global phase in iso decomposition of unitary is handled.""" umat = np.array([[1, 0], [0, -1]]) ugate = UnitaryGate(umat) cugate = ugate.control() ccugate = cugate.control() ccugate2 = ugate.control(2) ref_mat = _compute_control_matrix(umat, 2) self.assertTrue(Operator(ccugate2).equiv(Operator(ref_mat))) self.assertTrue(Operator(ccugate).equiv(Operator(ccugate2))) @data(1, 2, 3) def test_open_controlled_unitary_matrix(self, num_ctrl_qubits): """test open controlled unitary matrix""" # verify truth table num_target_qubits = 2 num_qubits = num_ctrl_qubits + num_target_qubits target_op = Operator(XGate()) for i in range(num_target_qubits - 1): target_op = target_op.tensor(XGate()) for i in range(2**num_qubits): input_bitstring = bin(i)[2:].zfill(num_qubits) input_target = input_bitstring[0:num_target_qubits] input_ctrl = input_bitstring[-num_ctrl_qubits:] phi = Statevector.from_label(input_bitstring) cop = Operator( _compute_control_matrix(target_op.data, num_ctrl_qubits, ctrl_state=input_ctrl) ) for j in range(2**num_qubits): output_bitstring = bin(j)[2:].zfill(num_qubits) output_target = output_bitstring[0:num_target_qubits] output_ctrl = output_bitstring[-num_ctrl_qubits:] psi = Statevector.from_label(output_bitstring) cxout = np.dot(phi.data, psi.evolve(cop).data) if input_ctrl == output_ctrl: # flip the target bits cond_output = "".join([str(int(not int(a))) for a in input_target]) else: cond_output = input_target if cxout == 1: self.assertTrue((output_ctrl == input_ctrl) and (output_target == cond_output)) else: self.assertTrue( ((output_ctrl == input_ctrl) and (output_target != cond_output)) or output_ctrl != input_ctrl ) def test_open_control_cx_unrolling(self): """test unrolling of open control gates when gate is in basis""" qc = QuantumCircuit(2) qc.cx(0, 1, ctrl_state=0) dag = circuit_to_dag(qc) unroller = Unroller(["u3", "cx"]) uqc = dag_to_circuit(unroller.run(dag)) ref_circuit = QuantumCircuit(2) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) ref_circuit.cx(0, 1) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) self.assertEqual(uqc, ref_circuit) def test_open_control_cy_unrolling(self): """test unrolling of open control gates when gate is in basis""" qc = QuantumCircuit(2) qc.cy(0, 1, ctrl_state=0) dag = circuit_to_dag(qc) unroller = Unroller(["u3", "cy"]) uqc = dag_to_circuit(unroller.run(dag)) ref_circuit = QuantumCircuit(2) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) ref_circuit.cy(0, 1) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) self.assertEqual(uqc, ref_circuit) def test_open_control_ccx_unrolling(self): """test unrolling of open control gates when gate is in basis""" qreg = QuantumRegister(3) qc = QuantumCircuit(qreg) ccx = CCXGate(ctrl_state=0) qc.append(ccx, [0, 1, 2]) dag = circuit_to_dag(qc) unroller = Unroller(["x", "ccx"]) unrolled_dag = unroller.run(dag) # ┌───┐ ┌───┐ # q0_0: ┤ X ├──■──┤ X ├ # ├───┤ │ ├───┤ # q0_1: ┤ X ├──■──┤ X ├ # └───┘┌─┴─┐└───┘ # q0_2: ─────┤ X ├───── # └───┘ ref_circuit = QuantumCircuit(qreg) ref_circuit.x(qreg[0]) ref_circuit.x(qreg[1]) ref_circuit.ccx(qreg[0], qreg[1], qreg[2]) ref_circuit.x(qreg[0]) ref_circuit.x(qreg[1]) ref_dag = circuit_to_dag(ref_circuit) self.assertEqual(unrolled_dag, ref_dag) def test_ccx_ctrl_state_consistency(self): """Test the consistency of parameters ctrl_state in CCX See issue: https://github.com/Qiskit/qiskit-terra/issues/6465 """ qreg = QuantumRegister(3) qc = QuantumCircuit(qreg) qc.ccx(qreg[0], qreg[1], qreg[2], ctrl_state=0) ref_circuit = QuantumCircuit(qreg) ccx = CCXGate(ctrl_state=0) ref_circuit.append(ccx, [qreg[0], qreg[1], qreg[2]]) self.assertEqual(qc, ref_circuit) def test_open_control_composite_unrolling(self): """test unrolling of open control gates when gate is in basis""" # create composite gate qreg = QuantumRegister(2) qcomp = QuantumCircuit(qreg, name="bell") qcomp.h(qreg[0]) qcomp.cx(qreg[0], qreg[1]) bell = qcomp.to_gate() # create controlled composite gate cqreg = QuantumRegister(3) qc = QuantumCircuit(cqreg) qc.append(bell.control(ctrl_state=0), qc.qregs[0][:]) dag = circuit_to_dag(qc) unroller = Unroller(["x", "u1", "cbell"]) unrolled_dag = unroller.run(dag) # create reference circuit ref_circuit = QuantumCircuit(cqreg) ref_circuit.x(cqreg[0]) ref_circuit.append(bell.control(), [cqreg[0], cqreg[1], cqreg[2]]) ref_circuit.x(cqreg[0]) ref_dag = circuit_to_dag(ref_circuit) self.assertEqual(unrolled_dag, ref_dag) @data(*ControlledGate.__subclasses__()) def test_standard_base_gate_setting(self, gate_class): """Test all gates in standard extensions which are of type ControlledGate and have a base gate setting. """ num_free_params = len(_get_free_params(gate_class.__init__, ignore=["self"])) free_params = [0.1 * i for i in range(num_free_params)] if gate_class in [MCU1Gate, MCPhaseGate]: free_params[1] = 3 elif gate_class in [MCXGate]: free_params[0] = 3 base_gate = gate_class(*free_params) cgate = base_gate.control() # the base gate of CU is U (3 params), the base gate of CCU is CU (4 params) if gate_class == CUGate: self.assertListEqual(cgate.base_gate.params[:3], base_gate.base_gate.params[:3]) else: self.assertEqual(base_gate.base_gate, cgate.base_gate) @combine( gate=[cls for cls in allGates.__dict__.values() if isinstance(cls, type)], num_ctrl_qubits=[1, 2], ctrl_state=[None, 0, 1], ) def test_all_inverses(self, gate, num_ctrl_qubits, ctrl_state): """Test all gates in standard extensions except those that cannot be controlled or are being deprecated. """ if not (issubclass(gate, ControlledGate) or issubclass(gate, allGates.IGate)): # only verify basic gates right now, as already controlled ones # will generate differing definitions try: numargs = len(_get_free_params(gate)) args = [2] * numargs gate = gate(*args) self.assertEqual( gate.inverse().control(num_ctrl_qubits, ctrl_state=ctrl_state), gate.control(num_ctrl_qubits, ctrl_state=ctrl_state).inverse(), ) except AttributeError: # skip gates that do not have a control attribute (e.g. barrier) pass @data(2, 3) def test_relative_phase_toffoli_gates(self, num_ctrl_qubits): """Test the relative phase Toffoli gates. This test compares the matrix representation of the relative phase gate classes (i.e. RCCXGate().to_matrix()), the matrix obtained from the unitary simulator, and the exact version of the gate as obtained through `_compute_control_matrix`. """ # get target matrix (w/o relative phase) base_mat = XGate().to_matrix() target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) # build the matrix for the relative phase toffoli using the unitary simulator circuit = QuantumCircuit(num_ctrl_qubits + 1) if num_ctrl_qubits == 2: circuit.rccx(0, 1, 2) else: # num_ctrl_qubits == 3: circuit.rcccx(0, 1, 2, 3) simulator = BasicAer.get_backend("unitary_simulator") simulated_mat = execute(circuit, simulator).result().get_unitary() # get the matrix representation from the class itself if num_ctrl_qubits == 2: repr_mat = RCCXGate().to_matrix() else: # num_ctrl_qubits == 3: repr_mat = RC3XGate().to_matrix() # test up to phase # note, that all entries may have an individual phase! (as opposed to a global phase) self.assertTrue(matrix_equal(np.abs(simulated_mat), target_mat)) # compare simulated matrix with the matrix representation provided by the class self.assertTrue(matrix_equal(simulated_mat, repr_mat)) def test_open_controlled_gate(self): """ Test controlled gates with control on '0' """ base_gate = XGate() base_mat = base_gate.to_matrix() num_ctrl_qubits = 3 ctrl_state = 5 cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = None cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = 0 cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = 7 cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = "110" cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) def test_open_controlled_gate_raises(self): """ Test controlled gates with open controls raises if ctrl_state isn't allowed. """ base_gate = XGate() num_ctrl_qubits = 3 with self.assertRaises(CircuitError): base_gate.control(num_ctrl_qubits, ctrl_state=-1) with self.assertRaises(CircuitError): base_gate.control(num_ctrl_qubits, ctrl_state=2**num_ctrl_qubits) with self.assertRaises(CircuitError): base_gate.control(num_ctrl_qubits, ctrl_state="201") def test_base_gate_params_reference(self): """ Test all gates in standard extensions which are of type ControlledGate and have a base gate setting have params which reference the one in their base gate. """ num_ctrl_qubits = 1 for gate_class in ControlledGate.__subclasses__(): with self.subTest(i=repr(gate_class)): num_free_params = len(_get_free_params(gate_class.__init__, ignore=["self"])) free_params = [0.1 * (i + 1) for i in range(num_free_params)] if gate_class in [MCU1Gate, MCPhaseGate]: free_params[1] = 3 elif gate_class in [MCXGate]: free_params[0] = 3 base_gate = gate_class(*free_params) if base_gate.params: cgate = base_gate.control(num_ctrl_qubits) self.assertIs(cgate.base_gate.params, cgate.params) def test_assign_parameters(self): """Test assigning parameters to quantum circuit with controlled gate.""" qc = QuantumCircuit(2, name="assign") ptest = Parameter("p") gate = CRYGate(ptest) qc.append(gate, [0, 1]) subs1, subs2 = {ptest: Parameter("a")}, {ptest: Parameter("b")} bound1 = qc.assign_parameters(subs1, inplace=False) bound2 = qc.assign_parameters(subs2, inplace=False) self.assertEqual(qc.parameters, {ptest}) self.assertEqual(bound1.parameters, {subs1[ptest]}) self.assertEqual(bound2.parameters, {subs2[ptest]}) @data(-1, 0, 1.4, "1", 4, 10) def test_improper_num_ctrl_qubits(self, num_ctrl_qubits): """ Test improperly specified num_ctrl_qubits. """ num_qubits = 4 with self.assertRaises(CircuitError): ControlledGate( name="cgate", num_qubits=num_qubits, params=[], num_ctrl_qubits=num_ctrl_qubits ) def test_improper_num_ctrl_qubits_base_gate(self): """Test that the allowed number of control qubits takes the base gate into account.""" with self.assertRaises(CircuitError): ControlledGate( name="cx?", num_qubits=2, params=[], num_ctrl_qubits=2, base_gate=XGate() ) self.assertIsInstance( ControlledGate( name="cx?", num_qubits=2, params=[], num_ctrl_qubits=1, base_gate=XGate() ), ControlledGate, ) self.assertIsInstance( ControlledGate( name="p", num_qubits=1, params=[np.pi], num_ctrl_qubits=1, base_gate=Gate("gphase", 0, [np.pi]), ), ControlledGate, ) def test_open_controlled_equality(self): """ Test open controlled gates are equal if their base gates and control states are equal. """ self.assertEqual(XGate().control(1), XGate().control(1)) self.assertNotEqual(XGate().control(1), YGate().control(1)) self.assertNotEqual(XGate().control(1), XGate().control(2)) self.assertEqual(XGate().control(1, ctrl_state="0"), XGate().control(1, ctrl_state="0")) self.assertNotEqual(XGate().control(1, ctrl_state="0"), XGate().control(1, ctrl_state="1")) def test_cx_global_phase(self): """ Test controlling CX with global phase """ theta = pi / 2 circ = QuantumCircuit(2, global_phase=theta) circ.cx(0, 1) cx = circ.to_gate() self.assertNotEqual(Operator(CXGate()), Operator(cx)) ccx = cx.control(1) base_mat = Operator(cx).data target = _compute_control_matrix(base_mat, 1) self.assertEqual(Operator(ccx), Operator(target)) expected = QuantumCircuit(*ccx.definition.qregs) expected.ccx(0, 1, 2) expected.p(theta, 0) self.assertEqual(ccx.definition, expected) @data(1, 2) def test_controlled_global_phase(self, num_ctrl_qubits): """ Test controlled global phase on base gate. """ theta = pi / 4 circ = QuantumCircuit(2, global_phase=theta) base_gate = circ.to_gate() base_mat = Operator(base_gate).data target = _compute_control_matrix(base_mat, num_ctrl_qubits) cgate = base_gate.control(num_ctrl_qubits) ccirc = circ.control(num_ctrl_qubits) self.assertEqual(Operator(cgate), Operator(target)) self.assertEqual(Operator(ccirc), Operator(target)) @data(1, 2) def test_rz_composite_global_phase(self, num_ctrl_qubits): """ Test controlling CX with global phase """ theta = pi / 4 circ = QuantumCircuit(2, global_phase=theta) circ.rz(0.1, 0) circ.rz(0.2, 1) ccirc = circ.control(num_ctrl_qubits) base_gate = circ.to_gate() cgate = base_gate.control(num_ctrl_qubits) base_mat = Operator(base_gate).data target = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertEqual(Operator(cgate), Operator(target)) self.assertEqual(Operator(ccirc), Operator(target)) @data(1, 2) def test_nested_global_phase(self, num_ctrl_qubits): """ Test controlling a gate with nested global phase. """ theta = pi / 4 circ = QuantumCircuit(1, global_phase=theta) circ.z(0) v = circ.to_gate() qc = QuantumCircuit(1) qc.append(v, [0]) ctrl_qc = qc.control(num_ctrl_qubits) base_mat = Operator(qc).data target = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertEqual(Operator(ctrl_qc), Operator(target)) @data(1, 2) def test_control_zero_operand_gate(self, num_ctrl_qubits): """Test that a zero-operand gate (such as a make-shift global-phase gate) can be controlled.""" gate = QuantumCircuit(global_phase=np.pi).to_gate() controlled = gate.control(num_ctrl_qubits) self.assertIsInstance(controlled, ControlledGate) self.assertEqual(controlled.num_ctrl_qubits, num_ctrl_qubits) self.assertEqual(controlled.num_qubits, num_ctrl_qubits) target = np.eye(2**num_ctrl_qubits, dtype=np.complex128) target.flat[-1] = -1 self.assertEqual(Operator(controlled), Operator(target)) @ddt class TestOpenControlledToMatrix(QiskitTestCase): """Test controlled_gates implementing to_matrix work with ctrl_state""" @combine(gate_class=ControlledGate.__subclasses__(), ctrl_state=[0, None]) def test_open_controlled_to_matrix(self, gate_class, ctrl_state): """Test open controlled to_matrix.""" num_free_params = len(_get_free_params(gate_class.__init__, ignore=["self"])) free_params = [0.1 * i for i in range(1, num_free_params + 1)] if gate_class in [MCU1Gate, MCPhaseGate]: free_params[1] = 3 elif gate_class in [MCXGate]: free_params[0] = 3 cgate = gate_class(*free_params) cgate.ctrl_state = ctrl_state base_mat = Operator(cgate.base_gate).data if gate_class == CUGate: # account for global phase base_mat = np.array(base_mat) * np.exp(1j * cgate.params[3]) target = _compute_control_matrix(base_mat, cgate.num_ctrl_qubits, ctrl_state=ctrl_state) try: actual = cgate.to_matrix() except CircuitError as cerr: self.skipTest(str(cerr)) self.assertTrue(np.allclose(actual, target)) @ddt class TestSingleControlledRotationGates(QiskitTestCase): """Test the controlled rotation gates controlled on one qubit.""" from qiskit.circuit.library.standard_gates import u1, rx, ry, rz num_ctrl = 2 num_target = 1 theta = pi / 2 gu1 = u1.U1Gate(theta) grx = rx.RXGate(theta) gry = ry.RYGate(theta) grz = rz.RZGate(theta) ugu1 = ac._unroll_gate(gu1, ["p", "u", "cx"]) ugrx = ac._unroll_gate(grx, ["p", "u", "cx"]) ugry = ac._unroll_gate(gry, ["p", "u", "cx"]) ugrz = ac._unroll_gate(grz, ["p", "u", "cx"]) ugrz.params = grz.params cgu1 = ugu1.control(num_ctrl) cgrx = ugrx.control(num_ctrl) cgry = ugry.control(num_ctrl) cgrz = ugrz.control(num_ctrl) @data((gu1, cgu1), (grx, cgrx), (gry, cgry), (grz, cgrz)) @unpack def test_single_controlled_rotation_gates(self, gate, cgate): """Test the controlled rotation gates controlled on one qubit.""" if gate.name == "rz": iden = Operator.from_label("I") zgen = Operator.from_label("Z") op_mat = (np.cos(0.5 * self.theta) * iden - 1j * np.sin(0.5 * self.theta) * zgen).data else: op_mat = Operator(gate).data ref_mat = Operator(cgate).data cop_mat = _compute_control_matrix(op_mat, self.num_ctrl) self.assertTrue(matrix_equal(cop_mat, ref_mat)) cqc = QuantumCircuit(self.num_ctrl + self.num_target) cqc.append(cgate, cqc.qregs[0]) dag = circuit_to_dag(cqc) unroller = Unroller(["u", "cx"]) uqc = dag_to_circuit(unroller.run(dag)) self.log.info("%s gate count: %d", cgate.name, uqc.size()) self.log.info("\n%s", str(uqc)) # these limits could be changed if gate.name == "ry": self.assertLessEqual(uqc.size(), 32, f"\n{uqc}") elif gate.name == "rz": self.assertLessEqual(uqc.size(), 43, f"\n{uqc}") else: self.assertLessEqual(uqc.size(), 20, f"\n{uqc}") def test_composite(self): """Test composite gate count.""" qreg = QuantumRegister(self.num_ctrl + self.num_target) qc = QuantumCircuit(qreg, name="composite") qc.append(self.grx.control(self.num_ctrl), qreg) qc.append(self.gry.control(self.num_ctrl), qreg) qc.append(self.gry, qreg[0 : self.gry.num_qubits]) qc.append(self.grz.control(self.num_ctrl), qreg) dag = circuit_to_dag(qc) unroller = Unroller(["u", "cx"]) uqc = dag_to_circuit(unroller.run(dag)) self.log.info("%s gate count: %d", uqc.name, uqc.size()) self.assertLessEqual(uqc.size(), 96, f"\n{uqc}") # this limit could be changed @ddt class TestControlledStandardGates(QiskitTestCase): """Tests for control standard gates.""" @combine( num_ctrl_qubits=[1, 2, 3], gate_class=[cls for cls in allGates.__dict__.values() if isinstance(cls, type)], ) def test_controlled_standard_gates(self, num_ctrl_qubits, gate_class): """Test controlled versions of all standard gates.""" theta = pi / 2 ctrl_state_ones = 2**num_ctrl_qubits - 1 ctrl_state_zeros = 0 ctrl_state_mixed = ctrl_state_ones >> int(num_ctrl_qubits / 2) numargs = len(_get_free_params(gate_class)) args = [theta] * numargs if gate_class in [MSGate, Barrier]: args[0] = 2 elif gate_class in [MCU1Gate, MCPhaseGate]: args[1] = 2 elif issubclass(gate_class, MCXGate): args = [5] gate = gate_class(*args) for ctrl_state in (ctrl_state_ones, ctrl_state_zeros, ctrl_state_mixed): with self.subTest(i=f"{gate_class.__name__}, ctrl_state={ctrl_state}"): if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0: # skip matrices that include ancilla qubits continue try: cgate = gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) except (AttributeError, QiskitError): # 'object has no attribute "control"' # skipping Id and Barrier continue base_mat = Operator(gate).data target_mat = _compute_control_matrix( base_mat, num_ctrl_qubits, ctrl_state=ctrl_state ) self.assertEqual(Operator(cgate), Operator(target_mat)) @ddt class TestParameterCtrlState(QiskitTestCase): """Test gate equality with ctrl_state parameter.""" @data( (RXGate(0.5), CRXGate(0.5)), (RYGate(0.5), CRYGate(0.5)), (RZGate(0.5), CRZGate(0.5)), (XGate(), CXGate()), (YGate(), CYGate()), (ZGate(), CZGate()), (U1Gate(0.5), CU1Gate(0.5)), (PhaseGate(0.5), CPhaseGate(0.5)), (SwapGate(), CSwapGate()), (HGate(), CHGate()), (U3Gate(0.1, 0.2, 0.3), CU3Gate(0.1, 0.2, 0.3)), (UGate(0.1, 0.2, 0.3), CUGate(0.1, 0.2, 0.3, 0)), ) @unpack def test_ctrl_state_one(self, gate, controlled_gate): """Test controlled gates with ctrl_state See https://github.com/Qiskit/qiskit-terra/pull/4025 """ self.assertEqual( Operator(gate.control(1, ctrl_state="1")), Operator(controlled_gate.to_matrix()) ) @ddt class TestControlledGateLabel(QiskitTestCase): """Tests for controlled gate labels.""" gates_and_args = [ (XGate, []), (YGate, []), (ZGate, []), (HGate, []), (CXGate, []), (CCXGate, []), (C3XGate, []), (C3SXGate, []), (C4XGate, []), (MCXGate, [5]), (PhaseGate, [0.1]), (U1Gate, [0.1]), (CYGate, []), (CZGate, []), (CPhaseGate, [0.1]), (CU1Gate, [0.1]), (SwapGate, []), (SXGate, []), (CSXGate, []), (CCXGate, []), (RZGate, [0.1]), (RXGate, [0.1]), (RYGate, [0.1]), (CRYGate, [0.1]), (CRXGate, [0.1]), (CSwapGate, []), (UGate, [0.1, 0.2, 0.3]), (U3Gate, [0.1, 0.2, 0.3]), (CHGate, []), (CRZGate, [0.1]), (CUGate, [0.1, 0.2, 0.3, 0.4]), (CU3Gate, [0.1, 0.2, 0.3]), (MSGate, [5, 0.1]), (RCCXGate, []), (RC3XGate, []), (MCU1Gate, [0.1, 1]), (MCXGate, [5]), ] @data(*gates_and_args) @unpack def test_control_label(self, gate, args): """Test gate(label=...).control(label=...)""" cgate = gate(*args, label="a gate").control(label="a controlled gate") self.assertEqual(cgate.label, "a controlled gate") self.assertEqual(cgate.base_gate.label, "a gate") @data(*gates_and_args) @unpack def test_control_label_1(self, gate, args): """Test gate(label=...).control(1, label=...)""" cgate = gate(*args, label="a gate").control(1, label="a controlled gate") self.assertEqual(cgate.label, "a controlled gate") self.assertEqual(cgate.base_gate.label, "a gate") if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Diagonal gate tests.""" import unittest import numpy as np from qiskit import QuantumCircuit, QuantumRegister, BasicAer, execute from qiskit import QiskitError from qiskit.test import QiskitTestCase from qiskit.compiler import transpile from qiskit.extensions.quantum_initializer import DiagonalGate from qiskit.quantum_info.operators.predicates import matrix_equal class TestDiagonalGate(QiskitTestCase): """ Diagonal gate tests. """ def test_diag_gate(self): """Test diagonal gates.""" for phases in [ [0, 0], [0, 0.8], [0, 0, 1, 1], [0, 1, 0.5, 1], (2 * np.pi * np.random.rand(2**3)).tolist(), (2 * np.pi * np.random.rand(2**4)).tolist(), (2 * np.pi * np.random.rand(2**5)).tolist(), ]: with self.subTest(phases=phases): diag = [np.exp(1j * ph) for ph in phases] num_qubits = int(np.log2(len(diag))) q = QuantumRegister(num_qubits) qc = QuantumCircuit(q) qc.diagonal(diag, q[0:num_qubits]) # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"], optimization_level=0) # Simulate the decomposed gate simulator = BasicAer.get_backend("unitary_simulator") result = execute(qc, simulator).result() unitary = result.get_unitary(qc) unitary_desired = _get_diag_gate_matrix(diag) self.assertTrue(matrix_equal(unitary, unitary_desired, ignore_phase=False)) def test_mod1_entries(self): """Test that diagonal raises if entries do not have modules of 1.""" from qiskit.quantum_info.operators.predicates import ATOL_DEFAULT, RTOL_DEFAULT with self.assertRaises(QiskitError): DiagonalGate([1, 1 - 2 * ATOL_DEFAULT - RTOL_DEFAULT]) def _get_diag_gate_matrix(diag): return np.diagflat(diag) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-function-docstring, missing-module-docstring import unittest from inspect import signature from math import pi import numpy as np from scipy.linalg import expm from ddt import data, ddt, unpack from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, execute from qiskit.exceptions import QiskitError from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase from qiskit.circuit import Gate, ControlledGate from qiskit.circuit.library import ( U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate, XXMinusYYGate, XXPlusYYGate, RZGate, XGate, YGate, GlobalPhaseGate, ) from qiskit import BasicAer from qiskit.quantum_info import Pauli from qiskit.quantum_info.operators.predicates import matrix_equal, is_unitary_matrix from qiskit.utils.optionals import HAS_TWEEDLEDUM from qiskit.quantum_info import Operator from qiskit import transpile class TestStandard1Q(QiskitTestCase): """Standard Extension Test. Gates with a single Qubit""" def setUp(self): super().setUp() self.qr = QuantumRegister(3, "q") self.qr2 = QuantumRegister(3, "r") self.cr = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.qr, self.qr2, self.cr) def test_barrier(self): self.circuit.barrier(self.qr[1]) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_barrier_wires(self): self.circuit.barrier(1) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_barrier_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.barrier, self.cr[0]) self.assertRaises(CircuitError, qc.barrier, self.cr) self.assertRaises(CircuitError, qc.barrier, (self.qr, "a")) self.assertRaises(CircuitError, qc.barrier, 0.0) def test_conditional_barrier_invalid(self): qc = self.circuit barrier = qc.barrier(self.qr) self.assertRaises(QiskitError, barrier.c_if, self.cr, 0) def test_barrier_reg(self): self.circuit.barrier(self.qr) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_barrier_none(self): self.circuit.barrier() self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual( self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2], self.qr2[0], self.qr2[1], self.qr2[2]), ) def test_ccx(self): self.circuit.ccx(self.qr[0], self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "ccx") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_ccx_wires(self): self.circuit.ccx(0, 1, 2) self.assertEqual(self.circuit[0].operation.name, "ccx") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_ccx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.ccx, self.cr[0], self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.ccx, self.qr[0], self.qr[0], self.qr[2]) self.assertRaises(CircuitError, qc.ccx, 0.0, self.qr[0], self.qr[2]) self.assertRaises(CircuitError, qc.ccx, self.cr, self.qr, self.qr) self.assertRaises(CircuitError, qc.ccx, "a", self.qr[1], self.qr[2]) def test_ch(self): self.circuit.ch(self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "ch") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_ch_wires(self): self.circuit.ch(0, 1) self.assertEqual(self.circuit[0].operation.name, "ch") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_ch_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.ch, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.ch, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.ch, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.ch, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.ch, self.cr, self.qr) self.assertRaises(CircuitError, qc.ch, "a", self.qr[1]) def test_cif_reg(self): self.circuit.h(self.qr[0]).c_if(self.cr, 7) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[0],)) self.assertEqual(self.circuit[0].operation.condition, (self.cr, 7)) def test_cif_single_bit(self): self.circuit.h(self.qr[0]).c_if(self.cr[0], True) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[0],)) self.assertEqual(self.circuit[0].operation.condition, (self.cr[0], True)) def test_crz(self): self.circuit.crz(1, self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "crz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_cry(self): self.circuit.cry(1, self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "cry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crx(self): self.circuit.crx(1, self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "crx") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crz_wires(self): self.circuit.crz(1, 0, 1) self.assertEqual(self.circuit[0].operation.name, "crz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_cry_wires(self): self.circuit.cry(1, 0, 1) self.assertEqual(self.circuit[0].operation.name, "cry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crx_wires(self): self.circuit.crx(1, 0, 1) self.assertEqual(self.circuit[0].operation.name, "crx") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.crz, 0, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.crz, 0, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.crz, 0, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.crz, self.qr[2], self.qr[1], self.qr[0]) self.assertRaises(CircuitError, qc.crz, 0, self.qr[1], self.cr[2]) self.assertRaises(CircuitError, qc.crz, 0, (self.qr, 3), self.qr[1]) self.assertRaises(CircuitError, qc.crz, 0, self.cr, self.qr) # TODO self.assertRaises(CircuitError, qc.crz, 'a', self.qr[1], self.qr[2]) def test_cry_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cry, 0, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.cry, 0, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cry, 0, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cry, self.qr[2], self.qr[1], self.qr[0]) self.assertRaises(CircuitError, qc.cry, 0, self.qr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cry, 0, (self.qr, 3), self.qr[1]) self.assertRaises(CircuitError, qc.cry, 0, self.cr, self.qr) # TODO self.assertRaises(CircuitError, qc.cry, 'a', self.qr[1], self.qr[2]) def test_crx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.crx, 0, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.crx, 0, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.crx, 0, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.crx, self.qr[2], self.qr[1], self.qr[0]) self.assertRaises(CircuitError, qc.crx, 0, self.qr[1], self.cr[2]) self.assertRaises(CircuitError, qc.crx, 0, (self.qr, 3), self.qr[1]) self.assertRaises(CircuitError, qc.crx, 0, self.cr, self.qr) # TODO self.assertRaises(CircuitError, qc.crx, 'a', self.qr[1], self.qr[2]) def test_cswap(self): self.circuit.cswap(self.qr[0], self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cswap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_cswap_wires(self): self.circuit.cswap(0, 1, 2) self.assertEqual(self.circuit[0].operation.name, "cswap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_cswap_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cswap, self.cr[0], self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cswap, self.qr[1], self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cswap, self.qr[1], 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cswap, self.cr[0], self.cr[1], self.qr[0]) self.assertRaises(CircuitError, qc.cswap, self.qr[0], self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, 0.0, self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, (self.qr, 3), self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, self.cr, self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, "a", self.qr[1], self.qr[2]) def test_cu1(self): self.circuit.append(CU1Gate(1), [self.qr[1], self.qr[2]]) self.assertEqual(self.circuit[0].operation.name, "cu1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cu1_wires(self): self.circuit.append(CU1Gate(1), [1, 2]) self.assertEqual(self.circuit[0].operation.name, "cu1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cu3(self): self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr[2]]) self.assertEqual(self.circuit[0].operation.name, "cu3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cu3_wires(self): self.circuit.append(CU3Gate(1, 2, 3), [1, 2]) self.assertEqual(self.circuit[0].operation.name, "cu3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cx(self): self.circuit.cx(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cx") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cx_wires(self): self.circuit.cx(1, 2) self.assertEqual(self.circuit[0].operation.name, "cx") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cx, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cx, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cx, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cx, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.cx, self.cr, self.qr) self.assertRaises(CircuitError, qc.cx, "a", self.qr[1]) def test_cy(self): self.circuit.cy(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cy") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cy_wires(self): self.circuit.cy(1, 2) self.assertEqual(self.circuit[0].operation.name, "cy") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cy_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cy, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cy, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cy, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cy, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.cy, self.cr, self.qr) self.assertRaises(CircuitError, qc.cy, "a", self.qr[1]) def test_cz(self): self.circuit.cz(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cz") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cz_wires(self): self.circuit.cz(1, 2) self.assertEqual(self.circuit[0].operation.name, "cz") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cz, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cz, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cz, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cz, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.cz, self.cr, self.qr) self.assertRaises(CircuitError, qc.cz, "a", self.qr[1]) def test_h(self): self.circuit.h(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_h_wires(self): self.circuit.h(1) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_h_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.h, self.cr[0]) self.assertRaises(CircuitError, qc.h, self.cr) self.assertRaises(CircuitError, qc.h, (self.qr, 3)) self.assertRaises(CircuitError, qc.h, (self.qr, "a")) self.assertRaises(CircuitError, qc.h, 0.0) def test_h_reg(self): instruction_set = self.circuit.h(self.qr) self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "h") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_h_reg_inv(self): instruction_set = self.circuit.h(self.qr).inverse() self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "h") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_iden(self): self.circuit.i(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "id") self.assertEqual(self.circuit[0].operation.params, []) def test_iden_wires(self): self.circuit.i(1) self.assertEqual(self.circuit[0].operation.name, "id") self.assertEqual(self.circuit[0].operation.params, []) def test_iden_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.i, self.cr[0]) self.assertRaises(CircuitError, qc.i, self.cr) self.assertRaises(CircuitError, qc.i, (self.qr, 3)) self.assertRaises(CircuitError, qc.i, (self.qr, "a")) self.assertRaises(CircuitError, qc.i, 0.0) def test_iden_reg(self): instruction_set = self.circuit.i(self.qr) self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "id") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_iden_reg_inv(self): instruction_set = self.circuit.i(self.qr).inverse() self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "id") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_rx(self): self.circuit.rx(1, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rx") self.assertEqual(self.circuit[0].operation.params, [1]) def test_rx_wires(self): self.circuit.rx(1, 1) self.assertEqual(self.circuit[0].operation.name, "rx") self.assertEqual(self.circuit[0].operation.params, [1]) def test_rx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.rx, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.rx, self.qr[1], 0) self.assertRaises(CircuitError, qc.rx, 0, self.cr[0]) self.assertRaises(CircuitError, qc.rx, 0, 0.0) self.assertRaises(CircuitError, qc.rx, self.qr[2], self.qr[1]) self.assertRaises(CircuitError, qc.rx, 0, (self.qr, 3)) self.assertRaises(CircuitError, qc.rx, 0, self.cr) # TODO self.assertRaises(CircuitError, qc.rx, 'a', self.qr[1]) self.assertRaises(CircuitError, qc.rx, 0, "a") def test_rx_reg(self): instruction_set = self.circuit.rx(1, self.qr) self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "rx") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1]) def test_rx_reg_inv(self): instruction_set = self.circuit.rx(1, self.qr).inverse() self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "rx") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_rx_pi(self): qc = self.circuit qc.rx(pi / 2, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rx") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_ry(self): self.circuit.ry(1, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "ry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_ry_wires(self): self.circuit.ry(1, 1) self.assertEqual(self.circuit[0].operation.name, "ry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_ry_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.ry, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.ry, self.qr[1], 0) self.assertRaises(CircuitError, qc.ry, 0, self.cr[0]) self.assertRaises(CircuitError, qc.ry, 0, 0.0) self.assertRaises(CircuitError, qc.ry, self.qr[2], self.qr[1]) self.assertRaises(CircuitError, qc.ry, 0, (self.qr, 3)) self.assertRaises(CircuitError, qc.ry, 0, self.cr) # TODO self.assertRaises(CircuitError, qc.ry, 'a', self.qr[1]) self.assertRaises(CircuitError, qc.ry, 0, "a") def test_ry_reg(self): instruction_set = self.circuit.ry(1, self.qr) self.assertEqual(instruction_set[0].operation.name, "ry") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1]) def test_ry_reg_inv(self): instruction_set = self.circuit.ry(1, self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "ry") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_ry_pi(self): qc = self.circuit qc.ry(pi / 2, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "ry") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) def test_rz(self): self.circuit.rz(1, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_rz_wires(self): self.circuit.rz(1, 1) self.assertEqual(self.circuit[0].operation.name, "rz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_rz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.rz, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.rz, self.qr[1], 0) self.assertRaises(CircuitError, qc.rz, 0, self.cr[0]) self.assertRaises(CircuitError, qc.rz, 0, 0.0) self.assertRaises(CircuitError, qc.rz, self.qr[2], self.qr[1]) self.assertRaises(CircuitError, qc.rz, 0, (self.qr, 3)) self.assertRaises(CircuitError, qc.rz, 0, self.cr) # TODO self.assertRaises(CircuitError, qc.rz, 'a', self.qr[1]) self.assertRaises(CircuitError, qc.rz, 0, "a") def test_rz_reg(self): instruction_set = self.circuit.rz(1, self.qr) self.assertEqual(instruction_set[0].operation.name, "rz") self.assertEqual(instruction_set[2].operation.params, [1]) def test_rz_reg_inv(self): instruction_set = self.circuit.rz(1, self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "rz") self.assertEqual(instruction_set[2].operation.params, [-1]) def test_rz_pi(self): self.circuit.rz(pi / 2, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rz") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_rzz(self): self.circuit.rzz(1, self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "rzz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_rzz_wires(self): self.circuit.rzz(1, 1, 2) self.assertEqual(self.circuit[0].operation.name, "rzz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_rzz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.rzz, 1, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.rzz, 1, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.rzz, 1, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.rzz, 1, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.rzz, 1, self.cr, self.qr) self.assertRaises(CircuitError, qc.rzz, 1, "a", self.qr[1]) self.assertRaises(CircuitError, qc.rzz, 0.1, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.rzz, 0.1, self.qr[0], self.qr[0]) def test_s(self): self.circuit.s(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "s") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_s_wires(self): self.circuit.s(1) self.assertEqual(self.circuit[0].operation.name, "s") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_s_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.s, self.cr[0]) self.assertRaises(CircuitError, qc.s, self.cr) self.assertRaises(CircuitError, qc.s, (self.qr, 3)) self.assertRaises(CircuitError, qc.s, (self.qr, "a")) self.assertRaises(CircuitError, qc.s, 0.0) def test_s_reg(self): instruction_set = self.circuit.s(self.qr) self.assertEqual(instruction_set[0].operation.name, "s") self.assertEqual(instruction_set[2].operation.params, []) def test_s_reg_inv(self): instruction_set = self.circuit.s(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "sdg") self.assertEqual(instruction_set[2].operation.params, []) def test_sdg(self): self.circuit.sdg(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "sdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_sdg_wires(self): self.circuit.sdg(1) self.assertEqual(self.circuit[0].operation.name, "sdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_sdg_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.sdg, self.cr[0]) self.assertRaises(CircuitError, qc.sdg, self.cr) self.assertRaises(CircuitError, qc.sdg, (self.qr, 3)) self.assertRaises(CircuitError, qc.sdg, (self.qr, "a")) self.assertRaises(CircuitError, qc.sdg, 0.0) def test_sdg_reg(self): instruction_set = self.circuit.sdg(self.qr) self.assertEqual(instruction_set[0].operation.name, "sdg") self.assertEqual(instruction_set[2].operation.params, []) def test_sdg_reg_inv(self): instruction_set = self.circuit.sdg(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "s") self.assertEqual(instruction_set[2].operation.params, []) def test_swap(self): self.circuit.swap(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "swap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_swap_wires(self): self.circuit.swap(1, 2) self.assertEqual(self.circuit[0].operation.name, "swap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_swap_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.swap, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.swap, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.swap, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.swap, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.swap, self.cr, self.qr) self.assertRaises(CircuitError, qc.swap, "a", self.qr[1]) self.assertRaises(CircuitError, qc.swap, self.qr, self.qr2[[1, 2]]) self.assertRaises(CircuitError, qc.swap, self.qr[:2], self.qr2) def test_t(self): self.circuit.t(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "t") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_t_wire(self): self.circuit.t(1) self.assertEqual(self.circuit[0].operation.name, "t") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_t_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.t, self.cr[0]) self.assertRaises(CircuitError, qc.t, self.cr) self.assertRaises(CircuitError, qc.t, (self.qr, 3)) self.assertRaises(CircuitError, qc.t, (self.qr, "a")) self.assertRaises(CircuitError, qc.t, 0.0) def test_t_reg(self): instruction_set = self.circuit.t(self.qr) self.assertEqual(instruction_set[0].operation.name, "t") self.assertEqual(instruction_set[2].operation.params, []) def test_t_reg_inv(self): instruction_set = self.circuit.t(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "tdg") self.assertEqual(instruction_set[2].operation.params, []) def test_tdg(self): self.circuit.tdg(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "tdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_tdg_wires(self): self.circuit.tdg(1) self.assertEqual(self.circuit[0].operation.name, "tdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_tdg_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.tdg, self.cr[0]) self.assertRaises(CircuitError, qc.tdg, self.cr) self.assertRaises(CircuitError, qc.tdg, (self.qr, 3)) self.assertRaises(CircuitError, qc.tdg, (self.qr, "a")) self.assertRaises(CircuitError, qc.tdg, 0.0) def test_tdg_reg(self): instruction_set = self.circuit.tdg(self.qr) self.assertEqual(instruction_set[0].operation.name, "tdg") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_tdg_reg_inv(self): instruction_set = self.circuit.tdg(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "t") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_u1(self): self.circuit.append(U1Gate(1), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u1_wires(self): self.circuit.append(U1Gate(1), [1]) self.assertEqual(self.circuit[0].operation.name, "u1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u1_reg(self): instruction_set = self.circuit.append(U1Gate(1), [self.qr]) self.assertEqual(instruction_set[0].operation.name, "u1") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1]) def test_u1_reg_inv(self): instruction_set = self.circuit.append(U1Gate(1), [self.qr]).inverse() self.assertEqual(instruction_set[0].operation.name, "u1") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_u1_pi(self): qc = self.circuit qc.append(U1Gate(pi / 2), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u1") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u2(self): self.circuit.append(U2Gate(1, 2), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u2") self.assertEqual(self.circuit[0].operation.params, [1, 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u2_wires(self): self.circuit.append(U2Gate(1, 2), [1]) self.assertEqual(self.circuit[0].operation.name, "u2") self.assertEqual(self.circuit[0].operation.params, [1, 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u2_reg(self): instruction_set = self.circuit.append(U2Gate(1, 2), [self.qr]) self.assertEqual(instruction_set[0].operation.name, "u2") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1, 2]) def test_u2_reg_inv(self): instruction_set = self.circuit.append(U2Gate(1, 2), [self.qr]).inverse() self.assertEqual(instruction_set[0].operation.name, "u2") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-pi - 2, -1 + pi]) def test_u2_pi(self): self.circuit.append(U2Gate(pi / 2, 0.3 * pi), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u2") self.assertEqual(self.circuit[0].operation.params, [pi / 2, 0.3 * pi]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u3(self): self.circuit.append(U3Gate(1, 2, 3), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u3_wires(self): self.circuit.append(U3Gate(1, 2, 3), [1]) self.assertEqual(self.circuit[0].operation.name, "u3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u3_reg(self): instruction_set = self.circuit.append(U3Gate(1, 2, 3), [self.qr]) self.assertEqual(instruction_set[0].operation.name, "u3") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_u3_reg_inv(self): instruction_set = self.circuit.append(U3Gate(1, 2, 3), [self.qr]).inverse() self.assertEqual(instruction_set[0].operation.name, "u3") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_u3_pi(self): self.circuit.append(U3Gate(pi, pi / 2, 0.3 * pi), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u3") self.assertEqual(self.circuit[0].operation.params, [pi, pi / 2, 0.3 * pi]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_x(self): self.circuit.x(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "x") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_x_wires(self): self.circuit.x(1) self.assertEqual(self.circuit[0].operation.name, "x") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_x_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.x, self.cr[0]) self.assertRaises(CircuitError, qc.x, self.cr) self.assertRaises(CircuitError, qc.x, (self.qr, "a")) self.assertRaises(CircuitError, qc.x, 0.0) def test_x_reg(self): instruction_set = self.circuit.x(self.qr) self.assertEqual(instruction_set[0].operation.name, "x") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_x_reg_inv(self): instruction_set = self.circuit.x(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "x") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_y(self): self.circuit.y(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "y") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_y_wires(self): self.circuit.y(1) self.assertEqual(self.circuit[0].operation.name, "y") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_y_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.y, self.cr[0]) self.assertRaises(CircuitError, qc.y, self.cr) self.assertRaises(CircuitError, qc.y, (self.qr, "a")) self.assertRaises(CircuitError, qc.y, 0.0) def test_y_reg(self): instruction_set = self.circuit.y(self.qr) self.assertEqual(instruction_set[0].operation.name, "y") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_y_reg_inv(self): instruction_set = self.circuit.y(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "y") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_z(self): self.circuit.z(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "z") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_z_wires(self): self.circuit.z(1) self.assertEqual(self.circuit[0].operation.name, "z") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_z_reg(self): instruction_set = self.circuit.z(self.qr) self.assertEqual(instruction_set[0].operation.name, "z") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_z_reg_inv(self): instruction_set = self.circuit.z(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "z") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_global_phase(self): qc = self.circuit qc.append(GlobalPhaseGate(0.1), []) self.assertEqual(self.circuit[0].operation.name, "global_phase") self.assertEqual(self.circuit[0].operation.params, [0.1]) self.assertEqual(self.circuit[0].qubits, ()) def test_global_phase_inv(self): instruction_set = self.circuit.append(GlobalPhaseGate(0.1), []).inverse() self.assertEqual(len(instruction_set), 1) self.assertEqual(instruction_set[0].operation.params, [-0.1]) def test_global_phase_matrix(self): """Test global_phase matrix.""" theta = 0.1 np.testing.assert_allclose( np.array(GlobalPhaseGate(theta)), np.array([[np.exp(1j * theta)]], dtype=complex), atol=1e-7, ) def test_global_phase_consistency(self): """Tests compatibility of GlobalPhaseGate with QuantumCircuit.global_phase""" theta = 0.1 qc1 = QuantumCircuit(0, global_phase=theta) qc2 = QuantumCircuit(0) qc2.append(GlobalPhaseGate(theta), []) np.testing.assert_allclose( Operator(qc1), Operator(qc2), atol=1e-7, ) def test_transpile_global_phase_consistency(self): """Tests compatibility of transpiled GlobalPhaseGate with QuantumCircuit.global_phase""" qc1 = QuantumCircuit(0, global_phase=0.3) qc2 = QuantumCircuit(0, global_phase=0.2) qc2.append(GlobalPhaseGate(0.1), []) np.testing.assert_allclose( Operator(transpile(qc1, basis_gates=["u"])), Operator(transpile(qc2, basis_gates=["u"])), atol=1e-7, ) @ddt class TestStandard2Q(QiskitTestCase): """Standard Extension Test. Gates with two Qubits""" def setUp(self): super().setUp() self.qr = QuantumRegister(3, "q") self.qr2 = QuantumRegister(3, "r") self.cr = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.qr, self.qr2, self.cr) def test_barrier_reg_bit(self): self.circuit.barrier(self.qr, self.qr2[0]) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2], self.qr2[0])) def test_ch_reg_reg(self): instruction_set = self.circuit.ch(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_reg_reg_inv(self): instruction_set = self.circuit.ch(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_reg_bit(self): instruction_set = self.circuit.ch(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual( instruction_set[1].qubits, ( self.qr[1], self.qr2[1], ), ) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_reg_bit_inv(self): instruction_set = self.circuit.ch(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual( instruction_set[1].qubits, ( self.qr[1], self.qr2[1], ), ) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_bit_reg(self): instruction_set = self.circuit.ch(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_crz_reg_reg(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crz_reg_reg_inv(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crz_reg_bit(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crz_reg_bit_inv(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crz_bit_reg(self): instruction_set = self.circuit.crz(1, self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crz_bit_reg_inv(self): instruction_set = self.circuit.crz(1, self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cry_reg_reg(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cry_reg_reg_inv(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cry_reg_bit(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cry_reg_bit_inv(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cry_bit_reg(self): instruction_set = self.circuit.cry(1, self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cry_bit_reg_inv(self): instruction_set = self.circuit.cry(1, self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crx_reg_reg(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crx_reg_reg_inv(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crx_reg_bit(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crx_reg_bit_inv(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crx_bit_reg(self): instruction_set = self.circuit.crx(1, self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crx_bit_reg_inv(self): instruction_set = self.circuit.crx(1, self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu1_reg_reg(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cu1_reg_reg_inv(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu1_reg_bit(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2[1]]) self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cu1_reg_bit_inv(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2[1]]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu1_bit_reg(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr[1], self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cu1_bit_reg_inv(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr[1], self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu3_reg_reg(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_cu3_reg_reg_inv(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_cu3_reg_bit(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2[1]]) self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_cu3_reg_bit_inv(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2[1]]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_cu3_bit_reg(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_cu3_bit_reg_inv(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_cx_reg_reg(self): instruction_set = self.circuit.cx(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_reg_reg_inv(self): instruction_set = self.circuit.cx(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_reg_bit(self): instruction_set = self.circuit.cx(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_reg_bit_inv(self): instruction_set = self.circuit.cx(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_bit_reg(self): instruction_set = self.circuit.cx(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_bit_reg_inv(self): instruction_set = self.circuit.cx(self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_reg(self): instruction_set = self.circuit.cy(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_reg_inv(self): instruction_set = self.circuit.cy(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_bit(self): instruction_set = self.circuit.cy(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_bit_inv(self): instruction_set = self.circuit.cy(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_bit_reg(self): instruction_set = self.circuit.cy(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_bit_reg_inv(self): instruction_set = self.circuit.cy(self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_reg(self): instruction_set = self.circuit.cz(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_reg_inv(self): instruction_set = self.circuit.cz(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_bit(self): instruction_set = self.circuit.cz(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_bit_inv(self): instruction_set = self.circuit.cz(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_bit_reg(self): instruction_set = self.circuit.cz(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_bit_reg_inv(self): instruction_set = self.circuit.cz(self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_swap_reg_reg(self): instruction_set = self.circuit.swap(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "swap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_swap_reg_reg_inv(self): instruction_set = self.circuit.swap(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "swap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) @unpack @data( (0, 0, np.eye(4)), ( np.pi / 2, np.pi / 2, np.array( [ [np.sqrt(2) / 2, 0, 0, -np.sqrt(2) / 2], [0, 1, 0, 0], [0, 0, 1, 0], [np.sqrt(2) / 2, 0, 0, np.sqrt(2) / 2], ] ), ), ( np.pi, np.pi / 2, np.array([[0, 0, 0, -1], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]), ), ( 2 * np.pi, np.pi / 2, np.array([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]), ), ( np.pi / 2, np.pi, np.array( [ [np.sqrt(2) / 2, 0, 0, 1j * np.sqrt(2) / 2], [0, 1, 0, 0], [0, 0, 1, 0], [1j * np.sqrt(2) / 2, 0, 0, np.sqrt(2) / 2], ] ), ), (4 * np.pi, 0, np.eye(4)), ) def test_xx_minus_yy_matrix(self, theta: float, beta: float, expected: np.ndarray): """Test XX-YY matrix.""" gate = XXMinusYYGate(theta, beta) np.testing.assert_allclose(np.array(gate), expected, atol=1e-7) def test_xx_minus_yy_exponential_formula(self): """Test XX-YY exponential formula.""" theta, beta = np.random.uniform(-10, 10, size=2) gate = XXMinusYYGate(theta, beta) x = np.array(XGate()) y = np.array(YGate()) xx = np.kron(x, x) yy = np.kron(y, y) rz1 = np.kron(np.array(RZGate(beta)), np.eye(2)) np.testing.assert_allclose( np.array(gate), rz1 @ expm(-0.25j * theta * (xx - yy)) @ rz1.T.conj(), atol=1e-7, ) def test_xx_plus_yy_exponential_formula(self): """Test XX+YY exponential formula.""" theta, beta = np.random.uniform(-10, 10, size=2) gate = XXPlusYYGate(theta, beta) x = np.array(XGate()) y = np.array(YGate()) xx = np.kron(x, x) yy = np.kron(y, y) rz0 = np.kron(np.eye(2), np.array(RZGate(beta))) np.testing.assert_allclose( np.array(gate), rz0.T.conj() @ expm(-0.25j * theta * (xx + yy)) @ rz0, atol=1e-7, ) class TestStandard3Q(QiskitTestCase): """Standard Extension Test. Gates with three Qubits""" def setUp(self): super().setUp() self.qr = QuantumRegister(3, "q") self.qr2 = QuantumRegister(3, "r") self.qr3 = QuantumRegister(3, "s") self.cr = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.qr, self.qr2, self.qr3, self.cr) def test_ccx_reg_reg_reg(self): instruction_set = self.circuit.ccx(self.qr, self.qr2, self.qr3) self.assertEqual(instruction_set[0].operation.name, "ccx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_ccx_reg_reg_inv(self): instruction_set = self.circuit.ccx(self.qr, self.qr2, self.qr3).inverse() self.assertEqual(instruction_set[0].operation.name, "ccx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cswap_reg_reg_reg(self): instruction_set = self.circuit.cswap(self.qr, self.qr2, self.qr3) self.assertEqual(instruction_set[0].operation.name, "cswap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cswap_reg_reg_inv(self): instruction_set = self.circuit.cswap(self.qr, self.qr2, self.qr3).inverse() self.assertEqual(instruction_set[0].operation.name, "cswap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) class TestStandardMethods(QiskitTestCase): """Standard Extension Test.""" @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") def test_to_matrix(self): """test gates implementing to_matrix generate matrix which matches definition.""" from qiskit.circuit.library.pauli_evolution import PauliEvolutionGate from qiskit.circuit.library.generalized_gates.pauli import PauliGate from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression params = [0.1 * (i + 1) for i in range(10)] gate_class_list = Gate.__subclasses__() + ControlledGate.__subclasses__() simulator = BasicAer.get_backend("unitary_simulator") for gate_class in gate_class_list: if hasattr(gate_class, "__abstractmethods__"): # gate_class is abstract continue sig = signature(gate_class) free_params = len(set(sig.parameters) - {"label", "ctrl_state"}) try: if gate_class == PauliGate: # special case due to PauliGate using string parameters gate = gate_class("IXYZ") elif gate_class == BooleanExpression: gate = gate_class("x") elif gate_class == PauliEvolutionGate: gate = gate_class(Pauli("XYZ")) else: gate = gate_class(*params[0:free_params]) except (CircuitError, QiskitError, AttributeError, TypeError): self.log.info("Cannot init gate with params only. Skipping %s", gate_class) continue if gate.name in ["U", "CX"]: continue circ = QuantumCircuit(gate.num_qubits) circ.append(gate, range(gate.num_qubits)) try: gate_matrix = gate.to_matrix() except CircuitError: # gate doesn't implement to_matrix method: skip self.log.info('to_matrix method FAILED for "%s" gate', gate.name) continue definition_unitary = execute([circ], simulator).result().get_unitary() with self.subTest(gate_class): # TODO check for exact equality once BasicAer can handle global phase self.assertTrue(matrix_equal(definition_unitary, gate_matrix, ignore_phase=True)) self.assertTrue(is_unitary_matrix(gate_matrix)) @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") def test_to_matrix_op(self): """test gates implementing to_matrix generate matrix which matches definition using Operator.""" from qiskit.circuit.library.generalized_gates.gms import MSGate from qiskit.circuit.library.generalized_gates.pauli import PauliGate from qiskit.circuit.library.pauli_evolution import PauliEvolutionGate from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression params = [0.1 * i for i in range(1, 11)] gate_class_list = Gate.__subclasses__() + ControlledGate.__subclasses__() for gate_class in gate_class_list: if hasattr(gate_class, "__abstractmethods__"): # gate_class is abstract continue sig = signature(gate_class) if gate_class == MSGate: # due to the signature (num_qubits, theta, *, n_qubits=Noe) the signature detects # 3 arguments but really its only 2. This if can be removed once the deprecated # n_qubits argument is no longer supported. free_params = 2 else: free_params = len(set(sig.parameters) - {"label", "ctrl_state"}) try: if gate_class == PauliGate: # special case due to PauliGate using string parameters gate = gate_class("IXYZ") elif gate_class == BooleanExpression: gate = gate_class("x") elif gate_class == PauliEvolutionGate: gate = gate_class(Pauli("XYZ")) else: gate = gate_class(*params[0:free_params]) except (CircuitError, QiskitError, AttributeError, TypeError): self.log.info("Cannot init gate with params only. Skipping %s", gate_class) continue if gate.name in ["U", "CX"]: continue try: gate_matrix = gate.to_matrix() except CircuitError: # gate doesn't implement to_matrix method: skip self.log.info('to_matrix method FAILED for "%s" gate', gate.name) continue if not hasattr(gate, "definition") or not gate.definition: continue definition_unitary = Operator(gate.definition).data self.assertTrue(matrix_equal(definition_unitary, gate_matrix)) self.assertTrue(is_unitary_matrix(gate_matrix)) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test hardcoded decomposition rules and matrix definitions for standard gates.""" import inspect import numpy as np from ddt import ddt, data, idata, unpack from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase from qiskit.circuit import ParameterVector, Gate, ControlledGate from qiskit.circuit.library import standard_gates from qiskit.circuit.library import ( HGate, CHGate, IGate, RGate, RXGate, CRXGate, RYGate, CRYGate, RZGate, CRZGate, SGate, SdgGate, CSwapGate, TGate, TdgGate, U1Gate, CU1Gate, U2Gate, U3Gate, CU3Gate, XGate, CXGate, ECRGate, CCXGate, YGate, CYGate, ZGate, CZGate, RYYGate, PhaseGate, CPhaseGate, UGate, CUGate, SXGate, SXdgGate, CSXGate, RVGate, XXMinusYYGate, ) from qiskit.circuit.library.standard_gates.equivalence_library import ( StandardEquivalenceLibrary as std_eqlib, ) from .gate_utils import _get_free_params class TestGateDefinitions(QiskitTestCase): """Test the decomposition of a gate in terms of other gates yields the equivalent matrix as the hardcoded matrix definition up to a global phase.""" def test_ch_definition(self): # TODO: expand this to all gates """Test ch gate matrix and definition.""" circ = QuantumCircuit(2) circ.ch(0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_ccx_definition(self): """Test ccx gate matrix and definition.""" circ = QuantumCircuit(3) circ.ccx(0, 1, 2) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_crz_definition(self): """Test crz gate matrix and definition.""" circ = QuantumCircuit(2) circ.crz(1, 0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_cry_definition(self): """Test cry gate matrix and definition.""" circ = QuantumCircuit(2) circ.cry(1, 0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_crx_definition(self): """Test crx gate matrix and definition.""" circ = QuantumCircuit(2) circ.crx(1, 0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_cswap_definition(self): """Test cswap gate matrix and definition.""" circ = QuantumCircuit(3) circ.cswap(0, 1, 2) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_cu1_definition(self): """Test cu1 gate matrix and definition.""" circ = QuantumCircuit(2) circ.append(CU1Gate(1), [0, 1]) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_cu3_definition(self): """Test cu3 gate matrix and definition.""" circ = QuantumCircuit(2) circ.append(CU3Gate(1, 1, 1), [0, 1]) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_cx_definition(self): """Test cx gate matrix and definition.""" circ = QuantumCircuit(2) circ.cx(0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_ecr_definition(self): """Test ecr gate matrix and definition.""" circ = QuantumCircuit(2) circ.ecr(0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_rv_definition(self): """Test R(v) gate to_matrix and definition.""" qreg = QuantumRegister(1) circ = QuantumCircuit(qreg) vec = np.array([0.1, 0.2, 0.3], dtype=float) circ.rv(*vec, 0) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_rv_r_equiv(self): """Test R(v) gate is equivalent to R gate.""" theta = np.pi / 5 phi = np.pi / 3 rgate = RGate(theta, phi) axis = np.array([np.cos(phi), np.sin(phi), 0]) # RGate axis rotvec = theta * axis rv = RVGate(*rotvec) rg_matrix = rgate.to_matrix() rv_matrix = rv.to_matrix() np.testing.assert_array_max_ulp(rg_matrix.real, rv_matrix.real, 4) np.testing.assert_array_max_ulp(rg_matrix.imag, rv_matrix.imag, 4) def test_rv_zero(self): """Test R(v) gate with zero vector returns identity""" rv = RVGate(0, 0, 0) self.assertTrue(np.array_equal(rv.to_matrix(), np.array([[1, 0], [0, 1]]))) def test_xx_minus_yy_definition(self): """Test XX-YY gate decomposition.""" theta, beta = np.random.uniform(-10, 10, size=2) gate = XXMinusYYGate(theta, beta) circuit = QuantumCircuit(2) circuit.append(gate, [0, 1]) decomposed_circuit = circuit.decompose() self.assertTrue(len(decomposed_circuit) > len(circuit)) self.assertTrue(Operator(circuit).equiv(Operator(decomposed_circuit), atol=1e-7)) @ddt class TestStandardGates(QiskitTestCase): """Standard Extension Test.""" @unpack @data( *inspect.getmembers( standard_gates, predicate=lambda value: (inspect.isclass(value) and issubclass(value, Gate)), ) ) def test_definition_parameters(self, class_name, gate_class): """Verify definitions from standard library include correct parameters.""" free_params = _get_free_params(gate_class) n_params = len(free_params) param_vector = ParameterVector("th", n_params) if class_name in ("MCPhaseGate", "MCU1Gate"): param_vector = param_vector[:-1] gate = gate_class(*param_vector, num_ctrl_qubits=2) elif class_name in ("MCXGate", "MCXGrayCode", "MCXRecursive", "MCXVChain"): num_ctrl_qubits = 2 param_vector = param_vector[:-1] gate = gate_class(num_ctrl_qubits, *param_vector) elif class_name == "MSGate": num_qubits = 2 param_vector = param_vector[:-1] gate = gate_class(num_qubits, *param_vector) else: gate = gate_class(*param_vector) if gate.definition is not None: self.assertEqual(gate.definition.parameters, set(param_vector)) @unpack @data( *inspect.getmembers( standard_gates, predicate=lambda value: (inspect.isclass(value) and issubclass(value, Gate)), ) ) def test_inverse(self, class_name, gate_class): """Verify self-inverse pair yield identity for all standard gates.""" free_params = _get_free_params(gate_class) n_params = len(free_params) float_vector = [0.1 + 0.1 * i for i in range(n_params)] if class_name in ("MCPhaseGate", "MCU1Gate"): float_vector = float_vector[:-1] gate = gate_class(*float_vector, num_ctrl_qubits=2) elif class_name in ("MCXGate", "MCXGrayCode", "MCXRecursive", "MCXVChain"): num_ctrl_qubits = 3 float_vector = float_vector[:-1] gate = gate_class(num_ctrl_qubits, *float_vector) elif class_name == "PauliGate": pauli_string = "IXYZ" gate = gate_class(pauli_string) else: gate = gate_class(*float_vector) from qiskit.quantum_info.operators.predicates import is_identity_matrix self.assertTrue(is_identity_matrix(Operator(gate).dot(gate.inverse()).data)) if gate.definition is not None: self.assertTrue(is_identity_matrix(Operator(gate).dot(gate.definition.inverse()).data)) self.assertTrue(is_identity_matrix(Operator(gate).dot(gate.inverse().definition).data)) @ddt class TestGateEquivalenceEqual(QiskitTestCase): """Test the decomposition of a gate in terms of other gates yields the same matrix as the hardcoded matrix definition.""" class_list = Gate.__subclasses__() + ControlledGate.__subclasses__() exclude = { "ControlledGate", "DiagonalGate", "UCGate", "MCGupDiag", "MCU1Gate", "UnitaryGate", "HamiltonianGate", "MCPhaseGate", "UCPauliRotGate", "SingleQubitUnitary", "MCXGate", "VariadicZeroParamGate", "ClassicalFunction", "ClassicalElement", "StatePreparation", "LinearFunction", "PermutationGate", "Commuting2qBlock", "PauliEvolutionGate", "_U0Gate", "_DefinedGate", } # Amazingly, Python's scoping rules for class bodies means that this is the closest we can get # to a "natural" comprehension or functional iterable definition: # https://docs.python.org/3/reference/executionmodel.html#resolution-of-names @idata(filter(lambda x, exclude=exclude: x.__name__ not in exclude, class_list)) def test_equivalence_phase(self, gate_class): """Test that the equivalent circuits from the equivalency_library have equal matrix representations""" n_params = len(_get_free_params(gate_class)) params = [0.1 * i for i in range(1, n_params + 1)] if gate_class.__name__ == "RXXGate": params = [np.pi / 2] if gate_class.__name__ in ["MSGate"]: params[0] = 2 if gate_class.__name__ in ["PauliGate"]: params = ["IXYZ"] if gate_class.__name__ in ["BooleanExpression"]: params = ["x | y"] gate = gate_class(*params) equiv_lib_list = std_eqlib.get_entry(gate) for ieq, equivalency in enumerate(equiv_lib_list): with self.subTest(msg=gate.name + "_" + str(ieq)): op1 = Operator(gate) op2 = Operator(equivalency) self.assertEqual(op1, op2) @ddt class TestStandardEquivalenceLibrary(QiskitTestCase): """Standard Extension Test.""" @data( HGate, CHGate, IGate, RGate, RXGate, CRXGate, RYGate, CRYGate, RZGate, CRZGate, SGate, SdgGate, CSwapGate, TGate, TdgGate, U1Gate, CU1Gate, U2Gate, U3Gate, CU3Gate, XGate, CXGate, ECRGate, CCXGate, YGate, CYGate, ZGate, CZGate, RYYGate, PhaseGate, CPhaseGate, UGate, CUGate, SXGate, SXdgGate, CSXGate, ) def test_definition_parameters(self, gate_class): """Verify decompositions from standard equivalence library match definitions.""" n_params = len(_get_free_params(gate_class)) param_vector = ParameterVector("th", n_params) float_vector = [0.1 * i for i in range(n_params)] param_gate = gate_class(*param_vector) float_gate = gate_class(*float_vector) param_entry = std_eqlib.get_entry(param_gate) float_entry = std_eqlib.get_entry(float_gate) if not param_gate.definition or not param_gate.definition.data: return self.assertGreaterEqual(len(param_entry), 1) self.assertGreaterEqual(len(float_entry), 1) param_qc = QuantumCircuit(param_gate.num_qubits) float_qc = QuantumCircuit(float_gate.num_qubits) param_qc.append(param_gate, param_qc.qregs[0]) float_qc.append(float_gate, float_qc.qregs[0]) self.assertTrue(any(equiv == param_qc.decompose() for equiv in param_entry)) self.assertTrue(any(equiv == float_qc.decompose() for equiv in float_entry))
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """HamiltonianGate tests""" import numpy as np from numpy.testing import assert_allclose import qiskit from qiskit.extensions.hamiltonian_gate import HamiltonianGate, UnitaryGate from qiskit.extensions.exceptions import ExtensionError from qiskit.test import QiskitTestCase from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Parameter from qiskit.quantum_info import Operator from qiskit.converters import circuit_to_dag, dag_to_circuit class TestHamiltonianGate(QiskitTestCase): """Tests for the HamiltonianGate class.""" def test_set_matrix(self): """Test instantiation""" hamiltonian = HamiltonianGate([[0, 1], [1, 0]], 1) self.assertEqual(hamiltonian.num_qubits, 1) def test_set_matrix_raises(self): """test non-unitary""" with self.assertRaises(ExtensionError): HamiltonianGate([[1, 0], [1, 1]], 1) def test_complex_time_raises(self): """test non-unitary""" with self.assertRaises(ExtensionError): HamiltonianGate([[1, 0], [1, 1]], 1j) def test_conjugate(self): """test conjugate""" ham = HamiltonianGate([[0, 1j], [-1j, 2]], np.pi / 4) np.testing.assert_array_almost_equal(ham.conjugate().to_matrix(), np.conj(ham.to_matrix())) def test_transpose(self): """test transpose""" ham = HamiltonianGate([[15, 1j], [-1j, -2]], np.pi / 7) np.testing.assert_array_almost_equal( ham.transpose().to_matrix(), np.transpose(ham.to_matrix()) ) def test_adjoint(self): """test adjoint operation""" ham = HamiltonianGate([[3, 4j], [-4j, -0.2]], np.pi * 0.143) np.testing.assert_array_almost_equal( ham.adjoint().to_matrix(), np.transpose(np.conj(ham.to_matrix())) ) class TestHamiltonianCircuit(QiskitTestCase): """Hamiltonian gate circuit tests.""" def test_1q_hamiltonian(self): """test 1 qubit hamiltonian""" qr = QuantumRegister(1, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = np.zeros((2, 2)) qc.x(qr[0]) theta = Parameter("theta") qc.append(HamiltonianGate(matrix, theta), [qr[0]]) qc = qc.bind_parameters({theta: 1}) # test of text drawer self.log.info(qc) dag = circuit_to_dag(qc) dag_nodes = dag.named_nodes("hamiltonian") self.assertTrue(len(dag_nodes) == 1) dnode = dag_nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, tuple(qc.qubits)) assert_allclose(dnode.op.to_matrix(), np.eye(2)) def test_error_and_deprecation_warning_on_qasm(self): """test that an error is thrown if the method `qasm` is called.""" matrix = np.zeros((2, 2)) hamiltonian_gate = HamiltonianGate(data=matrix, time=1) with self.assertRaises(ExtensionError): with self.assertWarns(DeprecationWarning): hamiltonian_gate.qasm() def test_2q_hamiltonian(self): """test 2 qubit hamiltonian""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) matrix = Operator.from_label("XY") qc.x(qr[0]) theta = Parameter("theta") uni2q = HamiltonianGate(matrix, theta) qc.append(uni2q, [qr[0], qr[1]]) qc2 = qc.bind_parameters({theta: -np.pi / 2}) dag = circuit_to_dag(qc2) nodes = dag.two_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, (qr[0], qr[1])) # Equality based on Pauli exponential identity np.testing.assert_array_almost_equal(dnode.op.to_matrix(), 1j * matrix.data) qc3 = dag_to_circuit(dag) self.assertEqual(qc2, qc3) def test_3q_hamiltonian(self): """test 3 qubit hamiltonian on non-consecutive bits""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.x(qr[0]) matrix = Operator.from_label("XZY") theta = Parameter("theta") uni3q = HamiltonianGate(matrix, theta) qc.append(uni3q, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) # test of text drawer self.log.info(qc) qc = qc.bind_parameters({theta: -np.pi / 2}) dag = circuit_to_dag(qc) nodes = dag.multi_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, (qr[0], qr[1], qr[3])) np.testing.assert_almost_equal(dnode.op.to_matrix(), 1j * matrix.data) def test_qobj_with_hamiltonian(self): """test qobj output with hamiltonian""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.rx(np.pi / 4, qr[0]) matrix = Operator.from_label("XIZ") theta = Parameter("theta") uni = HamiltonianGate(matrix, theta, label="XIZ") qc.append(uni, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) qc = qc.bind_parameters({theta: np.pi / 2}) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[1] self.assertEqual(instr.name, "hamiltonian") # Also test label self.assertEqual(instr.label, "XIZ") np.testing.assert_array_almost_equal( np.array(instr.params[0]).astype(np.complex64), matrix.data ) def test_decomposes_into_correct_unitary(self): """test 2 qubit hamiltonian""" qc = QuantumCircuit(2) matrix = Operator.from_label("XY") theta = Parameter("theta") uni2q = HamiltonianGate(matrix, theta) qc.append(uni2q, [0, 1]) qc = qc.bind_parameters({theta: -np.pi / 2}).decompose() decomposed_ham = qc.data[0].operation self.assertEqual(decomposed_ham, UnitaryGate(Operator.from_label("XY")))
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Non-string identifiers for circuit and record identifiers test""" import unittest from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase class TestAnonymousIds(QiskitTestCase): """Test the anonymous use of registers.""" def test_create_anonymous_classical_register(self): """ClassicalRegister with no name.""" cr = ClassicalRegister(size=3) self.assertIsInstance(cr, ClassicalRegister) def test_create_anonymous_quantum_register(self): """QuantumRegister with no name.""" qr = QuantumRegister(size=3) self.assertIsInstance(qr, QuantumRegister) def test_create_anonymous_classical_registers(self): """Several ClassicalRegister with no name.""" cr1 = ClassicalRegister(size=3) cr2 = ClassicalRegister(size=3) self.assertNotEqual(cr1.name, cr2.name) def test_create_anonymous_quantum_registers(self): """Several QuantumRegister with no name.""" qr1 = QuantumRegister(size=3) qr2 = QuantumRegister(size=3) self.assertNotEqual(qr1.name, qr2.name) def test_create_anonymous_mixed_registers(self): """Several Registers with no name.""" cr0 = ClassicalRegister(size=3) qr0 = QuantumRegister(size=3) # Get the current index count of the registers cr_index = int(cr0.name[1:]) qr_index = int(qr0.name[1:]) cr1 = ClassicalRegister(size=3) _ = QuantumRegister(size=3) qr2 = QuantumRegister(size=3) # Check that the counters for each kind are incremented separately. cr_current = int(cr1.name[1:]) qr_current = int(qr2.name[1:]) self.assertEqual(cr_current, cr_index + 1) self.assertEqual(qr_current, qr_index + 2) def test_create_circuit_noname(self): """Create_circuit with no name.""" qr = QuantumRegister(size=3) cr = ClassicalRegister(size=3) qc = QuantumCircuit(qr, cr) self.assertIsInstance(qc, QuantumCircuit) class TestInvalidIds(QiskitTestCase): """Circuits and records with invalid IDs""" def test_invalid_type_circuit_name(self): """QuantumCircuit() with invalid type name.""" qr = QuantumRegister(size=3) cr = ClassicalRegister(size=3) self.assertRaises(CircuitError, QuantumCircuit, qr, cr, name=1) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Initialize test. """ import math import unittest import numpy as np from ddt import ddt, data from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit import ClassicalRegister from qiskit import transpile from qiskit import execute, assemble, BasicAer from qiskit.quantum_info import state_fidelity, Statevector, Operator from qiskit.exceptions import QiskitError from qiskit.test import QiskitTestCase from qiskit.extensions.quantum_initializer import Initialize @ddt class TestInitialize(QiskitTestCase): """Qiskit Initialize tests.""" _desired_fidelity = 0.99 def test_uniform_superposition(self): """Initialize a uniform superposition on 2 qubits.""" desired_vector = [0.5, 0.5, 0.5, 0.5] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_deterministic_state(self): """Initialize a computational-basis state |01> on 2 qubits.""" desired_vector = [0, 1, 0, 0] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_statevector(self): """Initialize gates from a statevector.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/5134 (footnote) desired_vector = [0, 0, 0, 1] qc = QuantumCircuit(2) statevector = Statevector.from_label("11") qc.initialize(statevector, [0, 1]) self.assertEqual(qc.data[0].operation.params, desired_vector) def test_bell_state(self): """Initialize a Bell state on 2 qubits.""" desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_ghz_state(self): """Initialize a GHZ state on 3 qubits.""" desired_vector = [1 / math.sqrt(2), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_initialize_register(self): """Initialize one register out of two.""" desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") qr2 = QuantumRegister(2, "qr2") qc = QuantumCircuit(qr, qr2) qc.initialize(desired_vector, qr) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, np.kron([1, 0, 0, 0], desired_vector)) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_initialize_one_by_one(self): """Initializing qubits individually into product state same as initializing the pair.""" qubit_0_state = [1, 0] qubit_1_state = [1 / math.sqrt(2), 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") qc_a = QuantumCircuit(qr) qc_a.initialize(np.kron(qubit_1_state, qubit_0_state), qr) qc_b = QuantumCircuit(qr) qc_b.initialize(qubit_0_state, [qr[0]]) qc_b.initialize(qubit_1_state, [qr[1]]) job = execute([qc_a, qc_b], BasicAer.get_backend("statevector_simulator")) result = job.result() statevector_a = result.get_statevector(0) statevector_b = result.get_statevector(1) fidelity = state_fidelity(statevector_a, statevector_b) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_single_qubit(self): """Initialize a single qubit to a weighted superposition state.""" desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3)] qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_random_3qubit(self): """Initialize to a non-trivial 3-qubit state.""" desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0, ] qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_random_4qubit(self): """Initialize to a non-trivial 4-qubit state.""" desired_vector = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0), ] qr = QuantumRegister(4, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_malformed_amplitudes(self): """Initializing to a vector with 3 amplitudes fails.""" desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3), 0] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) self.assertRaises(QiskitError, qc.initialize, desired_vector, [qr[0], qr[1]]) def test_non_unit_probability(self): """Initializing to a vector with probabilities not summing to 1 fails.""" desired_vector = [1, 1] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) self.assertRaises(QiskitError, qc.initialize, desired_vector, [qr[0], qr[1]]) def test_normalize(self): """Test initializing with a non-normalized vector is normalized, if specified.""" desired_vector = [1, 1] normalized = np.asarray(desired_vector) / np.linalg.norm(desired_vector) qc = QuantumCircuit(1) qc.initialize(desired_vector, [0], normalize=True) op = qc.data[0].operation self.assertAlmostEqual(np.linalg.norm(op.params), 1) self.assertEqual(Statevector(qc), Statevector(normalized)) def test_wrong_vector_size(self): """Initializing to a vector with a size different to the qubit parameter length. See https://github.com/Qiskit/qiskit-terra/issues/2372""" qr = QuantumRegister(2) random_state = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0), ] qc = QuantumCircuit(qr) self.assertRaises(QiskitError, qc.initialize, random_state, qr[0:2]) def test_initialize_middle_circuit(self): """Reset + initialize gives the correct statevector.""" desired_vector = [0.5, 0.5, 0.5, 0.5] qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.reset(qr[0]) qc.reset(qr[1]) qc.initialize(desired_vector, [qr[0], qr[1]]) qc.measure(qr, cr) # statevector simulator does not support reset shots = 2000 threshold = 0.005 * shots job = execute(qc, BasicAer.get_backend("qasm_simulator"), shots=shots, seed_simulator=42) result = job.result() counts = result.get_counts() target = {"00": shots / 4, "01": shots / 4, "10": shots / 4, "11": shots / 4} self.assertDictAlmostEqual(counts, target, threshold) def test_math_amplitudes(self): """Initialize to amplitudes given by math expressions""" desired_vector = [ 0, math.cos(math.pi / 3) * complex(0, 1) / math.sqrt(4), math.sin(math.pi / 3) / math.sqrt(4), 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4), 1 / math.sqrt(4) * complex(0, 1), ] qr = QuantumRegister(4, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_combiner(self): """Combining two circuits containing initialize.""" desired_vector_1 = [1.0 / math.sqrt(2), 1.0 / math.sqrt(2)] desired_vector_2 = [1.0 / math.sqrt(2), -1.0 / math.sqrt(2)] qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") qc1 = QuantumCircuit(qr, cr) qc1.initialize(desired_vector_1, [qr[0]]) qc2 = QuantumCircuit(qr, cr) qc2.initialize(desired_vector_2, [qr[0]]) job = execute(qc1.compose(qc2), BasicAer.get_backend("statevector_simulator")) result = job.result() quantum_state = result.get_statevector() fidelity = state_fidelity(quantum_state, desired_vector_2) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_equivalence(self): """Test two similar initialize instructions evaluate to equal.""" desired_vector = [0.5, 0.5, 0.5, 0.5] qr = QuantumRegister(2, "qr") qc1 = QuantumCircuit(qr, name="circuit") qc1.initialize(desired_vector, [qr[0], qr[1]]) qc2 = QuantumCircuit(qr, name="circuit") qc2.initialize(desired_vector, [qr[0], qr[1]]) self.assertEqual(qc1, qc2) def test_max_number_cnots(self): """ Check if the number of cnots <= 2^(n+1) - 2n (arXiv:quant-ph/0406176) """ num_qubits = 4 _optimization_level = 0 vector = np.array( [ 0.1314346 + 0.0j, 0.32078572 - 0.01542775j, 0.13146466 + 0.0945312j, 0.21090852 + 0.07935982j, 0.1700122 - 0.07905648j, 0.15570757 - 0.12309154j, 0.18039667 + 0.04904504j, 0.22227187 - 0.05055569j, 0.23573255 - 0.09894111j, 0.27307292 - 0.10372994j, 0.24162792 + 0.1090791j, 0.3115577 + 0.1211683j, 0.1851788 + 0.08679141j, 0.36226463 - 0.09940202j, 0.13863395 + 0.10558225j, 0.30767986 + 0.02073838j, ] ) vector = vector / np.linalg.norm(vector) qr = QuantumRegister(num_qubits, "qr") circuit = QuantumCircuit(qr) circuit.initialize(vector, qr) b = transpile( circuit, basis_gates=["u1", "u2", "u3", "cx"], optimization_level=_optimization_level, seed_transpiler=42, ) number_cnots = b.count_ops()["cx"] max_cnots = 2 ** (num_qubits + 1) - 2 * num_qubits self.assertLessEqual(number_cnots, max_cnots) def test_from_labels(self): """Initialize from labels.""" desired_sv = Statevector.from_label("01+-lr") qc = QuantumCircuit(6) qc.initialize("01+-lr", range(6)) actual_sv = Statevector.from_instruction(qc) self.assertTrue(desired_sv == actual_sv) def test_from_int(self): """Initialize from int.""" desired_sv = Statevector.from_label("110101") qc = QuantumCircuit(6) qc.initialize(53, range(6)) actual_sv = Statevector.from_instruction(qc) self.assertTrue(desired_sv == actual_sv) def _remove_resets(self, circ): circ.data = [instr for instr in circ.data if instr.operation.name != "reset"] def test_global_phase_random(self): """Test global phase preservation with random state vectors""" from qiskit.quantum_info.random import random_statevector repeats = 5 for n_qubits in [1, 2, 4]: for irep in range(repeats): with self.subTest(i=f"{n_qubits}_{irep}"): dim = 2**n_qubits qr = QuantumRegister(n_qubits) initializer = QuantumCircuit(qr) target = random_statevector(dim) initializer.initialize(target, qr) uninit = initializer.data[0].operation.definition self._remove_resets(uninit) evolve = Statevector(uninit) self.assertEqual(target, evolve) def test_global_phase_1q(self): """Test global phase preservation with some simple 1q statevectors""" target_list = [ Statevector([1j, 0]), Statevector([0, 1j]), Statevector([1j / np.sqrt(2), 1j / np.sqrt(2)]), ] n_qubits = 1 dim = 2**n_qubits qr = QuantumRegister(n_qubits) for target in target_list: with self.subTest(i=target): initializer = QuantumCircuit(qr) initializer.initialize(target, qr) # need to get rid of the resets in order to use the Operator class disentangler = Operator(initializer.data[0].operation.definition.data[1].operation) zero = Statevector.from_int(0, dim) actual = zero & disentangler self.assertEqual(target, actual) @data(2, "11", [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) def test_decompose_contains_stateprep(self, state): """Test initialize decomposes to a StatePreparation and reset""" qc = QuantumCircuit(2) qc.initialize(state) decom_circ = qc.decompose() self.assertEqual(decom_circ.data[0].operation.name, "reset") self.assertEqual(decom_circ.data[1].operation.name, "reset") self.assertEqual(decom_circ.data[2].operation.name, "state_preparation") def test_mutating_params(self): """Test mutating Initialize params correctly updates StatePreparation params""" init = Initialize("11") init.params = "00" qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.append(init, qr) decom_circ = qc.decompose() self.assertEqual(decom_circ.data[2].operation.name, "state_preparation") self.assertEqual(decom_circ.data[2].operation.params, ["0", "0"]) class TestInstructionParam(QiskitTestCase): """Test conversion of numpy type parameters.""" def test_diag(self): """Verify diagonal gate converts numpy.complex to complex.""" # ref: https://github.com/Qiskit/qiskit-aer/issues/696 diag = np.array([1 + 0j, 1 + 0j]) qc = QuantumCircuit(1) qc.diagonal(list(diag), [0]) params = qc.data[0].operation.params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) qobj = assemble(qc) params = qobj.experiments[0].instructions[0].params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) def test_init(self): """Verify initialize gate converts numpy.complex to complex.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/4151 qc = QuantumCircuit(1) vec = np.array([0, 0 + 1j]) qc.initialize(vec, 0) params = qc.data[0].operation.params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) qobj = assemble(qc) params = qobj.experiments[0].instructions[0].params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Test Qiskit's repeat instruction operation.""" import unittest from numpy import pi from qiskit.transpiler import PassManager from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.test import QiskitTestCase from qiskit.extensions import UnitaryGate from qiskit.circuit.library import SGate, U3Gate, CXGate from qiskit.circuit import Instruction, Measure, Gate from qiskit.transpiler.passes import Unroller from qiskit.circuit.exceptions import CircuitError class TestRepeatInt1Q(QiskitTestCase): """Test gate_q1.repeat() with integer""" def test_standard_1Q_two(self): """Test standard gate.repeat(2) method.""" qr = QuantumRegister(1, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(SGate(), [qr[0]]) expected_circ.append(SGate(), [qr[0]]) expected = expected_circ.to_instruction() result = SGate().repeat(2) self.assertEqual(result.name, "s*2") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) def test_standard_1Q_one(self): """Test standard gate.repeat(1) method.""" qr = QuantumRegister(1, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(SGate(), [qr[0]]) expected = expected_circ.to_instruction() result = SGate().repeat(1) self.assertEqual(result.name, "s*1") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) class TestRepeatInt2Q(QiskitTestCase): """Test gate_q2.repeat() with integer""" def test_standard_2Q_two(self): """Test standard 2Q gate.repeat(2) method.""" qr = QuantumRegister(2, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(CXGate(), [qr[0], qr[1]]) expected_circ.append(CXGate(), [qr[0], qr[1]]) expected = expected_circ.to_instruction() result = CXGate().repeat(2) self.assertEqual(result.name, "cx*2") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) def test_standard_2Q_one(self): """Test standard 2Q gate.repeat(1) method.""" qr = QuantumRegister(2, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(CXGate(), [qr[0], qr[1]]) expected = expected_circ.to_instruction() result = CXGate().repeat(1) self.assertEqual(result.name, "cx*1") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) class TestRepeatIntMeasure(QiskitTestCase): """Test Measure.repeat() with integer""" def test_measure_two(self): """Test Measure.repeat(2) method.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") expected_circ = QuantumCircuit(qr, cr) expected_circ.append(Measure(), [qr[0]], [cr[0]]) expected_circ.append(Measure(), [qr[0]], [cr[0]]) expected = expected_circ.to_instruction() result = Measure().repeat(2) self.assertEqual(result.name, "measure*2") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Instruction) self.assertNotIsInstance(result, Gate) def test_measure_one(self): """Test Measure.repeat(1) method.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") expected_circ = QuantumCircuit(qr, cr) expected_circ.append(Measure(), [qr[0]], [cr[0]]) expected = expected_circ.to_instruction() result = Measure().repeat(1) self.assertEqual(result.name, "measure*1") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Instruction) self.assertNotIsInstance(result, Gate) class TestRepeatUnroller(QiskitTestCase): """Test unrolling Gate.repeat""" def test_unroller_two(self): """Test unrolling gate.repeat(2).""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(SGate().repeat(2), [qr[0]]) result = PassManager(Unroller("u3")).run(circuit) expected = QuantumCircuit(qr) expected.append(U3Gate(0, 0, pi / 2), [qr[0]]) expected.append(U3Gate(0, 0, pi / 2), [qr[0]]) self.assertEqual(result, expected) def test_unroller_one(self): """Test unrolling gate.repeat(1).""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(SGate().repeat(1), [qr[0]]) result = PassManager(Unroller("u3")).run(circuit) expected = QuantumCircuit(qr) expected.append(U3Gate(0, 0, pi / 2), [qr[0]]) self.assertEqual(result, expected) class TestRepeatErrors(QiskitTestCase): """Test when Gate.repeat() should raise.""" def test_unitary_no_int(self): """Test UnitaryGate.repeat(2/3) method. Raises, since n is not int.""" with self.assertRaises(CircuitError) as context: _ = UnitaryGate([[0, 1j], [-1j, 0]]).repeat(2 / 3) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_no_int(self): """Test standard Gate.repeat(2/3) method. Raises, since n is not int.""" with self.assertRaises(CircuitError) as context: _ = SGate().repeat(2 / 3) self.assertIn("strictly positive integer", str(context.exception)) def test_measure_zero(self): """Test Measure.repeat(0) method. Raises, since n<1""" with self.assertRaises(CircuitError) as context: _ = Measure().repeat(0) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_1Q_zero(self): """Test standard 2Q gate.repeat(0) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = SGate().repeat(0) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_1Q_minus_one(self): """Test standard 2Q gate.repeat(-1) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = SGate().repeat(-1) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_2Q_minus_one(self): """Test standard 2Q gate.repeat(-1) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = CXGate().repeat(-1) self.assertIn("strictly positive integer", str(context.exception)) def test_measure_minus_one(self): """Test Measure.repeat(-1) method. Raises, since n<1""" with self.assertRaises(CircuitError) as context: _ = Measure().repeat(-1) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_2Q_zero(self): """Test standard 2Q gate.repeat(0) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = CXGate().repeat(0) self.assertIn("strictly positive integer", str(context.exception)) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Isometry tests.""" import unittest import numpy as np from ddt import ddt, data from qiskit.quantum_info.random import random_unitary from qiskit import BasicAer from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit import execute from qiskit.test import QiskitTestCase from qiskit.compiler import transpile from qiskit.quantum_info import Operator from qiskit.extensions.quantum_initializer.isometry import Isometry @ddt class TestIsometry(QiskitTestCase): """Qiskit isometry tests.""" @data( np.eye(2, 2), random_unitary(2, seed=868540).data, np.eye(4, 4), random_unitary(4, seed=16785).data[:, 0], np.eye(4, 4)[:, 0:2], random_unitary(4, seed=660477).data, np.eye(4, 4)[:, np.random.RandomState(seed=719010).permutation(4)][:, 0:2], np.eye(8, 8)[:, np.random.RandomState(seed=544326).permutation(8)], random_unitary(8, seed=247924).data[:, 0:4], random_unitary(8, seed=765720).data, random_unitary(16, seed=278663).data, random_unitary(16, seed=406498).data[:, 0:8], ) def test_isometry(self, iso): """Tests for the decomposition of isometries from m to n qubits""" if len(iso.shape) == 1: iso = iso.reshape((len(iso), 1)) num_q_output = int(np.log2(iso.shape[0])) num_q_input = int(np.log2(iso.shape[1])) q = QuantumRegister(num_q_output) qc = QuantumCircuit(q) qc.isometry(iso, q[:num_q_input], q[num_q_input:]) # Verify the circuit can be decomposed self.assertIsInstance(qc.decompose(), QuantumCircuit) # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"]) # Simulate the decomposed gate simulator = BasicAer.get_backend("unitary_simulator") result = execute(qc, simulator).result() unitary = result.get_unitary(qc) iso_from_circuit = unitary[::, 0 : 2**num_q_input] iso_desired = iso self.assertTrue(np.allclose(iso_from_circuit, iso_desired)) @data( np.eye(2, 2), random_unitary(2, seed=99506).data, np.eye(4, 4), random_unitary(4, seed=673459).data[:, 0], np.eye(4, 4)[:, 0:2], random_unitary(4, seed=124090).data, np.eye(4, 4)[:, np.random.RandomState(seed=889848).permutation(4)][:, 0:2], np.eye(8, 8)[:, np.random.RandomState(seed=94795).permutation(8)], random_unitary(8, seed=986292).data[:, 0:4], random_unitary(8, seed=632121).data, random_unitary(16, seed=623107).data, random_unitary(16, seed=889326).data[:, 0:8], ) def test_isometry_tolerance(self, iso): """Tests for the decomposition of isometries from m to n qubits with a custom tolerance""" if len(iso.shape) == 1: iso = iso.reshape((len(iso), 1)) num_q_output = int(np.log2(iso.shape[0])) num_q_input = int(np.log2(iso.shape[1])) q = QuantumRegister(num_q_output) qc = QuantumCircuit(q) # Compute isometry with custom tolerance qc.isometry(iso, q[:num_q_input], q[num_q_input:], epsilon=1e-3) # Verify the circuit can be decomposed self.assertIsInstance(qc.decompose(), QuantumCircuit) # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"]) # Simulate the decomposed gate simulator = BasicAer.get_backend("unitary_simulator") result = execute(qc, simulator).result() unitary = result.get_unitary(qc) iso_from_circuit = unitary[::, 0 : 2**num_q_input] self.assertTrue(np.allclose(iso_from_circuit, iso)) @data( np.eye(2, 2), random_unitary(2, seed=272225).data, np.eye(4, 4), random_unitary(4, seed=592640).data[:, 0], np.eye(4, 4)[:, 0:2], random_unitary(4, seed=714210).data, np.eye(4, 4)[:, np.random.RandomState(seed=719934).permutation(4)][:, 0:2], np.eye(8, 8)[:, np.random.RandomState(seed=284469).permutation(8)], random_unitary(8, seed=656745).data[:, 0:4], random_unitary(8, seed=583813).data, random_unitary(16, seed=101363).data, random_unitary(16, seed=583429).data[:, 0:8], ) def test_isometry_inverse(self, iso): """Tests for the inverse of isometries from m to n qubits""" if len(iso.shape) == 1: iso = iso.reshape((len(iso), 1)) num_q_output = int(np.log2(iso.shape[0])) q = QuantumRegister(num_q_output) qc = QuantumCircuit(q) qc.append(Isometry(iso, 0, 0), q) qc.append(Isometry(iso, 0, 0).inverse(), q) result = Operator(qc) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0])) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test circuits with variable parameters.""" import unittest import cmath import math import copy import pickle from operator import add, mul, sub, truediv from test import combine import numpy from ddt import data, ddt, named_data import qiskit import qiskit.circuit.library as circlib from qiskit.circuit.library.standard_gates.rz import RZGate from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.circuit import Gate, Instruction, Parameter, ParameterExpression, ParameterVector from qiskit.circuit.parametertable import ParameterReferences, ParameterTable, ParameterView from qiskit.circuit.exceptions import CircuitError from qiskit.compiler import assemble, transpile from qiskit.execute_function import execute from qiskit import pulse from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeOurense from qiskit.tools import parallel_map def raise_if_parameter_table_invalid(circuit): """Validates the internal consistency of a ParameterTable and its containing QuantumCircuit. Intended for use in testing. Raises: CircuitError: if QuantumCircuit and ParameterTable are inconsistent. """ table = circuit._parameter_table # Assert parameters present in circuit match those in table. circuit_parameters = { parameter for instruction in circuit._data for param in instruction.operation.params for parameter in param.parameters if isinstance(param, ParameterExpression) } table_parameters = set(table._table.keys()) if circuit_parameters != table_parameters: raise CircuitError( "Circuit/ParameterTable Parameter mismatch. " "Circuit parameters: {}. " "Table parameters: {}.".format(circuit_parameters, table_parameters) ) # Assert parameter locations in table are present in circuit. circuit_instructions = [instr.operation for instr in circuit._data] for parameter, instr_list in table.items(): for instr, param_index in instr_list: if instr not in circuit_instructions: raise CircuitError(f"ParameterTable instruction not present in circuit: {instr}.") if not isinstance(instr.params[param_index], ParameterExpression): raise CircuitError( "ParameterTable instruction does not have a " "ParameterExpression at param_index {}: {}." "".format(param_index, instr) ) if parameter not in instr.params[param_index].parameters: raise CircuitError( "ParameterTable instruction parameters does " "not match ParameterTable key. Instruction " "parameters: {} ParameterTable key: {}." "".format(instr.params[param_index].parameters, parameter) ) # Assert circuit has no other parameter locations other than those in table. for instruction in circuit._data: for param_index, param in enumerate(instruction.operation.params): if isinstance(param, ParameterExpression): parameters = param.parameters for parameter in parameters: if (instruction.operation, param_index) not in table[parameter]: raise CircuitError( "Found parameterized instruction not " "present in table. Instruction: {} " "param_index: {}".format(instruction.operation, param_index) ) @ddt class TestParameters(QiskitTestCase): """Test Parameters.""" def test_gate(self): """Test instantiating gate with variable parameters""" theta = Parameter("θ") theta_gate = Gate("test", 1, params=[theta]) self.assertEqual(theta_gate.name, "test") self.assertIsInstance(theta_gate.params[0], Parameter) def test_compile_quantum_circuit(self): """Test instantiating gate with variable parameters""" theta = Parameter("θ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) self.assertIn(theta, qc_aer.parameters) def test_duplicate_name_on_append(self): """Test adding a second parameter object with the same name fails.""" param_a = Parameter("a") param_a_again = Parameter("a") qc = QuantumCircuit(1) qc.rx(param_a, 0) self.assertRaises(CircuitError, qc.rx, param_a_again, 0) def test_get_parameters(self): """Test instantiating gate with variable parameters""" from qiskit.circuit.library.standard_gates.rx import RXGate theta = Parameter("θ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) rxg = RXGate(theta) qc.append(rxg, [qr[0]], []) vparams = qc._parameter_table self.assertEqual(len(vparams), 1) self.assertIs(theta, next(iter(vparams))) self.assertEqual(rxg, next(iter(vparams[theta]))[0]) def test_get_parameters_by_index(self): """Test getting parameters by index""" x = Parameter("x") y = Parameter("y") z = Parameter("z") v = ParameterVector("v", 3) qc = QuantumCircuit(1) qc.rx(x, 0) qc.rz(z, 0) qc.ry(y, 0) qc.u(*v, 0) self.assertEqual(x, qc.parameters[3]) self.assertEqual(y, qc.parameters[4]) self.assertEqual(z, qc.parameters[5]) for i, vi in enumerate(v): self.assertEqual(vi, qc.parameters[i]) def test_bind_parameters_anonymously(self): """Test setting parameters by insertion order anonymously""" phase = Parameter("phase") x = Parameter("x") y = Parameter("y") z = Parameter("z") v = ParameterVector("v", 3) qc = QuantumCircuit(1, global_phase=phase) qc.rx(x, 0) qc.rz(z, 0) qc.ry(y, 0) qc.u(*v, 0) params = [0.1 * i for i in range(len(qc.parameters))] order = [phase] + v[:] + [x, y, z] param_dict = dict(zip(order, params)) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bqc_anonymous = getattr(qc, assign_fun)(params) bqc_list = getattr(qc, assign_fun)(param_dict) self.assertEqual(bqc_anonymous, bqc_list) def test_bind_parameters_allow_unknown(self): """Test binding parameters allowing unknown parameters.""" a = Parameter("a") b = Parameter("b") c = a.bind({a: 1, b: 1}, allow_unknown_parameters=True) self.assertEqual(c, a.bind({a: 1})) @data(QuantumCircuit.assign_parameters, QuantumCircuit.bind_parameters) def test_bind_parameters_custom_definition_global_phase(self, assigner): """Test that a custom gate with a parametrised `global_phase` is assigned correctly.""" x = Parameter("x") custom = QuantumCircuit(1, global_phase=x).to_gate() base = QuantumCircuit(1) base.append(custom, [0], []) test = Operator(assigner(base, {x: math.pi})) expected = Operator(numpy.array([[-1, 0], [0, -1]])) self.assertEqual(test, expected) def test_bind_half_single_precision(self): """Test binding with 16bit and 32bit floats.""" phase = Parameter("phase") x = Parameter("x") y = Parameter("y") z = Parameter("z") v = ParameterVector("v", 3) for i in (numpy.float16, numpy.float32): with self.subTest(float_type=i): expr = (v[0] * (x + y + z) + phase) - (v[2] * v[1]) params = numpy.array([0.1 * j for j in range(8)], dtype=i) order = [phase] + v[:] + [x, y, z] param_dict = dict(zip(order, params)) bound_value = expr.bind(param_dict) self.assertAlmostEqual(float(bound_value), 0.09, delta=1e-4) def test_parameter_order(self): """Test the parameters are sorted by name but parameter vector order takes precedence. This means that the following set of parameters {a, z, x[0], x[1], x[2], x[3], x[10], x[11]} will be sorted as [a, x[0], x[1], x[2], x[3], x[10], x[11], z] """ a, b, some_name, z = (Parameter(name) for name in ["a", "b", "some_name", "z"]) x = ParameterVector("x", 12) a_vector = ParameterVector("a_vector", 15) qc = QuantumCircuit(2) qc.p(z, 0) for i, x_i in enumerate(reversed(x)): qc.rx(x_i, i % 2) qc.cry(a, 0, 1) qc.crz(some_name, 1, 0) for v_i in a_vector[::2]: qc.p(v_i, 0) for v_i in a_vector[1::2]: qc.p(v_i, 1) qc.p(b, 0) expected_order = [a] + a_vector[:] + [b, some_name] + x[:] + [z] actual_order = qc.parameters self.assertListEqual(expected_order, list(actual_order)) @data(True, False) def test_parameter_order_compose(self, front): """Test the parameter order is correctly maintained upon composing circuits.""" x = Parameter("x") y = Parameter("y") qc1 = QuantumCircuit(1) qc1.p(x, 0) qc2 = QuantumCircuit(1) qc2.rz(y, 0) order = [x, y] composed = qc1.compose(qc2, front=front) self.assertListEqual(list(composed.parameters), order) def test_parameter_order_append(self): """Test the parameter order is correctly maintained upon appending circuits.""" x = Parameter("x") y = Parameter("y") qc1 = QuantumCircuit(1) qc1.p(x, 0) qc2 = QuantumCircuit(1) qc2.rz(y, 0) qc1.append(qc2, [0]) self.assertListEqual(list(qc1.parameters), [x, y]) def test_parameter_order_composing_nested_circuit(self): """Test the parameter order after nesting circuits and instructions.""" x = ParameterVector("x", 5) inner = QuantumCircuit(1) inner.rx(x[0], [0]) mid = QuantumCircuit(2) mid.p(x[1], 1) mid.append(inner, [0]) mid.p(x[2], 0) mid.append(inner, [0]) outer = QuantumCircuit(2) outer.compose(mid, inplace=True) outer.ryy(x[3], 0, 1) outer.compose(inner, inplace=True) outer.rz(x[4], 0) order = [x[0], x[1], x[2], x[3], x[4]] self.assertListEqual(list(outer.parameters), order) def test_is_parameterized(self): """Test checking if a gate is parameterized (bound/unbound)""" from qiskit.circuit.library.standard_gates.h import HGate from qiskit.circuit.library.standard_gates.rx import RXGate theta = Parameter("θ") rxg = RXGate(theta) self.assertTrue(rxg.is_parameterized()) theta_bound = theta.bind({theta: 3.14}) rxg = RXGate(theta_bound) self.assertFalse(rxg.is_parameterized()) h_gate = HGate() self.assertFalse(h_gate.is_parameterized()) def test_fix_variable(self): """Test setting a variable to a constant value""" theta = Parameter("θ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, 0, qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bqc = getattr(qc, assign_fun)({theta: 0.5}) self.assertEqual(float(bqc.data[0].operation.params[0]), 0.5) self.assertEqual(float(bqc.data[1].operation.params[1]), 0.5) bqc = getattr(qc, assign_fun)({theta: 0.6}) self.assertEqual(float(bqc.data[0].operation.params[0]), 0.6) self.assertEqual(float(bqc.data[1].operation.params[1]), 0.6) def test_multiple_parameters(self): """Test setting multiple parameters""" theta = Parameter("θ") x = Parameter("x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) self.assertEqual(qc.parameters, {theta, x}) def test_multiple_named_parameters(self): """Test setting multiple named/keyword argument based parameters""" theta = Parameter(name="θ") x = Parameter(name="x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) self.assertEqual(theta.name, "θ") self.assertEqual(qc.parameters, {theta, x}) @named_data( ["int", 2, int], ["float", 2.5, float], ["float16", numpy.float16(2.5), float], ["float32", numpy.float32(2.5), float], ["float64", numpy.float64(2.5), float], ) def test_circuit_assignment_to_numeric(self, value, type_): """Test binding a numeric value to a circuit instruction""" x = Parameter("x") qc = QuantumCircuit(1) qc.append(Instruction("inst", 1, 0, [x]), (0,)) qc.assign_parameters({x: value}, inplace=True) bound = qc.data[0].operation.params[0] self.assertIsInstance(bound, type_) self.assertEqual(bound, value) def test_partial_binding(self): """Test that binding a subset of circuit parameters returns a new parameterized circuit.""" theta = Parameter("θ") x = Parameter("x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): pqc = getattr(qc, assign_fun)({theta: 2}) self.assertEqual(pqc.parameters, {x}) self.assertEqual(float(pqc.data[0].operation.params[0]), 2) self.assertEqual(float(pqc.data[1].operation.params[1]), 2) @data(True, False) def test_mixed_binding(self, inplace): """Test we can bind a mixed dict with Parameter objects and floats.""" theta = Parameter("θ") x, new_x = Parameter("x"), Parameter("new_x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) pqc = qc.assign_parameters({theta: 2, x: new_x}, inplace=inplace) if inplace: self.assertEqual(qc.parameters, {new_x}) else: self.assertEqual(pqc.parameters, {new_x}) def test_expression_partial_binding(self): """Test that binding a subset of expression parameters returns a new parameterized circuit.""" theta = Parameter("θ") phi = Parameter("phi") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta + phi, qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): pqc = getattr(qc, assign_fun)({theta: 2}) self.assertEqual(pqc.parameters, {phi}) self.assertTrue(isinstance(pqc.data[0].operation.params[0], ParameterExpression)) self.assertEqual(str(pqc.data[0].operation.params[0]), "phi + 2") fbqc = getattr(pqc, assign_fun)({phi: 1.0}) self.assertEqual(fbqc.parameters, set()) self.assertIsInstance(fbqc.data[0].operation.params[0], float) self.assertEqual(float(fbqc.data[0].operation.params[0]), 3) def test_two_parameter_expression_binding(self): """Verify that for a circuit with parameters theta and phi that we can correctly assign theta to -phi. """ theta = Parameter("theta") phi = Parameter("phi") qc = QuantumCircuit(1) qc.rx(theta, 0) qc.ry(phi, 0) self.assertEqual(len(qc._parameter_table[theta]), 1) self.assertEqual(len(qc._parameter_table[phi]), 1) qc.assign_parameters({theta: -phi}, inplace=True) self.assertEqual(len(qc._parameter_table[phi]), 2) def test_expression_partial_binding_zero(self): """Verify that binding remains possible even if a previous partial bind would reduce the expression to zero. """ theta = Parameter("theta") phi = Parameter("phi") qc = QuantumCircuit(1) qc.p(theta * phi, 0) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): pqc = getattr(qc, assign_fun)({theta: 0}) self.assertEqual(pqc.parameters, {phi}) self.assertTrue(isinstance(pqc.data[0].operation.params[0], ParameterExpression)) self.assertEqual(str(pqc.data[0].operation.params[0]), "0") fbqc = getattr(pqc, assign_fun)({phi: 1}) self.assertEqual(fbqc.parameters, set()) self.assertIsInstance(fbqc.data[0].operation.params[0], int) self.assertEqual(float(fbqc.data[0].operation.params[0]), 0) def test_raise_if_assigning_params_not_in_circuit(self): """Verify binding parameters which are not present in the circuit raises an error.""" x = Parameter("x") y = Parameter("y") z = ParameterVector("z", 3) qr = QuantumRegister(1) qc = QuantumCircuit(qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: qc = QuantumCircuit(qr) with self.subTest(assign_fun=assign_fun): qc.p(0.1, qr[0]) self.assertRaises(CircuitError, getattr(qc, assign_fun), {x: 1}) qc.p(x, qr[0]) self.assertRaises(CircuitError, getattr(qc, assign_fun), {x: 1, y: 2}) qc.p(z[1], qr[0]) self.assertRaises(CircuitError, getattr(qc, assign_fun), {z: [3, 4, 5]}) self.assertRaises(CircuitError, getattr(qc, assign_fun), {"a_str": 6}) self.assertRaises(CircuitError, getattr(qc, assign_fun), {None: 7}) def test_gate_multiplicity_binding(self): """Test binding when circuit contains multiple references to same gate""" qc = QuantumCircuit(1) theta = Parameter("theta") gate = RZGate(theta) qc.append(gate, [0], []) qc.append(gate, [0], []) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): qc2 = getattr(qc, assign_fun)({theta: 1.0}) self.assertEqual(len(qc2._parameter_table), 0) for instruction in qc2.data: self.assertEqual(float(instruction.operation.params[0]), 1.0) def test_calibration_assignment(self): """That that calibration mapping and the schedules they map are assigned together.""" theta = Parameter("theta") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [theta]), [0]) circ.measure(0, 0) rxt_q0 = pulse.Schedule( pulse.Play( pulse.library.Gaussian(duration=128, sigma=16, amp=0.2 * theta / 3.14), pulse.DriveChannel(0), ) ) circ.add_calibration("rxt", [0], rxt_q0, [theta]) circ = circ.assign_parameters({theta: 3.14}) instruction = circ.data[0] cal_key = ( tuple(circ.find_bit(q).index for q in instruction.qubits), tuple(instruction.operation.params), ) self.assertEqual(cal_key, ((0,), (3.14,))) # Make sure that key from instruction data matches the calibrations dictionary self.assertIn(cal_key, circ.calibrations["rxt"]) sched = circ.calibrations["rxt"][cal_key] self.assertEqual(sched.instructions[0][1].pulse.amp, 0.2) def test_calibration_assignment_doesnt_mutate(self): """That that assignment doesn't mutate the original circuit.""" theta = Parameter("theta") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [theta]), [0]) circ.measure(0, 0) rxt_q0 = pulse.Schedule( pulse.Play( pulse.library.Gaussian(duration=128, sigma=16, amp=0.2 * theta / 3.14), pulse.DriveChannel(0), ) ) circ.add_calibration("rxt", [0], rxt_q0, [theta]) circ_copy = copy.deepcopy(circ) assigned_circ = circ.assign_parameters({theta: 3.14}) self.assertEqual(circ.calibrations, circ_copy.calibrations) self.assertNotEqual(assigned_circ.calibrations, circ.calibrations) def test_calibration_assignment_w_expressions(self): """That calibrations with multiple parameters are assigned correctly""" theta = Parameter("theta") sigma = Parameter("sigma") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [theta / 2, sigma]), [0]) circ.measure(0, 0) rxt_q0 = pulse.Schedule( pulse.Play( pulse.library.Gaussian(duration=128, sigma=4 * sigma, amp=0.2 * theta / 3.14), pulse.DriveChannel(0), ) ) circ.add_calibration("rxt", [0], rxt_q0, [theta / 2, sigma]) circ = circ.assign_parameters({theta: 3.14, sigma: 4}) instruction = circ.data[0] cal_key = ( tuple(circ.find_bit(q).index for q in instruction.qubits), tuple(instruction.operation.params), ) self.assertEqual(cal_key, ((0,), (3.14 / 2, 4))) # Make sure that key from instruction data matches the calibrations dictionary self.assertIn(cal_key, circ.calibrations["rxt"]) sched = circ.calibrations["rxt"][cal_key] self.assertEqual(sched.instructions[0][1].pulse.amp, 0.2) self.assertEqual(sched.instructions[0][1].pulse.sigma, 16) def test_substitution(self): """Test Parameter substitution (vs bind).""" alpha = Parameter("⍺") beta = Parameter("beta") schedule = pulse.Schedule(pulse.ShiftPhase(alpha, pulse.DriveChannel(0))) circ = QuantumCircuit(3, 3) circ.append(Gate("my_rz", 1, [alpha]), [0]) circ.add_calibration("my_rz", [0], schedule, [alpha]) circ = circ.assign_parameters({alpha: 2 * beta}) circ = circ.assign_parameters({beta: 1.57}) cal_sched = circ.calibrations["my_rz"][((0,), (3.14,))] self.assertEqual(float(cal_sched.instructions[0][1].phase), 3.14) def test_partial_assignment(self): """Expressions of parameters with partial assignment.""" alpha = Parameter("⍺") beta = Parameter("beta") gamma = Parameter("γ") phi = Parameter("ϕ") with pulse.build() as my_cal: pulse.set_frequency(alpha + beta, pulse.DriveChannel(0)) pulse.shift_frequency(gamma + beta, pulse.DriveChannel(0)) pulse.set_phase(phi, pulse.DriveChannel(1)) circ = QuantumCircuit(2, 2) circ.append(Gate("custom", 2, [alpha, beta, gamma, phi]), [0, 1]) circ.add_calibration("custom", [0, 1], my_cal, [alpha, beta, gamma, phi]) # Partial bind delta = 1e9 freq = 4.5e9 shift = 0.5e9 phase = 3.14 / 4 circ = circ.assign_parameters({alpha: freq - delta}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(cal_sched.instructions[0][1].frequency, freq - delta + beta) circ = circ.assign_parameters({beta: delta}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(float(cal_sched.instructions[0][1].frequency), freq) self.assertEqual(cal_sched.instructions[1][1].frequency, gamma + delta) circ = circ.assign_parameters({gamma: shift - delta}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(float(cal_sched.instructions[1][1].frequency), shift) self.assertEqual(cal_sched.instructions[2][1].phase, phi) circ = circ.assign_parameters({phi: phase}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(float(cal_sched.instructions[2][1].phase), phase) def test_circuit_generation(self): """Test creating a series of circuits parametrically""" theta = Parameter("θ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) # generate list of circuits for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): circs = [] theta_list = numpy.linspace(0, numpy.pi, 20) for theta_i in theta_list: circs.append(getattr(qc_aer, assign_fun)({theta: theta_i})) qobj = assemble(circs) for index, theta_i in enumerate(theta_list): res = float(qobj.experiments[index].instructions[0].params[0]) self.assertTrue(math.isclose(res, theta_i), f"{res} != {theta_i}") def test_circuit_composition(self): """Test preservation of parameters when combining circuits.""" theta = Parameter("θ") qr = QuantumRegister(1) cr = ClassicalRegister(1) qc1 = QuantumCircuit(qr, cr) qc1.rx(theta, qr) phi = Parameter("phi") qc2 = QuantumCircuit(qr, cr) qc2.ry(phi, qr) qc2.h(qr) qc2.measure(qr, cr) qc3 = qc1.compose(qc2) self.assertEqual(qc3.parameters, {theta, phi}) def test_composite_instruction(self): """Test preservation of parameters via parameterized instructions.""" theta = Parameter("θ") qr1 = QuantumRegister(1, name="qr1") qc1 = QuantumCircuit(qr1) qc1.rx(theta, qr1) qc1.rz(numpy.pi / 2, qr1) qc1.ry(theta, qr1) gate = qc1.to_instruction() self.assertEqual(gate.params, [theta]) phi = Parameter("phi") qr2 = QuantumRegister(3, name="qr2") qc2 = QuantumCircuit(qr2) qc2.ry(phi, qr2[0]) qc2.h(qr2) qc2.append(gate, qargs=[qr2[1]]) self.assertEqual(qc2.parameters, {theta, phi}) def test_parameter_name_conflicts_raises(self): """Verify attempting to add different parameters with matching names raises an error.""" theta1 = Parameter("theta") theta2 = Parameter("theta") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.p(theta1, 0) self.assertRaises(CircuitError, qc.p, theta2, 0) def test_bind_ryrz_vector(self): """Test binding a list of floats to a ParameterVector""" qc = QuantumCircuit(4) depth = 4 theta = ParameterVector("θ", length=len(qc.qubits) * depth * 2) theta_iter = iter(theta) for _ in range(depth): for q in qc.qubits: qc.ry(next(theta_iter), q) qc.rz(next(theta_iter), q) for i, q in enumerate(qc.qubits[:-1]): qc.cx(qc.qubits[i], qc.qubits[i + 1]) qc.barrier() theta_vals = numpy.linspace(0, 1, len(theta)) * numpy.pi self.assertEqual(set(qc.parameters), set(theta.params)) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bqc = getattr(qc, assign_fun)({theta: theta_vals}) for instruction in bqc.data: if hasattr(instruction.operation, "params") and instruction.operation.params: self.assertIn(float(instruction.operation.params[0]), theta_vals) def test_compile_vector(self): """Test compiling a circuit with an unbound ParameterVector""" qc = QuantumCircuit(4) depth = 4 theta = ParameterVector("θ", length=len(qc.qubits) * depth * 2) theta_iter = iter(theta) for _ in range(depth): for q in qc.qubits: qc.ry(next(theta_iter), q) qc.rz(next(theta_iter), q) for i, q in enumerate(qc.qubits[:-1]): qc.cx(qc.qubits[i], qc.qubits[i + 1]) qc.barrier() backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) for param in theta: self.assertIn(param, qc_aer.parameters) def test_instruction_ryrz_vector(self): """Test constructing a circuit from instructions with remapped ParameterVectors""" qubits = 5 depth = 4 ryrz = QuantumCircuit(qubits, name="ryrz") theta = ParameterVector("θ0", length=len(ryrz.qubits) * 2) theta_iter = iter(theta) for q in ryrz.qubits: ryrz.ry(next(theta_iter), q) ryrz.rz(next(theta_iter), q) cxs = QuantumCircuit(qubits - 1, name="cxs") for i, _ in enumerate(cxs.qubits[:-1:2]): cxs.cx(cxs.qubits[2 * i], cxs.qubits[2 * i + 1]) paramvecs = [] qc = QuantumCircuit(qubits) for i in range(depth): theta_l = ParameterVector(f"θ{i + 1}", length=len(ryrz.qubits) * 2) ryrz_inst = ryrz.to_instruction(parameter_map={theta: theta_l}) paramvecs += [theta_l] qc.append(ryrz_inst, qargs=qc.qubits) qc.append(cxs, qargs=qc.qubits[1:]) qc.append(cxs, qargs=qc.qubits[:-1]) qc.barrier() backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) for vec in paramvecs: for param in vec: self.assertIn(param, qc_aer.parameters) @data("single", "vector") def test_parameter_equality_through_serialization(self, ptype): """Verify parameters maintain their equality after serialization.""" if ptype == "single": x1 = Parameter("x") x2 = Parameter("x") else: x1 = ParameterVector("x", 2)[0] x2 = ParameterVector("x", 2)[0] x1_p = pickle.loads(pickle.dumps(x1)) x2_p = pickle.loads(pickle.dumps(x2)) self.assertEqual(x1, x1_p) self.assertEqual(x2, x2_p) self.assertNotEqual(x1, x2_p) self.assertNotEqual(x2, x1_p) def test_binding_parameterized_circuits_built_in_multiproc(self): """Verify subcircuits built in a subprocess can still be bound.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2429 num_processes = 4 qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) parameters = [Parameter(f"x{i}") for i in range(num_processes)] results = parallel_map( _construct_circuit, parameters, task_args=(qr,), num_processes=num_processes ) for qc in results: circuit.compose(qc, inplace=True) parameter_values = [{x: 1.0 for x in parameters}] qobj = assemble( circuit, backend=BasicAer.get_backend("qasm_simulator"), parameter_binds=parameter_values, ) self.assertEqual(len(qobj.experiments), 1) self.assertEqual(len(qobj.experiments[0].instructions), 4) self.assertTrue( all( len(inst.params) == 1 and isinstance(inst.params[0], float) and float(inst.params[0]) == 1 for inst in qobj.experiments[0].instructions ) ) def test_transpiling_multiple_parameterized_circuits(self): """Verify several parameterized circuits can be transpiled at once.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2864 qr = QuantumRegister(1) qc1 = QuantumCircuit(qr) qc2 = QuantumCircuit(qr) theta = Parameter("theta") qc1.u(theta, 0, 0, qr[0]) qc2.u(theta, 3.14, 0, qr[0]) circuits = [qc1, qc2] job = execute( circuits, BasicAer.get_backend("unitary_simulator"), shots=512, parameter_binds=[{theta: 1}], ) self.assertTrue(len(job.result().results), 2) @data(0, 1, 2, 3) def test_transpile_across_optimization_levels(self, opt_level): """Verify parameterized circuits can be transpiled with all default pass managers.""" qc = QuantumCircuit(5, 5) theta = Parameter("theta") phi = Parameter("phi") qc.rx(theta, 0) qc.x(0) for i in range(5 - 1): qc.rxx(phi, i, i + 1) qc.measure(range(5 - 1), range(5 - 1)) transpile(qc, FakeOurense(), optimization_level=opt_level) def test_repeated_gates_to_dag_and_back(self): """Verify circuits with repeated parameterized gates can be converted to DAG and back, maintaining consistency of circuit._parameter_table.""" from qiskit.converters import circuit_to_dag, dag_to_circuit qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") qc.p(theta, qr[0]) double_qc = qc.compose(qc) test_qc = dag_to_circuit(circuit_to_dag(double_qc)) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bound_test_qc = getattr(test_qc, assign_fun)({theta: 1}) self.assertEqual(len(bound_test_qc.parameters), 0) def test_rebinding_instruction_copy(self): """Test rebinding a copied instruction does not modify the original.""" theta = Parameter("th") qc = QuantumCircuit(1) qc.rx(theta, 0) instr = qc.to_instruction() qc1 = QuantumCircuit(1) qc1.append(instr, [0]) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): output1 = getattr(qc1, assign_fun)({theta: 0.1}).decompose() output2 = getattr(qc1, assign_fun)({theta: 0.2}).decompose() expected1 = QuantumCircuit(1) expected1.rx(0.1, 0) expected2 = QuantumCircuit(1) expected2.rx(0.2, 0) self.assertEqual(expected1, output1) self.assertEqual(expected2, output2) @combine(target_type=["gate", "instruction"], parameter_type=["numbers", "parameters"]) def test_decompose_propagates_bound_parameters(self, target_type, parameter_type): """Verify bind-before-decompose preserves bound values.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2482 theta = Parameter("th") qc = QuantumCircuit(1) qc.rx(theta, 0) if target_type == "gate": inst = qc.to_gate() elif target_type == "instruction": inst = qc.to_instruction() qc2 = QuantumCircuit(1) qc2.append(inst, [0]) if parameter_type == "numbers": bound_qc2 = qc2.assign_parameters({theta: 0.5}) expected_parameters = set() expected_qc2 = QuantumCircuit(1) expected_qc2.rx(0.5, 0) else: phi = Parameter("ph") bound_qc2 = qc2.assign_parameters({theta: phi}) expected_parameters = {phi} expected_qc2 = QuantumCircuit(1) expected_qc2.rx(phi, 0) decomposed_qc2 = bound_qc2.decompose() with self.subTest(msg="testing parameters of initial circuit"): self.assertEqual(qc2.parameters, {theta}) with self.subTest(msg="testing parameters of bound circuit"): self.assertEqual(bound_qc2.parameters, expected_parameters) with self.subTest(msg="testing parameters of deep decomposed bound circuit"): self.assertEqual(decomposed_qc2.parameters, expected_parameters) with self.subTest(msg="testing deep decomposed circuit"): self.assertEqual(decomposed_qc2, expected_qc2) @combine(target_type=["gate", "instruction"], parameter_type=["numbers", "parameters"]) def test_decompose_propagates_deeply_bound_parameters(self, target_type, parameter_type): """Verify bind-before-decompose preserves deeply bound values.""" theta = Parameter("th") qc1 = QuantumCircuit(1) qc1.rx(theta, 0) if target_type == "gate": inst = qc1.to_gate() elif target_type == "instruction": inst = qc1.to_instruction() qc2 = QuantumCircuit(1) qc2.append(inst, [0]) if target_type == "gate": inst = qc2.to_gate() elif target_type == "instruction": inst = qc2.to_instruction() qc3 = QuantumCircuit(1) qc3.append(inst, [0]) if parameter_type == "numbers": bound_qc3 = qc3.assign_parameters({theta: 0.5}) expected_parameters = set() expected_qc3 = QuantumCircuit(1) expected_qc3.rx(0.5, 0) else: phi = Parameter("ph") bound_qc3 = qc3.assign_parameters({theta: phi}) expected_parameters = {phi} expected_qc3 = QuantumCircuit(1) expected_qc3.rx(phi, 0) deep_decomposed_qc3 = bound_qc3.decompose().decompose() with self.subTest(msg="testing parameters of initial circuit"): self.assertEqual(qc3.parameters, {theta}) with self.subTest(msg="testing parameters of bound circuit"): self.assertEqual(bound_qc3.parameters, expected_parameters) with self.subTest(msg="testing parameters of deep decomposed bound circuit"): self.assertEqual(deep_decomposed_qc3.parameters, expected_parameters) with self.subTest(msg="testing deep decomposed circuit"): self.assertEqual(deep_decomposed_qc3, expected_qc3) @data("gate", "instruction") def test_executing_parameterized_instruction_bound_early(self, target_type): """Verify bind-before-execute preserves bound values.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2482 theta = Parameter("theta") sub_qc = QuantumCircuit(2) sub_qc.h(0) sub_qc.cx(0, 1) sub_qc.rz(theta, [0, 1]) sub_qc.cx(0, 1) sub_qc.h(0) if target_type == "gate": sub_inst = sub_qc.to_gate() elif target_type == "instruction": sub_inst = sub_qc.to_instruction() unbound_qc = QuantumCircuit(2, 1) unbound_qc.append(sub_inst, [0, 1], []) unbound_qc.measure(0, 0) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bound_qc = getattr(unbound_qc, assign_fun)({theta: numpy.pi / 2}) shots = 1024 job = execute(bound_qc, backend=BasicAer.get_backend("qasm_simulator"), shots=shots) self.assertDictAlmostEqual(job.result().get_counts(), {"1": shots}, 0.05 * shots) def test_num_parameters(self): """Test the num_parameters property.""" with self.subTest(msg="standard case"): theta = Parameter("θ") x = Parameter("x") qc = QuantumCircuit(1) qc.rx(theta, 0) qc.u(0, theta, x, 0) self.assertEqual(qc.num_parameters, 2) with self.subTest(msg="parameter vector"): params = ParameterVector("x", length=3) qc = QuantumCircuit(4) qc.rx(params[0], 2) qc.ry(params[1], 1) qc.rz(params[2], 3) self.assertEqual(qc.num_parameters, 3) with self.subTest(msg="no params"): qc = QuantumCircuit(1) qc.x(0) self.assertEqual(qc.num_parameters, 0) def test_execute_result_names(self): """Test unique names for list of parameter binds.""" theta = Parameter("θ") reps = 5 qc = QuantumCircuit(1, 1) qc.rx(theta, 0) qc.measure(0, 0) plist = [{theta: i} for i in range(reps)] simulator = BasicAer.get_backend("qasm_simulator") result = execute(qc, backend=simulator, parameter_binds=plist).result() result_names = {res.name for res in result.results} self.assertEqual(reps, len(result_names)) def test_to_instruction_after_inverse(self): """Verify converting an inverse generates a valid ParameterTable""" # ref: https://github.com/Qiskit/qiskit-terra/issues/4235 qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) inv_instr = qc.inverse().to_instruction() self.assertIsInstance(inv_instr, Instruction) def test_repeated_circuit(self): """Test repeating a circuit maintains the parameters.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) rep = qc.repeat(3) self.assertEqual(rep.parameters, {theta}) def test_copy_after_inverse(self): """Verify circuit.inverse generates a valid ParameterTable.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) inverse = qc.inverse() self.assertIn(theta, inverse.parameters) raise_if_parameter_table_invalid(inverse) def test_copy_after_reverse(self): """Verify circuit.reverse generates a valid ParameterTable.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) reverse = qc.reverse_ops() self.assertIn(theta, reverse.parameters) raise_if_parameter_table_invalid(reverse) def test_copy_after_dot_data_setter(self): """Verify setting circuit.data generates a valid ParameterTable.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) qc.data = [] self.assertEqual(qc.parameters, set()) raise_if_parameter_table_invalid(qc) def test_circuit_with_ufunc(self): """Test construction of circuit and binding of parameters after we apply universal functions.""" from math import pi phi = Parameter(name="phi") theta = Parameter(name="theta") qc = QuantumCircuit(2) qc.p(numpy.abs(-phi), 0) qc.p(numpy.cos(phi), 0) qc.p(numpy.sin(phi), 0) qc.p(numpy.tan(phi), 0) qc.rz(numpy.arccos(theta), 1) qc.rz(numpy.arctan(theta), 1) qc.rz(numpy.arcsin(theta), 1) qc.assign_parameters({phi: pi, theta: 1}, inplace=True) qc_ref = QuantumCircuit(2) qc_ref.p(pi, 0) qc_ref.p(-1, 0) qc_ref.p(0, 0) qc_ref.p(0, 0) qc_ref.rz(0, 1) qc_ref.rz(pi / 4, 1) qc_ref.rz(pi / 2, 1) self.assertEqual(qc, qc_ref) def test_compile_with_ufunc(self): """Test compiling of circuit with unbound parameters after we apply universal functions.""" from math import pi theta = ParameterVector("theta", length=7) qc = QuantumCircuit(7) qc.rx(numpy.abs(theta[0]), 0) qc.rx(numpy.cos(theta[1]), 1) qc.rx(numpy.sin(theta[2]), 2) qc.rx(numpy.tan(theta[3]), 3) qc.rx(numpy.arccos(theta[4]), 4) qc.rx(numpy.arctan(theta[5]), 5) qc.rx(numpy.arcsin(theta[6]), 6) # transpile to different basis transpiled = transpile(qc, basis_gates=["rz", "sx", "x", "cx"], optimization_level=0) for x in theta: self.assertIn(x, transpiled.parameters) bound = transpiled.bind_parameters({theta: [-1, pi, pi, pi, 1, 1, 1]}) expected = QuantumCircuit(7) expected.rx(1.0, 0) expected.rx(-1.0, 1) expected.rx(0.0, 2) expected.rx(0.0, 3) expected.rx(0.0, 4) expected.rx(pi / 4, 5) expected.rx(pi / 2, 6) expected = transpile(expected, basis_gates=["rz", "sx", "x", "cx"], optimization_level=0) self.assertEqual(expected, bound) def test_parametervector_resize(self): """Test the resize method of the parameter vector.""" vec = ParameterVector("x", 2) element = vec[1] # store an entry for instancecheck later on with self.subTest("shorten"): vec.resize(1) self.assertEqual(len(vec), 1) self.assertListEqual([param.name for param in vec], _paramvec_names("x", 1)) with self.subTest("enlargen"): vec.resize(3) self.assertEqual(len(vec), 3) # ensure we still have the same instance not a copy with the same name # this is crucial for adding parameters to circuits since we cannot use the same # name if the instance is not the same self.assertIs(element, vec[1]) self.assertListEqual([param.name for param in vec], _paramvec_names("x", 3)) def test_raise_if_sub_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") with self.assertRaisesRegex(CircuitError, "not present"): x.subs({y: z}) def test_sub_allow_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") subbed = x.subs({y: z}, allow_unknown_parameters=True) self.assertEqual(subbed, x) def _construct_circuit(param, qr): qc = QuantumCircuit(qr) qc.ry(param, qr[0]) return qc def _paramvec_names(prefix, length): return [f"{prefix}[{i}]" for i in range(length)] @ddt class TestParameterExpressions(QiskitTestCase): """Test expressions of Parameters.""" supported_operations = [add, sub, mul, truediv] def test_compare_to_value_when_bound(self): """Verify expression can be compared to a fixed value when fully bound.""" x = Parameter("x") bound_expr = x.bind({x: 2.3}) self.assertEqual(bound_expr, 2.3) def test_abs_function_when_bound(self): """Verify expression can be used with abs functions when bound.""" x = Parameter("x") xb_1 = x.bind({x: 2.0}) xb_2 = x.bind({x: 3.0 + 4.0j}) self.assertEqual(abs(xb_1), 2.0) self.assertEqual(abs(-xb_1), 2.0) self.assertEqual(abs(xb_2), 5.0) def test_abs_function_when_not_bound(self): """Verify expression can be used with abs functions when not bound.""" x = Parameter("x") y = Parameter("y") self.assertEqual(abs(x), abs(-x)) self.assertEqual(abs(x) * abs(y), abs(x * y)) self.assertEqual(abs(x) / abs(y), abs(x / y)) def test_cast_to_complex_when_bound(self): """Verify that the cast to complex works for bound objects.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 1.0, y: 1j}) self.assertEqual(complex(bound_expr), 1 + 1j) def test_raise_if_cast_to_complex_when_not_fully_bound(self): """Verify raises if casting to complex and not fully bound.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 1j}) with self.assertRaisesRegex(TypeError, "unbound parameters"): complex(bound_expr) def test_cast_to_float_when_bound(self): """Verify expression can be cast to a float when fully bound.""" x = Parameter("x") bound_expr = x.bind({x: 2.3}) self.assertEqual(float(bound_expr), 2.3) def test_cast_to_float_when_underlying_expression_bound(self): """Verify expression can be cast to a float when it still contains unbound parameters, but the underlying symbolic expression has a knowable value.""" x = Parameter("x") expr = x - x + 2.3 self.assertEqual(float(expr), 2.3) def test_cast_to_float_intermediate_complex_value(self): """Verify expression can be cast to a float when it is fully bound, but an intermediate part of the expression evaluation involved complex types. Sympy is generally more permissive than symengine here, and sympy's tends to be the expected behaviour for our users.""" x = Parameter("x") bound_expr = (x + 1.0 + 1.0j).bind({x: -1.0j}) self.assertEqual(float(bound_expr), 1.0) def test_cast_to_float_of_complex_fails(self): """Test that an attempt to produce a float from a complex value fails if there is an imaginary part, with a sensible error message.""" x = Parameter("x") bound_expr = (x + 1.0j).bind({x: 1.0}) with self.assertRaisesRegex(TypeError, "could not cast expression to float"): float(bound_expr) def test_raise_if_cast_to_float_when_not_fully_bound(self): """Verify raises if casting to float and not fully bound.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 2.3}) with self.assertRaisesRegex(TypeError, "unbound parameters"): float(bound_expr) def test_cast_to_int_when_bound(self): """Verify expression can be cast to an int when fully bound.""" x = Parameter("x") bound_expr = x.bind({x: 2.3}) self.assertEqual(int(bound_expr), 2) def test_cast_to_int_when_bound_truncates_after_evaluation(self): """Verify expression can be cast to an int when fully bound, but truncated only after evaluation.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 2.3, y: 0.8}) self.assertEqual(int(bound_expr), 3) def test_cast_to_int_when_underlying_expression_bound(self): """Verify expression can be cast to a int when it still contains unbound parameters, but the underlying symbolic expression has a knowable value.""" x = Parameter("x") expr = x - x + 2.3 self.assertEqual(int(expr), 2) def test_raise_if_cast_to_int_when_not_fully_bound(self): """Verify raises if casting to int and not fully bound.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 2.3}) with self.assertRaisesRegex(TypeError, "unbound parameters"): int(bound_expr) def test_raise_if_sub_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") expr = x + 2 y = Parameter("y") z = Parameter("z") with self.assertRaisesRegex(CircuitError, "not present"): expr.subs({y: z}) def test_sub_allow_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") expr = x + 2 y = Parameter("y") z = Parameter("z") subbed = expr.subs({y: z}, allow_unknown_parameters=True) self.assertEqual(subbed, expr) def test_raise_if_subbing_in_parameter_name_conflict(self): """Verify we raise if substituting in conflicting parameter names.""" x = Parameter("x") y_first = Parameter("y") expr = x + y_first y_second = Parameter("y") # Replacing an existing name is okay. expr.subs({y_first: y_second}) with self.assertRaisesRegex(CircuitError, "Name conflict"): expr.subs({x: y_second}) def test_expressions_of_parameter_with_constant(self): """Verify operating on a Parameter with a constant.""" good_constants = [2, 1.3, 0, -1, -1.0, numpy.pi, 1j] x = Parameter("x") for op in self.supported_operations: for const in good_constants: expr = op(const, x) bound_expr = expr.bind({x: 2.3}) self.assertEqual(complex(bound_expr), op(const, 2.3)) # Division by zero will raise. Tested elsewhere. if const == 0 and op == truediv: continue # Repeat above, swapping position of Parameter and constant. expr = op(x, const) bound_expr = expr.bind({x: 2.3}) res = complex(bound_expr) expected = op(2.3, const) self.assertTrue(cmath.isclose(res, expected), f"{res} != {expected}") def test_complex_parameter_bound_to_real(self): """Test a complex parameter expression can be real if bound correctly.""" x, y = Parameter("x"), Parameter("y") with self.subTest("simple 1j * x"): qc = QuantumCircuit(1) qc.rx(1j * x, 0) bound = qc.bind_parameters({x: 1j}) ref = QuantumCircuit(1) ref.rx(-1, 0) self.assertEqual(bound, ref) with self.subTest("more complex expression"): qc = QuantumCircuit(1) qc.rx(0.5j * x - y * y + 2 * y, 0) bound = qc.bind_parameters({x: -4, y: 1j}) ref = QuantumCircuit(1) ref.rx(1, 0) self.assertEqual(bound, ref) def test_complex_angle_raises_when_not_supported(self): """Test parameters are validated when fully bound and errors are raised accordingly.""" x = Parameter("x") qc = QuantumCircuit(1) qc.r(x, 1j * x, 0) with self.subTest("binding x to 0 yields real parameters"): bound = qc.bind_parameters({x: 0}) ref = QuantumCircuit(1) ref.r(0, 0, 0) self.assertEqual(bound, ref) with self.subTest("binding x to 1 yields complex parameters"): # RGate does not support complex parameters with self.assertRaises(CircuitError): bound = qc.bind_parameters({x: 1}) def test_operating_on_a_parameter_with_a_non_float_will_raise(self): """Verify operations between a Parameter and a non-float will raise.""" bad_constants = ["1", numpy.Inf, numpy.NaN, None, {}, []] x = Parameter("x") for op in self.supported_operations: for const in bad_constants: with self.subTest(op=op, const=const): with self.assertRaises(TypeError): _ = op(const, x) with self.assertRaises(TypeError): _ = op(x, const) def test_expressions_division_by_zero(self): """Verify dividing a Parameter by 0, or binding 0 as a denominator raises.""" x = Parameter("x") with self.assertRaises(ZeroDivisionError): _ = x / 0 with self.assertRaises(ZeroDivisionError): _ = x / 0.0 expr = 2 / x with self.assertRaises(ZeroDivisionError): _ = expr.bind({x: 0}) with self.assertRaises(ZeroDivisionError): _ = expr.bind({x: 0.0}) def test_expressions_of_parameter_with_parameter(self): """Verify operating on two Parameters.""" x = Parameter("x") y = Parameter("y") for op in self.supported_operations: expr = op(x, y) partially_bound_expr = expr.bind({x: 2.3}) self.assertEqual(partially_bound_expr.parameters, {y}) fully_bound_expr = partially_bound_expr.bind({y: -numpy.pi}) self.assertEqual(fully_bound_expr.parameters, set()) self.assertEqual(float(fully_bound_expr), op(2.3, -numpy.pi)) bound_expr = expr.bind({x: 2.3, y: -numpy.pi}) self.assertEqual(bound_expr.parameters, set()) self.assertEqual(float(bound_expr), op(2.3, -numpy.pi)) def test_expressions_operation_order(self): """Verify ParameterExpressions respect order of operations.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") # Parenthesis before multiplication/division expr = (x + y) * z bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 9) expr = x * (y + z) bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 5) # Multiplication/division before addition/subtraction expr = x + y * z bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 7) expr = x * y + z bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 5) def test_nested_expressions(self): """Verify ParameterExpressions can also be the target of operations.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") expr1 = x * y expr2 = expr1 + z bound_expr2 = expr2.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr2), 5) def test_negated_expression(self): """Verify ParameterExpressions can be negated.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") expr1 = -x + y expr2 = -expr1 * (-z) bound_expr2 = expr2.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr2), 3) def test_standard_cu3(self): """This tests parameter negation in standard extension gate cu3.""" from qiskit.circuit.library import CU3Gate x = Parameter("x") y = Parameter("y") z = Parameter("z") qc = qiskit.QuantumCircuit(2) qc.append(CU3Gate(x, y, z), [0, 1]) try: qc.decompose() except TypeError: self.fail("failed to decompose cu3 gate with negated parameter expression") def test_name_collision(self): """Verify Expressions of distinct Parameters of shared name raises.""" x = Parameter("p") y = Parameter("p") # Expression of the same Parameter are valid. _ = x + x _ = x - x _ = x * x _ = x / x with self.assertRaises(CircuitError): _ = x + y with self.assertRaises(CircuitError): _ = x - y with self.assertRaises(CircuitError): _ = x * y with self.assertRaises(CircuitError): _ = x / y @combine(target_type=["gate", "instruction"], order=["bind-decompose", "decompose-bind"]) def test_to_instruction_with_expression(self, target_type, order): """Test preservation of expressions via parameterized instructions. ┌───────┐┌──────────┐┌───────────┐ qr1_0: |0>┤ Rx(θ) ├┤ Rz(pi/2) ├┤ Ry(phi*θ) ├ └───────┘└──────────┘└───────────┘ ┌───────────┐ qr2_0: |0>───┤ Ry(delta) ├─── ┌──┴───────────┴──┐ qr2_1: |0>┤ Circuit0(phi,θ) ├ └─────────────────┘ qr2_2: |0>─────────────────── """ theta = Parameter("θ") phi = Parameter("phi") qr1 = QuantumRegister(1, name="qr1") qc1 = QuantumCircuit(qr1) qc1.rx(theta, qr1) qc1.rz(numpy.pi / 2, qr1) qc1.ry(theta * phi, qr1) if target_type == "gate": gate = qc1.to_gate() elif target_type == "instruction": gate = qc1.to_instruction() self.assertEqual(gate.params, [phi, theta]) delta = Parameter("delta") qr2 = QuantumRegister(3, name="qr2") qc2 = QuantumCircuit(qr2) qc2.ry(delta, qr2[0]) qc2.append(gate, qargs=[qr2[1]]) self.assertEqual(qc2.parameters, {delta, theta, phi}) binds = {delta: 1, theta: 2, phi: 3} expected_qc = QuantumCircuit(qr2) expected_qc.rx(2, 1) expected_qc.rz(numpy.pi / 2, 1) expected_qc.ry(3 * 2, 1) expected_qc.r(1, numpy.pi / 2, 0) if order == "bind-decompose": decomp_bound_qc = qc2.assign_parameters(binds).decompose() elif order == "decompose-bind": decomp_bound_qc = qc2.decompose().assign_parameters(binds) self.assertEqual(decomp_bound_qc.parameters, set()) self.assertEqual(decomp_bound_qc, expected_qc) @combine(target_type=["gate", "instruction"], order=["bind-decompose", "decompose-bind"]) def test_to_instruction_expression_parameter_map(self, target_type, order): """Test preservation of expressions via instruction parameter_map.""" theta = Parameter("θ") phi = Parameter("phi") qr1 = QuantumRegister(1, name="qr1") qc1 = QuantumCircuit(qr1) qc1.rx(theta, qr1) qc1.rz(numpy.pi / 2, qr1) qc1.ry(theta * phi, qr1) theta_p = Parameter("theta") phi_p = Parameter("phi") if target_type == "gate": gate = qc1.to_gate(parameter_map={theta: theta_p, phi: phi_p}) elif target_type == "instruction": gate = qc1.to_instruction(parameter_map={theta: theta_p, phi: phi_p}) self.assertListEqual(gate.params, [theta_p, phi_p]) delta = Parameter("delta") qr2 = QuantumRegister(3, name="qr2") qc2 = QuantumCircuit(qr2) qc2.ry(delta, qr2[0]) qc2.append(gate, qargs=[qr2[1]]) self.assertListEqual(list(qc2.parameters), [delta, phi_p, theta_p]) binds = {delta: 1, theta_p: 2, phi_p: 3} expected_qc = QuantumCircuit(qr2) expected_qc.rx(2, 1) expected_qc.rz(numpy.pi / 2, 1) expected_qc.ry(3 * 2, 1) expected_qc.r(1, numpy.pi / 2, 0) if order == "bind-decompose": decomp_bound_qc = qc2.assign_parameters(binds).decompose() elif order == "decompose-bind": decomp_bound_qc = qc2.decompose().assign_parameters(binds) self.assertEqual(decomp_bound_qc.parameters, set()) self.assertEqual(decomp_bound_qc, expected_qc) def test_binding_across_broadcast_instruction(self): """Bind a parameter which was included via a broadcast instruction.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/3008 theta = Parameter("θ") n = 5 qc = QuantumCircuit(n, 1) qc.h(0) for i in range(n - 1): qc.cx(i, i + 1) qc.barrier() qc.rz(theta, range(n)) qc.barrier() for i in reversed(range(n - 1)): qc.cx(i, i + 1) qc.h(0) qc.measure(0, 0) theta_range = numpy.linspace(0, 2 * numpy.pi, 128) circuits = [qc.assign_parameters({theta: theta_val}) for theta_val in theta_range] self.assertEqual(len(circuits), len(theta_range)) for theta_val, bound_circ in zip(theta_range, circuits): rz_gates = [ inst.operation for inst in bound_circ.data if isinstance(inst.operation, RZGate) ] self.assertEqual(len(rz_gates), n) self.assertTrue(all(float(gate.params[0]) == theta_val for gate in rz_gates)) def test_substituting_parameter_with_simple_expression(self): """Substitute a simple parameter expression for a parameter.""" x = Parameter("x") y = Parameter("y") sub_ = y / 2 updated_expr = x.subs({x: sub_}) expected = y / 2 self.assertEqual(updated_expr, expected) def test_substituting_parameter_with_compound_expression(self): """Substitute a simple parameter expression for a parameter.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") sub_ = y * z updated_expr = x.subs({x: sub_}) expected = y * z self.assertEqual(updated_expr, expected) def test_substituting_simple_with_simple_expression(self): """Substitute a simple parameter expression in a parameter expression.""" x = Parameter("x") expr = x * x y = Parameter("y") sub_ = y / 2 updated_expr = expr.subs({x: sub_}) expected = y * y / 4 self.assertEqual(updated_expr, expected) def test_substituting_compound_expression(self): """Substitute a compound parameter expression in a parameter expression.""" x = Parameter("x") expr = x * x y = Parameter("y") z = Parameter("z") sub_ = y + z updated_expr = expr.subs({x: sub_}) expected = (y + z) * (y + z) self.assertEqual(updated_expr, expected) def test_conjugate(self): """Test calling conjugate on a ParameterExpression.""" x = Parameter("x") self.assertEqual((x.conjugate() + 1j), (x - 1j).conjugate()) @data( circlib.RGate, circlib.RXGate, circlib.RYGate, circlib.RZGate, circlib.RXXGate, circlib.RYYGate, circlib.RZXGate, circlib.RZZGate, circlib.CRXGate, circlib.CRYGate, circlib.CRZGate, circlib.XXPlusYYGate, ) def test_bound_gate_to_matrix(self, gate_class): """Test to_matrix works if previously free parameters are bound. The conversion might fail, if trigonometric functions such as cos are called on the parameters and the parameters are still of type ParameterExpression. """ num_parameters = 2 if gate_class == circlib.RGate else 1 params = list(range(1, 1 + num_parameters)) free_params = ParameterVector("th", num_parameters) gate = gate_class(*params) num_qubits = gate.num_qubits circuit = QuantumCircuit(num_qubits) circuit.append(gate_class(*free_params), list(range(num_qubits))) bound_circuit = circuit.assign_parameters({free_params: params}) numpy.testing.assert_array_almost_equal(Operator(bound_circuit).data, gate.to_matrix()) def test_parameter_expression_grad(self): """Verify correctness of ParameterExpression gradients.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") with self.subTest(msg="first order gradient"): expr = (x + y) * z self.assertEqual(expr.gradient(x), z) self.assertEqual(expr.gradient(z), (x + y)) with self.subTest(msg="second order gradient"): expr = x * x self.assertEqual(expr.gradient(x), 2 * x) self.assertEqual(expr.gradient(x).gradient(x), 2) def test_bound_expression_is_real(self): """Test is_real on bound parameters.""" x = Parameter("x") self.assertEqual(x.is_real(), None) self.assertEqual((1j * x).is_real(), None) expr = 1j * x bound = expr.bind({x: 2}) self.assertEqual(bound.is_real(), False) bound = x.bind({x: 0 + 0j}) self.assertEqual(bound.is_real(), True) bound = x.bind({x: 0 + 1j}) self.assertEqual(bound.is_real(), False) bound = x.bind({x: 1 + 0j}) self.assertEqual(bound.is_real(), True) bound = x.bind({x: 1 + 1j}) self.assertEqual(bound.is_real(), False) class TestParameterEquality(QiskitTestCase): """Test equality of Parameters and ParameterExpressions.""" def test_parameter_equal_self(self): """Verify a parameter is equal to it self.""" theta = Parameter("theta") self.assertEqual(theta, theta) def test_parameter_not_equal_param_of_same_name(self): """Verify a parameter is not equal to a Parameter of the same name.""" theta1 = Parameter("theta") theta2 = Parameter("theta") self.assertNotEqual(theta1, theta2) def test_parameter_expression_equal_to_self(self): """Verify an expression is equal to itself.""" theta = Parameter("theta") expr = 2 * theta self.assertEqual(expr, expr) def test_parameter_expression_equal_to_identical(self): """Verify an expression is equal an identical expression.""" theta = Parameter("theta") expr1 = 2 * theta expr2 = 2 * theta self.assertEqual(expr1, expr2) def test_parameter_expression_equal_floats_to_ints(self): """Verify an expression with float and int is identical.""" theta = Parameter("theta") expr1 = 2.0 * theta expr2 = 2 * theta self.assertEqual(expr1, expr2) def test_parameter_expression_not_equal_if_params_differ(self): """Verify expressions not equal if parameters are different.""" theta1 = Parameter("theta") theta2 = Parameter("theta") expr1 = 2 * theta1 expr2 = 2 * theta2 self.assertNotEqual(expr1, expr2) def test_parameter_equal_to_identical_expression(self): """Verify parameters and ParameterExpressions can be equal if identical.""" theta = Parameter("theta") phi = Parameter("phi") expr = (theta + phi).bind({phi: 0}) self.assertEqual(expr, theta) self.assertEqual(theta, expr) def test_parameter_symbol_equal_after_ufunc(self): """Verfiy ParameterExpression phi and ParameterExpression cos(phi) have the same symbol map""" phi = Parameter("phi") cos_phi = numpy.cos(phi) self.assertEqual(phi._parameter_symbols, cos_phi._parameter_symbols) class TestParameterReferences(QiskitTestCase): """Test the ParameterReferences class.""" def test_equal_inst_diff_instance(self): """Different value equal instructions are treated as distinct.""" theta = Parameter("theta") gate1 = RZGate(theta) gate2 = RZGate(theta) self.assertIsNot(gate1, gate2) self.assertEqual(gate1, gate2) refs = ParameterReferences(((gate1, 0), (gate2, 0))) # test __contains__ self.assertIn((gate1, 0), refs) self.assertIn((gate2, 0), refs) gate_ids = {id(gate1), id(gate2)} self.assertEqual(gate_ids, {id(gate) for gate, _ in refs}) self.assertTrue(all(idx == 0 for _, idx in refs)) def test_pickle_unpickle(self): """Membership testing after pickle/unpickle.""" theta = Parameter("theta") gate1 = RZGate(theta) gate2 = RZGate(theta) self.assertIsNot(gate1, gate2) self.assertEqual(gate1, gate2) refs = ParameterReferences(((gate1, 0), (gate2, 0))) to_pickle = (gate1, refs) pickled = pickle.dumps(to_pickle) (gate1_new, refs_new) = pickle.loads(pickled) self.assertEqual(len(refs_new), len(refs)) self.assertNotIn((gate1, 0), refs_new) self.assertIn((gate1_new, 0), refs_new) def test_equal_inst_same_instance(self): """Referentially equal instructions are treated as same.""" theta = Parameter("theta") gate = RZGate(theta) refs = ParameterReferences(((gate, 0), (gate, 0))) self.assertIn((gate, 0), refs) self.assertEqual(len(refs), 1) self.assertIs(next(iter(refs))[0], gate) self.assertEqual(next(iter(refs))[1], 0) def test_extend_refs(self): """Extending references handles duplicates.""" theta = Parameter("theta") ref0 = (RZGate(theta), 0) ref1 = (RZGate(theta), 0) ref2 = (RZGate(theta), 0) refs = ParameterReferences((ref0,)) refs |= ParameterReferences((ref0, ref1, ref2, ref1, ref0)) self.assertEqual(refs, ParameterReferences((ref0, ref1, ref2))) def test_copy_param_refs(self): """Copy of parameter references is a shallow copy.""" theta = Parameter("theta") ref0 = (RZGate(theta), 0) ref1 = (RZGate(theta), 0) ref2 = (RZGate(theta), 0) ref3 = (RZGate(theta), 0) refs = ParameterReferences((ref0, ref1)) refs_copy = refs.copy() # Check same gate instances in copy gate_ids = {id(ref0[0]), id(ref1[0])} self.assertEqual({id(gate) for gate, _ in refs_copy}, gate_ids) # add new ref to original and check copy not modified refs.add(ref2) self.assertNotIn(ref2, refs_copy) self.assertEqual(refs_copy, ParameterReferences((ref0, ref1))) # add new ref to copy and check original not modified refs_copy.add(ref3) self.assertNotIn(ref3, refs) self.assertEqual(refs, ParameterReferences((ref0, ref1, ref2))) class TestParameterTable(QiskitTestCase): """Test the ParameterTable class.""" def test_init_param_table(self): """Parameter table init from mapping.""" p1 = Parameter("theta") p2 = Parameter("theta") ref0 = (RZGate(p1), 0) ref1 = (RZGate(p1), 0) ref2 = (RZGate(p2), 0) mapping = {p1: ParameterReferences((ref0, ref1)), p2: ParameterReferences((ref2,))} table = ParameterTable(mapping) # make sure editing mapping doesn't change `table` del mapping[p1] self.assertEqual(table[p1], ParameterReferences((ref0, ref1))) self.assertEqual(table[p2], ParameterReferences((ref2,))) def test_set_references(self): """References replacement by parameter key.""" p1 = Parameter("theta") ref0 = (RZGate(p1), 0) ref1 = (RZGate(p1), 0) table = ParameterTable() table[p1] = ParameterReferences((ref0, ref1)) self.assertEqual(table[p1], ParameterReferences((ref0, ref1))) table[p1] = ParameterReferences((ref1,)) self.assertEqual(table[p1], ParameterReferences((ref1,))) def test_set_references_from_iterable(self): """Parameter table init from iterable.""" p1 = Parameter("theta") ref0 = (RZGate(p1), 0) ref1 = (RZGate(p1), 0) ref2 = (RZGate(p1), 0) table = ParameterTable({p1: ParameterReferences((ref0, ref1))}) table[p1] = (ref2, ref1, ref0) self.assertEqual(table[p1], ParameterReferences((ref2, ref1, ref0))) class TestParameterView(QiskitTestCase): """Test the ParameterView object.""" def setUp(self): super().setUp() x, y, z = Parameter("x"), Parameter("y"), Parameter("z") self.params = [x, y, z] self.view1 = ParameterView([x, y]) self.view2 = ParameterView([y, z]) self.view3 = ParameterView([x]) def test_and(self): """Test __and__.""" self.assertEqual(self.view1 & self.view2, {self.params[1]}) def test_or(self): """Test __or__.""" self.assertEqual(self.view1 | self.view2, set(self.params)) def test_xor(self): """Test __xor__.""" self.assertEqual(self.view1 ^ self.view2, {self.params[0], self.params[2]}) def test_len(self): """Test __len__.""" self.assertEqual(len(self.view1), 2) def test_le(self): """Test __le__.""" self.assertTrue(self.view1 <= self.view1) self.assertFalse(self.view1 <= self.view3) def test_lt(self): """Test __lt__.""" self.assertTrue(self.view3 < self.view1) def test_ge(self): """Test __ge__.""" self.assertTrue(self.view1 >= self.view1) self.assertFalse(self.view3 >= self.view1) def test_gt(self): """Test __lt__.""" self.assertTrue(self.view1 > self.view3) def test_eq(self): """Test __eq__.""" self.assertTrue(self.view1 == self.view1) self.assertFalse(self.view3 == self.view1) def test_ne(self): """Test __eq__.""" self.assertTrue(self.view1 != self.view2) self.assertFalse(self.view3 != self.view3) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the piecewise polynomial Pauli rotations.""" import unittest from collections import defaultdict import numpy as np from ddt import ddt, data, unpack from qiskit.test.base import QiskitTestCase from qiskit import BasicAer, execute from qiskit.circuit import QuantumCircuit from qiskit.circuit.library.arithmetic.piecewise_polynomial_pauli_rotations import ( PiecewisePolynomialPauliRotations, ) @ddt class TestPiecewisePolynomialRotations(QiskitTestCase): """Test the piecewise polynomial Pauli rotations.""" def assertFunctionIsCorrect(self, function_circuit, reference): """Assert that ``function_circuit`` implements the reference function ``reference``.""" num_state_qubits = function_circuit.num_state_qubits num_ancilla_qubits = function_circuit.num_ancillas circuit = QuantumCircuit(num_state_qubits + 1 + num_ancilla_qubits) circuit.h(list(range(num_state_qubits))) circuit.append(function_circuit.to_instruction(), list(range(circuit.num_qubits))) backend = BasicAer.get_backend("statevector_simulator") statevector = execute(circuit, backend).result().get_statevector() probabilities = defaultdict(float) for i, statevector_amplitude in enumerate(statevector): i = bin(i)[2:].zfill(circuit.num_qubits)[num_ancilla_qubits:] probabilities[i] += np.real(np.abs(statevector_amplitude) ** 2) unrolled_probabilities = [] unrolled_expectations = [] for i, probability in probabilities.items(): x, last_qubit = int(i[1:], 2), i[0] if last_qubit == "0": expected_amplitude = np.cos(reference(x)) / np.sqrt(2**num_state_qubits) else: expected_amplitude = np.sin(reference(x)) / np.sqrt(2**num_state_qubits) unrolled_probabilities += [probability] unrolled_expectations += [np.real(np.abs(expected_amplitude) ** 2)] np.testing.assert_almost_equal(unrolled_probabilities, unrolled_expectations) @data( (1, [0], [[1]]), (2, [0, 2], [[2], [-0.5, 1]]), (3, [0, 2, 5], [[1, 0, -1], [2, 1], [1, 1, 1]]), (4, [2, 5, 7, 16], [[1, -1], [1, 2, 3], [1, 2, 3, 4]]), (3, [0, 1], [[1, 0], [1, -2]]), ) @unpack def test_piecewise_polynomial_function(self, num_state_qubits, breakpoints, coeffs): """Test the piecewise linear rotations.""" def pw_poly(x): for i, point in enumerate(reversed(breakpoints[: len(coeffs)])): if x >= point: # Rescale the coefficients to take into account the 2 * theta argument from the # rotation gates rescaled_c = [coeff / 2 for coeff in coeffs[-(i + 1)][::-1]] return np.poly1d(rescaled_c)(x) return 0 pw_polynomial_rotations = PiecewisePolynomialPauliRotations( num_state_qubits, breakpoints, coeffs ) self.assertFunctionIsCorrect(pw_polynomial_rotations, pw_poly) def test_piecewise_polynomial_rotations_mutability(self): """Test the mutability of the linear rotations circuit.""" def pw_poly(x): for i, point in enumerate(reversed(breakpoints[: len(coeffs)])): if x >= point: # Rescale the coefficients to take into account the 2 * theta argument from the # rotation gates rescaled_c = [coeff / 2 for coeff in coeffs[-(i + 1)][::-1]] return np.poly1d(rescaled_c)(x) return 0 pw_polynomial_rotations = PiecewisePolynomialPauliRotations() with self.subTest(msg="missing number of state qubits"): with self.assertRaises(AttributeError): # no state qubits set print(pw_polynomial_rotations.draw()) with self.subTest(msg="default setup, just setting number of state qubits"): pw_polynomial_rotations.num_state_qubits = 2 self.assertFunctionIsCorrect(pw_polynomial_rotations, lambda x: 1 / 2) with self.subTest(msg="setting non-default values"): breakpoints = [0, 2] coeffs = [[0, -2 * 1.2], [-2 * 1, 2 * 1, 2 * 3]] pw_polynomial_rotations.breakpoints = breakpoints pw_polynomial_rotations.coeffs = coeffs self.assertFunctionIsCorrect(pw_polynomial_rotations, pw_poly) with self.subTest(msg="changing all values"): pw_polynomial_rotations.num_state_qubits = 4 breakpoints = [1, 3, 6] coeffs = [[0, -2 * 1.2], [-2 * 1, 2 * 1, 2 * 3], [-2 * 2]] pw_polynomial_rotations.breakpoints = breakpoints pw_polynomial_rotations.coeffs = coeffs self.assertFunctionIsCorrect(pw_polynomial_rotations, pw_poly) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test registerless QuantumCircuit and Gates on wires""" import numpy from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit, AncillaQubit from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase class TestRegisterlessCircuit(QiskitTestCase): """Test registerless QuantumCircuit.""" def test_circuit_constructor_qwires(self): """Create a QuantumCircuit directly with quantum wires""" circuit = QuantumCircuit(2) expected = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(circuit, expected) def test_circuit_constructor_wires_wrong(self): """Create a registerless QuantumCircuit wrongly""" self.assertRaises(CircuitError, QuantumCircuit, 1, 2, 3) # QuantumCircuit(1, 2, 3) def test_circuit_constructor_wires_wrong_mix(self): """Create an almost-registerless QuantumCircuit""" # QuantumCircuit(1, ClassicalRegister(2)) self.assertRaises(CircuitError, QuantumCircuit, 1, ClassicalRegister(2)) class TestAddingBitsWithoutRegisters(QiskitTestCase): """Test adding Bit instances outside of Registers.""" def test_circuit_constructor_on_bits(self): """Verify we can add bits directly to a circuit.""" qubits = [Qubit(), Qubit()] clbits = [Clbit()] ancillas = [AncillaQubit(), AncillaQubit()] qc = QuantumCircuit(qubits, clbits, ancillas) self.assertEqual(qc.qubits, qubits + ancillas) self.assertEqual(qc.clbits, clbits) self.assertEqual(qc.ancillas, ancillas) self.assertEqual(qc.qregs, []) self.assertEqual(qc.cregs, []) def test_circuit_constructor_on_invalid_bits(self): """Verify we raise if passed not a Bit.""" with self.assertRaisesRegex(CircuitError, "Expected an instance of"): _ = QuantumCircuit([3.14]) def test_raise_if_bits_already_present(self): """Verify we raise when attempting to add a Bit already in the circuit.""" qubits = [Qubit()] with self.assertRaisesRegex(CircuitError, "bits found already"): _ = QuantumCircuit(qubits, qubits) qc = QuantumCircuit(qubits) with self.assertRaisesRegex(CircuitError, "bits found already"): qc.add_bits(qubits) qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) with self.assertRaisesRegex(CircuitError, "bits found already"): qc.add_bits(qr[:]) def test_addding_individual_bit(self): """Verify we can add a single bit to a circuit.""" qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) new_bit = Qubit() qc.add_bits([new_bit]) self.assertEqual(qc.qubits, list(qr) + [new_bit]) self.assertEqual(qc.qregs, [qr]) def test_inserted_ancilla_bits_are_added_to_qubits(self): """Verify AncillaQubits added via .add_bits are added to .qubits.""" anc = AncillaQubit() qb = Qubit() qc = QuantumCircuit() qc.add_bits([anc, qb]) self.assertEqual(qc.qubits, [anc, qb]) class TestGatesOnWires(QiskitTestCase): """Test gates on wires.""" def test_circuit_single_wire_h(self): """Test circuit on wire (H gate).""" qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) circuit.h(1) expected = QuantumCircuit(qreg) expected.h(qreg[1]) self.assertEqual(circuit, expected) def test_circuit_two_wire_cx(self): """Test circuit two wires (CX gate).""" qreg = QuantumRegister(2) expected = QuantumCircuit(qreg) expected.cx(qreg[0], qreg[1]) circuit = QuantumCircuit(qreg) circuit.cx(0, 1) self.assertEqual(circuit, expected) def test_circuit_single_wire_measure(self): """Test circuit on wire (measure gate).""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg, creg) circuit.measure(1, 1) expected = QuantumCircuit(qreg, creg) expected.measure(qreg[1], creg[1]) self.assertEqual(circuit, expected) def test_circuit_multi_qregs_h(self): """Test circuit multi qregs and wires (H gate).""" qreg0 = QuantumRegister(2) qreg1 = QuantumRegister(2) circuit = QuantumCircuit(qreg0, qreg1) circuit.h(0) circuit.h(2) expected = QuantumCircuit(qreg0, qreg1) expected.h(qreg0[0]) expected.h(qreg1[0]) self.assertEqual(circuit, expected) def test_circuit_multi_qreg_cregs_measure(self): """Test circuit multi qregs/cregs and wires (measure).""" qreg0 = QuantumRegister(2) creg0 = ClassicalRegister(2) qreg1 = QuantumRegister(2) creg1 = ClassicalRegister(2) circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1) circuit.measure(0, 2) circuit.measure(2, 1) expected = QuantumCircuit(qreg0, qreg1, creg0, creg1) expected.measure(qreg0[0], creg1[0]) expected.measure(qreg1[0], creg0[1]) self.assertEqual(circuit, expected) def test_circuit_barrier(self): """Test barrier on wires.""" qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.barrier(0) circuit.barrier(2) expected = QuantumCircuit(qreg01, qreg23) expected.barrier(qreg01[0]) expected.barrier(qreg23[0]) self.assertEqual(circuit, expected) def test_circuit_conditional(self): """Test conditional on wires.""" qreg = QuantumRegister(2) creg = ClassicalRegister(4) circuit = QuantumCircuit(qreg, creg) circuit.h(0).c_if(creg, 3) expected = QuantumCircuit(qreg, creg) expected.h(qreg[0]).c_if(creg, 3) self.assertEqual(circuit, expected) def test_circuit_qwire_out_of_range(self): """Fail if quantum wire is out of range.""" qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) self.assertRaises(CircuitError, circuit.h, 99) # circuit.h(99) def test_circuit_cwire_out_of_range(self): """Fail if classical wire is out of range.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg, creg) self.assertRaises(CircuitError, circuit.measure, 1, 99) # circuit.measure(1, 99) def test_circuit_initialize(self): """Test initialize on wires.""" init_vector = [0.5, 0.5, 0.5, 0.5] qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.initialize(init_vector, [0, 2]) expected = QuantumCircuit(qreg01, qreg23) expected.initialize(init_vector, [qreg01[0], qreg23[0]]) self.assertEqual(circuit, expected) def test_circuit_initialize_single_qubit(self): """Test initialize on single qubit.""" init_vector = [numpy.sqrt(0.5), numpy.sqrt(0.5)] qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) circuit.initialize(init_vector, qreg[0]) expected = QuantumCircuit(qreg) expected.initialize(init_vector, [qreg[0]]) self.assertEqual(circuit, expected) def test_mixed_register_and_registerless_indexing(self): """Test indexing if circuit contains bits in and out of registers.""" bits = [Qubit(), Qubit()] qreg = QuantumRegister(3, "q") circuit = QuantumCircuit(bits, qreg) for i in range(len(circuit.qubits)): circuit.rz(i, i) expected_qubit_order = bits + qreg[:] expected_circuit = QuantumCircuit(bits, qreg) for i in range(len(expected_circuit.qubits)): expected_circuit.rz(i, expected_qubit_order[i]) self.assertEqual(circuit.data, expected_circuit.data) class TestGatesOnWireRange(QiskitTestCase): """Test gates on wire range.""" def test_wire_range(self): """Test gate wire range""" qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) circuit.h(range(0, 2)) expected = QuantumCircuit(qreg) expected.h(qreg[0:2]) self.assertEqual(circuit, expected) def test_circuit_multi_qregs_h(self): """Test circuit multi qregs in range of wires (H gate).""" qreg0 = QuantumRegister(2) qreg1 = QuantumRegister(2) circuit = QuantumCircuit(qreg0, qreg1) circuit.h(range(0, 3)) expected = QuantumCircuit(qreg0, qreg1) expected.h(qreg0[0]) expected.h(qreg0[1]) expected.h(qreg1[0]) self.assertEqual(circuit, expected) def test_circuit_multi_qreg_cregs_measure(self): """Test circuit multi qregs in range of wires (measure).""" qreg0 = QuantumRegister(2) creg0 = ClassicalRegister(2) qreg1 = QuantumRegister(2) creg1 = ClassicalRegister(2) circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1) circuit.measure(range(1, 3), range(0, 4, 2)) expected = QuantumCircuit(qreg0, qreg1, creg0, creg1) expected.measure(qreg0[1], creg0[0]) expected.measure(qreg1[0], creg1[0]) self.assertEqual(circuit, expected) def test_circuit_barrier(self): """Test barrier on range of wires with multi regs.""" qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.barrier(range(0, 3)) expected = QuantumCircuit(qreg01, qreg23) expected.barrier(qreg01[0], qreg01[1], qreg23[0]) self.assertEqual(circuit, expected) def test_circuit_initialize(self): """Test initialize on wires.""" init_vector = [0.5, 0.5, 0.5, 0.5] qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.initialize(init_vector, range(1, 3)) expected = QuantumCircuit(qreg01, qreg23) expected.initialize(init_vector, [qreg01[1], qreg23[0]]) self.assertEqual(circuit, expected) def test_circuit_conditional(self): """Test conditional on wires.""" qreg0 = QuantumRegister(2) qreg1 = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg0, qreg1, creg) circuit.h(range(1, 3)).c_if(creg, 3) expected = QuantumCircuit(qreg0, qreg1, creg) expected.h(qreg0[1]).c_if(creg, 3) expected.h(qreg1[0]).c_if(creg, 3) self.assertEqual(circuit, expected) def test_circuit_qwire_out_of_range(self): """Fail if quantum wire is out of range.""" qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) self.assertRaises(CircuitError, circuit.h, range(9, 99)) # circuit.h(range(9,99)) def test_circuit_cwire_out_of_range(self): """Fail if classical wire is out of range.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg, creg) # circuit.measure(1, range(9,99)) self.assertRaises(CircuitError, circuit.measure, 1, range(9, 99)) class TestGatesOnWireSlice(QiskitTestCase): """Test gates on wire slice.""" def test_wire_slice(self): """Test gate wire slice""" qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) circuit.h(slice(0, 2)) expected = QuantumCircuit(qreg) expected.h(qreg[0:2]) self.assertEqual(circuit, expected) def test_wire_list(self): """Test gate wire list of integers""" qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) circuit.h([0, 1]) expected = QuantumCircuit(qreg) expected.h(qreg[0:2]) self.assertEqual(circuit, expected) def test_wire_np_int(self): """Test gate wire with numpy int""" numpy_int = numpy.dtype("int").type(2) qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) circuit.h(numpy_int) expected = QuantumCircuit(qreg) expected.h(qreg[2]) self.assertEqual(circuit, expected) def test_wire_np_1d_array(self): """Test gate wire with numpy array (one-dimensional)""" numpy_arr = numpy.array([0, 1]) qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) circuit.h(numpy_arr) expected = QuantumCircuit(qreg) expected.h(qreg[0]) expected.h(qreg[1]) self.assertEqual(circuit, expected) def test_circuit_multi_qregs_h(self): """Test circuit multi qregs in slices of wires (H gate).""" qreg0 = QuantumRegister(2) qreg1 = QuantumRegister(2) circuit = QuantumCircuit(qreg0, qreg1) circuit.h(slice(0, 3)) expected = QuantumCircuit(qreg0, qreg1) expected.h(qreg0[0]) expected.h(qreg0[1]) expected.h(qreg1[0]) self.assertEqual(circuit, expected) def test_circuit_multi_qreg_cregs_measure(self): """Test circuit multi qregs in slices of wires (measure).""" qreg0 = QuantumRegister(2) creg0 = ClassicalRegister(2) qreg1 = QuantumRegister(2) creg1 = ClassicalRegister(2) circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1) circuit.measure(slice(1, 3), slice(0, 4, 2)) expected = QuantumCircuit(qreg0, qreg1, creg0, creg1) expected.measure(qreg0[1], creg0[0]) expected.measure(qreg1[0], creg1[0]) self.assertEqual(circuit, expected) def test_circuit_barrier(self): """Test barrier on slice of wires with multi regs.""" qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.barrier(slice(0, 3)) expected = QuantumCircuit(qreg01, qreg23) expected.barrier([qreg01[0], qreg01[1], qreg23[0]]) self.assertEqual(circuit, expected) def test_circuit_initialize(self): """Test initialize on wires.""" init_vector = [0.5, 0.5, 0.5, 0.5] qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.initialize(init_vector, slice(1, 3)) expected = QuantumCircuit(qreg01, qreg23) expected.initialize(init_vector, [qreg01[1], qreg23[0]]) self.assertEqual(circuit, expected) def test_circuit_conditional(self): """Test conditional on wires.""" qreg0 = QuantumRegister(2) qreg1 = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg0, qreg1, creg) circuit.h(slice(1, 3)).c_if(creg, 3) expected = QuantumCircuit(qreg0, qreg1, creg) expected.h(qreg0[1]).c_if(creg, 3) expected.h(qreg1[0]).c_if(creg, 3) self.assertEqual(circuit, expected) def test_circuit_qwire_out_of_range(self): """Fail if quantum wire is out of range.""" qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) self.assertRaises(CircuitError, circuit.h, slice(9, 99)) # circuit.h(slice(9,99)) def test_circuit_cwire_out_of_range(self): """Fail if classical wire is out of range.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg, creg) # circuit.measure(1, slice(9,99)) self.assertRaises(CircuitError, circuit.measure, 1, slice(9, 99)) def test_wire_np_2d_array(self): """Test gate wire with numpy array (two-dimensional). Raises.""" numpy_arr = numpy.array([[0, 1], [2, 3]]) qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) self.assertRaises(CircuitError, circuit.h, numpy_arr) # circuit.h(numpy_arr) class TestBitConditional(QiskitTestCase): """Test gates with single bit conditionals.""" def test_bit_conditional_single_gate(self): """Test circuit with a single gate conditioned on a bit.""" qreg = QuantumRegister(1) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg, creg) circuit.h(0).c_if(0, True) expected = QuantumCircuit(qreg, creg) expected.h(qreg[0]).c_if(creg[0], True) self.assertEqual(circuit, expected) def test_bit_conditional_multiple_gates(self): """Test circuit with multiple gates conditioned on individual bits.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) creg1 = ClassicalRegister(1) circuit = QuantumCircuit(qreg, creg, creg1) circuit.h(0).c_if(0, True) circuit.h(1).c_if(1, False) circuit.cx(1, 0).c_if(2, True) expected = QuantumCircuit(qreg, creg, creg1) expected.h(qreg[0]).c_if(creg[0], True) expected.h(qreg[1]).c_if(creg[1], False) expected.cx(qreg[1], qreg[0]).c_if(creg1[0], True) self.assertEqual(circuit, expected)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-function-docstring """Test scheduled circuit (quantum circuit with duration).""" from ddt import ddt, data from qiskit import QuantumCircuit, QiskitError from qiskit import transpile, assemble, BasicAer from qiskit.circuit import Parameter from qiskit.providers.fake_provider import FakeParis from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.instruction_durations import InstructionDurations from qiskit.test.base import QiskitTestCase @ddt class TestScheduledCircuit(QiskitTestCase): """Test scheduled circuit (quantum circuit with duration).""" def setUp(self): super().setUp() self.backend_with_dt = FakeParis() self.backend_without_dt = FakeParis() delattr(self.backend_without_dt.configuration(), "dt") self.dt = 2.2222222222222221e-10 self.simulator_backend = BasicAer.get_backend("qasm_simulator") def test_schedule_circuit_when_backend_tells_dt(self): """dt is known to transpiler by backend""" qc = QuantumCircuit(2) qc.delay(0.1, 0, unit="ms") # 450000[dt] qc.delay(100, 0, unit="ns") # 450[dt] qc.h(0) # 160[dt] qc.h(1) # 160[dt] sc = transpile(qc, self.backend_with_dt, scheduling_method="alap", layout_method="trivial") self.assertEqual(sc.duration, 450610) self.assertEqual(sc.unit, "dt") self.assertEqual(sc.data[0].operation.name, "delay") self.assertEqual(sc.data[0].operation.duration, 450450) self.assertEqual(sc.data[0].operation.unit, "dt") self.assertEqual(sc.data[1].operation.name, "rz") self.assertEqual(sc.data[1].operation.duration, 0) self.assertEqual(sc.data[1].operation.unit, "dt") self.assertEqual(sc.data[4].operation.name, "delay") self.assertEqual(sc.data[4].operation.duration, 450450) self.assertEqual(sc.data[4].operation.unit, "dt") qobj = assemble(sc, self.backend_with_dt) self.assertEqual(qobj.experiments[0].instructions[0].name, "delay") self.assertEqual(qobj.experiments[0].instructions[0].params[0], 450450) self.assertEqual(qobj.experiments[0].instructions[4].name, "delay") self.assertEqual(qobj.experiments[0].instructions[4].params[0], 450450) def test_schedule_circuit_when_transpile_option_tells_dt(self): """dt is known to transpiler by transpile option""" qc = QuantumCircuit(2) qc.delay(0.1, 0, unit="ms") # 450000[dt] qc.delay(100, 0, unit="ns") # 450[dt] qc.h(0) qc.h(1) sc = transpile( qc, self.backend_without_dt, scheduling_method="alap", dt=self.dt, layout_method="trivial", ) self.assertEqual(sc.duration, 450610) self.assertEqual(sc.unit, "dt") self.assertEqual(sc.data[0].operation.name, "delay") self.assertEqual(sc.data[0].operation.duration, 450450) self.assertEqual(sc.data[0].operation.unit, "dt") self.assertEqual(sc.data[1].operation.name, "rz") self.assertEqual(sc.data[1].operation.duration, 0) self.assertEqual(sc.data[1].operation.unit, "dt") self.assertEqual(sc.data[4].operation.name, "delay") self.assertEqual(sc.data[4].operation.duration, 450450) self.assertEqual(sc.data[4].operation.unit, "dt") def test_schedule_circuit_in_sec_when_no_one_tells_dt(self): """dt is unknown and all delays and gate times are in SI""" qc = QuantumCircuit(2) qc.delay(0.1, 0, unit="ms") qc.delay(100, 0, unit="ns") qc.h(0) qc.h(1) sc = transpile( qc, self.backend_without_dt, scheduling_method="alap", layout_method="trivial" ) self.assertAlmostEqual(sc.duration, 450610 * self.dt) self.assertEqual(sc.unit, "s") self.assertEqual(sc.data[0].operation.name, "delay") self.assertAlmostEqual(sc.data[0].operation.duration, 1.0e-4 + 1.0e-7) self.assertEqual(sc.data[0].operation.unit, "s") self.assertEqual(sc.data[1].operation.name, "rz") self.assertAlmostEqual(sc.data[1].operation.duration, 160 * self.dt) self.assertEqual(sc.data[1].operation.unit, "s") self.assertEqual(sc.data[4].operation.name, "delay") self.assertAlmostEqual(sc.data[4].operation.duration, 1.0e-4 + 1.0e-7) self.assertEqual(sc.data[4].operation.unit, "s") with self.assertRaises(QiskitError): assemble(sc, self.backend_without_dt) def test_cannot_schedule_circuit_with_mixed_SI_and_dt_when_no_one_tells_dt(self): """dt is unknown but delays and gate times have a mix of SI and dt""" qc = QuantumCircuit(2) qc.delay(100, 0, unit="ns") qc.delay(30, 0, unit="dt") qc.h(0) qc.h(1) with self.assertRaises(QiskitError): transpile(qc, self.backend_without_dt, scheduling_method="alap") def test_transpile_single_delay_circuit(self): qc = QuantumCircuit(1) qc.delay(1234, 0) sc = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") self.assertEqual(sc.duration, 1234) self.assertEqual(sc.data[0].operation.name, "delay") self.assertEqual(sc.data[0].operation.duration, 1234) self.assertEqual(sc.data[0].operation.unit, "dt") def test_transpile_t1_circuit(self): qc = QuantumCircuit(1) qc.x(0) # 320 [dt] qc.delay(1000, 0, unit="ns") # 4500 [dt] qc.measure_all() # 19584 [dt] scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") self.assertEqual(scheduled.duration, 23060) def test_transpile_delay_circuit_with_backend(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(100, 1, unit="ns") # 450 [dt] qc.cx(0, 1) # 1760 [dt] scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial" ) self.assertEqual(scheduled.duration, 2082) def test_transpile_delay_circuit_without_backend(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) scheduled = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", 0, 200), ("cx", [0, 1], 700)], ) self.assertEqual(scheduled.duration, 1200) def test_transpile_circuit_with_custom_instruction(self): """See: https://github.com/Qiskit/qiskit-terra/issues/5154""" bell = QuantumCircuit(2, name="bell") bell.h(0) bell.cx(0, 1) qc = QuantumCircuit(2) qc.delay(500, 1) qc.append(bell.to_instruction(), [0, 1]) scheduled = transpile( qc, scheduling_method="alap", instruction_durations=[("bell", [0, 1], 1000)] ) self.assertEqual(scheduled.duration, 1500) def test_transpile_delay_circuit_with_dt_but_without_scheduling_method(self): qc = QuantumCircuit(1) qc.delay(100, 0, unit="ns") transpiled = transpile(qc, backend=self.backend_with_dt) self.assertEqual(transpiled.duration, None) # not scheduled self.assertEqual(transpiled.data[0].operation.duration, 450) # unit is converted ns -> dt def test_transpile_delay_circuit_without_scheduling_method_or_durs(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) not_scheduled = transpile(qc) self.assertEqual(not_scheduled.duration, None) def test_raise_error_if_transpile_with_scheduling_method_but_without_durations(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) with self.assertRaises(TranspilerError): transpile(qc, scheduling_method="alap") def test_invalidate_schedule_circuit_if_new_instruction_is_appended(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500 * self.dt, 1, "s") qc.cx(0, 1) scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") # append a gate to a scheduled circuit scheduled.h(0) self.assertEqual(scheduled.duration, None) def test_default_units_for_my_own_duration_users(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) # accept None for qubits scheduled = transpile( qc, basis_gates=["h", "cx", "delay"], scheduling_method="alap", instruction_durations=[("h", 0, 200), ("cx", None, 900)], ) self.assertEqual(scheduled.duration, 1400) # prioritize specified qubits over None scheduled = transpile( qc, basis_gates=["h", "cx", "delay"], scheduling_method="alap", instruction_durations=[("h", 0, 200), ("cx", None, 900), ("cx", [0, 1], 800)], ) self.assertEqual(scheduled.duration, 1300) def test_unit_seconds_when_using_backend_durations(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500 * self.dt, 1, "s") qc.cx(0, 1) # usual case scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial" ) self.assertEqual(scheduled.duration, 2132) # update durations durations = InstructionDurations.from_backend(self.backend_with_dt) durations.update([("cx", [0, 1], 1000 * self.dt, "s")]) scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="alap", instruction_durations=durations, layout_method="trivial", ) self.assertEqual(scheduled.duration, 1500) def test_per_qubit_durations(self): """See: https://github.com/Qiskit/qiskit-terra/issues/5109""" qc = QuantumCircuit(3) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) qc.h(1) sc = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", None, 200), ("cx", [0, 1], 700)], ) self.assertEqual(sc.qubit_start_time(0), 300) self.assertEqual(sc.qubit_stop_time(0), 1200) self.assertEqual(sc.qubit_start_time(1), 500) self.assertEqual(sc.qubit_stop_time(1), 1400) self.assertEqual(sc.qubit_start_time(2), 0) self.assertEqual(sc.qubit_stop_time(2), 0) self.assertEqual(sc.qubit_start_time(0, 1), 300) self.assertEqual(sc.qubit_stop_time(0, 1), 1400) qc.measure_all() sc = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx", "measure"], instruction_durations=[("h", None, 200), ("cx", [0, 1], 700), ("measure", None, 1000)], ) q = sc.qubits self.assertEqual(sc.qubit_start_time(q[0]), 300) self.assertEqual(sc.qubit_stop_time(q[0]), 2400) self.assertEqual(sc.qubit_start_time(q[1]), 500) self.assertEqual(sc.qubit_stop_time(q[1]), 2400) self.assertEqual(sc.qubit_start_time(q[2]), 1400) self.assertEqual(sc.qubit_stop_time(q[2]), 2400) self.assertEqual(sc.qubit_start_time(*q), 300) self.assertEqual(sc.qubit_stop_time(*q), 2400) def test_change_dt_in_transpile(self): qc = QuantumCircuit(1, 1) qc.x(0) qc.measure(0, 0) # default case scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="asap") org_duration = scheduled.duration # halve dt in sec = double duration in dt scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="asap", dt=self.dt / 2 ) self.assertEqual(scheduled.duration, org_duration * 2) @data("asap", "alap") def test_duration_on_same_instruction_instance(self, scheduling_method): """See: https://github.com/Qiskit/qiskit-terra/issues/5771""" assert self.backend_with_dt.properties().gate_length( "cx", (0, 1) ) != self.backend_with_dt.properties().gate_length("cx", (1, 2)) qc = QuantumCircuit(3) qc.cz(0, 1) qc.cz(1, 2) sc = transpile(qc, backend=self.backend_with_dt, scheduling_method=scheduling_method) cxs = [inst.operation for inst in sc.data if inst.operation.name == "cx"] self.assertNotEqual(cxs[0].duration, cxs[1].duration) def test_transpile_and_assemble_delay_circuit_for_simulator(self): """See: https://github.com/Qiskit/qiskit-terra/issues/5962""" qc = QuantumCircuit(1) qc.delay(100, 0, "ns") circ = transpile(qc, self.simulator_backend) self.assertEqual(circ.duration, None) # not scheduled qobj = assemble(circ, self.simulator_backend) self.assertEqual(qobj.experiments[0].instructions[0].name, "delay") self.assertEqual(qobj.experiments[0].instructions[0].params[0], 1e-7) def test_transpile_and_assemble_t1_circuit_for_simulator(self): """Check if no scheduling is done in transpiling for simulator backends""" qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(0.1, 0, "us") qc.measure(0, 0) circ = transpile(qc, self.simulator_backend) self.assertEqual(circ.duration, None) # not scheduled qobj = assemble(circ, self.simulator_backend) self.assertEqual(qobj.experiments[0].instructions[1].name, "delay") self.assertAlmostEqual(qobj.experiments[0].instructions[1].params[0], 1e-7) # Tests for circuits with parameterized delays def test_can_transpile_circuits_after_assigning_parameters(self): """Check if not scheduled but duration is converted in dt""" idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = qc.assign_parameters({idle_dur: 0.1}) circ = transpile(qc, self.backend_with_dt) self.assertEqual(circ.duration, None) # not scheduled self.assertEqual(circ.data[1].operation.duration, 450) # converted in dt def test_can_transpile_and_assemble_circuits_with_assigning_parameters_inbetween(self): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) circ = transpile(qc, self.backend_with_dt) circ = circ.assign_parameters({idle_dur: 0.1}) qobj = assemble(circ, self.backend_with_dt) self.assertEqual(qobj.experiments[0].instructions[1].name, "delay") self.assertEqual(qobj.experiments[0].instructions[1].params[0], 450) def test_can_transpile_circuits_with_unbounded_parameters(self): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) # not assign parameter circ = transpile(qc, self.backend_with_dt) self.assertEqual(circ.duration, None) # not scheduled self.assertEqual(circ.data[1].operation.unit, "dt") # converted in dt self.assertEqual( circ.data[1].operation.duration, idle_dur * 1e-6 / self.dt ) # still parameterized def test_fail_to_assemble_circuits_with_unbounded_parameters(self): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = transpile(qc, self.backend_with_dt) with self.assertRaises(QiskitError): assemble(qc, self.backend_with_dt) @data("asap", "alap") def test_can_schedule_circuits_with_bounded_parameters(self, scheduling_method): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = qc.assign_parameters({idle_dur: 0.1}) circ = transpile(qc, self.backend_with_dt, scheduling_method=scheduling_method) self.assertIsNotNone(circ.duration) # scheduled @data("asap", "alap") def test_fail_to_schedule_circuits_with_unbounded_parameters(self, scheduling_method): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) # not assign parameter with self.assertRaises(TranspilerError): transpile(qc, self.backend_with_dt, scheduling_method=scheduling_method)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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=invalid-name """Single-qubit unitary tests.""" import unittest from test import combine import numpy as np from ddt import ddt from qiskit.quantum_info.random import random_unitary from qiskit import BasicAer from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit import execute from qiskit.test import QiskitTestCase from qiskit.extensions.quantum_initializer.squ import SingleQubitUnitary from qiskit.compiler import transpile from qiskit.quantum_info.operators.predicates import matrix_equal squs = [ np.eye(2, 2), np.array([[0.0, 1.0], [1.0, 0.0]]), 1 / np.sqrt(2) * np.array([[1.0, 1.0], [-1.0, 1.0]]), np.array([[np.exp(1j * 5.0 / 2), 0], [0, np.exp(-1j * 5.0 / 2)]]), random_unitary(2, seed=42).data, ] up_to_diagonal_list = [True, False] @ddt class TestSingleQubitUnitary(QiskitTestCase): """Qiskit ZYZ-decomposition tests.""" @combine(u=squs, up_to_diagonal=up_to_diagonal_list) def test_squ(self, u, up_to_diagonal): """Tests for single-qubit unitary decomposition.""" qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) qc.squ(u, qr[0], up_to_diagonal=up_to_diagonal) # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"]) # Simulate the decomposed gate simulator = BasicAer.get_backend("unitary_simulator") result = execute(qc, simulator).result() unitary = result.get_unitary(qc) if up_to_diagonal: squ = SingleQubitUnitary(u, up_to_diagonal=up_to_diagonal) unitary = np.dot(np.diagflat(squ.diag), unitary) unitary_desired = u self.assertTrue(matrix_equal(unitary_desired, unitary, ignore_phase=True)) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Tests for circuit templates.""" import unittest from test import combine from inspect import getmembers, isfunction from ddt import ddt import numpy as np from qiskit import QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.quantum_info.operators import Operator import qiskit.circuit.library.templates as templib @ddt class TestTemplates(QiskitTestCase): """Tests for the circuit templates.""" circuits = [o[1]() for o in getmembers(templib) if isfunction(o[1])] for circuit in circuits: if isinstance(circuit, QuantumCircuit): circuit.assign_parameters({param: 0.2 for param in circuit.parameters}, inplace=True) @combine(template_circuit=circuits) def test_template(self, template_circuit): """test to verify that all templates are equivalent to the identity""" target = Operator(template_circuit) value = Operator(np.eye(2**template_circuit.num_qubits)) self.assertTrue(target.equiv(value)) if __name__ == "__main__": unittest.main()