diff --git a/qiskit/providers/aer/aerjob.py b/qiskit/providers/aer/aerjob.py index 275544e03b..5912f2b505 100644 --- a/qiskit/providers/aer/aerjob.py +++ b/qiskit/providers/aer/aerjob.py @@ -14,6 +14,7 @@ """This module implements the job class used for AerBackend objects.""" +import warnings from concurrent import futures import logging import functools @@ -55,6 +56,10 @@ def __init__(self, backend, job_id, fn, qobj, *args): super().__init__(backend, job_id) self._fn = fn self._qobj = qobj + if args: + warnings.warn('Using *args for AerJob is deprecated. All backend' + ' options should be contained in the assembled Qobj.', + DeprecationWarning) self._args = args self._future = None @@ -70,7 +75,9 @@ def submit(self): if self._future is not None: raise JobError("We have already submitted the job!") - self._future = self._executor.submit(self._fn, self._job_id, self._qobj, + self._future = self._executor.submit(self._fn, + self._qobj, + self._job_id, *self._args) @requires_submit diff --git a/qiskit/providers/aer/backends/aerbackend.py b/qiskit/providers/aer/backends/aerbackend.py index ae467f8bf1..28bcb8543a 100644 --- a/qiskit/providers/aer/backends/aerbackend.py +++ b/qiskit/providers/aer/backends/aerbackend.py @@ -9,34 +9,30 @@ # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. - """ Qiskit Aer qasm simulator backend. """ +import copy import json import logging import datetime -import os import time import uuid +import warnings +from abc import ABC, abstractmethod from numpy import ndarray from qiskit.providers import BaseBackend from qiskit.providers.models import BackendStatus -from qiskit.qobj import validate_qobj_against_schema from qiskit.result import Result -from qiskit.util import local_hardware_info from ..aerjob import AerJob +from ..aererror import AerError # Logger logger = logging.getLogger(__name__) -# Location where we put external libraries that will be loaded at runtime -# by the simulator extension -LIBRARY_DIR = os.path.dirname(__file__) - class AerJSONEncoder(json.JSONEncoder): """ @@ -59,10 +55,15 @@ def default(self, obj): return super().default(obj) -class AerBackend(BaseBackend): +class AerBackend(BaseBackend, ABC): """Qiskit Aer Backend class.""" - - def __init__(self, controller, configuration, provider=None): + def __init__(self, + configuration, + properties=None, + defaults=None, + available_methods=None, + backend_options=None, + provider=None): """Aer class for backends. This method should initialize the module and its configuration, and @@ -70,126 +71,327 @@ def __init__(self, controller, configuration, provider=None): not available. Args: - controller (function): Aer controller to be executed - configuration (BackendConfiguration): backend configuration - provider (BaseProvider): provider responsible for this backend + configuration (BackendConfiguration): backend configuration. + properties (BackendProperties or None): Optional, backend properties. + defaults (PulseDefaults or None): Optional, backend pulse defaults. + available_methods (list or None): Optional, the available simulation methods + if backend supports multiple methods. + provider (BaseProvider): Optional, provider responsible for this backend. + backend_options (dict or None): Optional set custom backend options. Raises: - FileNotFoundError if backend executable is not available. AerError: if there is no name in the configuration """ + # Init configuration and provider in BaseBackend + configuration.simulator = True super().__init__(configuration, provider=provider) - self._controller = controller + + # Initialize backend properties and pulse defaults. + self._properties = properties + self._defaults = defaults + + # Custom configuration, properties, and pulse defaults which will store + # any configured modifications to the base simulator values. + self._custom_configuration = None + self._custom_properties = None + self._custom_defaults = None + + # Set available methods + self._available_methods = [] if available_methods is None else available_methods + + # Set custom configured options from backend_options dictionary + self._options = {} + if backend_options is not None: + for key, val in backend_options.items(): + self._set_option(key, val) # pylint: disable=arguments-differ - def run(self, qobj, backend_options=None, noise_model=None, validate=False): + def run(self, + qobj, + backend_options=None, # DEPRECATED + validate=True, + **run_options): """Run a qobj on the backend. Args: qobj (QasmQobj): The Qobj to be executed. - backend_options (dict or None): dictionary of backend options + backend_options (dict or None): DEPRECATED dictionary of backend options for the execution (default: None). - noise_model (NoiseModel or None): noise model to use for - simulation (default: None). validate (bool): validate the Qobj before running (default: True). + run_options (kwargs): additional run time backend options. Returns: AerJob: The simulation job. Additional Information: + * kwarg options specified in ``run_options`` will temporarily override + any set options of the same name for the current run. + * The entries in the ``backend_options`` will be combined with the ``Qobj.config`` dictionary with the values of entries in - ``backend_options`` taking precedence. - - * If present the ``noise_model`` will override any noise model - specified in the ``backend_options`` or ``Qobj.config``. + ``backend_options`` taking precedence. This kwarg is deprecated + and direct kwarg's should be used for options to pass them to + ``run_options``. """ + # DEPRECATED + if backend_options is not None: + warnings.warn( + 'Using `backend_options` kwarg has been deprecated as of' + ' qiskit-aer 0.7.0 and will be removed no earlier than 3' + ' months from that release date. Runtime backend options' + ' should now be added directly using kwargs for each option.', + DeprecationWarning, + stacklevel=3) + + # Add backend options to the Job qobj + qobj = self._format_qobj( + qobj, backend_options=backend_options, **run_options) + + # Optional validation + if validate: + self._validate(qobj) + # Submit job job_id = str(uuid.uuid4()) - aer_job = AerJob(self, job_id, self._run_job, qobj, - backend_options, noise_model, validate) + aer_job = AerJob(self, job_id, self._run, qobj) aer_job.submit() return aer_job + def configuration(self): + """Return the simulator backend configuration. + + Returns: + BackendConfiguration: the configuration for the backend. + """ + if self._custom_configuration is not None: + return self._custom_configuration + return self._configuration + + def properties(self): + """Return the simulator backend properties if set. + + Returns: + BackendProperties: The backend properties or ``None`` if the + backend does not have properties set. + """ + if self._custom_properties is not None: + return self._custom_properties + return self._properties + + def defaults(self): + """Return the simulator backend pulse defaults. + + Returns: + PulseDefaults: The backend pulse defaults or ``None`` if the + backend does not support pulse. + """ + if self._custom_defaults is not None: + return self._custom_defaults + return self._defaults + + @property + def options(self): + """Return the current simulator options""" + return self._options + + def set_options(self, **backend_options): + """Set the simulator options""" + for key, val in backend_options.items(): + self._set_option(key, val) + + def clear_options(self): + """Reset the simulator options to default values.""" + self._custom_configuration = None + self._custom_properties = None + self._custom_defaults = None + self._options = {} + + def available_methods(self): + """Return the available simulation methods.""" + return self._available_methods + def status(self): """Return backend status. Returns: BackendStatus: the status of the backend. """ - return BackendStatus(backend_name=self.name(), - backend_version=self.configuration().backend_version, - operational=True, - pending_jobs=0, - status_msg='') + return BackendStatus( + backend_name=self.name(), + backend_version=self.configuration().backend_version, + operational=True, + pending_jobs=0, + status_msg='') def _run_job(self, job_id, qobj, backend_options, noise_model, validate): """Run a qobj job""" - start = time.time() + warnings.warn( + 'The `_run_job` method has been deprecated. Use `_run` instead.', + DeprecationWarning) if validate: - validate_qobj_against_schema(qobj) - self._validate(qobj, backend_options, noise_model) - output = self._controller(self._format_qobj(qobj, backend_options, noise_model)) - end = time.time() - return Result.from_dict(self._format_results(job_id, output, end - start)) - - def _format_qobj(self, qobj, backend_options, noise_model): - """Format qobj string for qiskit aer controller""" - # Convert qobj to dict so as to avoid editing original - output = qobj.to_dict() - # Add new parameters to config from backend options - config = output["config"] - if backend_options is not None: - for key, val in backend_options.items(): - config[key] = val if not hasattr(val, 'to_dict') else val.to_dict() - # Add noise model to config - if noise_model is not None: - config["noise_model"] = noise_model - - # Add runtime config - if 'library_dir' not in config: - config['library_dir'] = LIBRARY_DIR - if "max_memory_mb" not in config: - max_memory_mb = int(local_hardware_info()['memory'] * 1024 / 2) - config['max_memory_mb'] = max_memory_mb - - self._validate_config(config) - # Return output - return output - - def _validate_config(self, config): - # sanity checks on config- should be removed upon fixing of assemble w.r.t. backend_options - if 'backend_options' in config: - if isinstance(config['backend_options'], dict): - for key, val in config['backend_options'].items(): - if hasattr(val, 'to_dict'): - config['backend_options'][key] = val.to_dict() - elif not isinstance(config['backend_options'], list): - raise ValueError("config[backend_options] must be a dict or list!") - # Double-check noise_model is a dict type - if 'noise_model' in config and not isinstance(config["noise_model"], dict): - if hasattr(config["noise_model"], 'to_dict'): - config["noise_model"] = config["noise_model"].to_dict() - else: - raise ValueError("noise_model must be a dict : " + str(type(config["noise_model"]))) - - def _format_results(self, job_id, output, time_taken): - """Construct Result object from simulator output.""" + warnings.warn( + 'The validate arg of `_run_job` has been removed. Use ' + 'validate=True in the `run` method instead.', + DeprecationWarning) + + # The new function swaps positional args qobj and job id so we do a + # type check to swap them back + if not isinstance(job_id, str) and isinstance(qobj, str): + job_id, qobj = qobj, job_id + run_qobj = self._format_qobj(qobj, backend_options=backend_options, + noise_model=noise_model) + return self._run(run_qobj, job_id) + + def _run(self, qobj, job_id=''): + """Run a job""" + # Start timer + start = time.time() + + # Run simulation + output = self._execute(qobj) + + # Validate output + if not isinstance(output, dict): + logger.error("%s: simulation failed.", self.name()) + if output: + logger.error('Output: %s', output) + raise AerError( + "simulation terminated without returning valid output.") + + # Format results output["job_id"] = job_id output["date"] = datetime.datetime.now().isoformat() output["backend_name"] = self.name() output["backend_version"] = self.configuration().backend_version - output["time_taken"] = time_taken - return output - def _validate(self, qobj, backend_options, noise_model): - """Validate the qobj, backend_options, noise_model for the backend""" + # Add execution time + output["time_taken"] = time.time() - start + return Result.from_dict(output) + + @abstractmethod + def _execute(self, qobj): + """Execute a qobj on the backend. + + Args: + qobj (QasmQobj or PulseQobj): simulator input. + + Returns: + dict: return a dictionary of results. + """ pass + def _validate(self, qobj): + """Validate the qobj for the backend""" + pass + + def _set_option(self, key, value): + """Special handling for setting backend options. + + This method should be extended by sub classes to + update special option values. + + Args: + key (str): key to update + value (any): value to update. + + Raises: + AerError: if key is 'method' and val isn't in available methods. + """ + # Check for key in configuration, properties, and defaults + # If the key requires modification of one of these fields a copy + # will be generated that can store the modified values without + # changing the original object + if hasattr(self._configuration, key): + self._set_configuration_option(key, value) + return + + if hasattr(self._properties, key): + self._set_properties_option(key, value) + return + + if hasattr(self._defaults, key): + self._set_defaults_option(key, value) + return + + # If key is method, we validate it is one of the available methods + if key == 'method' and value not in self._available_methods: + raise AerError("Invalid simulation method {}. Available methods" + " are: {}".format(value, self._available_methods)) + + # Add all other options to the options dict + # TODO: in the future this could be replaced with an options class + # for the simulators like configuration/properties to show all + # available options + if value is not None: + # Only add an option if its value is not None + self._options[key] = value + elif key in self._options: + # If setting an existing option to None remove it from options dict + self._options.pop(key) + + def _set_configuration_option(self, key, value): + """Special handling for setting backend configuration options.""" + if self._custom_configuration is None: + self._custom_configuration = copy.copy(self._configuration) + setattr(self._custom_configuration, key, value) + + def _set_properties_option(self, key, value): + """Special handling for setting backend properties options.""" + if self._custom_properties is None: + self._custom_properties = copy.copy(self._properties) + setattr(self._custom_properties, key, value) + + def _set_defaults_option(self, key, value): + """Special handling for setting backend defaults options.""" + if self._custom_defaults is None: + self._custom_defaults = copy.copy(self._defaults) + setattr(self._custom_defaults, key, value) + + def _format_qobj(self, qobj, + backend_options=None, # DEPRECATED + **run_options): + """Return execution sim config dict from backend options.""" + # Add options to qobj config overriding any existing fields + config = qobj.config + + # Add options + for key, val in self.options.items(): + setattr(config, key, val) + + # DEPRECATED backend options + if backend_options is not None: + for key, val in backend_options.items(): + setattr(config, key, val) + + # Override with run-time options + for key, val in run_options.items(): + setattr(config, key, val) + + return qobj + + def _run_config( + self, + backend_options=None, # DEPRECATED + **run_options): + """Return execution sim config dict from backend options.""" + # Get sim config + run_config = self._options.copy() + + # DEPRECATED backend options + if backend_options is not None: + for key, val in backend_options.items(): + run_config[key] = val + + # Override with run-time options + for key, val in run_options.items(): + run_config[key] = val + return run_config + def __repr__(self): - """Official string representation of an AerBackend.""" - display = "{}('{}')".format(self.__class__.__name__, self.name()) - provider = self.provider() - if provider is not None: - display = display + " from {}()".format(provider) - return "<" + display + ">" + """String representation of an AerBackend.""" + display = "backend_name='{}'".format(self.name()) + if self.provider(): + display += ', provider={}()'.format(self.provider()) + for key, val in self.options.items(): + display += ',\n {}={}'.format(key, repr(val)) + return '{}(\n{})'.format(self.__class__.__name__, display) diff --git a/qiskit/providers/aer/backends/backend_utils.py b/qiskit/providers/aer/backends/backend_utils.py new file mode 100644 index 0000000000..053722aeae --- /dev/null +++ b/qiskit/providers/aer/backends/backend_utils.py @@ -0,0 +1,68 @@ +# 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. + +# pylint: disable=invalid-name +""" +Qiskit Aer simulator backend utils +""" +import os +from math import log2 +from qiskit.util import local_hardware_info +from qiskit.circuit import QuantumCircuit +from qiskit.compiler import assemble + +# Available system memory +SYSTEM_MEMORY_GB = local_hardware_info()['memory'] + +# Max number of qubits for complex double statevector +# given available system memory +MAX_QUBITS_STATEVECTOR = int(log2(SYSTEM_MEMORY_GB * (1024**3) / 16)) + +# Location where we put external libraries that will be +# loaded at runtime by the simulator extension +LIBRARY_DIR = os.path.dirname(__file__) + + +def cpp_execute(controller, qobj): + """Execute qobj_dict on C++ controller wrapper""" + # Convert qobj to dict + qobj_dict = qobj.to_dict() + + # Convert noise model to dict + noise_model = qobj_dict['config'].pop('noise_model', None) + if noise_model is not None: + if not isinstance(noise_model, dict): + noise_model = noise_model.to_dict() + qobj_dict['config']['noise_model'] = noise_model + + # Location where we put external libraries that will be + # loaded at runtime by the simulator extension + qobj_dict['config']['library_dir'] = LIBRARY_DIR + + return controller(qobj_dict) + + +def available_methods(controller, methods): + """Check available simulation methods by running a dummy circuit.""" + # Test methods are available using the controller + dummy_circ = QuantumCircuit(1) + dummy_circ.i(0) + + valid_methods = [] + for method in methods: + qobj = assemble(dummy_circ, + optimization_level=0, + method=method) + result = cpp_execute(controller, qobj) + if result.get('success', False): + valid_methods.append(method) + return valid_methods diff --git a/qiskit/providers/aer/backends/pulse_simulator.py b/qiskit/providers/aer/backends/pulse_simulator.py index b97bc4b350..5dc9bdabae 100644 --- a/qiskit/providers/aer/backends/pulse_simulator.py +++ b/qiskit/providers/aer/backends/pulse_simulator.py @@ -10,25 +10,43 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=arguments-differ, missing-return-type-doc - """ Qiskit Aer pulse simulator backend. """ -import uuid -import time -import datetime +import copy import logging +from warnings import warn from numpy import inf -from qiskit.result import Result + from qiskit.providers.models import BackendConfiguration, PulseDefaults -from .aerbackend import AerBackend -from ..aerjob import AerJob + from ..version import __version__ +from ..aererror import AerError from ..pulse.controllers.pulse_controller import pulse_controller +from ..pulse.system_models.pulse_system_model import PulseSystemModel +from .aerbackend import AerBackend logger = logging.getLogger(__name__) +DEFAULT_CONFIGURATION = { + 'backend_name': 'pulse_simulator', + 'backend_version': __version__, + 'n_qubits': 20, + 'coupling_map': None, + 'url': 'https://github.com/Qiskit/qiskit-aer', + 'simulator': True, + 'meas_levels': [1, 2], + 'local': True, + 'conditional': True, + 'open_pulse': True, + 'memory': False, + 'max_shots': int(1e6), + 'description': 'A Pulse-based Hamiltonian simulator for Pulse Qobj files', + 'gates': [], + 'basis_gates': [] +} + class PulseSimulator(AerBackend): r"""Pulse schedule simulator backend. @@ -38,12 +56,26 @@ class PulseSimulator(AerBackend): physical system specified by :class:`~qiskit.providers.aer.pulse.PulseSystemModel` objects. Results are returned in the same format as when jobs are submitted to actual devices. - **Example** + **Examples** + + The minimal information a ``PulseSimulator`` needs to simulate is a + :class:`~qiskit.providers.aer.pulse.PulseSystemModel`, which can be supplied either by + setting the backend option before calling ``run``, e.g.: + + .. code-block:: python + + backend_sim = qiskit.providers.aer.PulseSimulator() + + # Set the pulse system model for the simulator + backend_sim.set_options(system_model=system_model) - To use the simulator, first :func:`~qiskit.assemble` a :class:`PulseQobj` object - from a list of pulse :class:`~qiskit.Schedule` objects, using ``backend=PulseSimulator()``. - Call the simulator with the :class:`PulseQobj` and a - :class:`~qiskit.providers.aer.pulse.PulseSystemModel` object representing the physical system. + # Assemble schedules using PulseSimulator as the backend + pulse_qobj = assemble(schedules, backend=backend_sim) + + # Run simulation + results = backend_sim.run(pulse_qobj) + + or by supplying the system model at runtime, e.g.: .. code-block:: python @@ -53,7 +85,23 @@ class PulseSimulator(AerBackend): pulse_qobj = assemble(schedules, backend=backend_sim) # Run simulation on a PulseSystemModel object - results = backend_sim.run(pulse_qobj, system_model) + results = backend_sim.run(pulse_qobj, system_model=system_model) + + Alternatively, an instance of the ``PulseSimulator`` may be further configured to contain more + information present in a real backend. The simplest way to do this is to instantiate the + ``PulseSimulator`` from a real backend: + + .. code-block:: python + + armonk_sim = qiskit.providers.aer.PulseSimulator.from_backend(FakeArmonk()) + pulse_qobj = assemble(schedules, backend=armonk_sim) + armonk_sim.run(pulse_qobj) + + In the above example, the ``PulseSimulator`` copies all configuration and default data from + ``FakeArmonk()``, and as such has the same affect as ``FakeArmonk()`` when passed as an + argument to ``assemble``. Furthermore it constructs a + :class:`~qiskit.providers.aer.pulse.PulseSystemModel` from the model details in the supplied + backend, which is then used in simulation. **Supported PulseQobj parameters** @@ -77,91 +125,205 @@ class PulseSimulator(AerBackend): **Other options** - :meth:`PulseSimulator.run` takes an additional ``dict`` argument ``backend_options`` for - customization. Accepted keys: + Additional valid keyword arguments for ``run()``: * ``'solver_options'``: A ``dict`` for solver options. Accepted keys are ``'atol'``, ``'rtol'``, ``'nsteps'``, ``'max_step'``, ``'num_cpus'``, ``'norm_tol'``, and ``'norm_steps'``. """ + def __init__(self, + configuration=None, + properties=None, + defaults=None, + provider=None, + **backend_options): + + if configuration is None: + configuration = BackendConfiguration.from_dict( + DEFAULT_CONFIGURATION) + else: + configuration = copy.copy(configuration) + configuration.meas_levels = self._meas_levels(configuration.meas_levels) + + if defaults is None: + defaults = PulseDefaults(qubit_freq_est=[inf], + meas_freq_est=[inf], + buffer=0, + cmd_def=[], + pulse_library=[]) + + super().__init__(configuration, + properties=properties, + defaults=defaults, + provider=provider, + backend_options=backend_options) - DEFAULT_CONFIGURATION = { - 'backend_name': 'pulse_simulator', - 'backend_version': __version__, - 'n_qubits': 20, - 'coupling_map': None, - 'url': 'https://github.com/Qiskit/qiskit-aer', - 'simulator': True, - 'meas_levels': [0, 1, 2], - 'local': True, - 'conditional': True, - 'open_pulse': True, - 'memory': False, - 'max_shots': int(1e6), - 'description': 'A pulse-based Hamiltonian simulator for Pulse Qobj files', - 'gates': [], - 'basis_gates': [] - } - - def __init__(self, configuration=None, provider=None): - - # purpose of defaults is to pass assemble checks - self._defaults = PulseDefaults(qubit_freq_est=[inf], - meas_freq_est=[inf], - buffer=0, - cmd_def=[], - pulse_library=[]) - super().__init__(self, - BackendConfiguration.from_dict(self.DEFAULT_CONFIGURATION), - provider=provider) - - def run(self, qobj, system_model, backend_options=None, validate=False): - """Run a qobj on system_model. + # Set up default system model + subsystem_list = backend_options.get('subsystem_list', None) + if backend_options.get('system_model') is None: + if hasattr(configuration, 'hamiltonian'): + system_model = PulseSystemModel.from_config( + configuration, subsystem_list) + self._set_system_model(system_model) + + # pylint: disable=arguments-differ, missing-param-doc + def run(self, + qobj, + *args, + backend_options=None, # DEPRECATED + validate=True, + **run_options): + """Run a qobj on the backend. Args: - qobj (PulseQobj): Qobj for pulse Schedules to run - system_model (PulseSystemModel): Physical model to run simulation on - backend_options (dict): Other options - validate (bool): Flag for validation checks + qobj (QasmQobj): The Qobj to be executed. + backend_options (dict or None): DEPRECATED dictionary of backend options + for the execution (default: None). + validate (bool): validate the Qobj before running (default: True). + run_options (kwargs): additional run time backend options. Returns: - Result: results of simulation + AerJob: The simulation job. + + Additional Information: + * kwarg options specified in ``run_options`` will override options + of the same kwarg specified in the simulator options, the + ``backend_options`` and the ``Qobj.config``. + + * The entries in the ``backend_options`` will be combined with + the ``Qobj.config`` dictionary with the values of entries in + ``backend_options`` taking precedence. This kwarg is deprecated + and direct kwarg's should be used for options to pass them to + ``run_options``. """ - # Submit job - job_id = str(uuid.uuid4()) - aer_job = AerJob(self, job_id, self._run_job, qobj, system_model, - backend_options, validate) - aer_job.submit() - return aer_job - - def _run_job(self, job_id, qobj, system_model, backend_options, validate): - """Run a qobj job""" - start = time.time() - if validate: - self._validate(qobj, backend_options, noise_model=None) - # Send problem specification to pulse_controller and get results - results = pulse_controller(qobj, system_model, backend_options) - end = time.time() - return self._format_results(job_id, results, end - start, qobj.qobj_id) - - def _format_results(self, job_id, results, time_taken, qobj_id): - """Construct Result object from simulator output.""" - # Add result metadata - output = {} - output['qobj_id'] = qobj_id - output['results'] = results - output['success'] = True - output["job_id"] = job_id - output["date"] = datetime.datetime.now().isoformat() - output["backend_name"] = self.name() - output["backend_version"] = self.configuration().backend_version - output["time_taken"] = time_taken - return Result.from_dict(output) - - def defaults(self): - """Return defaults. + if args: + if isinstance(args[0], PulseSystemModel): + warn( + 'Passing `system_model` as a positional argument to' + ' `PulseSimulator.run` has been deprecated as of' + ' qiskit-aer 0.7.0 and will be removed no earlier than 3' + ' months from that release date. Pass `system_model` as a kwarg' + ' `system_model=model` instead.', + DeprecationWarning, + stacklevel=3) + run_options['system_model'] = args[0] + if len(args) > 1: + backend_options = args[1] + if len(args) > 2: + validate = args[3] + elif isinstance(args[0], bool): + validate = args[0] + if len(args) > 1: + backend_options = args[1] + return super().run(qobj, backend_options=backend_options, validate=validate, + **run_options) + + @property + def _system_model(self): + return self._options.get('system_model') + + @classmethod + def from_backend(cls, backend, **options): + """Initialize simulator from backend.""" + configuration = copy.copy(backend.configuration()) + defaults = copy.copy(backend.defaults()) + properties = copy.copy(backend.properties()) + + backend_name = 'pulse_simulator({})'.format(configuration.backend_name) + description = 'A Pulse-based simulator configured from the backend: ' + description += configuration.backend_name + + sim = cls(configuration=configuration, + properties=properties, + defaults=defaults, + backend_name=backend_name, + description=description, + **options) + return sim + + def _execute(self, qobj): + """Execute a qobj on the backend. + + Args: + qobj (PulseQobj): simulator input. Returns: - PulseDefaults: object for passing assemble. + dict: return a dictionary of results. """ - return self._defaults + qobj.config.qubit_freq_est = self.defaults().qubit_freq_est + return pulse_controller(qobj) + + def _set_option(self, key, value): + """Set pulse simulation options and update backend.""" + if key == 'meas_levels': + self._set_configuration_option(key, self._meas_levels(value)) + return + + # Handle cases that require updating two places + if key in ['dt', 'u_channel_lo']: + self._set_configuration_option(key, value) + if self._system_model is not None: + setattr(self._system_model, key, value) + return + + if key == 'hamiltonian': + # if option is hamiltonian, set in configuration and reconstruct pulse system model + subsystem_list = self._options.get('subsystem_list', None) + system_model = PulseSystemModel.from_config(self.configuration(), + subsystem_list) + super()._set_option('system_model', system_model) + self._set_configuration_option(key, value) + return + + # if system model is specified directly + if key == 'system_model': + if hasattr(self.configuration(), 'hamiltonian'): + warn('Specifying both a configuration with a Hamiltonian and a ' + 'system model may result in inconsistencies.') + # Set config dt and u_channel_lo to system model values + self._set_system_model(value) + return + + # Set all other options from AerBackend + super()._set_option(key, value) + + def _set_system_model(self, system_model): + """Set system model option""" + self._set_configuration_option( + 'dt', getattr(system_model, 'dt', [])) + self._set_configuration_option( + 'u_channel_lo', getattr(system_model, 'u_channel_lo', [])) + super()._set_option('system_model', system_model) + + def _validate(self, qobj): + """Validation of qobj. + + Ensures that exactly one Acquire instruction is present in each + schedule. Checks SystemModel is in qobj config + """ + if getattr(qobj.config, 'system_model', None) is None: + raise AerError("PulseSimulator requires a system model to run.") + + for exp in qobj.experiments: + num_acquires = 0 + for instruction in exp.instructions: + if instruction.name == 'acquire': + num_acquires += 1 + + if num_acquires > 1: + raise AerError("PulseSimulator does not support multiple Acquire " + "instructions in a single schedule.") + + if num_acquires == 0: + raise AerError("PulseSimulator requires at least one Acquire " + "instruction per schedule.") + + @staticmethod + def _meas_levels(meas_levels): + """Function for setting meas_levels in a pulse simulator configuration.""" + if 0 in meas_levels: + warn('Measurement level 0 not supported in pulse simulator.') + tmp = copy.copy(meas_levels) + tmp.remove(0) + return tmp + return meas_levels diff --git a/qiskit/providers/aer/backends/qasm_simulator.py b/qiskit/providers/aer/backends/qasm_simulator.py index f652d4a052..0dc0908ba8 100644 --- a/qiskit/providers/aer/backends/qasm_simulator.py +++ b/qiskit/providers/aer/backends/qasm_simulator.py @@ -13,13 +13,15 @@ Qiskit Aer qasm simulator backend. """ +import copy import logging -from math import log2 -from qiskit.util import local_hardware_info from qiskit.providers.models import QasmBackendConfiguration -from .aerbackend import AerBackend + from ..version import __version__ -# pylint: disable=import-error,no-name-in-module +from .aerbackend import AerBackend +from .backend_utils import (cpp_execute, available_methods, + MAX_QUBITS_STATEVECTOR) +# pylint: disable=import-error, no-name-in-module from .controller_wrappers import qasm_controller_execute logger = logging.getLogger(__name__) @@ -29,34 +31,41 @@ class QasmSimulator(AerBackend): """ Noisy quantum circuit simulator backend. + **Configurable Options** + The `QasmSimulator` supports multiple simulation methods and - configurable options for each simulation method. These options are - specified in a dictionary which may be passed to the simulator using - the ``backend_options`` kwarg for :meth:`QasmSimulator.run` or - ``qiskit.execute``. + configurable options for each simulation method. These may be set using the + appropriate kwargs during initialization. They can also be set of updated + using the :meth:`set_options` method. - The default behavior chooses a simulation method automatically based on - the input circuit and noise model. A custom method can be specified using the - ``"method"`` field in ``backend_options`` as illustrated in the following - example. Available simulation methods and additional backend options are - listed below. + Run-time options may also be specified as kwargs using the :meth:`run` method. + These will not be stored in the backend and will only apply to that execution. + They will also override any previously set options. - **Example** + For example, to configure a density matrix simulator with a custom noise + model to use for every execution .. code-block:: python - backend = QasmSimulator() - backend_options = {"method": "statevector"} + noise_model = NoiseModel.from_backend(backend) + backend = QasmSimulator(method='density_matrix', + noise_model=noise_model) - # Circuit execution - job = execute(circuits, backend, backend_options=backend_options) + **Simulating an IBMQ Backend** + + The simulator can be automatically configured to mimic an IBMQ backend using + the :meth:`from_backend` method. This will configure the simulator to use the + basic device :class:`NoiseModel` for that backend, and the same basis gates + and coupling map. + + .. code-block:: python - # Qobj execution - job = backend.run(qobj, backend_options=backend_options) + backend = QasmSimulator.from_backend(backend) - **Simulation method** + **Simulation Method Option** - Available simulation methods are: + The simulation method is set using the ``method`` kwarg. + Supported simulation methods are: * ``"statevector"``: A dense statevector simulation that can sample measurement outcomes from *ideal* circuits with all measurements at @@ -95,36 +104,33 @@ class QasmSimulator(AerBackend): automatically for each circuit based on the circuit instructions, number of qubits, and noise model. - **Backend options** + **Additional Backend Options** - The following backend options may be used with in the - ``backend_options`` kwarg for :meth:`QasmSimulator.run` or - ``qiskit.execute``: + The following simulator specific backend options are supported - * ``"method"`` (str): Set the simulation method. See backend methods - for additional information (Default: "automatic"). + * ``method`` (str): Set the simulation method (Default: ``"automatic"``). - * ``"precision"`` (str): Set the floating point precision for - certain simulation methods to either "single" or "double" - precision (default: "double"). + * ``precision`` (str): Set the floating point precision for + certain simulation methods to either ``"single"`` or ``"double"`` + precision (default: ``"double"``). - * ``"zero_threshold"`` (double): Sets the threshold for truncating + * ``zero_threshold`` (double): Sets the threshold for truncating small values to zero in the result data (Default: 1e-10). - * ``"validation_threshold"`` (double): Sets the threshold for checking + * ``validation_threshold`` (double): Sets the threshold for checking if initial states are valid (Default: 1e-8). - * ``"max_parallel_threads"`` (int): Sets the maximum number of CPU + * ``max_parallel_threads`` (int): Sets the maximum number of CPU cores used by OpenMP for parallelization. If set to 0 the maximum will be set to the number of CPU cores (Default: 0). - * ``"max_parallel_experiments"`` (int): Sets the maximum number of + * ``max_parallel_experiments`` (int): Sets the maximum number of qobj experiments that may be executed in parallel up to the max_parallel_threads value. If set to 1 parallel circuit execution will be disabled. If set to 0 the maximum will be automatically set to max_parallel_threads (Default: 1). - * ``"max_parallel_shots"`` (int): Sets the maximum number of + * ``max_parallel_shots`` (int): Sets the maximum number of shots that may be executed in parallel during each experiment execution, up to the max_parallel_threads value. If set to 1 parallel shot execution will be disabled. If set to 0 the @@ -132,18 +138,18 @@ class QasmSimulator(AerBackend): Note that this cannot be enabled at the same time as parallel experiment execution (Default: 0). - * ``"max_memory_mb"`` (int): Sets the maximum size of memory + * ``max_memory_mb`` (int): Sets the maximum size of memory to store a state vector. If a state vector needs more, an error is thrown. In general, a state vector of n-qubits uses 2^n complex values (16 Bytes). If set to 0, the maximum will be automatically set to half the system memory size (Default: 0). - * ``"optimize_ideal_threshold"`` (int): Sets the qubit threshold for + * ``optimize_ideal_threshold`` (int): Sets the qubit threshold for applying circuit optimization passes on ideal circuits. Passes include gate fusion and truncation of unused qubits (Default: 5). - * ``"optimize_noise_threshold"`` (int): Sets the qubit threshold for + * ``optimize_noise_threshold`` (int): Sets the qubit threshold for applying circuit optimization passes on ideal circuits. Passes include gate fusion and truncation of unused qubits (Default: 12). @@ -151,7 +157,7 @@ class QasmSimulator(AerBackend): These backend options only apply when using the ``"statevector"`` simulation method: - * ``"statevector_parallel_threshold"`` (int): Sets the threshold that + * ``statevector_parallel_threshold`` (int): Sets the threshold that the number of qubits must be greater than to enable OpenMP parallelization for matrix multiplication during execution of an experiment. If parallel circuit or shot execution is enabled @@ -159,7 +165,7 @@ class QasmSimulator(AerBackend): max_parallel_threads. Note that setting this too low can reduce performance (Default: 14). - * ``"statevector_sample_measure_opt"`` (int): Sets the threshold that + * ``statevector_sample_measure_opt`` (int): Sets the threshold that the number of qubits must be greater than to enable a large qubit optimized implementation of measurement sampling. Note that setting this two low can reduce performance (Default: 10) @@ -167,7 +173,7 @@ class QasmSimulator(AerBackend): These backend options only apply when using the ``"stabilizer"`` simulation method: - * ``"stabilizer_max_snapshot_probabilities"`` (int): set the maximum + * ``stabilizer_max_snapshot_probabilities`` (int): set the maximum qubit number for the `~qiskit.providers.aer.extensions.SnapshotProbabilities` instruction (Default: 32). @@ -175,14 +181,14 @@ class QasmSimulator(AerBackend): These backend options only apply when using the ``"extended_stabilizer"`` simulation method: - * ``"extended_stabilizer_measure_sampling"`` (bool): Enable measure + * ``extended_stabilizer_measure_sampling`` (bool): Enable measure sampling optimization on supported circuits. This prevents the simulator from re-running the measure monte-carlo step for each shot. Enabling measure sampling may reduce accuracy of the measurement counts if the output distribution is strongly peaked (Default: False). - * ``"extended_stabilizer_mixing_time"`` (int): Set how long the + * ``extended_stabilizer_mixing_time`` (int): Set how long the monte-carlo method runs before performing measurements. If the output distribution is strongly peaked, this can be decreased alongside setting extended_stabilizer_disable_measurement_opt @@ -193,49 +199,45 @@ class QasmSimulator(AerBackend): smaller error needs more memory and computational time (Default: 0.05). - * ``"extended_stabilizer_norm_estimation_samples"`` (int): Number of + * ``extended_stabilizer_norm_estimation_samples`` (int): Number of samples used to compute the correct normalization for a statevector snapshot (Default: 100). - * ``"extended_stabilizer_parallel_threshold"`` (int): Set the minimum + * ``extended_stabilizer_parallel_threshold`` (int): Set the minimum size of the extended stabilizer decomposition before we enable OpenMP parallelization. If parallel circuit or shot execution is enabled this will only use unallocated CPU cores up to max_parallel_threads (Default: 100). - These backend options apply in circuit optimization passes: - - * ``"fusion_enable"`` (bool): Enable fusion optimization in circuit - optimization passes [Default: True] - * ``"fusion_verbose"`` (bool): Output gates generated in fusion optimization - into metadata [Default: False] - * ``"fusion_max_qubit"`` (int): Maximum number of qubits for a operation generated - in a fusion optimization [Default: 5] - * ``"fusion_threshold"`` (int): Threshold that number of qubits must be greater - than or equal to enable fusion optimization [Default: 20] - These backend options only apply when using the ``"matrix_product_state"`` simulation method: - * ``"matrix_product_state_max_bond_dimension"`` (int): Sets a limit + * ``matrix_product_state_max_bond_dimension`` (int): Sets a limit on the number of Schmidt coefficients retained at the end of the svd algorithm. Coefficients beyond this limit will be discarded. (Default: None, i.e., no limit on the bond dimension). - * ``"matrix_product_state_truncation_threshold"`` (double): + * ``matrix_product_state_truncation_threshold`` (double): Discard the smallest coefficients for which the sum of their squares is smaller than this threshold. (Default: 1e-16). - """ + These backend options apply in circuit optimization passes: - MAX_QUBIT_MEMORY = int( - log2(local_hardware_info()['memory'] * (1024**3) / 16)) + * ``fusion_enable`` (bool): Enable fusion optimization in circuit + optimization passes [Default: True] + * ``fusion_verbose`` (bool): Output gates generated in fusion optimization + into metadata [Default: False] + * ``fusion_max_qubit`` (int): Maximum number of qubits for a operation generated + in a fusion optimization [Default: 5] + * ``fusion_threshold`` (int): Threshold that number of qubits must be greater + than or equal to enable fusion optimization [Default: 20] + """ - DEFAULT_CONFIGURATION = { + _DEFAULT_CONFIGURATION = { 'backend_name': 'qasm_simulator', 'backend_version': __version__, - 'n_qubits': MAX_QUBIT_MEMORY, + 'n_qubits': MAX_QUBITS_STATEVECTOR, 'url': 'https://github.com/Qiskit/qiskit-aer', 'simulator': True, 'local': True, @@ -243,27 +245,121 @@ class QasmSimulator(AerBackend): 'open_pulse': False, 'memory': True, 'max_shots': int(1e6), - 'description': 'A C++ simulator with realistic noise for QASM Qobj files', + 'description': 'A C++ QasmQobj simulator with noise', 'coupling_map': None, 'basis_gates': [ - 'u1', 'u2', 'u3', 'p', 'r', 'rx', 'ry', 'rz', 'id', 'x', 'y', - 'z', 'h', 's', 'sdg', 'sx', 't', 'tdg', 'swap', 'cx', 'cy', - 'cz', 'csx', 'cp', 'cu1', 'cu2', 'cu3', 'rxx', 'ryy', 'rzz', - 'rzx', 'ccx', 'cswap', 'mcx', 'mcy', 'mcz', 'mcsx', 'mcp', - 'mcu1', 'mcu2', 'mcu3', 'mcrx', 'mcry', 'mcrz', 'mcr', - 'mcswap', 'unitary', 'diagonal', 'multiplexer', 'initialize', - 'kraus', 'superop', 'roerror', 'delay' + 'u1', 'u2', 'u3', 'p', 'r', 'rx', 'ry', 'rz', 'id', 'x', + 'y', 'z', 'h', 's', 'sdg', 'sx', 't', 'tdg', 'swap', 'cx', + 'cy', 'cz', 'csx', 'cp', 'cu1', 'cu2', 'cu3', 'rxx', 'ryy', + 'rzz', 'rzx', 'ccx', 'cswap', 'mcx', 'mcy', 'mcz', 'mcsx', + 'mcp', 'mcu1', 'mcu2', 'mcu3', 'mcrx', 'mcry', 'mcrz', + 'mcr', 'mcswap', 'unitary', 'diagonal', 'multiplexer', + 'initialize', 'kraus', 'roerror', 'delay' ], 'gates': [] } - def __init__(self, configuration=None, provider=None): - super().__init__( - qasm_controller_execute(), - QasmBackendConfiguration.from_dict(self.DEFAULT_CONFIGURATION), - provider=provider) + _AVAILABLE_METHODS = None + + def __init__(self, + configuration=None, + properties=None, + provider=None, + **backend_options): + + self._controller = qasm_controller_execute() + + # Update available methods for class + if QasmSimulator._AVAILABLE_METHODS is None: + QasmSimulator._AVAILABLE_METHODS = available_methods( + self._controller, [ + 'automatic', 'statevector', 'statevector_gpu', + 'statevector_thrust', 'density_matrix', + 'density_matrix_gpu', 'density_matrix_thrust', + 'stabilizer', 'matrix_product_state', 'extended_stabilizer' + ]) + + if configuration is None: + configuration = self._method_configuration() + super().__init__(configuration, + properties=properties, + available_methods=QasmSimulator._AVAILABLE_METHODS, + provider=provider, + backend_options=backend_options) + + @classmethod + def from_backend(cls, backend, **options): + """Initialize simulator from backend.""" + # pylint: disable=import-outside-toplevel + # Avoid cyclic import + from ..noise.noise_model import NoiseModel + + # Get configuration and properties from backend + configuration = copy.copy(backend.configuration()) + properties = copy.copy(backend.properties()) + + # Customize configuration name + name = configuration.backend_name + configuration.backend_name = 'qasm_simulator({})'.format(name) + + # Use automatic noise model if none is provided + if 'noise_model' not in options: + noise_model = NoiseModel.from_backend(backend) + if not noise_model.is_ideal(): + options['noise_model'] = noise_model + + # Initialize simulator + sim = cls(configuration=configuration, + properties=properties, + **options) + return sim + + def _execute(self, qobj): + """Execute a qobj on the backend. + + Args: + qobj (QasmQobj): simulator input. + + Returns: + dict: return a dictionary of results. + """ + return cpp_execute(self._controller, qobj) + + def _set_option(self, key, value): + """Set the simulation method and update configuration. - def _validate(self, qobj, backend_options, noise_model): + Args: + key (str): key to update + value (any): value to update. + + Raises: + AerError: if key is 'method' and val isn't in available methods. + """ + # If key is noise_model we also change the simulator config + # to use the noise_model basis gates by default. + if key == 'noise_model' and value is not None: + self._set_configuration_option('basis_gates', value.basis_gates) + + # If key is method we update our configurations + if key == 'method': + method_config = self._method_configuration(value) + self._set_configuration_option('description', method_config.description) + self._set_configuration_option('backend_name', method_config.backend_name) + self._set_configuration_option('n_qubits', method_config.n_qubits) + + # Take intersection of method basis gates and noise model basis gates + # if there is a noise model which has already set the basis gates + basis_gates = method_config.basis_gates + if 'noise_model' in self.options: + noise_basis_gates = self.options['noise_model'].basis_gates + basis_gates = list( + set(basis_gates).intersection(noise_basis_gates)) + self._set_configuration_option('basis_gates', basis_gates) + + # Set all other options from AerBackend + super()._set_option(key, value) + + def _validate(self, qobj): """Semantic validations of the qobj which cannot be done via schemas. Warn if no measurements in circuit with classical registers. @@ -285,3 +381,56 @@ def _validate(self, qobj, backend_options, noise_model): 'No measurements in circuit "%s": ' 'count data will return all zeros.', experiment.header.name) + + @staticmethod + def _method_configuration(method=None): + """Return QasmBackendConfiguration.""" + # Default configuration + config = QasmBackendConfiguration.from_dict( + QasmSimulator._DEFAULT_CONFIGURATION) + + # Statevector methods + if method in ['statevector', 'statevector_gpu', 'statevector_thrust']: + config.description = 'A C++ QasmQobj statevector simulator with noise' + + # Density Matrix methods + elif method in [ + 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust' + ]: + config.n_qubits = config.n_qubits // 2 + config.description = 'A C++ QasmQobj density matrix simulator with noise' + config.basis_gates = [ + 'u1', 'u2', 'u3', 'p', 'r', 'rx', 'ry', 'rz', 'id', 'x', + 'y', 'z', 'h', 's', 'sdg', 'sx', 't', 'tdg', 'swap', 'cx', + 'cy', 'cz', 'csx', 'cp', 'cu1', 'cu2', 'cu3', 'rxx', 'ryy', + 'rzz', 'rzx', 'ccx', 'unitary', 'diagonal', 'kraus', 'superop' + 'roerror', 'delay' + ] + + # Matrix product state method + elif method == 'matrix_product_state': + config.description = 'A C++ QasmQobj matrix product state simulator with noise' + config.basis_gates = [ + 'u1', 'u2', 'u3', 'cx', 'cz', 'id', 'x', 'y', 'z', 'h', 's', + 'sdg', 't', 'tdg', 'swap', 'ccx', 'unitary', 'roerror', 'delay' + ] + + # Stabilizer method + elif method == 'stabilizer': + config.n_qubits = 5000 # TODO: estimate from memory + config.description = 'A C++ QasmQobj Clifford stabilizer simulator with noise' + config.basis_gates = [ + 'id', 'x', 'y', 'z', 'h', 's', 'sdg', 'cx', 'cy', 'cz', + 'swap', 'roerror', 'delay' + ] + + # Extended stabilizer method + elif method == 'extended_stabilizer': + config.n_qubits = 63 # TODO: estimate from memory + config.description = 'A C++ QasmQobj ranked stabilizer simulator with noise' + config.basis_gates = [ + 'cx', 'cz', 'id', 'x', 'y', 'z', 'h', 's', 'sdg', 'swap', + 'u0', 'u1', 'ccx', 'ccz', 'roerror', 'delay' + ] + + return config diff --git a/qiskit/providers/aer/backends/statevector_simulator.py b/qiskit/providers/aer/backends/statevector_simulator.py index 20733023c7..f03ceab0ae 100644 --- a/qiskit/providers/aer/backends/statevector_simulator.py +++ b/qiskit/providers/aer/backends/statevector_simulator.py @@ -9,19 +9,20 @@ # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. - """ Qiskit Aer statevector simulator backend. """ import logging -from math import log2 from qiskit.util import local_hardware_info from qiskit.providers.models import QasmBackendConfiguration -from .aerbackend import AerBackend + from ..aererror import AerError from ..version import __version__ -# pylint: disable=import-error,no-name-in-module +from .aerbackend import AerBackend +from .backend_utils import (cpp_execute, available_methods, + MAX_QUBITS_STATEVECTOR) +# pylint: disable=import-error, no-name-in-module from .controller_wrappers import statevector_controller_execute # Logger @@ -31,35 +32,58 @@ class StatevectorSimulator(AerBackend): """Ideal quantum circuit statevector simulator - **Backend options** + **Configurable Options** + + The `StatevectorSimulator` supports CPU and GPU simulation methods and + additional configurable options. These may be set using the appropriate kwargs + during initialization. They can also be set of updated using the + :meth:`set_options` method. + + Run-time options may also be specified as kwargs using the :meth:`run` method. + These will not be stored in the backend and will only apply to that execution. + They will also override any previously set options. + + For example, to configure a a single-precision simulator - The following backend options may be used with in the - ``backend_options`` kwarg for :meth:`StatevectorSimulator.run` or - ``qiskit.execute``. + .. code-block:: python - * ``"zero_threshold"`` (double): Sets the threshold for truncating + backend = StatevectorSimulator(precision='single') + + **Backend Options** + + The following configurable backend options are supported + + * ``method`` (str): Set the simulation method supported methods are + ``"statevector"`` for CPU simulation, and ``"statevector_gpu"`` + for GPU simulation (Default: ``"statevector"``). + + * ``precision`` (str): Set the floating point precision for + certain simulation methods to either ``"single"`` or ``"double"`` + precision (default: ``"double"``). + + * ``zero_threshold`` (double): Sets the threshold for truncating small values to zero in the result data (Default: 1e-10). - * ``"validation_threshold"`` (double): Sets the threshold for checking + * ``validation_threshold`` (double): Sets the threshold for checking if the initial statevector is valid (Default: 1e-8). - * ``"max_parallel_threads"`` (int): Sets the maximum number of CPU + * ``max_parallel_threads`` (int): Sets the maximum number of CPU cores used by OpenMP for parallelization. If set to 0 the maximum will be set to the number of CPU cores (Default: 0). - * ``"max_parallel_experiments"`` (int): Sets the maximum number of + * ``max_parallel_experiments`` (int): Sets the maximum number of qobj experiments that may be executed in parallel up to the max_parallel_threads value. If set to 1 parallel circuit execution will be disabled. If set to 0 the maximum will be automatically set to max_parallel_threads (Default: 1). - * ``"max_memory_mb"`` (int): Sets the maximum size of memory + * ``max_memory_mb`` (int): Sets the maximum size of memory to store a state vector. If a state vector needs more, an error is thrown. In general, a state vector of n-qubits uses 2^n complex values (16 Bytes). If set to 0, the maximum will be automatically set to half the system memory size (Default: 0). - * ``"statevector_parallel_threshold"`` (int): Sets the threshold that + * ``statevector_parallel_threshold`` (int): Sets the threshold that "n_qubits" must be greater than to enable OpenMP parallelization for matrix multiplication during execution of an experiment. If parallel circuit or shot execution is enabled @@ -68,12 +92,10 @@ class StatevectorSimulator(AerBackend): performance (Default: 14). """ - MAX_QUBIT_MEMORY = int(log2(local_hardware_info()['memory'] * (1024 ** 3) / 16)) - - DEFAULT_CONFIGURATION = { + _DEFAULT_CONFIGURATION = { 'backend_name': 'statevector_simulator', 'backend_version': __version__, - 'n_qubits': MAX_QUBIT_MEMORY, + 'n_qubits': MAX_QUBITS_STATEVECTOR, 'url': 'https://github.com/Qiskit/qiskit-aer', 'simulator': True, 'local': True, @@ -81,30 +103,63 @@ class StatevectorSimulator(AerBackend): 'open_pulse': False, 'memory': True, 'max_shots': int(1e6), # Note that this backend will only ever - # perform a single shot. This value is just - # so that the default shot value for execute - # will not raise an error when trying to run - # a simulation + # perform a single shot. This value is just + # so that the default shot value for execute + # will not raise an error when trying to run + # a simulation 'description': 'A C++ statevector simulator for QASM Qobj files', 'coupling_map': None, 'basis_gates': [ - 'u1', 'u2', 'u3', 'p', 'r', 'rx', 'ry', 'rz', 'id', 'x', 'y', - 'z', 'h', 's', 'sdg', 'sx', 't', 'tdg', 'swap', 'cx', 'cy', - 'cz', 'csx', 'cp', 'cu1', 'cu2', 'cu3', 'rxx', 'ryy', 'rzz', - 'rzx', 'ccx', 'cswap', 'mcx', 'mcy', 'mcz', 'mcsx', 'mcp', - 'mcu1', 'mcu2', 'mcu3', 'mcrx', 'mcry', 'mcrz', 'mcr', - 'mcswap', 'unitary', 'diagonal', 'multiplexer', 'initialize', - 'kraus', 'roerror', 'delay' + 'u1', 'u2', 'u3', 'p', 'r', 'rx', 'ry', 'rz', 'id', 'x', + 'y', 'z', 'h', 's', 'sdg', 'sx', 't', 'tdg', 'swap', 'cx', + 'cy', 'cz', 'csx', 'cp', 'cu1', 'cu2', 'cu3', 'rxx', 'ryy', + 'rzz', 'rzx', 'ccx', 'cswap', 'mcx', 'mcy', 'mcz', 'mcsx', + 'mcp', 'mcu1', 'mcu2', 'mcu3', 'mcrx', 'mcry', 'mcrz', + 'mcr', 'mcswap', 'unitary', 'diagonal', 'multiplexer', + 'initialize', 'kraus', 'roerror', 'delay' ], 'gates': [] } - def __init__(self, configuration=None, provider=None): - super().__init__(statevector_controller_execute(), - QasmBackendConfiguration.from_dict(self.DEFAULT_CONFIGURATION), - provider=provider) + # Cache available methods + _AVAILABLE_METHODS = None + + def __init__(self, + configuration=None, + properties=None, + provider=None, + **backend_options): + + self._controller = statevector_controller_execute() + + if StatevectorSimulator._AVAILABLE_METHODS is None: + StatevectorSimulator._AVAILABLE_METHODS = available_methods( + self._controller, [ + 'automatic', 'statevector', 'statevector_gpu', + 'statevector_thrust' + ]) + if configuration is None: + configuration = QasmBackendConfiguration.from_dict( + StatevectorSimulator._DEFAULT_CONFIGURATION) + super().__init__( + configuration, + properties=properties, + available_methods=StatevectorSimulator._AVAILABLE_METHODS, + provider=provider, + backend_options=backend_options) + + def _execute(self, qobj): + """Execute a qobj on the backend. + + Args: + qobj (QasmQobj): simulator input. + + Returns: + dict: return a dictionary of results. + """ + return cpp_execute(self._controller, qobj) - def _validate(self, qobj, backend_options, noise_model): + def _validate(self, qobj): """Semantic validations of the qobj which cannot be done via schemas. Some of these may later move to backend schemas. @@ -112,7 +167,7 @@ def _validate(self, qobj, backend_options, noise_model): 2. Check number of qubits will fit in local memory. """ name = self.name() - if noise_model is not None: + if getattr(qobj.config, 'noise_model', None) is not None: raise AerError("{} does not support noise.".format(name)) n_qubits = qobj.config.n_qubits @@ -120,7 +175,8 @@ def _validate(self, qobj, backend_options, noise_model): if n_qubits > max_qubits: raise AerError( 'Number of qubits ({}) is greater than max ({}) for "{}" with {} GB system memory.' - .format(n_qubits, max_qubits, name, int(local_hardware_info()['memory']))) + .format(n_qubits, max_qubits, name, + int(local_hardware_info()['memory']))) if qobj.config.shots != 1: logger.info('"%s" only supports 1 shot. Setting shots=1.', name) @@ -129,7 +185,7 @@ def _validate(self, qobj, backend_options, noise_model): for experiment in qobj.experiments: exp_name = experiment.header.name if getattr(experiment.config, 'shots', 1) != 1: - logger.info('"%s" only supports 1 shot. ' - 'Setting shots=1 for circuit "%s".', - name, exp_name) + logger.info( + '"%s" only supports 1 shot. ' + 'Setting shots=1 for circuit "%s".', name, exp_name) experiment.config.shots = 1 diff --git a/qiskit/providers/aer/backends/unitary_simulator.py b/qiskit/providers/aer/backends/unitary_simulator.py index c667c51393..f671d65150 100644 --- a/qiskit/providers/aer/backends/unitary_simulator.py +++ b/qiskit/providers/aer/backends/unitary_simulator.py @@ -16,14 +16,15 @@ """ import logging -from math import log2, sqrt from qiskit.util import local_hardware_info from qiskit.providers.models import QasmBackendConfiguration -from .aerbackend import AerBackend from ..aererror import AerError from ..version import __version__ -# pylint: disable=import-error,no-name-in-module +from .aerbackend import AerBackend +from .backend_utils import (cpp_execute, available_methods, + MAX_QUBITS_STATEVECTOR) +# pylint: disable=import-error, no-name-in-module from .controller_wrappers import unitary_controller_execute # Logger @@ -33,11 +34,34 @@ class UnitarySimulator(AerBackend): """Ideal quantum circuit unitary simulator. - **Backend options** + **Configurable Options** + + The `UnitarySimulator` supports CPU and GPU simulation methods and + additional configurable options. These may be set using the appropriate kwargs + during initialization. They can also be set of updated using the + :meth:`set_options` method. + + Run-time options may also be specified as kwargs using the :meth:`run` method. + These will not be stored in the backend and will only apply to that execution. + They will also override any previously set options. + + For example, to configure a a single-precision simulator + + .. code-block:: python + + backend = UnitarySimulator(precision='single') + + **Backend Options** + + The following configurable backend options are supported + + * ``method`` (str): Set the simulation method supported methods are + ``"unitary"`` for CPU simulation, and ``"untiary_gpu"`` + for GPU simulation (Default: ``"unitary"``). - The following backend options may be used with in the - ``backend_options`` kwarg for :meth:`UnitarySimulator.run` or - ``qiskit.execute``. + * ``precision`` (str): Set the floating point precision for + certain simulation methods to either ``"single"`` or ``"double"`` + precision (default: ``"double"``). * ``"initial_unitary"`` (matrix_like): Sets a custom initial unitary matrix for the simulation instead of identity (Default: None). @@ -74,15 +98,11 @@ class UnitarySimulator(AerBackend): performance (Default: 14). """ - MAX_QUBIT_MEMORY = int( - log2(sqrt(local_hardware_info()['memory'] * (1024**3) / 16))) - - DEFAULT_CONFIGURATION = { + _DEFAULT_CONFIGURATION = { 'backend_name': 'unitary_simulator', 'backend_version': __version__, - 'n_qubits': MAX_QUBIT_MEMORY, - 'url': - 'https://github.com/Qiskit/qiskit-aer', + 'n_qubits': MAX_QUBITS_STATEVECTOR // 2, + 'url': 'https://github.com/Qiskit/qiskit-aer', 'simulator': True, 'local': True, 'conditional': False, @@ -96,22 +116,53 @@ class UnitarySimulator(AerBackend): 'description': 'A C++ unitary simulator for QASM Qobj files', 'coupling_map': None, 'basis_gates': [ - 'u1', 'u2', 'u3', 'p', 'r', 'rx', 'ry', 'rz', 'id', 'x', 'y', - 'z', 'h', 's', 'sdg', 'sx', 't', 'tdg', 'swap', 'cx', 'cy', - 'cz', 'csx', 'cp', 'cu1', 'cu2', 'cu3', 'rxx', 'ryy', 'rzz', - 'rzx', 'ccx', 'cswap', 'mcx', 'mcy', 'mcz', 'mcsx', 'mcp', - 'mcu1', 'mcu2', 'mcu3', 'mcrx', 'mcry', 'mcrz', 'mcr', - 'mcswap', 'unitary', 'diagonal', 'multiplexer', 'delay' + 'u1', 'u2', 'u3', 'p', 'r', 'rx', 'ry', 'rz', 'id', 'x', + 'y', 'z', 'h', 's', 'sdg', 'sx', 't', 'tdg', 'swap', 'cx', + 'cy', 'cz', 'csx', 'cp', 'cu1', 'cu2', 'cu3', 'rxx', 'ryy', + 'rzz', 'rzx', 'ccx', 'cswap', 'mcx', 'mcy', 'mcz', 'mcsx', + 'mcp', 'mcu1', 'mcu2', 'mcu3', 'mcrx', 'mcry', 'mcrz', + 'mcr', 'mcswap', 'unitary', 'diagonal', 'multiplexer', 'delay' ], 'gates': [] } - def __init__(self, configuration=None, provider=None): - super().__init__(unitary_controller_execute(), - QasmBackendConfiguration.from_dict(self.DEFAULT_CONFIGURATION), - provider=provider) + _AVAILABLE_METHODS = None + + def __init__(self, + configuration=None, + properties=None, + provider=None, + **backend_options): + + self._controller = unitary_controller_execute() + + if UnitarySimulator._AVAILABLE_METHODS is None: + UnitarySimulator._AVAILABLE_METHODS = available_methods( + self._controller, + ['automatic', 'unitary', 'unitary_gpu', 'unitary_thrust']) + + if configuration is None: + configuration = QasmBackendConfiguration.from_dict( + UnitarySimulator._DEFAULT_CONFIGURATION) + + super().__init__(configuration, + properties=properties, + available_methods=UnitarySimulator._AVAILABLE_METHODS, + provider=provider, + backend_options=backend_options) + + def _execute(self, qobj): + """Execute a qobj on the backend. + + Args: + qobj (QasmQobj): simulator input. + + Returns: + dict: return a dictionary of results. + """ + return cpp_execute(self._controller, qobj) - def _validate(self, qobj, backend_options, noise_model): + def _validate(self, qobj): """Semantic validations of the qobj which cannot be done via schemas. Some of these may later move to backend schemas. 1. Set shots=1 @@ -119,7 +170,7 @@ def _validate(self, qobj, backend_options, noise_model): 3. Check number of qubits will fit in local memory. """ name = self.name() - if noise_model is not None: + if getattr(qobj.config, 'noise_model', None) is not None: raise AerError("{} does not support noise.".format(name)) n_qubits = qobj.config.n_qubits diff --git a/qiskit/providers/aer/noise/noise_model.py b/qiskit/providers/aer/noise/noise_model.py index d8fd2ad950..4b89f41a46 100644 --- a/qiskit/providers/aer/noise/noise_model.py +++ b/qiskit/providers/aer/noise/noise_model.py @@ -23,7 +23,6 @@ from ..backends.aerbackend import AerJSONEncoder from ..backends.qasm_simulator import QasmSimulator - from .noiseerror import NoiseError from .errors.quantum_error import QuantumError from .errors.readout_error import ReadoutError @@ -89,15 +88,15 @@ class NoiseModel: # Get the default basis gates for the Qiskit Aer Qasm Simulator # this is used to decide what are instructions for a noise model # and what are labels for other named instructions - _QASMSIMULATOR_BASIS_GATES = QasmSimulator.DEFAULT_CONFIGURATION[ - 'basis_gates'] + # NOTE: we exclude kraus, roerror, and initialize instructions here + _QASMSIMULATOR_BASIS_GATES = QasmSimulator._DEFAULT_CONFIGURATION['basis_gates'] # Checks for standard 1-3 qubit instructions _1qubit_instructions = set([ "x90", "u1", "u2", "u3", "U", "id", "x", "y", "z", "h", "s", "sdg", "t", "tdg", "r", "rx", "ry", "rz", "p" ]) - _2qubit_instructions = set(["cx", "cz", "swap", "rxx", "ryy", "rzz", + _2qubit_instructions = set(["cx", "cy", "cz", "swap", "rxx", "ryy", "rzz", "rzx", "cu1", "cu2", "cu3", "cp"]) _3qubit_instructions = set(["ccx", "cswap"]) @@ -301,8 +300,27 @@ def from_backend(cls, backend, noise_model.add_quantum_error(error, name, qubits, warnings=warnings) return noise_model - def __repr__(self): - """Display noise model""" + def is_ideal(self): + """Return True if the noise model has no noise terms.""" + # Get default errors + if self._default_quantum_errors: + return False + if self._default_readout_error: + return False + if self._local_quantum_errors: + return False + if self._local_readout_errors: + return False + if self._nonlocal_quantum_errors: + return False + return True + + def __str__(self): + """Noise model string representation""" + + # Check if noise model is ideal + if self.is_ideal(): + return "NoiseModel: Ideal" # Get default errors default_error_ops = [] @@ -331,27 +349,24 @@ def __repr__(self): self._str2qubits(nq_str))) output = "NoiseModel:" - if default_error_ops == [] and local_error_ops == [] and nonlocal_error_ops == []: - output += " Ideal" - else: - output += "\n Basis gates: {}".format(self.basis_gates) - if self._noise_instructions: - output += "\n Instructions with noise: {}".format( - list(self._noise_instructions)) - if self._noise_qubits: - output += "\n Qubits with noise: {}".format( - list(self._noise_qubits)) - if self._x90_gates: - output += "\n X-90 based single qubit gates: {}".format( - list(self._x90_gates)) - if default_error_ops != []: - output += "\n All-qubits errors: {}".format(default_error_ops) - if local_error_ops != []: - output += "\n Specific qubit errors: {}".format( - local_error_ops) - if nonlocal_error_ops != []: - output += "\n Non-local specific qubit errors: {}".format( - nonlocal_error_ops) + output += "\n Basis gates: {}".format(self.basis_gates) + if self._noise_instructions: + output += "\n Instructions with noise: {}".format( + list(self._noise_instructions)) + if self._noise_qubits: + output += "\n Qubits with noise: {}".format( + list(self._noise_qubits)) + if self._x90_gates: + output += "\n X-90 based single qubit gates: {}".format( + list(self._x90_gates)) + if default_error_ops != []: + output += "\n All-qubits errors: {}".format(default_error_ops) + if local_error_ops != []: + output += "\n Specific qubit errors: {}".format( + local_error_ops) + if nonlocal_error_ops != []: + output += "\n Non-local specific qubit errors: {}".format( + nonlocal_error_ops) return output def __eq__(self, other): @@ -398,7 +413,8 @@ def add_basis_gates(self, instructions, warnings=True): # If the instruction is in the default basis gates for the # QasmSimulator we add it to the basis gates. if name in self._QASMSIMULATOR_BASIS_GATES: - if name not in ['measure', 'reset']: + if name not in ['measure', 'reset', 'initialize', + 'kraus', 'superop', 'roerror']: self._basis_gates.add(name) elif warnings: logger.warning( diff --git a/qiskit/providers/aer/pulse/controllers/digest_pulse_qobj.py b/qiskit/providers/aer/pulse/controllers/digest_pulse_qobj.py index d840bfb29e..e504e75d66 100644 --- a/qiskit/providers/aer/pulse/controllers/digest_pulse_qobj.py +++ b/qiskit/providers/aer/pulse/controllers/digest_pulse_qobj.py @@ -64,7 +64,7 @@ def __init__(self): self.experiments = None -def digest_pulse_qobj(qobj, channels, dt, qubit_list, backend_options=None): +def digest_pulse_qobj(qobj, channels, dt, qubit_list): """ Given a PulseQobj (and other parameters), returns a DigestedPulseQobj containing relevant extracted information @@ -73,7 +73,6 @@ def digest_pulse_qobj(qobj, channels, dt, qubit_list, backend_options=None): channels (OrderedDict): channel dictionary dt (float): pulse sample width qubit_list (list): list of qubits to include - backend_options (dict): dict with options that can override all other parameters Returns: DigestedPulseQobj: digested pulse qobj @@ -83,10 +82,6 @@ def digest_pulse_qobj(qobj, channels, dt, qubit_list, backend_options=None): AerError: for unsupported features or invalid qobj TypeError: for arguments of invalid type """ - - if backend_options is None: - backend_options = {} - digested_qobj = DigestedPulseQobj() qobj_dict = qobj.to_dict() @@ -95,10 +90,6 @@ def digest_pulse_qobj(qobj, channels, dt, qubit_list, backend_options=None): # raises errors for unsupported features _unsupported_errors(qobj_dict) - # override anything in qobj_config that is present in backend_options - for key in backend_options.keys(): - qobj_config[key] = backend_options[key] - if 'memory_slots' not in qobj_config: raise ValueError('Number of memory_slots must be specific in Qobj config') diff --git a/qiskit/providers/aer/pulse/controllers/pulse_controller.py b/qiskit/providers/aer/pulse/controllers/pulse_controller.py index c3a514f9a6..207b0b6a27 100644 --- a/qiskit/providers/aer/pulse/controllers/pulse_controller.py +++ b/qiskit/providers/aer/pulse/controllers/pulse_controller.py @@ -29,13 +29,11 @@ from .pulse_utils import get_ode_rhs_functor -def pulse_controller(qobj, system_model, backend_options): +def pulse_controller(qobj): """ Interprets PulseQobj input, runs simulations, and returns results Parameters: - qobj (qobj): pulse qobj containing a list of pulse schedules - system_model (PulseSystemModel): contains system model information - backend_options (dict): dict of options, which overrides other parameters + qobj (PulseQobj): pulse qobj containing a list of pulse schedules Returns: list: simulation results @@ -44,22 +42,17 @@ def pulse_controller(qobj, system_model, backend_options): ValueError: if input is of incorrect format Exception: for invalid ODE options """ - pulse_sim_desc = PulseSimDescription() pulse_de_model = PulseInternalDEModel() - if backend_options is None: - backend_options = {} - - noise_model = backend_options.get('noise_model', None) - - # post warnings for unsupported features - _unsupported_warnings(noise_model) + config = qobj.config # ############################### # ### Extract model parameters # ############################### + system_model = config.system_model + # Get qubit list and number qubit_list = system_model.subsystem_list if qubit_list is None: @@ -84,8 +77,8 @@ def pulse_controller(qobj, system_model, backend_options): estates = [qobj_gen.state(state) for state in ham_model._estates.T[:]] # initial state set here - if 'initial_state' in backend_options: - pulse_sim_desc.initial_state = Qobj(backend_options['initial_state']) + if hasattr(config, 'initial_state'): + pulse_sim_desc.initial_state = Qobj(config.initial_state) else: pulse_sim_desc.initial_state = estates[0] @@ -96,6 +89,11 @@ def pulse_controller(qobj, system_model, backend_options): pulse_de_model.dt = system_model.dt # Parse noise + noise_model = getattr(config, 'noise_model', None) + + # post warnings for unsupported features + _unsupported_warnings(noise_model) + if noise_model: noise = NoiseParser(noise_dict=noise_model, dim_osc=dim_osc, dim_qub=dim_qub) noise.parse() @@ -110,8 +108,7 @@ def pulse_controller(qobj, system_model, backend_options): digested_qobj = digest_pulse_qobj(qobj, pulse_de_model.channels, system_model.dt, - qubit_list, - backend_options) + qubit_list) # extract simulation-description level qobj content pulse_sim_desc.shots = digested_qobj.shots @@ -133,12 +130,14 @@ def pulse_controller(qobj, system_model, backend_options): # if it wasn't specified in the PulseQobj, draw from system_model if qubit_lo_freq is None: - qubit_lo_freq = system_model._qubit_freq_est + default_freq = getattr(config, 'qubit_freq_est', [np.inf]) + if default_freq != [np.inf]: + qubit_lo_freq = default_freq - # if still None draw from the Hamiltonian + # if still None, or is the placeholder value draw from the Hamiltonian if qubit_lo_freq is None: qubit_lo_freq = system_model.hamiltonian.get_qubit_lo_from_drift() - warn('Warning: qubit_lo_freq was not specified in PulseQobj or in PulseSystemModel, ' + + warn('Warning: qubit_lo_freq was not specified in PulseQobj and there is no default, ' 'so it is beign automatically determined from the drift Hamiltonian.') pulse_de_model.freqs = system_model.calculate_channel_frequencies(qubit_lo_freq=qubit_lo_freq) @@ -147,14 +146,15 @@ def pulse_controller(qobj, system_model, backend_options): # ### Parse backend_options # # solver-specific information should be extracted in the solver # ############################### - pulse_sim_desc.seed = int(backend_options['seed']) if 'seed' in backend_options else None - pulse_sim_desc.q_level_meas = int(backend_options.get('q_level_meas', 1)) + + pulse_sim_desc.seed = int(config.seed) if hasattr(config, 'seed') else None + pulse_sim_desc.q_level_meas = int(getattr(config, 'q_level_meas', 1)) # solver options allowed_solver_options = ['atol', 'rtol', 'nsteps', 'max_step', 'num_cpus', 'norm_tol', 'norm_steps', 'method'] - solver_options = backend_options.get('solver_options', {}) + solver_options = getattr(config, 'solver_options', {}) for key in solver_options: if key not in allowed_solver_options: raise Exception('Invalid solver_option: {}'.format(key)) @@ -203,7 +203,12 @@ def pulse_controller(qobj, system_model, backend_options): else run_monte_carlo_experiments) exp_results, exp_times = run_experiments(pulse_sim_desc, pulse_de_model, solver_options) - return format_exp_results(exp_results, exp_times, pulse_sim_desc) + output = { + 'results': format_exp_results(exp_results, exp_times, pulse_sim_desc), + 'success': True, + 'qobj_id': qobj.qobj_id + } + return output def format_exp_results(exp_results, exp_times, pulse_sim_desc): @@ -288,7 +293,6 @@ def format_exp_results(exp_results, exp_times, pulse_sim_desc): results['data']['memory'] = results['data']['memory'][0] all_results.append(results) - return all_results diff --git a/qiskit/providers/aer/pulse/system_models/pulse_system_model.py b/qiskit/providers/aer/pulse/system_models/pulse_system_model.py index 1e02d1c0ab..77582e8ffc 100644 --- a/qiskit/providers/aer/pulse/system_models/pulse_system_model.py +++ b/qiskit/providers/aer/pulse/system_models/pulse_system_model.py @@ -30,8 +30,6 @@ class PulseSystemModel(): * ``"hamiltonian"``: a :class:`HamiltonianModel` object representing the Hamiltonian of the system. - * ``"qubit_freq_est"`` and ``"meas_freq_est"``: optional default values for - qubit and measurement frequencies. * ``"u_channel_lo"``: A description of :class:`ControlChannel` local oscillator frequencies in terms of qubit local oscillator frequencies. * ``"control_channel_labels"``: Optional list of identifying information for @@ -55,8 +53,6 @@ class PulseSystemModel(): """ def __init__(self, hamiltonian=None, - qubit_freq_est=None, - meas_freq_est=None, u_channel_lo=None, control_channel_labels=None, subsystem_list=None, @@ -65,10 +61,6 @@ def __init__(self, Args: hamiltonian (HamiltonianModel): The Hamiltonian of the system. - qubit_freq_est (list): list of qubit lo frequencies defaults to be used in simulation - if none are specified in the PulseQobj. - meas_freq_est (list): list of qubit meas frequencies defaults to be used in simulation - if none are specified in the PulseQobj. u_channel_lo (list): list of ControlChannel frequency specifications. control_channel_labels (list): list of labels for control channels, which can be of any type. @@ -78,10 +70,6 @@ def __init__(self, AerError: if hamiltonian is not None or a HamiltonianModel """ - # default type values - self._qubit_freq_est = qubit_freq_est - self._meas_freq_est = meas_freq_est - # necessary values if hamiltonian is not None and not isinstance(hamiltonian, HamiltonianModel): raise AerError("hamiltonian must be a HamiltonianModel object") @@ -110,23 +98,24 @@ def from_backend(cls, backend, subsystem_list=None): raise AerError("{} is not a Qiskit backend".format(backend)) # get relevant information from backend - defaults = backend.defaults() config = backend.configuration() if not config.open_pulse: raise AerError('{} is not an open pulse backend'.format(backend)) - # draw defaults - qubit_freq_est = getattr(defaults, 'qubit_freq_est', None) - meas_freq_est = getattr(defaults, 'meas_freq_est', None) + return cls.from_config(config, subsystem_list) + + @classmethod + def from_config(cls, configuration, subsystem_list=None): + """Construct a model from configuration and defaults.""" # draw from configuration # if no subsystem_list, use all for device - subsystem_list = subsystem_list or list(range(config.n_qubits)) - ham_string = config.hamiltonian + subsystem_list = subsystem_list or list(range(configuration.n_qubits)) + ham_string = configuration.hamiltonian hamiltonian = HamiltonianModel.from_dict(ham_string, subsystem_list) - u_channel_lo = getattr(config, 'u_channel_lo', None) - dt = getattr(config, 'dt', None) + u_channel_lo = getattr(configuration, 'u_channel_lo', None) + dt = getattr(configuration, 'dt', None) control_channel_labels = [None] * len(u_channel_lo) # populate control_channel_dict @@ -163,8 +152,6 @@ def from_backend(cls, backend, subsystem_list=None): control_channel_labels[u_idx] = {'driven_q': drive_idx, 'freq': u_string} return cls(hamiltonian=hamiltonian, - qubit_freq_est=qubit_freq_est, - meas_freq_est=meas_freq_est, u_channel_lo=u_channel_lo, control_channel_labels=control_channel_labels, subsystem_list=subsystem_list, @@ -190,8 +177,7 @@ def calculate_channel_frequencies(self, qubit_lo_freq=None): Args: qubit_lo_freq (list or None): list of qubit linear - oscillator drive frequencies. If None these will be calculated - using self._qubit_freq_est. + oscillator drive frequencies. Returns: OrderedDict: a dictionary of channel frequencies. @@ -200,10 +186,7 @@ def calculate_channel_frequencies(self, qubit_lo_freq=None): ValueError: If channel or u_channel_lo are invalid. """ if not qubit_lo_freq: - if not self._qubit_freq_est: - raise ValueError("No qubit_lo_freq to use.") - - qubit_lo_freq = self._qubit_freq_est + raise ValueError("qubit_lo_freq is a required function parameter.") if self.u_channel_lo is None: raise ValueError("{} has no u_channel_lo.".format(self.__class__.__name__)) diff --git a/releasenotes/notes/configurable-backends-a55cd6a39a0a1561.yaml b/releasenotes/notes/configurable-backends-a55cd6a39a0a1561.yaml new file mode 100644 index 0000000000..6b91dd9ca3 --- /dev/null +++ b/releasenotes/notes/configurable-backends-a55cd6a39a0a1561.yaml @@ -0,0 +1,35 @@ +--- +features: + - | + Make simulator backends configurable. This allows setting persistant options + such as simulation method and noise model for each simulator backend object. + + The :class:`~qiskit.providers.aer.QasmSimulator` and + :class:`~qiskit.providers.aer.PulseSimulator` can also be configured from + an :class:`~qiskit.providers.ibmq.IBMQBackend` backend object using the + `:meth:`~qiskit.providers.aer.QasmSimulator.from_backend` method. + For the :class:`~qiskit.providers.aer.QasmSimulator` this will configure the coupling map, + basis gates, and basic device noise model based on the backend configuration and + properties. For the :class:`~qiskit.providers.aer.PulseSimulator` the system model + and defaults will be configured automatically from the backend configuration, properties and + defaults. + + A benefit is that a :class:`~qiskit.providers.aer.PulseSimulator` instance configured from + a backend better serves as a drop-in replacement to the original backend, making it easier to + swap in and out a simulator and real backend, e.g. when testing code on a simulator before + using a real backend. + For example, in the following code-block, the :class:`~qiskit.providers.aer.PulseSimulator` is + instantiated from the ``FakeArmonk()`` backend. All configuration and default data is copied + into the simulator instance, and so when it is passed as an argument to ``assemble``, + it behaves as if the original backend was supplied (e.g. defaults from ``FakeArmonk`` will be + present and used by ``assemble``). + + .. code-block:: python + + armonk_sim = qiskit.providers.aer.PulseSimulator.from_backend(FakeArmonk()) + pulse_qobj = assemble(schedules, backend=armonk_sim) + armonk_sim.run(pulse_qobj) + + While the above example is small, the demonstrated 'drop-in replacement' behavior should + greatly improve the usability in more complicated work-flows, e.g. when calibration experiments + are constructed using backend attributes. diff --git a/test/benchmark/fusion_benchmarks.py b/test/benchmark/fusion_benchmarks.py index dd8e52b95d..490df2b89f 100644 --- a/test/benchmark/fusion_benchmarks.py +++ b/test/benchmark/fusion_benchmarks.py @@ -50,7 +50,8 @@ def qft_circuit(num_qubit, use_cu1): def time_quantum_fourier_transform(self, num_qubit, fusion_enable, use_cu1): """ Benchmark QFT """ - result = self.backend.run(self.circuit[(num_qubit, use_cu1)], backend_options={'fusion_enable': fusion_enable}).result() + result = self.backend.run(self.circuit[(num_qubit, use_cu1)], + fusion_enable=fusion_enable).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status) @@ -105,6 +106,6 @@ def build_model_circuit_kak(width, depth, seed=None): def time_random_transform(self, num_qubits, fusion_enable): circ = self.build_model_circuit_kak(num_qubits, num_qubits, 1) qobj = assemble(circ) - result = self.backend.run(qobj, backend_options={'fusion_enable': fusion_enable}).result() + result = self.backend.run(qobj, fusion_enable=fusion_enable).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status) diff --git a/test/benchmark/randomized_benchmarking.py b/test/benchmark/randomized_benchmarking.py index 3c4789043e..5069c2760b 100644 --- a/test/benchmark/randomized_benchmarking.py +++ b/test/benchmark/randomized_benchmarking.py @@ -87,7 +87,7 @@ def time_run_rb_circuit(self, _, simulator_method, noise_model): 'noise_model': noise_model(), } job = self.sim_backend.run(self.qobj, - backend_options=backend_options) + **backend_options) job.result() def peakmem_run_rb_circuit(self, _, simulator_method, noise_model): @@ -96,5 +96,5 @@ def peakmem_run_rb_circuit(self, _, simulator_method, noise_model): 'noise_model': noise_model(), } job = self.sim_backend.run(self.qobj, - backend_options=backend_options) + **backend_options) job.result() diff --git a/test/terra/backends/qasm_simulator/qasm_algorithms.py b/test/terra/backends/qasm_simulator/qasm_algorithms.py index 453e8f6bf0..e7fc5c98d7 100644 --- a/test/terra/backends/qasm_simulator/qasm_algorithms.py +++ b/test/terra/backends/qasm_simulator/qasm_algorithms.py @@ -34,7 +34,7 @@ def test_grovers_default_basis_gates(self): final_measure=True, allow_sampling=True) targets = ref_algorithms.grovers_counts(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -45,7 +45,7 @@ def test_teleport_default_basis_gates(self): circuits = ref_algorithms.teleport_circuit() targets = ref_algorithms.teleport_counts(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -72,7 +72,7 @@ def test_grovers_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -87,7 +87,7 @@ def test_teleport_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -110,7 +110,7 @@ def test_grovers_minimal_basis_gates(self): targets = ref_algorithms.grovers_counts(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -122,7 +122,7 @@ def test_teleport_minimal_basis_gates(self): targets = ref_algorithms.teleport_counts(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) diff --git a/test/terra/backends/qasm_simulator/qasm_cliffords.py b/test/terra/backends/qasm_simulator/qasm_cliffords.py index 26a5aa760b..a3808e946e 100644 --- a/test/terra/backends/qasm_simulator/qasm_cliffords.py +++ b/test/terra/backends/qasm_simulator/qasm_cliffords.py @@ -35,7 +35,7 @@ def test_h_gate_deterministic_default_basis_gates(self): final_measure=True) targets = ref_1q_clifford.h_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -47,7 +47,7 @@ def test_h_gate_nondeterministic_default_basis_gates(self): final_measure=True) targets = ref_1q_clifford.h_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -76,7 +76,7 @@ def test_z_gate_deterministic_default_basis_gates(self): final_measure=True) targets = ref_1q_clifford.z_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -91,7 +91,7 @@ def test_y_gate_deterministic_default_basis_gates(self): final_measure=True) targets = ref_1q_clifford.y_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -106,7 +106,7 @@ def test_s_gate_deterministic_default_basis_gates(self): final_measure=True) targets = ref_1q_clifford.s_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -121,7 +121,7 @@ def test_s_gate_nondeterministic_default_basis_gates(self): circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -139,7 +139,7 @@ def test_sdg_gate_deterministic_default_basis_gates(self): circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -151,7 +151,7 @@ def test_sdg_gate_nondeterministic_default_basis_gates(self): final_measure=True) targets = ref_1q_clifford.sdg_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -166,7 +166,7 @@ def test_cx_gate_deterministic_default_basis_gates(self): final_measure=True) targets = ref_2q_clifford.cx_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -178,7 +178,7 @@ def test_cx_gate_nondeterministic_default_basis_gates(self): final_measure=True) targets = ref_2q_clifford.cx_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -193,7 +193,7 @@ def test_cz_gate_deterministic_default_basis_gates(self): final_measure=True) targets = ref_2q_clifford.cz_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -205,7 +205,7 @@ def test_cz_gate_nondeterministic_default_basis_gates(self): final_measure=True) targets = ref_2q_clifford.cz_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -220,7 +220,7 @@ def test_swap_gate_deterministic_default_basis_gates(self): final_measure=True) targets = ref_2q_clifford.swap_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -232,7 +232,7 @@ def test_swap_gate_nondeterministic_default_basis_gates(self): final_measure=True) targets = ref_2q_clifford.swap_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -258,7 +258,7 @@ def test_h_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -274,7 +274,7 @@ def test_h_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -293,7 +293,7 @@ def test_x_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -313,7 +313,7 @@ def test_z_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -326,7 +326,7 @@ def test_z_gate_deterministic_minimal_basis_gates(self): targets = ref_1q_clifford.z_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -341,7 +341,7 @@ def test_y_gate_deterministic_default_basis_gates(self): final_measure=True) targets = ref_1q_clifford.y_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -357,7 +357,7 @@ def test_y_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -376,7 +376,7 @@ def test_s_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -392,7 +392,7 @@ def test_s_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -426,7 +426,7 @@ def test_sdg_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -445,7 +445,7 @@ def test_cx_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -494,7 +494,7 @@ def test_cz_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -513,7 +513,7 @@ def test_swap_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -529,7 +529,7 @@ def test_swap_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -553,7 +553,7 @@ def test_h_gate_deterministic_minimal_basis_gates(self): targets = ref_1q_clifford.h_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -566,7 +566,7 @@ def test_h_gate_nondeterministic_minimal_basis_gates(self): targets = ref_1q_clifford.h_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -598,7 +598,7 @@ def test_z_gate_deterministic_minimal_basis_gates(self): targets = ref_1q_clifford.z_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -615,7 +615,7 @@ def test_y_gate_deterministic_minimal_basis_gates(self): targets = ref_1q_clifford.y_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -632,7 +632,7 @@ def test_s_gate_deterministic_minimal_basis_gates(self): targets = ref_1q_clifford.s_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -645,7 +645,7 @@ def test_s_gate_nondeterministic_minimal_basis_gates(self): targets = ref_1q_clifford.s_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -661,7 +661,7 @@ def test_sdg_gate_deterministic_minimal_basis_gates(self): targets = ref_1q_clifford.sdg_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -674,7 +674,7 @@ def test_sdg_gate_nondeterministic_minimal_basis_gates(self): targets = ref_1q_clifford.sdg_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -690,7 +690,7 @@ def test_cx_gate_deterministic_minimal_basis_gates(self): targets = ref_2q_clifford.cx_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -703,7 +703,7 @@ def test_cx_gate_nondeterministic_minimal_basis_gates(self): targets = ref_2q_clifford.cx_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -719,7 +719,7 @@ def test_cz_gate_deterministic_minimal_basis_gates(self): targets = ref_2q_clifford.cz_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -732,7 +732,7 @@ def test_cz_gate_nondeterministic_minimal_basis_gates(self): targets = ref_2q_clifford.cz_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -748,7 +748,7 @@ def test_swap_gate_deterministic_minimal_basis_gates(self): targets = ref_2q_clifford.swap_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -761,7 +761,7 @@ def test_swap_gate_nondeterministic_minimal_basis_gates(self): targets = ref_2q_clifford.swap_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) diff --git a/test/terra/backends/qasm_simulator/qasm_conditional.py b/test/terra/backends/qasm_simulator/qasm_conditional.py index a8dca33160..7772e5db17 100644 --- a/test/terra/backends/qasm_simulator/qasm_conditional.py +++ b/test/terra/backends/qasm_simulator/qasm_conditional.py @@ -35,7 +35,7 @@ def test_conditional_gates_1bit(self): targets = ref_conditionals.conditional_counts_1bit(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -47,7 +47,7 @@ def test_conditional_gates_2bit(self): targets = ref_conditionals.conditional_counts_2bit(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -69,7 +69,7 @@ def test_conditional_unitary_1bit(self): targets = ref_conditionals.conditional_counts_1bit(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -81,7 +81,7 @@ def test_conditional_unitary_2bit(self): targets = ref_conditionals.conditional_counts_2bit(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -103,7 +103,7 @@ def test_conditional_unitary_1bit(self): targets = ref_conditionals.conditional_counts_1bit(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -115,7 +115,7 @@ def test_conditional_kraus_2bit(self): targets = ref_conditionals.conditional_counts_2bit(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -137,7 +137,7 @@ def test_conditional_superop_1bit(self): targets = ref_conditionals.conditional_counts_1bit(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -149,6 +149,6 @@ def test_conditional_superop_2bit(self): targets = ref_conditionals.conditional_counts_2bit(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) diff --git a/test/terra/backends/qasm_simulator/qasm_delay_measure.py b/test/terra/backends/qasm_simulator/qasm_delay_measure.py index 17e7be1c7b..7725977111 100644 --- a/test/terra/backends/qasm_simulator/qasm_delay_measure.py +++ b/test/terra/backends/qasm_simulator/qasm_delay_measure.py @@ -54,7 +54,7 @@ def test_delay_measure_enable(self): backend_options['optimize_ideal_threshold'] = 0 result = self.SIMULATOR.run( qobj, - backend_options=backend_options).result() + **backend_options).result() self.assertSuccess(result) metadata = result.results[0].metadata self.assertTrue(metadata.get('measure_sampling')) @@ -65,7 +65,7 @@ def test_delay_measure_enable(self): backend_options['optimize_ideal_threshold'] = 0 result = self.SIMULATOR.run( qobj, - backend_options=backend_options).result() + **backend_options).result() self.assertSuccess(result) metadata = result.results[0].metadata self.assertTrue(metadata.get('measure_sampling')) @@ -76,7 +76,7 @@ def test_delay_measure_enable(self): backend_options['optimize_ideal_threshold'] = 0 result = self.SIMULATOR.run( qobj, - backend_options=backend_options).result() + **backend_options).result() self.assertSuccess(result) metadata = result.results[0].metadata self.assertFalse(metadata.get('measure_sampling')) @@ -95,7 +95,7 @@ def test_delay_measure_verbose(self): result = self.SIMULATOR.run( qobj, - backend_options=backend_options).result() + **backend_options).result() self.assertSuccess(result) metadata = result.results[0].metadata self.assertIn('delay_measure_verbose', metadata) @@ -108,7 +108,7 @@ def test_delay_measure_verbose(self): result = self.SIMULATOR.run( qobj, - backend_options=backend_options).result() + **backend_options).result() self.assertSuccess(result) metadata = result.results[0].metadata self.assertNotIn('delay_measure_verbose', metadata) @@ -121,7 +121,7 @@ def test_delay_measure_verbose(self): result = self.SIMULATOR.run( qobj, - backend_options=backend_options).result() + **backend_options).result() self.assertSuccess(result) metadata = result.results[0].metadata self.assertNotIn('delay_measure_verbose', metadata) diff --git a/test/terra/backends/qasm_simulator/qasm_fusion.py b/test/terra/backends/qasm_simulator/qasm_fusion.py index 0dfa0c94e7..cac29d67e2 100644 --- a/test/terra/backends/qasm_simulator/qasm_fusion.py +++ b/test/terra/backends/qasm_simulator/qasm_fusion.py @@ -102,7 +102,7 @@ def test_fusion_theshold(self): circuit.measure_all() qobj = assemble(circuit, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() self.assertSuccess(result) meta = self.fusion_metadata(result) self.assertFalse(meta.get('applied', False)) @@ -114,7 +114,7 @@ def test_fusion_theshold(self): circuit.measure_all() qobj = assemble(circuit, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() self.assertSuccess(result) meta = self.fusion_metadata(result) self.assertTrue(meta.get('applied', False)) @@ -126,7 +126,7 @@ def test_fusion_theshold(self): circuit.measure_all() qobj = assemble(circuit, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() self.assertSuccess(result) meta = self.fusion_metadata(result) self.assertTrue(meta.get('applied', False)) @@ -141,7 +141,7 @@ def test_fusion_verbose(self): with self.subTest(msg='verbose enabled'): backend_options = self.fusion_options(enabled=True, verbose=True, threshold=1) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() # Assert fusion applied succesfully self.assertSuccess(result) meta = self.fusion_metadata(result) @@ -153,7 +153,7 @@ def test_fusion_verbose(self): with self.subTest(msg='verbose disabled'): backend_options = self.fusion_options(enabled=True, verbose=False, threshold=1) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() # Assert fusion applied succesfully self.assertSuccess(result) meta = self.fusion_metadata(result) @@ -165,7 +165,7 @@ def test_fusion_verbose(self): with self.subTest(msg='verbose default'): backend_options = self.fusion_options(enabled=True, threshold=1) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() # Assert fusion applied succesfully self.assertSuccess(result) @@ -191,7 +191,7 @@ def test_kraus_noise_fusion(self): backend_options = self.fusion_options(enabled=True, threshold=1) result = self.SIMULATOR.run(qobj, noise_model=noise_model, - backend_options=backend_options).result() + **backend_options).result() meta = self.fusion_metadata(result) if backend_options.get('method') in ['density_matrix', 'density_matrix_thrust', @@ -221,7 +221,7 @@ def test_non_kraus_noise_fusion(self): backend_options = self.fusion_options(enabled=True, threshold=1) result = self.SIMULATOR.run(qobj, noise_model=noise_model, - backend_options=backend_options).result() + **backend_options).result() meta = self.fusion_metadata(result) if backend_options.get('method') in ['density_matrix', 'density_matrix_thrust', @@ -249,7 +249,7 @@ def test_control_fusion(self): with self.subTest(msg='fusion enabled'): backend_options = self.fusion_options(enabled=True, threshold=1) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) @@ -258,7 +258,7 @@ def test_control_fusion(self): with self.subTest(msg='fusion disabled'): backend_options = backend_options = self.fusion_options(enabled=False, threshold=1) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) @@ -268,7 +268,7 @@ def test_control_fusion(self): backend_options = self.fusion_options() result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) @@ -341,12 +341,12 @@ def test_fusion_operations(self): backend_options = self.fusion_options(enabled=False, threshold=1) result_disabled = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta_disabled = self.fusion_metadata(result_disabled) backend_options = self.fusion_options(enabled=True, threshold=1) result_enabled = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta_enabled = self.fusion_metadata(result_enabled) self.assertTrue(getattr(result_disabled, 'success', 'False')) @@ -374,12 +374,12 @@ def test_fusion_qv(self): backend_options = self.fusion_options(enabled=False, threshold=1) result_disabled = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta_disabled = self.fusion_metadata(result_disabled) backend_options = self.fusion_options(enabled=True, threshold=1) result_enabled = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta_enabled = self.fusion_metadata(result_enabled) self.assertTrue(getattr(result_disabled, 'success', 'False')) @@ -407,12 +407,12 @@ def test_fusion_qft(self): backend_options = self.fusion_options(enabled=False, threshold=1) result_disabled = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta_disabled = self.fusion_metadata(result_disabled) backend_options = self.fusion_options(enabled=True, threshold=1) result_enabled = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta_enabled = self.fusion_metadata(result_enabled) self.assertTrue(getattr(result_disabled, 'success', 'False')) diff --git a/test/terra/backends/qasm_simulator/qasm_initialize.py b/test/terra/backends/qasm_simulator/qasm_initialize.py index 6bb2353f89..376764caa9 100644 --- a/test/terra/backends/qasm_simulator/qasm_initialize.py +++ b/test/terra/backends/qasm_simulator/qasm_initialize.py @@ -42,7 +42,7 @@ def test_initialize_wrapper_1(self): [ circuits.extend(ref_initialize.initialize_circuits_w_1(init_state)) for init_state in init_states ] qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) # --------------------------------------------------------------------- @@ -62,7 +62,7 @@ def test_initialize_wrapper_2(self): [ circuits.extend(ref_initialize.initialize_circuits_w_2(init_state)) for init_state in init_states ] qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) # --------------------------------------------------------------------- @@ -77,7 +77,7 @@ def test_initialize_1(self): targets = ref_initialize.initialize_counts_1(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) opts = self.BACKEND_OPTS.copy() - result = self.SIMULATOR.run(qobj, backend_options=opts).result() + result = self.SIMULATOR.run(qobj, **opts).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -90,7 +90,7 @@ def test_initialize_2(self): targets = ref_initialize.initialize_counts_2(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) opts = self.BACKEND_OPTS.copy() - result = self.SIMULATOR.run(qobj, backend_options=opts).result() + result = self.SIMULATOR.run(qobj, **opts).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -101,6 +101,6 @@ def test_initialize_sampling_opt(self): targets = ref_initialize.initialize_counts_sampling_optimization(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) opts = self.BACKEND_OPTS.copy() - result = self.SIMULATOR.run(qobj, backend_options=opts).result() + result = self.SIMULATOR.run(qobj, **opts).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) diff --git a/test/terra/backends/qasm_simulator/qasm_measure.py b/test/terra/backends/qasm_simulator/qasm_measure.py index 55a674c559..4357d101fb 100644 --- a/test/terra/backends/qasm_simulator/qasm_measure.py +++ b/test/terra/backends/qasm_simulator/qasm_measure.py @@ -38,7 +38,7 @@ def test_measure_deterministic_with_sampling(self): target_memory = ref_measure.measure_memory_deterministic(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots, memory=True) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, target_counts, delta=0) self.compare_memory(result, circuits, target_memory) @@ -53,7 +53,7 @@ def test_measure_deterministic_without_sampling(self): target_memory = ref_measure.measure_memory_deterministic(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots, memory=True) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, target_counts, delta=0) self.compare_memory(result, circuits, target_memory) @@ -67,7 +67,7 @@ def test_measure_nondeterministic_with_sampling(self): targets = ref_measure.measure_counts_nondeterministic(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # Test sampling was enabled @@ -83,7 +83,7 @@ def test_measure_nondeterministic_without_sampling(self): targets = ref_measure.measure_counts_nondeterministic(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) self.compare_result_metadata(result, circuits, "measure_sampling", False) @@ -103,7 +103,7 @@ def test_measure_sampling_with_readouterror(self): qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( qobj, noise_model=noise_model, - backend_options=self.BACKEND_OPTS).result() + **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_result_metadata(result, circuits, "measure_sampling", True) @@ -126,7 +126,7 @@ def test_measure_sampling_with_quantum_noise(self): qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( qobj, noise_model=noise_model, - backend_options=self.BACKEND_OPTS).result() + **self.BACKEND_OPTS).result() self.assertSuccess(result) sampling = (self.BACKEND_OPTS.get("method", "automatic").startswith("density_matrix")) self.compare_result_metadata(result, circuits, "measure_sampling", sampling) @@ -150,7 +150,7 @@ def test_measure_deterministic_multi_qubit_with_sampling(self): target_memory = ref_measure.multiqubit_measure_memory_deterministic(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots, memory=True) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, target_counts, delta=0) self.compare_memory(result, circuits, target_memory) @@ -165,7 +165,7 @@ def test_measure_deterministic_multi_qubit_without_sampling(self): target_memory = ref_measure.multiqubit_measure_memory_deterministic(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots, memory=True) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.compare_counts(result, circuits, target_counts, delta=0) self.compare_memory(result, circuits, target_memory) self.compare_result_metadata(result, circuits, "measure_sampling", False) @@ -178,7 +178,7 @@ def test_measure_nondeterministic_multi_qubit_with_sampling(self): targets = ref_measure.multiqubit_measure_counts_nondeterministic(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) self.compare_result_metadata(result, circuits, "measure_sampling", True) @@ -191,7 +191,7 @@ def test_measure_nondeterministic_multi_qubit_without_sampling(self): targets = ref_measure.multiqubit_measure_counts_nondeterministic(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) self.compare_result_metadata(result, circuits, "measure_sampling", False) diff --git a/test/terra/backends/qasm_simulator/qasm_method.py b/test/terra/backends/qasm_simulator/qasm_method.py index 7dc016d856..fb20e7026e 100644 --- a/test/terra/backends/qasm_simulator/qasm_method.py +++ b/test/terra/backends/qasm_simulator/qasm_method.py @@ -42,7 +42,7 @@ def test_backend_method_clifford_circuits(self): qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() success = getattr(result, 'success', False) self.assertTrue(success) # Check simulation method @@ -76,8 +76,8 @@ def test_backend_method_clifford_circuits_and_reset_noise(self): qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run(qobj, - backend_options=self.BACKEND_OPTS, - noise_model=noise_model).result() + noise_model=noise_model, + **self.BACKEND_OPTS).result() success = getattr(result, 'success', False) self.assertTrue(success) # Check simulation method @@ -101,7 +101,7 @@ def test_backend_method_clifford_circuits_and_pauli_noise(self): final_measure=True) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() success = getattr(result, 'success', False) self.assertTrue(success) # Check simulation method @@ -125,8 +125,8 @@ def test_backend_method_clifford_circuits_and_unitary_noise(self): final_measure=True) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run(qobj, - backend_options=self.BACKEND_OPTS, - noise_model=noise_model).result() + noise_model=noise_model, + **self.BACKEND_OPTS).result() success = getattr(result, 'success', False) # Check simulation method method = self.BACKEND_OPTS.get('method', 'automatic') @@ -156,8 +156,8 @@ def test_backend_method_clifford_circuits_and_kraus_noise(self): qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run(qobj, - backend_options=self.BACKEND_OPTS, - noise_model=noise_model).result() + noise_model=noise_model, + **self.BACKEND_OPTS).result() success = getattr(result, 'success', False) # Check simulation method method = self.BACKEND_OPTS.get('method', 'automatic') @@ -184,7 +184,7 @@ def test_backend_method_nonclifford_circuits(self): qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() success = getattr(result, 'success', False) # Check simulation method method = self.BACKEND_OPTS.get('method', 'automatic') @@ -222,8 +222,8 @@ def test_backend_method_nonclifford_circuit_and_reset_noise(self): qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run(qobj, - backend_options=self.BACKEND_OPTS, - noise_model=noise_model).result() + noise_model=noise_model, + **self.BACKEND_OPTS).result() success = getattr(result, 'success', False) # Check simulation method method = self.BACKEND_OPTS.get('method', 'automatic') @@ -253,8 +253,8 @@ def test_backend_method_nonclifford_circuit_and_pauli_noise(self): qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run(qobj, - backend_options=self.BACKEND_OPTS, - noise_model=noise_model).result() + noise_model=noise_model, + **self.BACKEND_OPTS).result() success = getattr(result, 'success', False) # Check simulation method method = self.BACKEND_OPTS.get('method', 'automatic') @@ -283,8 +283,8 @@ def test_backend_method_nonclifford_circuit_and_unitary_noise(self): qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run(qobj, - backend_options=self.BACKEND_OPTS, - noise_model=noise_model).result() + noise_model=noise_model, + **self.BACKEND_OPTS).result() success = getattr(result, 'success', False) # Check simulation method method = self.BACKEND_OPTS.get('method', 'automatic') @@ -314,8 +314,8 @@ def test_backend_method_nonclifford_circuit_and_kraus_noise(self): qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run(qobj, - backend_options=self.BACKEND_OPTS, - noise_model=noise_model).result() + noise_model=noise_model, + **self.BACKEND_OPTS).result() success = getattr(result, 'success', False) # Check simulation method method = self.BACKEND_OPTS.get('method', 'automatic') diff --git a/test/terra/backends/qasm_simulator/qasm_multiplexer.py b/test/terra/backends/qasm_simulator/qasm_multiplexer.py index 3e93b1c00e..11e2c72662 100644 --- a/test/terra/backends/qasm_simulator/qasm_multiplexer.py +++ b/test/terra/backends/qasm_simulator/qasm_multiplexer.py @@ -33,7 +33,7 @@ def test_multiplexer_cx_gate_deterministic(self): circuits = ref_multiplexer.multiplexer_cx_gate_circuits_deterministic( final_measure=True) targets = ref_multiplexer.multiplexer_cx_gate_counts_deterministic(shots) - job = execute(circuits, self.SIMULATOR, shots=shots, backend_options=self.BACKEND_OPTS) + job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -44,7 +44,7 @@ def test_multiplexer_cx_gate_nondeterministic(self): circuits = ref_multiplexer.multiplexer_cx_gate_circuits_nondeterministic( final_measure=True) targets = ref_multiplexer.multiplexer_cx_gate_counts_nondeterministic(shots) - job = execute(circuits, self.SIMULATOR, shots=shots, backend_options=self.BACKEND_OPTS) + job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -60,7 +60,7 @@ def test_multiplexer_cxx_gate_deterministic(self): targets = ref_multiplexer.multiplexer_ccx_gate_counts_deterministic( shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -73,7 +73,7 @@ def test_multiplexer_cxx_gate_nondeterministic(self): targets = ref_multiplexer.multiplexer_ccx_gate_counts_nondeterministic( shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) diff --git a/test/terra/backends/qasm_simulator/qasm_noise.py b/test/terra/backends/qasm_simulator/qasm_noise.py index ebd6ef5221..cf76401d40 100644 --- a/test/terra/backends/qasm_simulator/qasm_noise.py +++ b/test/terra/backends/qasm_simulator/qasm_noise.py @@ -42,8 +42,7 @@ def test_readout_noise(self): qobj = assemble(circuit, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( qobj, - backend_options=self.BACKEND_OPTS, - noise_model=noise_model).result() + noise_model=noise_model, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, [circuit], [target], delta=0.05 * shots) @@ -66,8 +65,7 @@ def test_pauli_gate_noise(self): qobj = assemble(circuit, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( qobj, - backend_options=self.BACKEND_OPTS, - noise_model=noise_model).result() + noise_model=noise_model, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, [circuit], [target], delta=0.05 * shots) @@ -83,8 +81,7 @@ def test_pauli_reset_noise(self): qobj = assemble(circuit, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( qobj, - backend_options=self.BACKEND_OPTS, - noise_model=noise_model).result() + noise_model=noise_model, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, [circuit], [target], delta=0.05 * shots) @@ -100,8 +97,7 @@ def test_pauli_measure_noise(self): qobj = assemble(circuit, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( qobj, - backend_options=self.BACKEND_OPTS, - noise_model=noise_model).result() + noise_model=noise_model, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, [circuit], [target], delta=0.05 * shots) @@ -124,8 +120,8 @@ def test_reset_gate_noise(self): qobj = assemble(circuit, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( qobj, - backend_options=self.BACKEND_OPTS, - noise_model=noise_model).result() + noise_model=noise_model, + **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, [circuit], [target], delta=0.05 * shots) @@ -148,7 +144,7 @@ def test_kraus_gate_noise(self): qobj = assemble(circuit, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( qobj, - backend_options=self.BACKEND_OPTS, - noise_model=noise_model).result() + noise_model=noise_model, + **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, [circuit], [target], delta=0.05 * shots) diff --git a/test/terra/backends/qasm_simulator/qasm_noncliffords.py b/test/terra/backends/qasm_simulator/qasm_noncliffords.py index 594004c399..eaa6d87ad2 100644 --- a/test/terra/backends/qasm_simulator/qasm_noncliffords.py +++ b/test/terra/backends/qasm_simulator/qasm_noncliffords.py @@ -34,7 +34,7 @@ def test_t_gate_deterministic_default_basis_gates(self): final_measure=True) targets = ref_non_clifford.t_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -46,7 +46,7 @@ def test_t_gate_nondeterministic_default_basis_gates(self): final_measure=True) targets = ref_non_clifford.t_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -61,7 +61,7 @@ def test_tdg_gate_deterministic_default_basis_gates(self): final_measure=True) targets = ref_non_clifford.tdg_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -73,7 +73,7 @@ def test_tdg_gate_nondeterministic_default_basis_gates(self): final_measure=True) targets = ref_non_clifford.tdg_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -94,7 +94,7 @@ def test_ccx_gate_deterministic_default_basis_gates(self): final_measure=True) targets = ref_non_clifford.ccx_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -106,7 +106,7 @@ def test_ccx_gate_nondeterministic_default_basis_gates(self): final_measure=True) targets = ref_non_clifford.ccx_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -126,7 +126,7 @@ def test_cswap_gate_deterministic_default_basis_gates(self): final_measure=True) targets = ref_non_clifford.cswap_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -137,7 +137,7 @@ def test_cswap_gate_nondeterministic_default_basis_gates(self): final_measure=True) targets = ref_non_clifford.cswap_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -152,7 +152,7 @@ def test_cu1_gate_nondeterministic_default_basis_gates(self): final_measure=True) targets = ref_non_clifford.cu1_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -167,7 +167,7 @@ def test_cu3_gate_deterministic_default_basis_gates(self): final_measure=True) targets = ref_non_clifford.cu3_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -192,7 +192,7 @@ def test_t_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -207,7 +207,7 @@ def test_t_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -225,7 +225,7 @@ def test_tdg_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -240,7 +240,7 @@ def test_tdg_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -258,7 +258,7 @@ def test_ccx_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -273,7 +273,7 @@ def test_ccx_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -291,7 +291,7 @@ def test_cswap_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -306,7 +306,7 @@ def test_cswap_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -324,7 +324,7 @@ def test_cu1_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -342,7 +342,7 @@ def test_cu3_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -381,7 +381,7 @@ def test_t_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -399,7 +399,7 @@ def test_tdg_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -414,7 +414,7 @@ def test_tdg_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -432,7 +432,7 @@ def test_ccx_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -447,7 +447,7 @@ def test_ccx_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.1 * shots) @@ -465,7 +465,7 @@ def test_cu1_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.1 * shots) @@ -483,7 +483,7 @@ def test_cswap_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -498,7 +498,7 @@ def test_cswap_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.1 * shots) @@ -516,7 +516,7 @@ def test_cu3_gate_deterministic_default_basis_gates(self): self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) diff --git a/test/terra/backends/qasm_simulator/qasm_reset.py b/test/terra/backends/qasm_simulator/qasm_reset.py index 73af99ea8a..c235dfde39 100644 --- a/test/terra/backends/qasm_simulator/qasm_reset.py +++ b/test/terra/backends/qasm_simulator/qasm_reset.py @@ -36,7 +36,7 @@ def test_reset_deterministic(self): targets = ref_reset.reset_counts_deterministic(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -50,7 +50,7 @@ def test_reset_nondeterministic(self): targets = ref_reset.reset_counts_nondeterministic(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -61,7 +61,7 @@ def test_reset_sampling_opt(self): targets = ref_reset.reset_counts_sampling_optimization(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -72,6 +72,6 @@ def test_repeated_resets(self): targets = ref_reset.reset_counts_repeated(shots) qobj = assemble(circuits, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) diff --git a/test/terra/backends/qasm_simulator/qasm_snapshot.py b/test/terra/backends/qasm_simulator/qasm_snapshot.py index 12f40075dd..ea1f482edf 100644 --- a/test/terra/backends/qasm_simulator/qasm_snapshot.py +++ b/test/terra/backends/qasm_simulator/qasm_snapshot.py @@ -74,7 +74,7 @@ def test_snapshot_statevector_pre_measure_det(self): post_measure=False) qobj = assemble(circuits, self.SIMULATOR, shots=shots) - job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) method = self.BACKEND_OPTS.get('method', 'automatic') @@ -104,7 +104,7 @@ def test_snapshot_statevector_pre_measure_nondet(self): post_measure=False) qobj = assemble(circuits, self.SIMULATOR, shots=shots) - job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) method = self.BACKEND_OPTS.get('method', 'automatic') @@ -137,7 +137,7 @@ def test_snapshot_statevector_post_measure_det(self): post_measure=True) qobj = assemble(circuits, self.SIMULATOR, memory=True, shots=shots) - job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) method = self.BACKEND_OPTS.get('method', 'automatic') @@ -167,7 +167,7 @@ def test_snapshot_statevector_post_measure_nondet(self): post_measure=True) qobj = assemble(circuits, self.SIMULATOR, memory=True, shots=shots) - job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) method = self.BACKEND_OPTS.get('method', 'automatic') @@ -226,7 +226,7 @@ def test_snapshot_stabilizer_pre_measure_det(self): post_measure=False) qobj = assemble(circuits, self.SIMULATOR, shots=shots) - job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) method = self.BACKEND_OPTS.get('method', 'automatic') @@ -257,7 +257,7 @@ def test_snapshot_stabilizer_pre_measure_nondet(self): post_measure=False) qobj = assemble(circuits, self.SIMULATOR, shots=shots) - job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) method = self.BACKEND_OPTS.get('method', 'automatic') @@ -291,7 +291,7 @@ def test_snapshot_stabilizer_post_measure_det(self): post_measure=True) qobj = assemble(circuits, self.SIMULATOR, memory=True, shots=shots) - job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) method = self.BACKEND_OPTS.get('method', 'automatic') @@ -322,7 +322,7 @@ def test_snapshot_stabilizer_post_measure_nondet(self): post_measure=True) qobj = assemble(circuits, self.SIMULATOR, memory=True, shots=shots) - job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) method = self.BACKEND_OPTS.get('method', 'automatic') @@ -380,7 +380,7 @@ def test_density_matrix_snapshot_ideal(self): tmp = circ.copy() tmp.append(Snapshot(label, 'density_matrix', num_qubits), squbits) result = execute(tmp, self.SIMULATOR, - backend_options=self.BACKEND_OPTS).result() + **self.BACKEND_OPTS).result() if method not in QasmSnapshotDensityMatrixTests.SUPPORTED_QASM_METHODS: self.assertFalse(result.success) else: @@ -436,7 +436,7 @@ def test_snapshot_probabilities_pre_measure(self): circuits = snapshot_probabilities_circuits(post_measure=False) qobj = assemble(circuits, self.SIMULATOR, shots=shots) - job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) method = self.BACKEND_OPTS.get('method', 'automatic') @@ -469,7 +469,7 @@ def test_snapshot_probabilities_post_measure(self): circuits = snapshot_probabilities_circuits(post_measure=True) qobj = assemble(circuits, self.SIMULATOR, shots=shots) - job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) method = self.BACKEND_OPTS.get('method', 'automatic') @@ -529,7 +529,7 @@ def test_snapshot_expval_pauli_pre_measure(self): circuits = snapshot_expval_circuits(pauli=True, post_measure=False) qobj = assemble(circuits, self.SIMULATOR, shots=shots) - job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) method = self.BACKEND_OPTS.get('method', 'automatic') @@ -563,7 +563,7 @@ def test_snapshot_expval_pauli_post_measure(self): circuits = snapshot_expval_circuits(pauli=True, post_measure=True) qobj = assemble(circuits, self.SIMULATOR, shots=shots) - job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) method = self.BACKEND_OPTS.get('method', 'automatic') @@ -623,7 +623,7 @@ def general_test(self, pauli, num_qubits=None, seed=None): qc.snapshot_expectation_value('final', [(1, pauli)], pauli_qubits) qobj = assemble(qc) result = self.SIMULATOR.run( - qobj, backend_options=self.BACKEND_OPTS).result() + qobj, **self.BACKEND_OPTS).result() self.assertSuccess(result) snapshots = result.data(0).get('snapshots', {}) self.assertIn('expectation_value', snapshots) @@ -691,7 +691,7 @@ def test_snapshot_expval_matrix_pre_measure(self): circuits = snapshot_expval_circuits(pauli=False, post_measure=False) qobj = assemble(circuits, self.SIMULATOR, shots=shots) - job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) method = self.BACKEND_OPTS.get('method', 'automatic') @@ -725,7 +725,7 @@ def test_snapshot_expval_matrix_post_measure(self): circuits = snapshot_expval_circuits(pauli=False, post_measure=True) qobj = assemble(circuits, self.SIMULATOR, shots=shots) - job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) method = self.BACKEND_OPTS.get('method', 'automatic') diff --git a/test/terra/backends/qasm_simulator/qasm_standard_gates.py b/test/terra/backends/qasm_simulator/qasm_standard_gates.py index f03f3e2eb2..4d8c578acd 100644 --- a/test/terra/backends/qasm_simulator/qasm_standard_gates.py +++ b/test/terra/backends/qasm_simulator/qasm_standard_gates.py @@ -134,7 +134,7 @@ def test_gate_statevector(self, gate_cls, num_params): self.SIMULATOR, basis_gates=basis_gates, shots=1, - backend_options=backend_options).result() + **backend_options).result() # Check results success = getattr(result, 'success', False) @@ -181,7 +181,7 @@ def test_gate_density_matrix(self, gate_cls, num_params): self.SIMULATOR, basis_gates=basis_gates, shots=1, - backend_options=backend_options).result() + **backend_options).result() # Check results success = getattr(result, 'success', False) diff --git a/test/terra/backends/qasm_simulator/qasm_thread_management.py b/test/terra/backends/qasm_simulator/qasm_thread_management.py index 861f1e1023..0d08d4b51c 100644 --- a/test/terra/backends/qasm_simulator/qasm_thread_management.py +++ b/test/terra/backends/qasm_simulator/qasm_thread_management.py @@ -101,7 +101,7 @@ def test_max_memory_settings(self): # Test defaults opts = self.backend_options_parallel() result = execute(circuit, self.SIMULATOR, shots=shots, - backend_options=opts).result() + **opts).result() max_mem_result = result.metadata.get('max_memory_mb') self.assertGreaterEqual(max_mem_result, int(system_memory / 2), msg="Default 'max_memory_mb' is too small.") @@ -113,7 +113,7 @@ def test_max_memory_settings(self): opts = self.backend_options_parallel() opts['max_memory_mb'] = max_mem_target result = execute(circuit, self.SIMULATOR, shots=shots, - backend_options=opts).result() + **opts).result() max_mem_result = result.metadata.get('max_memory_mb') self.assertEqual(max_mem_result, max_mem_target, msg="Custom 'max_memory_mb' is not being set correctly.") @@ -124,7 +124,7 @@ def available_threads(self): result = execute(self.dummy_circuit(1), self.SIMULATOR, shots=1, - backend_options=opts).result() + **opts).result() return self.threads_used(result)[0]['total'] @requires_omp @@ -140,7 +140,7 @@ def test_parallel_thread_defaults(self): result = execute(self.dummy_circuit(1), self.SIMULATOR, shots=10*max_threads, - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -157,7 +157,7 @@ def test_parallel_thread_defaults(self): self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -173,7 +173,7 @@ def test_parallel_thread_defaults(self): result = execute(self.measure_in_middle_circuit(1), self.SIMULATOR, shots=10*max_threads, - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -189,7 +189,7 @@ def test_parallel_thread_defaults(self): result = execute(max_threads*[self.dummy_circuit(1)], self.SIMULATOR, shots=10*max_threads, - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -206,7 +206,7 @@ def test_parallel_thread_defaults(self): self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -223,7 +223,7 @@ def test_parallel_thread_defaults(self): self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -257,7 +257,7 @@ def test_parallel_thread_assignment_priority(self): result = execute(self.dummy_circuit(1), self.SIMULATOR, shots=10*max_threads, - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -274,7 +274,7 @@ def test_parallel_thread_assignment_priority(self): self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -290,7 +290,7 @@ def test_parallel_thread_assignment_priority(self): result = execute(self.measure_in_middle_circuit(1), self.SIMULATOR, shots=10*max_threads, - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -306,7 +306,7 @@ def test_parallel_thread_assignment_priority(self): result = execute(max_threads*[self.dummy_circuit(1)], self.SIMULATOR, shots=10*max_threads, - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': max_threads, @@ -323,7 +323,7 @@ def test_parallel_thread_assignment_priority(self): self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': max_threads, @@ -340,7 +340,7 @@ def test_parallel_thread_assignment_priority(self): self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': max_threads, @@ -363,7 +363,7 @@ def test_parallel_experiment_thread_assignment(self): result = execute(self.dummy_circuit(1), self.SIMULATOR, shots=10*max_threads, - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -378,7 +378,7 @@ def test_parallel_experiment_thread_assignment(self): result = execute(max_threads*[self.dummy_circuit(1)], self.SIMULATOR, shots=10*max_threads, - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': max_threads, @@ -394,7 +394,7 @@ def test_parallel_experiment_thread_assignment(self): self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': max_threads, @@ -410,7 +410,7 @@ def test_parallel_experiment_thread_assignment(self): self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': max_threads, @@ -429,7 +429,7 @@ def test_parallel_experiment_thread_assignment(self): result = execute(2 * [circuit], self.SIMULATOR, shots=10*max_threads, - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -452,7 +452,7 @@ def test_parallel_shot_thread_assignment(self): result = execute(self.dummy_circuit(1), self.SIMULATOR, shots=10*max_threads, - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -467,7 +467,7 @@ def test_parallel_shot_thread_assignment(self): result = execute(max_threads*[self.dummy_circuit(1)], self.SIMULATOR, shots=10*max_threads, - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -483,7 +483,7 @@ def test_parallel_shot_thread_assignment(self): self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -499,7 +499,7 @@ def test_parallel_shot_thread_assignment(self): self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -518,7 +518,7 @@ def test_parallel_shot_thread_assignment(self): result = execute(2 * [circuit], self.SIMULATOR, shots=10*max_threads, - backend_options=opts).result() + **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, @@ -545,7 +545,7 @@ def _test_qasm_explicit_parallelization(self): result = execute( circuit, self.SIMULATOR, shots=shots, - backend_options=backend_opts).result() + **backend_opts).result() if result.metadata['omp_enabled']: self.assertEqual( result.metadata['parallel_experiments'], diff --git a/test/terra/backends/qasm_simulator/qasm_truncate.py b/test/terra/backends/qasm_simulator/qasm_truncate.py index e128f21bf0..b28a59e304 100644 --- a/test/terra/backends/qasm_simulator/qasm_truncate.py +++ b/test/terra/backends/qasm_simulator/qasm_truncate.py @@ -161,7 +161,7 @@ def test_truncate_ideal_sparse_circuit(self): result = execute(circuit, qasm_sim, shots=100, - backend_options=backend_options).result() + **backend_options).result() metadata = result.results[0].metadata self.assertTrue('truncate_qubits' in metadata, msg="truncate_qubits must work.") active_qubits = sorted(metadata['truncate_qubits'].get('active_qubits', [])) @@ -193,7 +193,7 @@ def test_truncate_nonlocal_noise(self): qasm_sim, shots=100, noise_model=noise_model, - backend_options=backend_options).result() + **backend_options).result() metadata = result.results[0].metadata self.assertTrue('truncate_qubits' in metadata, msg="truncate_qubits must work.") active_qubits = sorted(metadata['truncate_qubits'].get('active_qubits', [])) @@ -217,7 +217,7 @@ def test_truncate(self): noise_model=NoiseModel.from_backend(self.device_properties()), shots=100, coupling_map=[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 0]], # 10-qubit device - backend_options=backend_options).result() + **backend_options).result() self.assertTrue('truncate_qubits' in result.to_dict()['results'][0]['metadata'], msg="truncate_qubits must work.") @@ -236,7 +236,7 @@ def test_no_truncate(self): noise_model=NoiseModel.from_backend(self.device_properties()), shots=100, coupling_map=[[1, 0], [1, 2], [1, 3], [2, 0], [2, 1], [2, 3], [3, 0], [3, 1], [3, 2]], # 4-qubit device - backend_options=backend_options).result() + **backend_options).result() self.assertFalse('truncate_qubits' in result.to_dict()['results'][0]['metadata'], msg="truncate_qubits must work.") @@ -257,7 +257,7 @@ def test_truncate_disable(self): noise_model=NoiseModel.from_backend(self.device_properties()), shots=100, coupling_map=[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 0]], # 10-qubit device - backend_options=backend_options).result() + **backend_options).result() self.assertFalse('truncate_qubits' in result.to_dict()['results'][0]['metadata'], msg="truncate_qubits must not work.") \ No newline at end of file diff --git a/test/terra/backends/qasm_simulator/qasm_unitary_gate.py b/test/terra/backends/qasm_simulator/qasm_unitary_gate.py index 7c1ce0bd57..7c855d90e8 100644 --- a/test/terra/backends/qasm_simulator/qasm_unitary_gate.py +++ b/test/terra/backends/qasm_simulator/qasm_unitary_gate.py @@ -40,7 +40,7 @@ def test_unitary_gate(self): targets = ref_unitary_gate.unitary_gate_counts_deterministic( shots) result = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS).result() + **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -50,7 +50,7 @@ def test_random_unitary_gate(self): circuits = ref_unitary_gate.unitary_random_gate_circuits_nondeterministic(final_measure=True) targets = ref_unitary_gate.unitary_random_gate_counts_nondeterministic(shots) result = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS).result() + **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -73,6 +73,6 @@ def test_diagonal_gate(self): targets = ref_diagonal_gate.diagonal_gate_counts_deterministic( shots) result = execute(circuits, self.SIMULATOR, shots=shots, - backend_options=self.BACKEND_OPTS).result() + **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) diff --git a/test/terra/backends/statevector_simulator/statevector_basics.py b/test/terra/backends/statevector_simulator/statevector_basics.py index be2c403274..05532310ba 100644 --- a/test/terra/backends/statevector_simulator/statevector_basics.py +++ b/test/terra/backends/statevector_simulator/statevector_basics.py @@ -43,7 +43,7 @@ def test_initialize_1(self): circuits = ref_initialize.initialize_circuits_1(final_measure=False) targets = ref_initialize.initialize_statevector_1() qobj = assemble(circuits, shots=1) - sim_job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + sim_job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = sim_job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -53,7 +53,7 @@ def test_initialize_2(self): circuits = ref_initialize.initialize_circuits_2(final_measure=False) targets = ref_initialize.initialize_statevector_2() qobj = assemble(circuits, shots=1) - sim_job = self.SIMULATOR.run(qobj, backend_options=self.BACKEND_OPTS) + sim_job = self.SIMULATOR.run(qobj, **self.BACKEND_OPTS) result = sim_job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -70,7 +70,7 @@ def test_reset_deterministic(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -85,7 +85,7 @@ def test_reset_nondeterministic(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -101,7 +101,7 @@ def test_measure(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -117,7 +117,7 @@ def test_conditional_gate_1bit(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -130,7 +130,7 @@ def test_conditional_unitary_1bit(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -143,7 +143,7 @@ def test_conditional_gate_2bit(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) @@ -157,7 +157,7 @@ def test_conditional_unitary_2bit(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -173,7 +173,7 @@ def test_h_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -187,7 +187,7 @@ def test_h_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -201,7 +201,7 @@ def test_h_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -214,7 +214,7 @@ def test_h_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -228,7 +228,7 @@ def test_h_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -242,7 +242,7 @@ def test_h_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -258,7 +258,7 @@ def test_x_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -272,7 +272,7 @@ def test_x_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -286,7 +286,7 @@ def test_x_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -302,7 +302,7 @@ def test_z_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -316,7 +316,7 @@ def test_z_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -330,7 +330,7 @@ def test_z_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -346,7 +346,7 @@ def test_y_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -360,7 +360,7 @@ def test_y_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -374,7 +374,7 @@ def test_y_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -390,7 +390,7 @@ def test_s_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -404,7 +404,7 @@ def test_s_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -418,7 +418,7 @@ def test_s_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -431,7 +431,7 @@ def test_s_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -445,7 +445,7 @@ def test_s_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -459,7 +459,7 @@ def test_s_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -475,7 +475,7 @@ def test_sdg_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -489,7 +489,7 @@ def test_sdg_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -503,7 +503,7 @@ def test_sdg_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -516,7 +516,7 @@ def test_sdg_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -530,7 +530,7 @@ def test_sdg_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -544,7 +544,7 @@ def test_sdg_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -560,7 +560,7 @@ def test_cx_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -574,7 +574,7 @@ def test_cx_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -588,7 +588,7 @@ def test_cx_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -601,7 +601,7 @@ def test_cx_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -615,7 +615,7 @@ def test_cx_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -629,7 +629,7 @@ def test_cx_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -645,7 +645,7 @@ def test_cz_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -659,7 +659,7 @@ def test_cz_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -673,7 +673,7 @@ def test_cz_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -686,7 +686,7 @@ def test_cz_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -700,7 +700,7 @@ def test_cz_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -714,7 +714,7 @@ def test_cz_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -730,7 +730,7 @@ def test_swap_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -744,7 +744,7 @@ def test_swap_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -758,7 +758,7 @@ def test_swap_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -771,7 +771,7 @@ def test_swap_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -785,7 +785,7 @@ def test_swap_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -799,7 +799,7 @@ def test_swap_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -815,7 +815,7 @@ def test_t_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -829,7 +829,7 @@ def test_t_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -843,7 +843,7 @@ def test_t_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -856,7 +856,7 @@ def test_t_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -870,7 +870,7 @@ def test_t_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -884,7 +884,7 @@ def test_t_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -900,7 +900,7 @@ def test_tdg_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -914,7 +914,7 @@ def test_tdg_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -928,7 +928,7 @@ def test_tdg_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -941,7 +941,7 @@ def test_tdg_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -955,7 +955,7 @@ def test_tdg_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -969,7 +969,7 @@ def test_tdg_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -985,7 +985,7 @@ def test_ccx_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -999,7 +999,7 @@ def test_ccx_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1013,7 +1013,7 @@ def test_ccx_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1026,7 +1026,7 @@ def test_ccx_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1040,7 +1040,7 @@ def test_ccx_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1054,7 +1054,7 @@ def test_ccx_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1070,7 +1070,7 @@ def test_unitary_gate(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1083,7 +1083,7 @@ def test_diagonal_gate(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1099,7 +1099,7 @@ def test_cu1_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1113,7 +1113,7 @@ def test_cu1_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1127,7 +1127,7 @@ def test_cu1_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1144,7 +1144,7 @@ def test_cswap_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1158,7 +1158,7 @@ def test_cswap_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1172,7 +1172,7 @@ def test_cswap_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1185,7 +1185,7 @@ def test_cswap_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1199,7 +1199,7 @@ def test_cswap_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1213,7 +1213,7 @@ def test_cswap_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1230,7 +1230,7 @@ def test_cu3_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1244,7 +1244,7 @@ def test_cu3_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1258,7 +1258,7 @@ def test_cu3_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_statevector(result, circuits, targets) @@ -1275,7 +1275,7 @@ def test_qobj_global_phase(self): targets = ref_1q_clifford.h_gate_statevector_nondeterministic() qobj = assemble(transpile(circuits, self.SIMULATOR), - shots=1, backend_options=self.BACKEND_OPTS) + shots=1, **self.BACKEND_OPTS) # Set global phases for i, _ in enumerate(circuits): global_phase = (-1) ** i * (pi / 4) diff --git a/test/terra/backends/statevector_simulator/statevector_fusion.py b/test/terra/backends/statevector_simulator/statevector_fusion.py index 73bf3c818d..ed547ace5a 100644 --- a/test/terra/backends/statevector_simulator/statevector_fusion.py +++ b/test/terra/backends/statevector_simulator/statevector_fusion.py @@ -50,7 +50,7 @@ def test_fusion_theshold(self): circuit = transpile(circuit, self.SIMULATOR) qobj = assemble([circuit], shots=1) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) @@ -61,7 +61,7 @@ def test_fusion_theshold(self): circuit = transpile(circuit, self.SIMULATOR) qobj = assemble([circuit], shots=1) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) @@ -72,7 +72,7 @@ def test_fusion_theshold(self): circuit = transpile(circuit, self.SIMULATOR) qobj = assemble([circuit], shots=1) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) @@ -88,7 +88,7 @@ def test_fusion_disable(self): with self.subTest(msg='test fusion enable'): backend_options = self.fusion_options(enabled=True, threshold=1) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) @@ -97,7 +97,7 @@ def test_fusion_disable(self): with self.subTest(msg='test fusion disable'): backend_options = self.fusion_options(enabled=False, threshold=1) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) @@ -112,12 +112,12 @@ def test_fusion_output(self): options_disabled = self.fusion_options(enabled=False, threshold=1) result_disabled = self.SIMULATOR.run( - qobj, backend_options=options_disabled).result() + qobj, **options_disabled).result() self.assertSuccess(result_disabled) options_enabled = self.fusion_options(enabled=True, threshold=1) result_enabled = self.SIMULATOR.run( - qobj, backend_options=options_enabled).result() + qobj, **options_enabled).result() self.assertSuccess(result_enabled) sv_no_fusion = Statevector(result_disabled.get_statevector(0)) diff --git a/test/terra/backends/test_config_pulse_simulator.py b/test/terra/backends/test_config_pulse_simulator.py new file mode 100644 index 0000000000..43d3311408 --- /dev/null +++ b/test/terra/backends/test_config_pulse_simulator.py @@ -0,0 +1,338 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2018, 2019, 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. +""" +Configurable PulseSimulator Tests +""" + +import sys +import unittest +import warnings +import numpy as np +from test.terra import common + +from qiskit.test.mock.backends.armonk.fake_armonk import FakeArmonk +from qiskit.test.mock.backends.athens.fake_athens import FakeAthens + +from qiskit.providers.aer.backends import PulseSimulator +from qiskit.pulse import (Schedule, Play, ShiftPhase, SetPhase, Delay, Acquire, + Waveform, DriveChannel, ControlChannel, + AcquireChannel, MemorySlot) +from qiskit.providers.aer.aererror import AerError + +from qiskit.compiler import assemble +from qiskit.providers.aer.pulse.system_models.pulse_system_model import PulseSystemModel +from qiskit.providers.aer.pulse.system_models.hamiltonian_model import HamiltonianModel +from qiskit.providers.models.backendconfiguration import UchannelLO + + +class TestConfigPulseSimulator(common.QiskitAerTestCase): + r"""PulseSimulator tests.""" + + def test_from_backend(self): + """Test that configuration, defaults, and properties are correclty imported.""" + + athens_backend = FakeAthens() + athens_sim = PulseSimulator.from_backend(athens_backend) + + self.assertEqual(athens_backend.properties(), athens_sim.properties()) + # check that configuration is correctly imported + backend_dict = athens_backend.configuration().to_dict() + sim_dict = athens_sim.configuration().to_dict() + for key in sim_dict: + if key == 'backend_name': + self.assertEqual(sim_dict[key], 'pulse_simulator(fake_athens)') + elif key == 'description': + desc = 'A Pulse-based simulator configured from the backend: fake_athens' + self.assertEqual(sim_dict[key], desc) + elif key == 'simulator': + self.assertTrue(sim_dict[key], True) + else: + self.assertEqual(sim_dict[key], backend_dict[key]) + + backend_dict = athens_backend.defaults().to_dict() + sim_dict = athens_sim.defaults().to_dict() + for key in sim_dict: + if key == 'pulse_library': + # need to compare pulse libraries directly due to containing dictionaries + for idx, entry in enumerate(sim_dict[key]): + for entry_key in entry: + if entry_key == 'samples': + self.assertTrue(all(entry[entry_key] == backend_dict[key][idx][entry_key])) + else: + self.assertTrue(entry[entry_key] == backend_dict[key][idx][entry_key]) + else: + self.assertEqual(sim_dict[key], backend_dict[key]) + + def test_from_backend_system_model(self): + """Test that the system model is correctly imported from the backend.""" + + athens_backend = FakeAthens() + athens_sim = PulseSimulator.from_backend(athens_backend) + + # u channel lo + athens_attr = athens_backend.configuration().u_channel_lo + sim_attr = athens_sim.configuration().u_channel_lo + model_attr = athens_sim._system_model.u_channel_lo + self.assertTrue(sim_attr == athens_attr and model_attr == athens_attr) + + # dt + athens_attr = athens_backend.configuration().dt + sim_attr = athens_sim.configuration().dt + model_attr = athens_sim._system_model.dt + self.assertTrue(sim_attr == athens_attr and model_attr == athens_attr) + + def test_set_system_model_options(self): + """Test setting of options that need to be changed in multiple places.""" + + athens_backend = FakeAthens() + athens_sim = PulseSimulator.from_backend(athens_backend) + + # u channel lo + set_attr = [[UchannelLO(0, 1.0 + 0.0j)]] + athens_sim.set_options(u_channel_lo=set_attr) + sim_attr = athens_sim.configuration().u_channel_lo + model_attr = athens_sim._system_model.u_channel_lo + self.assertTrue(sim_attr == set_attr and model_attr == set_attr) + + # dt + set_attr = 5. + athens_sim.set_options(dt=set_attr) + sim_attr = athens_sim.configuration().dt + model_attr = athens_sim._system_model.dt + self.assertTrue(sim_attr == set_attr and model_attr == set_attr) + + def test_set_meas_levels(self): + """Test setting of meas_levels.""" + + athens_backend = FakeAthens() + athens_sim = PulseSimulator.from_backend(athens_backend) + + # test that a warning is thrown when meas_level 0 is attempted to be set + with warnings.catch_warnings(record=True) as w: + # Cause all warnings to always be triggered. + warnings.simplefilter("always") + + athens_sim.set_options(meas_levels=[0,1,2]) + + self.assertEqual(len(w), 1) + self.assertTrue('Measurement level 0 not supported' in str(w[-1].message)) + self.assertEqual(athens_sim.configuration().meas_levels, [1, 2]) + + self.assertTrue(athens_sim.configuration().meas_levels == [1, 2]) + + athens_sim.set_options(meas_levels=[2]) + self.assertTrue(athens_sim.configuration().meas_levels == [2]) + + def test_set_system_model_from_backend(self): + """Test setting system model when constructing from backend.""" + + armonk_backend = FakeArmonk() + system_model = self._system_model_1Q() + + # these are 1q systems so this doesn't make sense but can still be used to test + system_model.u_channel_lo = [[UchannelLO(0, 1.0 + 0.0j)]] + + armonk_sim = None + + # construct backend and catch warning + with warnings.catch_warnings(record=True) as w: + # Cause all warnings to always be triggered. + warnings.simplefilter("always") + + armonk_sim = PulseSimulator.from_backend(backend=armonk_backend, + system_model=system_model) + + self.assertEqual(len(w), 1) + self.assertTrue('inconsistencies' in str(w[-1].message)) + + # check that system model properties have been imported + self.assertEqual(armonk_sim.configuration().dt, system_model.dt) + self.assertEqual(armonk_sim.configuration().u_channel_lo, system_model.u_channel_lo) + + def test_set_system_model_in_constructor(self): + """Test setting system model when constructing.""" + + system_model = self._system_model_1Q() + + # these are 1q systems so this doesn't make sense but can still be used to test + system_model.u_channel_lo = [[UchannelLO(0, 1.0 + 0.0j)]] + + # construct directly + test_sim = None + # construct backend and verify no warnings + with warnings.catch_warnings(record=True) as w: + # Cause all warnings to always be triggered. + warnings.simplefilter("always") + + test_sim = PulseSimulator(system_model=system_model) + + self.assertEqual(len(w), 0) + + # check that system model properties have been imported + self.assertEqual(test_sim.configuration().dt, system_model.dt) + self.assertEqual(test_sim.configuration().u_channel_lo, system_model.u_channel_lo) + + def test_set_system_model_after_construction(self): + """Test setting the system model after construction.""" + + system_model = self._system_model_1Q() + + # these are 1q systems so this doesn't make sense but can still be used to test + system_model.u_channel_lo = [[UchannelLO(0, 1.0 + 0.0j)]] + + # first test setting after construction with no hamiltonian + test_sim = PulseSimulator() + + with warnings.catch_warnings(record=True) as w: + # Cause all warnings to always be triggered. + warnings.simplefilter("always") + + test_sim.set_options(system_model=system_model) + self.assertEqual(len(w), 0) + + # check that system model properties have been imported + self.assertEqual(test_sim._system_model, system_model) + self.assertEqual(test_sim.configuration().dt, system_model.dt) + self.assertEqual(test_sim.configuration().u_channel_lo, system_model.u_channel_lo) + + # next, construct a pulse simulator with a config containing a Hamiltonian and observe + # warnings + armonk_backend = FakeArmonk() + test_sim = PulseSimulator(configuration=armonk_backend.configuration()) + + # add system model and verify warning is raised + with warnings.catch_warnings(record=True) as w: + # Cause all warnings to always be triggered. + warnings.simplefilter("always") + + armonk_sim = test_sim.set_options(system_model=system_model) + + self.assertEqual(len(w), 1) + self.assertTrue('inconsistencies' in str(w[-1].message)) + + self.assertEqual(test_sim.configuration().dt, system_model.dt) + self.assertEqual(test_sim.configuration().u_channel_lo, system_model.u_channel_lo) + + def test_validation_num_acquires(self): + """Test that validation fails if 0 or >1 acquire is given in a schedule.""" + + test_sim = PulseSimulator.from_backend(FakeArmonk()) + + # check that too many acquires results in an error + qobj = assemble([self._1Q_schedule(num_acquires=2)], + backend=test_sim, + meas_level=2, + qubit_lo_freq=[0.], + meas_return='single', + shots=256) + + try: + test_sim.run(qobj).result() + except AerError as error: + self.assertTrue('does not support multiple Acquire' in error.message) + + # check that no acquires results in an error + qobj = assemble([self._1Q_schedule(num_acquires=0)], + backend=test_sim, + meas_level=2, + qubit_lo_freq=[0.], + meas_return='single', + shots=256) + + try: + test_sim.run(qobj).result() + except AerError as error: + self.assertTrue('requires at least one Acquire' in error.message) + + def test_run_simulation_from_backend(self): + """Construct from a backend and run a simulation.""" + armonk_backend = FakeArmonk() + + # manually override parameters to insulate from future changes to FakeArmonk + freq_est = 4.97e9 + drive_est = 6.35e7 + armonk_backend.defaults().qubit_freq_est = [freq_est] + armonk_backend.configuration().hamiltonian['h_str']= ['wq0*0.5*(I0-Z0)', 'omegad0*X0||D0'] + armonk_backend.configuration().hamiltonian['vars'] = {'wq0': 2 * np.pi * freq_est, + 'omegad0': drive_est} + armonk_backend.configuration().hamiltonian['qub'] = {'0': 2} + dt = 2.2222222222222221e-10 + armonk_backend.configuration().dt = dt + + armonk_sim = PulseSimulator.from_backend(armonk_backend) + + total_samples = 250 + amp = np.pi / (drive_est * dt * total_samples) + + sched = self._1Q_schedule(total_samples, amp) + qobj = assemble([sched], + backend=armonk_sim, + meas_level=2, + meas_return='single', + shots=1) + # run and verify that a pi pulse had been done + result = armonk_sim.run(qobj).result() + final_vec = result.get_statevector() + probabilities = np.abs(final_vec)**2 + self.assertTrue(probabilities[0] < 1e-5) + self.assertTrue(probabilities[1] > 1 - 1e-5) + + def _system_model_1Q(self, omega_0=5., r=0.02): + """Constructs a standard model for a 1 qubit system. + + Args: + omega_0 (float): qubit frequency + r (float): drive strength + + Returns: + PulseSystemModel: model for qubit system + """ + + hamiltonian = {} + hamiltonian['h_str'] = [ + '2*np.pi*omega0*0.5*Z0', '2*np.pi*r*0.5*X0||D0' + ] + hamiltonian['vars'] = {'omega0': omega_0, 'r': r} + hamiltonian['qub'] = {'0': 2} + ham_model = HamiltonianModel.from_dict(hamiltonian) + + u_channel_lo = [] + subsystem_list = [0] + dt = 1. + + return PulseSystemModel(hamiltonian=ham_model, + u_channel_lo=u_channel_lo, + subsystem_list=subsystem_list, + dt=dt) + + def _1Q_schedule(self, total_samples=100, amp=1., num_acquires=1): + """Creates a schedule for a single qubit. + + Args: + total_samples (int): number of samples in the drive pulse + amp (complex): amplitude of drive pulse + num_acquires (int): number of acquire instructions to include in the schedule + + Returns: + schedule (pulse schedule): + """ + + schedule = Schedule() + schedule |= Play(Waveform(amp * np.ones(total_samples)), DriveChannel(0)) + for _ in range(num_acquires): + schedule |= Acquire(total_samples, AcquireChannel(0), + MemorySlot(0)) << schedule.duration + return schedule + + +if __name__ == '__main__': + unittest.main() diff --git a/test/terra/backends/test_pulse_simulator.py b/test/terra/backends/test_pulse_simulator.py index 43a7d656cc..11cf93db4a 100644 --- a/test/terra/backends/test_pulse_simulator.py +++ b/test/terra/backends/test_pulse_simulator.py @@ -26,21 +26,22 @@ from qiskit.compiler import assemble from qiskit.quantum_info import state_fidelity -from qiskit.pulse import (Schedule, Play, ShiftPhase, SetPhase, Delay, Acquire, SamplePulse, - DriveChannel, ControlChannel, AcquireChannel, MemorySlot) +from qiskit.pulse import (Schedule, Play, ShiftPhase, SetPhase, Delay, Acquire, + Waveform, DriveChannel, ControlChannel, + AcquireChannel, MemorySlot) from qiskit.providers.aer.pulse.de.DE_Methods import ScipyODE from qiskit.providers.aer.pulse.de.DE_Options import DE_Options from qiskit.providers.aer.pulse.system_models.pulse_system_model import PulseSystemModel from qiskit.providers.aer.pulse.system_models.hamiltonian_model import HamiltonianModel from qiskit.providers.models.backendconfiguration import UchannelLO -from .pulse_sim_independent import (simulate_1q_model, simulate_2q_exchange_model, +from .pulse_sim_independent import (simulate_1q_model, + simulate_2q_exchange_model, simulate_3d_oscillator_model) class TestPulseSimulator(common.QiskitAerTestCase): r"""PulseSimulator tests.""" - def setUp(self): """ Set configuration settings for pulse simulator""" super().setUp() @@ -66,14 +67,17 @@ def test_x_gate(self): r = 0.01 total_samples = 100 - system_model = self._system_model_1Q(omega_0, r) + # initial state and seed + y0 = np.array([1.0, 0.0]) + seed = 9000 + + # set up simulator + pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r)) # set up constant pulse for doing a pi pulse schedule = self._1Q_constant_sched(total_samples) - - # set up schedule and qobj qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], @@ -81,27 +85,22 @@ def test_x_gate(self): memory_slots=1, shots=256) - # set backend backend_options including initial state - y0 = np.array([1.0, 0.0]) - backend_options = {'seed' : 9000, 'initial_state' : y0} - - # run simulation - result = self.backend_sim.run(qobj, - system_model=system_model, - backend_options=backend_options).result() + result = pulse_sim.run(qobj, initial_state=y0, seed=seed).result() pulse_sim_yf = result.get_statevector() # set up and run independent simulation samples = np.ones((total_samples, 1)) - indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_0]), samples, 1.) + indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_0]), + samples, 1.) # approximate analytic solution - phases = np.exp(-1j * 2 * np.pi * omega_0 * total_samples * np.array([1., -1.]) / 2) + phases = np.exp(-1j * 2 * np.pi * omega_0 * total_samples * + np.array([1., -1.]) / 2) approx_yf = phases * np.array([0., -1j]) # test final state - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1-10**-5) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1 - 10**-5) self.assertGreaterEqual(state_fidelity(pulse_sim_yf, approx_yf), 0.99) # test counts @@ -122,14 +121,17 @@ def test_x_gate_rwa(self): r = 0.01 / 2 total_samples = 100 - system_model = self._system_model_1Q(omega_0, r) + # initial state and seed + y0 = np.array([1.0, 0.0]) + seed = 9000 + + # set up simulator + pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r)) # set up constant pulse for doing a pi pulse schedule = self._1Q_constant_sched(total_samples) - - # set up schedule and qobj qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], @@ -137,22 +139,14 @@ def test_x_gate_rwa(self): memory_slots=1, shots=1) - # set backend backend_options including initial state - y0 = np.array([1.0, 0.0]) - backend_options = {'seed' : 9000, 'initial_state' : y0} - - # run simulation - result = self.backend_sim.run(qobj, - system_model=system_model, - backend_options=backend_options).result() + result = pulse_sim.run(qobj, initial_state=y0, seed=seed).result() pulse_sim_yf = result.get_statevector() # expected final state yf = np.array([0., -1j]) # test final state - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1-10**-5) - + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1 - 10**-5) def test_x_half_gate(self): """Test a schedule for a pi/2 pulse on a 2 level system. Same setup as test_x_gate but @@ -166,14 +160,17 @@ def test_x_half_gate(self): r = 0.01 total_samples = 50 - system_model = self._system_model_1Q(omega_0, r) + # initial state and seed + y0 = np.array([1.0, 0.0]) + seed = 9000 + + # set up simulator + pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r)) # set up constant pulse for doing a pi pulse schedule = self._1Q_constant_sched(total_samples) - - # set up schedule and qobj qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], @@ -181,27 +178,23 @@ def test_x_half_gate(self): memory_slots=1, shots=256) - # set backend backend_options - y0 = np.array([1.0, 0.0]) - backend_options = {'seed' : 9000, 'initial_state' : y0} - - # run simulation - result = self.backend_sim.run(qobj, - system_model=system_model, - backend_options=backend_options).result() + result = pulse_sim.run(qobj, initial_state=y0, seed=seed).result() pulse_sim_yf = result.get_statevector() # set up and run independent simulation samples = np.ones((total_samples, 1)) - indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_d]), samples, 1.) + indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_d]), + samples, 1.) # approximate analytic solution - phases = np.exp(-1j * 2 * np.pi * omega_0 * total_samples * np.array([1., -1.]) / 2) + phases = np.exp(-1j * 2 * np.pi * omega_0 * total_samples * + np.array([1., -1.]) / 2) approx_yf = phases * (expm(-1j * (np.pi / 4) * self.X) @ y0) # test final state - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1-10**-5) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), + 1 - 10**-5) self.assertGreaterEqual(state_fidelity(pulse_sim_yf, approx_yf), 0.99) # test counts @@ -221,14 +214,17 @@ def test_y_half_gate(self): r = 0.01 total_samples = 50 - system_model = self._system_model_1Q(omega_0, r) + # initial state and seed + y0 = np.array([1.0, 0.0]) + seed = 9000 + + # set up simulator + pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r)) # set up constant pulse for doing a pi pulse schedule = self._1Q_constant_sched(total_samples, amp=1j) - - # set up schedule and qobj qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], @@ -236,27 +232,23 @@ def test_y_half_gate(self): memory_slots=1, shots=256) - # set backend backend_options - y0 = np.array([1.0, 0.0]) - backend_options = {'seed' : 9000, 'initial_state' : y0} - - # run simulation - result = self.backend_sim.run(qobj, - system_model=system_model, - backend_options=backend_options).result() + result = pulse_sim.run(qobj, initial_state=y0, seed=seed).result() pulse_sim_yf = result.get_statevector() # set up and run independent simulation samples = 1j * np.ones((total_samples, 1)) - indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_d]), samples, 1.) + indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_d]), + samples, 1.) # approximate analytic solution - phases = np.exp(-1j * 2 * np.pi * omega_0 * total_samples * np.array([1., -1.]) / 2) + phases = np.exp(-1j * 2 * np.pi * omega_0 * total_samples * + np.array([1., -1.]) / 2) approx_yf = phases * (expm(-1j * (np.pi / 4) * self.Y) @ y0) # test final state - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1-10**-5) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), + 1 - 10**-5) self.assertGreaterEqual(state_fidelity(pulse_sim_yf, approx_yf), 0.99) # test counts @@ -277,13 +269,20 @@ def test_1Q_noise(self): r = 0.01 total_samples = 100 - system_model = self._system_model_1Q(omega_0, r) + # initial state, seed, and noise model + y0 = np.array([1.0, 0.0]) + seed = 9000 + noise_model = {"qubit": {"0": {"Sm": 1.}}} + + # set up simulator + pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r), + noise_model=noise_model) # set up constant pulse for doing a pi pulse schedule = self._1Q_constant_sched(total_samples) qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], @@ -291,14 +290,7 @@ def test_1Q_noise(self): memory_slots=2, shots=10) - # set seed for simulation, and set noise - y0 = np.array([1., 0.]) - backend_options = {'seed' : 9000, 'initial_state' : y0} - backend_options['noise_model'] = {"qubit": {"0": {"Sm": 1.}}} - - # run simulation - result = self.backend_sim.run(qobj, system_model=system_model, - backend_options=backend_options).result() + result = pulse_sim.run(qobj, initial_state=y0, seed=seed).result() # test results # This level of noise is high enough that all counts should yield 0, @@ -319,14 +311,16 @@ def test_unitary_parallel(self): r = 0.01 total_samples = 50 - system_model = self._system_model_1Q(omega_0, r) + # initial state and seed + y0 = np.array([1.0, 0.0]) + seed = 9000 + + pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r)) # set up constant pulse for doing a pi pulse schedule = self._1Q_constant_sched(total_samples) - - # set up schedule and qobj qobj = assemble([schedule, schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], @@ -334,13 +328,7 @@ def test_unitary_parallel(self): memory_slots=1, shots=256) - # set backend backend_options - y0 = np.array([1., 0.]) - backend_options = backend_options = {'seed' : 9000, 'initial_state' : y0} - - # run simulation - result = self.backend_sim.run(qobj, system_model=system_model, - backend_options=backend_options).result() + result = pulse_sim.run(qobj, initial_state=y0, seed=seed).result() # test results, checking both runs in parallel counts = result.get_counts() @@ -349,11 +337,11 @@ def test_unitary_parallel(self): self.assertDictAlmostEqual(counts[0], exp_counts0) self.assertDictAlmostEqual(counts[1], exp_counts1) - def test_dt_scaling_x_gate(self): """Test that dt is being used correctly by the solver.""" total_samples = 100 + # do the same thing as test_x_gate, but scale dt and all frequency parameters # define test case for a single scaling def scale_test(scale): @@ -366,15 +354,20 @@ def scale_test(scale): r = 0.01 / scale total_samples = 100 - # set up system model and scale time + # initial state and seed + y0 = np.array([1.0, 0.0]) + seed = 9000 + + + # set up simulator system_model = self._system_model_1Q(omega_0, r) - system_model.dt = system_model.dt * scale + pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r)) + pulse_sim.set_options(dt=scale) # set up constant pulse for doing a pi pulse schedule = self._1Q_constant_sched(total_samples) - qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], @@ -382,28 +375,26 @@ def scale_test(scale): memory_slots=2, shots=256) - # set backend backend_options - y0 = np.array([1., 0.]) - backend_options = {'seed' : 9000, 'initial_state': y0} - - # run simulation - result = self.backend_sim.run(qobj, system_model=system_model, - backend_options=backend_options).result() + result = pulse_sim.run(qobj, initial_state=y0, seed=seed).result() pulse_sim_yf = result.get_statevector() # set up and run independent simulation samples = np.ones((total_samples, 1)) - indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_0]), samples, scale) + indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_0]), + samples, scale) # approximate analytic solution - phases = np.exp(-1j * 2 * np.pi * omega_0 * total_samples * np.array([1., -1.]) / 2) + phases = np.exp(-1j * 2 * np.pi * omega_0 * total_samples * + np.array([1., -1.]) / 2) approx_yf = phases * np.array([0., -1j]) # test final state - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1-10**-5) - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, approx_yf), 0.99) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), + 1 - 10**-5) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, approx_yf), + 0.99) counts = result.get_counts() exp_counts = {'1': 256} @@ -426,14 +417,19 @@ def test_arbitrary_constant_drive(self): r_vals = [3 / total_samples, 5 / total_samples, 0.1] phase_vals = [5 * np.pi / 7, 19 * np.pi / 14, np.pi / 4] + # initial state and seed + y0 = np.array([1.0, 0.0]) + seed = 9000 + for i in range(num_tests): with self.subTest(i=i): - system_model = self._system_model_1Q(omega_0, r_vals[i]) - schedule = self._1Q_constant_sched(total_samples, amp=np.exp(-1j * phase_vals[i])) + # set up simulator + pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r_vals[i])) + schedule = self._1Q_constant_sched(total_samples, amp=np.exp(-1j *phase_vals[i])) qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], @@ -441,28 +437,33 @@ def test_arbitrary_constant_drive(self): memory_slots=2, shots=1) - # Run qobj and compare prop to expected result - y0 = np.array([1., 0.]) - backend_options = {'seed' : 9000, 'initial_state' : y0} - result = self.backend_sim.run(qobj, system_model, backend_options).result() - + result = pulse_sim.run(qobj, initial_state=y0, seed=seed).result() pulse_sim_yf = result.get_statevector() + # set up and run independent simulation - samples = np.exp(-1j * phase_vals[i]) * np.ones((total_samples, 1)) + samples = np.exp(-1j * phase_vals[i]) * np.ones( + (total_samples, 1)) - indep_yf = simulate_1q_model(y0, omega_0, r_vals[i], np.array([omega_d_vals[i]]), samples, 1.) + indep_yf = simulate_1q_model(y0, omega_0, r_vals[i], + np.array([omega_d_vals[i]]), + samples, 1.) # approximate analytic solution - phases = np.exp(-1j * 2 * np.pi * omega_d_vals[i] * total_samples * np.array([1., -1.]) / 2) + phases = np.exp(-1j * 2 * np.pi * omega_d_vals[i] * + total_samples * np.array([1., -1.]) / 2) detuning = omega_0 - omega_d_vals[i] amp = np.exp(-1j * phase_vals[i]) - rwa_ham = 2 * np.pi * (detuning * self.Z / 2 + r_vals[i] * np.array([[0, amp.conj()], [amp, 0.]]) / 4) + rwa_ham = 2 * np.pi * ( + detuning * self.Z / 2 + + r_vals[i] * np.array([[0, amp.conj()], [amp, 0.]]) / 4) approx_yf = phases * (expm(-1j * rwa_ham * total_samples) @ y0) # test final state - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1-10**-5) - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, approx_yf), 0.99) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), + 1 - 10**-5) + self.assertGreaterEqual( + state_fidelity(pulse_sim_yf, approx_yf), 0.99) def test_3d_oscillator(self): """Test simulation of a duffing oscillator truncated to 3 dimensions.""" @@ -475,56 +476,56 @@ def test_3d_oscillator(self): # Test pi pulse r = 0.5 / total_samples - system_model = self._system_model_3d_oscillator(freq, anharm, r) - schedule = self._1Q_constant_sched(total_samples) + # set up simulator + system_model = system_model = self._system_model_3d_oscillator(freq, anharm, r) + pulse_sim = PulseSimulator(system_model=system_model) + schedule = self._1Q_constant_sched(total_samples) qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], qubit_lo_freq=[freq], shots=1) - backend_options = {'seed' : 9000} - result = self.backend_sim.run(qobj, system_model, backend_options).result() + result = pulse_sim.run(qobj).result() pulse_sim_yf = result.get_statevector() - # set up and run independent simulation y0 = np.array([1., 0., 0.]) samples = np.ones((total_samples, 1)) - indep_yf = simulate_3d_oscillator_model(y0, freq, anharm, r, np.array([freq]), samples, 1.) + indep_yf = simulate_3d_oscillator_model(y0, freq, anharm, r, + np.array([freq]), samples, 1.) # test final state - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1-10**-5) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1 - 10**-5) + # test with different input state + y0 = np.array([0., 0., 1.]) # Test some irregular value r = 1.49815 / total_samples - system_model = self._system_model_3d_oscillator(freq, anharm, r) - schedule = self._1Q_constant_sched(total_samples) + pulse_sim.set_options(system_model=system_model) + schedule = self._1Q_constant_sched(total_samples) qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], qubit_lo_freq=[freq], shots=1) - - y0 = np.array([0., 0., 1.]) - backend_options = {'seed' : 9000, 'initial_state' : y0} - - result = self.backend_sim.run(qobj, system_model, backend_options).result() + result = pulse_sim.run(qobj, initial_state=y0).result() pulse_sim_yf = result.get_statevector() samples = np.ones((total_samples, 1)) - indep_yf = simulate_3d_oscillator_model(y0, freq, anharm, r, np.array([freq]), samples, 1.) + indep_yf = simulate_3d_oscillator_model(y0, freq, anharm, r, + np.array([freq]), samples, 1.) # test final state - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1-10**-5) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1 - 10**-5) def test_2Q_interaction(self): r"""Test 2 qubit interaction via controlled operations using u channels.""" @@ -536,12 +537,14 @@ def test_2Q_interaction(self): omega_d0 = 0. omega_d1 = 0. - system_model = self._system_model_2Q(j) + y0 = np.kron(np.array([1., 0.]), np.array([0., 1.])) + seed=9000 - schedule = self._2Q_constant_sched(total_samples) + pulse_sim = PulseSimulator(system_model=self._system_model_2Q(j)) + schedule = self._2Q_constant_sched(total_samples) qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], @@ -549,10 +552,7 @@ def test_2Q_interaction(self): memory_slots=2, shots=1) - y0 = np.kron(np.array([1., 0.]), np.array([0., 1.])) - backend_options = {'seed' : 9000, 'initial_state': y0} - - result = self.backend_sim.run(qobj, system_model, backend_options).result() + result = pulse_sim.run(qobj, initial_state=y0, seed=seed).result() pulse_sim_yf = result.get_statevector() # exact analytic solution @@ -562,9 +562,8 @@ def test_2Q_interaction(self): # run with different initial state y0 = np.kron(np.array([1., 0.]), np.array([1., 0.])) - backend_options = {'seed' : 9000, 'initial_state': y0} - result = self.backend_sim.run(qobj, system_model, backend_options).result() + result = pulse_sim.run(qobj, initial_state=y0, seed=seed).result() pulse_sim_yf = result.get_statevector() # exact analytic solution @@ -572,7 +571,6 @@ def test_2Q_interaction(self): self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1 - (10**-5)) - def test_subsystem_restriction(self): r"""Test behavior of subsystem_list subsystem restriction""" @@ -583,12 +581,16 @@ def test_subsystem_restriction(self): omega_d = 0. subsystem_list = [0, 2] - system_model = self._system_model_3Q(j, subsystem_list=subsystem_list) + y0 = np.kron(np.array([1., 0.]), np.array([0., 1.])) - schedule = self._3Q_constant_sched(total_samples, u_idx=0, subsystem_list=subsystem_list) + system_model = self._system_model_3Q(j, subsystem_list=subsystem_list) + pulse_sim = PulseSimulator(system_model=system_model) + schedule = self._3Q_constant_sched(total_samples, + u_idx=0, + subsystem_list=subsystem_list) qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], @@ -596,10 +598,8 @@ def test_subsystem_restriction(self): memory_slots=2, shots=1) - y0 = np.kron(np.array([1., 0.]), np.array([0., 1.])) - backend_options = {'seed' : 9000, 'initial_state': y0} + result = pulse_sim.run(qobj, initial_state=y0).result() - result = self.backend_sim.run(qobj, system_model, backend_options).result() pulse_sim_yf = result.get_statevector() yf = expm(-1j * 0.5 * 2 * np.pi * np.kron(self.X, self.Z) / 4) @ y0 @@ -607,9 +607,8 @@ def test_subsystem_restriction(self): self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1 - (10**-5)) y0 = np.kron(np.array([1., 0.]), np.array([1., 0.])) - backend_options = {'seed' : 9000, 'initial_state': y0} - result = self.backend_sim.run(qobj, system_model, backend_options).result() + result = pulse_sim.run(qobj, initial_state=y0).result() pulse_sim_yf = result.get_statevector() yf = expm(-1j * 0.5 * 2 * np.pi * np.kron(self.X, self.Z) / 4) @ y0 @@ -619,10 +618,13 @@ def test_subsystem_restriction(self): subsystem_list = [1, 2] system_model = self._system_model_3Q(j, subsystem_list=subsystem_list) - schedule = self._3Q_constant_sched(total_samples, u_idx=1, subsystem_list=subsystem_list) - + y0 = np.kron(np.array([1., 0.]), np.array([0., 1.])) + pulse_sim.set_options(system_model=system_model) + schedule = self._3Q_constant_sched(total_samples, + u_idx=1, + subsystem_list=subsystem_list) qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], @@ -630,10 +632,7 @@ def test_subsystem_restriction(self): memory_slots=2, shots=1) - y0 = np.kron(np.array([1., 0.]), np.array([0., 1.])) - backend_options = {'seed' : 9000, 'initial_state': y0} - - result = self.backend_sim.run(qobj, system_model, backend_options).result() + result = pulse_sim.run(qobj, initial_state=y0).result() pulse_sim_yf = result.get_statevector() yf = expm(-1j * 0.5 * 2 * np.pi * np.kron(self.X, self.Z) / 4) @ y0 @@ -641,9 +640,9 @@ def test_subsystem_restriction(self): self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1 - (10**-5)) y0 = np.kron(np.array([1., 0.]), np.array([1., 0.])) - backend_options = {'seed' : 9000, 'initial_state': y0} + pulse_sim.set_options(initial_state=y0) - result = self.backend_sim.run(qobj, system_model, backend_options).result() + result = pulse_sim.run(qobj).result() pulse_sim_yf = result.get_statevector() yf = expm(-1j * 0.5 * 2 * np.pi * np.kron(self.X, self.Z) / 4) @ y0 @@ -656,7 +655,12 @@ def test_simulation_without_variables(self): variables """ - ham_dict = {'h_str': ['np.pi*Z0', '0.02*np.pi*X0||D0'], 'qub': {'0': 2}} + ham_dict = { + 'h_str': ['np.pi*Z0', '0.02*np.pi*X0||D0'], + 'qub': { + '0': 2 + } + } ham_model = HamiltonianModel.from_dict(ham_dict) u_channel_lo = [] @@ -667,12 +671,15 @@ def test_simulation_without_variables(self): u_channel_lo=u_channel_lo, subsystem_list=subsystem_list, dt=dt) + pulse_sim = PulseSimulator(system_model=system_model, + initial_state=np.array([1., 0.]), + seed=9000) # set up schedule and qobj total_samples = 50 schedule = self._1Q_constant_sched(total_samples) qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], @@ -680,12 +687,8 @@ def test_simulation_without_variables(self): memory_slots=2, shots=256) - # set backend backend_options - backend_options = {'seed' : 9000, 'initial_state' : np.array([1., 0.])} - # run simulation - result = self.backend_sim.run(qobj, system_model=system_model, - backend_options=backend_options).result() + result = pulse_sim.run(qobj).result() # test results counts = result.get_counts() @@ -703,15 +706,20 @@ def test_meas_level_1(self): # Require omega_a*time = pi to implement pi pulse (x gate) # num of samples gives time - r = 1. / (2 * total_samples) + r = 1. / (2 * total_samples) system_model = self._system_model_1Q(omega_0, r) amp = np.exp(-1j * np.pi / 2) schedule = self._1Q_constant_sched(total_samples, amp=amp) + y0=np.array([1.0, 0.0]) + pulse_sim = PulseSimulator(system_model=system_model, + initial_state=y0, + seed=9000) + qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=1, meas_return='single', meas_map=[[0]], @@ -719,17 +727,16 @@ def test_meas_level_1(self): memory_slots=2, shots=shots) - # set backend backend_options - y0 = np.array([1.0, 0.0]) - backend_options = {'seed' : 9000, 'initial_state' : y0} - result = self.backend_sim.run(qobj, system_model, backend_options).result() + result = pulse_sim.run(qobj).result() pulse_sim_yf = result.get_statevector() samples = amp * np.ones((total_samples, 1)) - indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_d]), samples, 1.) + indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_d]), + samples, 1.) # test final state - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1-10**-5) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), + 1 - 10**-5) # Verify that (about) half the IQ vals have abs val 1 and half have abs val 0 # (use prop for easier comparison) @@ -760,41 +767,47 @@ def test_gaussian_drive(self): # num of samples gives time r = np.pi / total_samples + # initial state and seed + y0 = np.array([1., 0.]) + seed = 9000 + # Test gaussian drive results for a few different sigma gauss_sigmas = [total_samples / 6, total_samples / 3, total_samples] - system_model = self._system_model_1Q(omega_0, r) + # set up pulse simulator + pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r)) for gauss_sigma in gauss_sigmas: with self.subTest(gauss_sigma=gauss_sigma): times = 1.0 * np.arange(total_samples) gaussian_samples = np.exp(-times**2 / 2 / gauss_sigma**2) - drive_pulse = SamplePulse(gaussian_samples, name='drive_pulse') + drive_pulse = Waveform(gaussian_samples, name='drive_pulse') # construct schedule schedule = Schedule() schedule |= Play(drive_pulse, DriveChannel(0)) - schedule |= Acquire(1, AcquireChannel(0), MemorySlot(0)) << schedule.duration + schedule |= Acquire(1, AcquireChannel(0), + MemorySlot(0)) << schedule.duration qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], qubit_lo_freq=[omega_d], memory_slots=2, shots=1) - y0 = np.array([1., 0.]) - backend_options = {'seed' : 9000, 'initial_state' : y0} - result = self.backend_sim.run(qobj, system_model, backend_options).result() + result = pulse_sim.run(qobj, initial_state=y0, seed=seed).result() pulse_sim_yf = result.get_statevector() # run independent simulation - yf = simulate_1q_model(y0, omega_0, r, np.array([omega_d]), gaussian_samples, 1.) + yf = simulate_1q_model(y0, omega_0, r, np.array([omega_d]), + gaussian_samples, 1.) # Check fidelity of statevectors - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1-(10**-5)) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), + 1 - (10**-5)) def test_2Q_exchange(self): r"""Test a more complicated 2q simulation""" @@ -805,18 +818,17 @@ def test_2Q_exchange(self): total_samples = 25 hamiltonian = {} - hamiltonian['h_str'] = ['2*np.pi*v0*0.5*Z0', - '2*np.pi*v1*0.5*Z1', - '2*np.pi*r*0.5*X0||D0', - '2*np.pi*r*0.5*X1||D1', - '2*np.pi*j*0.5*I0*I1', - '2*np.pi*j*0.5*X0*X1', - '2*np.pi*j*0.5*Y0*Y1', - '2*np.pi*j*0.5*Z0*Z1'] - hamiltonian['vars'] = {'v0': q_freqs[0], - 'v1': q_freqs[1], - 'r': r, - 'j': j} + hamiltonian['h_str'] = [ + '2*np.pi*v0*0.5*Z0', '2*np.pi*v1*0.5*Z1', '2*np.pi*r*0.5*X0||D0', + '2*np.pi*r*0.5*X1||D1', '2*np.pi*j*0.5*I0*I1', + '2*np.pi*j*0.5*X0*X1', '2*np.pi*j*0.5*Y0*Y1', '2*np.pi*j*0.5*Z0*Z1' + ] + hamiltonian['vars'] = { + 'v0': q_freqs[0], + 'v1': q_freqs[1], + 'r': r, + 'j': j + } hamiltonian['qub'] = {'0': 2, '1': 2} ham_model = HamiltonianModel.from_dict(hamiltonian) @@ -832,40 +844,43 @@ def test_2Q_exchange(self): # try some random schedule schedule = Schedule() - drive_pulse = SamplePulse(np.ones(total_samples)) + drive_pulse = Waveform(np.ones(total_samples)) schedule += Play(drive_pulse, DriveChannel(0)) schedule |= Play(drive_pulse, DriveChannel(1)) << 2 * total_samples - schedule |= Acquire(total_samples, - AcquireChannel(0), + schedule |= Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) << 3 * total_samples - schedule |= Acquire(total_samples, - AcquireChannel(1), + schedule |= Acquire(total_samples, AcquireChannel(1), MemorySlot(1)) << 3 * total_samples + y0 = np.array([1., 0., 0., 0.]) + pulse_sim = PulseSimulator(system_model=system_model, + initial_state=y0, + seed=9000) + qobj = assemble([schedule], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], qubit_lo_freq=q_freqs, memory_slots=2, shots=1000) - y0 = np.array([1., 0., 0., 0.]) - backend_options = {'seed' : 9000, 'initial_state' : y0} - - result = self.backend_sim.run(qobj, system_model, backend_options).result() + result = pulse_sim.run(qobj).result() pulse_sim_yf = result.get_statevector() # set up and run independent simulation - d0_samps = np.concatenate((np.ones(total_samples), np.zeros(2 * total_samples))) - d1_samps = np.concatenate((np.zeros(2 * total_samples), np.ones(total_samples))) + d0_samps = np.concatenate( + (np.ones(total_samples), np.zeros(2 * total_samples))) + d1_samps = np.concatenate( + (np.zeros(2 * total_samples), np.ones(total_samples))) samples = np.array([d0_samps, d1_samps]).transpose() q_freqs = np.array(q_freqs) - yf = simulate_2q_exchange_model(y0, q_freqs, r, j, q_freqs, samples, 1.) + yf = simulate_2q_exchange_model(y0, q_freqs, r, j, q_freqs, samples, + 1.) # Check fidelity of statevectors - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1-(10**-5)) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1 - (10**-5)) def test_delay_instruction(self): """Test for delay instruction.""" @@ -891,17 +906,21 @@ def test_delay_instruction(self): # so that the x rotation is transformed into a z rotation. # if delays are not handled correctly this process should fail sched = Schedule() - sched += Play(SamplePulse([0.5]), DriveChannel(1)) + sched += Play(Waveform([0.5]), DriveChannel(1)) sched += Delay(1, DriveChannel(1)) - sched += Play(SamplePulse([-0.5]), DriveChannel(1)) + sched += Play(Waveform([-0.5]), DriveChannel(1)) sched += Delay(1, DriveChannel(0)) - sched += Play(SamplePulse([1.]), DriveChannel(0)) + sched += Play(Waveform([1.]), DriveChannel(0)) sched |= Acquire(1, AcquireChannel(0), MemorySlot(0)) << sched.duration + # Result of schedule should be the unitary -1j*Z, so check rotation of an X eigenstate + pulse_sim = PulseSimulator(system_model=system_model, + initial_state=np.array([1., 1.]) / np.sqrt(2)) + qobj = assemble([sched], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], @@ -909,28 +928,25 @@ def test_delay_instruction(self): memory_slots=2, shots=1) - - # Result of schedule should be the unitary -1j*Z, so check rotation of an X eigenstate - backend_options = {'initial_state': np.array([1., 1.]) / np.sqrt(2)} - - results = self.backend_sim.run(qobj, system_model, backend_options).result() + results = pulse_sim.run(qobj).result() statevector = results.get_statevector() expected_vector = np.array([-1j, 1j]) / np.sqrt(2) - self.assertGreaterEqual(state_fidelity(statevector, expected_vector), 1 - (10**-5)) + self.assertGreaterEqual(state_fidelity(statevector, expected_vector), + 1 - (10**-5)) # verify validity of simulation when no delays included sched = Schedule() - sched += Play(SamplePulse([0.5]), DriveChannel(1)) - sched += Play(SamplePulse([-0.5]), DriveChannel(1)) + sched += Play(Waveform([0.5]), DriveChannel(1)) + sched += Play(Waveform([-0.5]), DriveChannel(1)) - sched += Play(SamplePulse([1.]), DriveChannel(0)) + sched += Play(Waveform([1.]), DriveChannel(0)) sched |= Acquire(1, AcquireChannel(0), MemorySlot(0)) << sched.duration qobj = assemble([sched], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], @@ -938,15 +954,15 @@ def test_delay_instruction(self): memory_slots=2, shots=1) - backend_options = {'initial_state': np.array([1., 1.]) / np.sqrt(2)} - - results = self.backend_sim.run(qobj, system_model, backend_options).result() + results = pulse_sim.run(qobj).result() statevector = results.get_statevector() - U = expm(1j * np.pi * self.Y /4) @ expm(-1j * np.pi * (self.Y / 4 + self.X / 2)) + U = expm(1j * np.pi * self.Y / 4) @ expm(-1j * np.pi * + (self.Y / 4 + self.X / 2)) expected_vector = U @ np.array([1., 1.]) / np.sqrt(2) - self.assertGreaterEqual(state_fidelity(statevector, expected_vector), 1 - (10**-5)) + self.assertGreaterEqual(state_fidelity(statevector, expected_vector), + 1 - (10**-5)) def test_shift_phase(self): """Test ShiftPhase command.""" @@ -960,53 +976,54 @@ def test_shift_phase(self): # Also do it in multiple phase shifts to test accumulation sched = Schedule() amp1 = 0.12 - sched += Play(SamplePulse([amp1]), DriveChannel(0)) + sched += Play(Waveform([amp1]), DriveChannel(0)) phi1 = 0.12374 * np.pi sched += ShiftPhase(phi1, DriveChannel(0)) amp2 = 0.492 - sched += Play(SamplePulse([amp2]), DriveChannel(0)) + sched += Play(Waveform([amp2]), DriveChannel(0)) phi2 = 0.5839 * np.pi sched += ShiftPhase(phi2, DriveChannel(0)) amp3 = 0.12 + 0.21 * 1j - sched += Play(SamplePulse([amp3]), DriveChannel(0)) + sched += Play(Waveform([amp3]), DriveChannel(0)) sched |= Acquire(1, AcquireChannel(0), MemorySlot(0)) << sched.duration + y0 = np.array([1., 0]) + + pulse_sim = PulseSimulator(system_model=system_model, + initial_state=y0) qobj = assemble([sched], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], qubit_lo_freq=[omega_0], memory_slots=2, shots=1) - - y0 = np.array([1., 0]) - backend_options = {'initial_state': y0} - - results = self.backend_sim.run(qobj, system_model, backend_options).result() + results = pulse_sim.run(qobj).result() pulse_sim_yf = results.get_statevector() #run independent simulation - samples = np.array([[amp1], - [amp2 * np.exp(1j * phi1)], + samples = np.array([[amp1], [amp2 * np.exp(1j * phi1)], [amp3 * np.exp(1j * (phi1 + phi2))]]) - indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_0]), samples, 1.) + indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_0]), + samples, 1.) - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1 - (10**-5)) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), + 1 - (10**-5)) # run another schedule with only a single shift phase to verify sched = Schedule() amp1 = 0.12 - sched += Play(SamplePulse([amp1]), DriveChannel(0)) + sched += Play(Waveform([amp1]), DriveChannel(0)) phi1 = 0.12374 * np.pi sched += ShiftPhase(phi1, DriveChannel(0)) amp2 = 0.492 - sched += Play(SamplePulse([amp2]), DriveChannel(0)) + sched += Play(Waveform([amp2]), DriveChannel(0)) sched |= Acquire(1, AcquireChannel(0), MemorySlot(0)) << sched.duration qobj = assemble([sched], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], @@ -1014,17 +1031,16 @@ def test_shift_phase(self): memory_slots=2, shots=1) - y0 = np.array([1., 0]) - backend_options = {'initial_state': y0} - - results = self.backend_sim.run(qobj, system_model, backend_options).result() + results = pulse_sim.run(qobj).result() pulse_sim_yf = results.get_statevector() #run independent simulation samples = np.array([[amp1], [amp2 * np.exp(1j * phi1)]]) - indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_0]), samples, 1.) + indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_0]), + samples, 1.) - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1 - (10**-5)) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), + 1 - (10**-5)) def test_set_phase(self): """Test SetPhase command. Similar to the ShiftPhase test but includes a mixing of @@ -1038,45 +1054,45 @@ def test_set_phase(self): # intermix shift and set phase instructions to verify absolute v.s. relative changes sched = Schedule() amp1 = 0.12 - sched += Play(SamplePulse([amp1]), DriveChannel(0)) + sched += Play(Waveform([amp1]), DriveChannel(0)) phi1 = 0.12374 * np.pi sched += ShiftPhase(phi1, DriveChannel(0)) amp2 = 0.492 - sched += Play(SamplePulse([amp2]), DriveChannel(0)) + sched += Play(Waveform([amp2]), DriveChannel(0)) phi2 = 0.5839 * np.pi sched += SetPhase(phi2, DriveChannel(0)) amp3 = 0.12 + 0.21 * 1j - sched += Play(SamplePulse([amp3]), DriveChannel(0)) + sched += Play(Waveform([amp3]), DriveChannel(0)) phi3 = 0.1 * np.pi sched += ShiftPhase(phi3, DriveChannel(0)) amp4 = 0.2 + 0.3 * 1j - sched += Play(SamplePulse([amp4]), DriveChannel(0)) + sched += Play(Waveform([amp4]), DriveChannel(0)) sched |= Acquire(1, AcquireChannel(0), MemorySlot(0)) << sched.duration + y0 = np.array([1., 0.]) + pulse_sim = PulseSimulator(system_model=system_model, + initial_state=y0) qobj = assemble([sched], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], qubit_lo_freq=[omega_0], memory_slots=2, shots=1) - - y0 = np.array([1., 0.]) - backend_options = {'initial_state': y0} - - results = self.backend_sim.run(qobj, system_model, backend_options).result() + results = pulse_sim.run(qobj).result() pulse_sim_yf = results.get_statevector() #run independent simulation - samples = np.array([[amp1], - [amp2 * np.exp(1j * phi1)], + samples = np.array([[amp1], [amp2 * np.exp(1j * phi1)], [amp3 * np.exp(1j * phi2)], [amp4 * np.exp(1j * (phi2 + phi3))]]) - indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_0]), samples, 1.) + indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_0]), + samples, 1.) - self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1 - (10**-5)) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), + 1 - (10**-5)) def test_set_phase_rwa(self): """Test SetPhase command using an RWA approximate solution.""" @@ -1087,27 +1103,27 @@ def test_set_phase_rwa(self): sched = Schedule() sched += SetPhase(np.pi / 2, DriveChannel(0)) - sched += Play(SamplePulse(np.ones(100)), DriveChannel(0)) + sched += Play(Waveform(np.ones(100)), DriveChannel(0)) sched |= Acquire(1, AcquireChannel(0), MemorySlot(0)) << sched.duration + y0 = np.array([1., 1.]) / np.sqrt(2) + pulse_sim = PulseSimulator(system_model=system_model, + initial_state=y0) qobj = assemble([sched], - backend=self.backend_sim, + backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], qubit_lo_freq=[omega_0], memory_slots=2, shots=1) - - y0 = np.array([1., 1.]) / np.sqrt(2) - backend_options = {'initial_state': y0} - - results = self.backend_sim.run(qobj, system_model, backend_options).result() + results = pulse_sim.run(qobj).result() pulse_sim_yf = results.get_statevector() #run independent simulation - phases = np.exp((-1j * 2 * np.pi * omega_0 * np.array([1, -1]) / 2) * 100) + phases = np.exp( + (-1j * 2 * np.pi * omega_0 * np.array([1, -1]) / 2) * 100) approx_yf = phases * (expm(-1j * (np.pi / 2) * self.Y) @ y0) self.assertGreaterEqual(state_fidelity(pulse_sim_yf, approx_yf), 0.99) @@ -1124,7 +1140,9 @@ def _system_model_1Q(self, omega_0, r): """ hamiltonian = {} - hamiltonian['h_str'] = ['2*np.pi*omega0*0.5*Z0', '2*np.pi*r*0.5*X0||D0'] + hamiltonian['h_str'] = [ + '2*np.pi*omega0*0.5*Z0', '2*np.pi*r*0.5*X0||D0' + ] hamiltonian['vars'] = {'omega0': omega_0, 'r': r} hamiltonian['qub'] = {'0': 2} ham_model = HamiltonianModel.from_dict(hamiltonian) @@ -1150,10 +1168,11 @@ def _1Q_constant_sched(self, total_samples, amp=1.): """ # set up constant pulse for doing a pi pulse - drive_pulse = SamplePulse(amp * np.ones(total_samples)) + drive_pulse = Waveform(amp * np.ones(total_samples)) schedule = Schedule() schedule |= Play(drive_pulse, DriveChannel(0)) - schedule |= Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) << schedule.duration + schedule |= Acquire(total_samples, AcquireChannel(0), + MemorySlot(0)) << schedule.duration return schedule @@ -1169,13 +1188,15 @@ def _system_model_2Q(self, j): """ hamiltonian = {} - hamiltonian['h_str'] = ['a*X0||D0', 'a*X0||D1', '2*np.pi*j*0.25*(Z0*X1)||U0'] + hamiltonian['h_str'] = [ + 'a*X0||D0', 'a*X0||D1', '2*np.pi*j*0.25*(Z0*X1)||U0' + ] hamiltonian['vars'] = {'a': 0, 'j': j} hamiltonian['qub'] = {'0': 2, '1': 2} ham_model = HamiltonianModel.from_dict(hamiltonian) # set the U0 to have frequency of drive channel 0 - u_channel_lo = [[UchannelLO(0, 1.0+0.0j)]] + u_channel_lo = [[UchannelLO(0, 1.0 + 0.0j)]] subsystem_list = [0, 1] dt = 1. @@ -1184,7 +1205,6 @@ def _system_model_2Q(self, j): subsystem_list=subsystem_list, dt=dt) - def _2Q_constant_sched(self, total_samples, amp=1., u_idx=0): """Creates a runnable schedule with a single pulse on a U channel for two qubits. @@ -1198,15 +1218,16 @@ def _2Q_constant_sched(self, total_samples, amp=1., u_idx=0): """ # set up constant pulse for doing a pi pulse - drive_pulse = SamplePulse(amp * np.ones(total_samples)) + drive_pulse = Waveform(amp * np.ones(total_samples)) schedule = Schedule() schedule |= Play(drive_pulse, ControlChannel(u_idx)) - schedule |= Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) << total_samples - schedule |= Acquire(total_samples, AcquireChannel(1), MemorySlot(1)) << total_samples + schedule |= Acquire(total_samples, AcquireChannel(0), + MemorySlot(0)) << total_samples + schedule |= Acquire(total_samples, AcquireChannel(1), + MemorySlot(1)) << total_samples return schedule - def _system_model_3Q(self, j, subsystem_list=[0, 2]): """Constructs a model for a 3 qubit system, with the goal that the restriction to [0, 2] and to qubits [1, 2] is the same as in _system_model_2Q @@ -1220,13 +1241,17 @@ def _system_model_3Q(self, j, subsystem_list=[0, 2]): """ hamiltonian = {} - hamiltonian['h_str'] = ['2*np.pi*j*0.25*(Z0*X2)||U0', '2*np.pi*j*0.25*(Z1*X2)||U1'] + hamiltonian['h_str'] = [ + '2*np.pi*j*0.25*(Z0*X2)||U0', '2*np.pi*j*0.25*(Z1*X2)||U1' + ] hamiltonian['vars'] = {'j': j} hamiltonian['qub'] = {'0': 2, '1': 2, '2': 2} - ham_model = HamiltonianModel.from_dict(hamiltonian, subsystem_list=subsystem_list) + ham_model = HamiltonianModel.from_dict(hamiltonian, + subsystem_list=subsystem_list) # set the U0 to have frequency of drive channel 0 - u_channel_lo = [[UchannelLO(0, 1.0 + 0.0j)], [UchannelLO(0, 1.0 + 0.0j)]] + u_channel_lo = [[UchannelLO(0, 1.0 + 0.0j)], + [UchannelLO(0, 1.0 + 0.0j)]] dt = 1. return PulseSystemModel(hamiltonian=ham_model, @@ -1234,7 +1259,11 @@ def _system_model_3Q(self, j, subsystem_list=[0, 2]): subsystem_list=subsystem_list, dt=dt) - def _3Q_constant_sched(self, total_samples, amp=1., u_idx=0, subsystem_list=[0, 2]): + def _3Q_constant_sched(self, + total_samples, + amp=1., + u_idx=0, + subsystem_list=[0, 2]): """Creates a runnable schedule for the 3Q system after the system is restricted to 2 qubits. @@ -1249,12 +1278,11 @@ def _3Q_constant_sched(self, total_samples, amp=1., u_idx=0, subsystem_list=[0, """ # set up constant pulse for doing a pi pulse - drive_pulse = SamplePulse(amp * np.ones(total_samples)) + drive_pulse = Waveform(amp * np.ones(total_samples)) schedule = Schedule() schedule |= Play(drive_pulse, ControlChannel(u_idx)) for idx in subsystem_list: - schedule |= Acquire(total_samples, - AcquireChannel(idx), + schedule |= Acquire(total_samples, AcquireChannel(idx), MemorySlot(idx)) << total_samples return schedule @@ -1271,10 +1299,10 @@ def _system_model_3d_oscillator(self, freq, anharm, r): PulseSystemModel: model for oscillator system """ hamiltonian = {} - hamiltonian['h_str'] = ['np.pi*(2*v-alpha)*O0', - 'np.pi*alpha*O0*O0', - '2*np.pi*r*X0||D0'] - hamiltonian['vars'] = {'v' : freq, 'alpha': anharm, 'r': r} + hamiltonian['h_str'] = [ + 'np.pi*(2*v-alpha)*O0', 'np.pi*alpha*O0*O0', '2*np.pi*r*X0||D0' + ] + hamiltonian['vars'] = {'v': freq, 'alpha': anharm, 'r': r} hamiltonian['qub'] = {'0': 3} ham_model = HamiltonianModel.from_dict(hamiltonian) @@ -1287,5 +1315,6 @@ def _system_model_3d_oscillator(self, freq, anharm, r): subsystem_list=subsystem_list, dt=dt) + if __name__ == '__main__': unittest.main() diff --git a/test/terra/backends/test_qasm_simulator_extended_stabilizer.py b/test/terra/backends/test_qasm_simulator_extended_stabilizer.py index c9e239a2f4..d21f8e03cb 100644 --- a/test/terra/backends/test_qasm_simulator_extended_stabilizer.py +++ b/test/terra/backends/test_qasm_simulator_extended_stabilizer.py @@ -55,7 +55,7 @@ def test_reset_deterministic(self): circuits = ref_reset.reset_circuits_deterministic(final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_reset.reset_counts_deterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -69,7 +69,7 @@ def test_reset_nondeterministic(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_reset.reset_counts_nondeterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -84,7 +84,7 @@ def test_measure_deterministic_with_sampling(self): allow_sampling=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_measure.measure_counts_deterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -96,7 +96,7 @@ def test_measure_deterministic_without_sampling(self): allow_sampling=False) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_measure.measure_counts_deterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -108,7 +108,7 @@ def test_measure_nondeterministic_with_sampling(self): allow_sampling=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_measure.measure_counts_nondeterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -120,7 +120,7 @@ def test_measure_nondeterministic_without_sampling(self): allow_sampling=False) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_measure.measure_counts_nondeterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -135,7 +135,7 @@ def test_measure_deterministic_multi_qubit_with_sampling(self): allow_sampling=True) targets = ref_measure.multiqubit_measure_counts_deterministic(shots) qobj = assemble(circuits, QasmSimulator(), shots=shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -147,7 +147,7 @@ def test_measure_deterministic_multi_qubit_without_sampling(self): allow_sampling=False) targets = ref_measure.multiqubit_measure_counts_deterministic(shots) qobj = assemble(circuits, QasmSimulator(), shots=shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -159,7 +159,7 @@ def test_measure_nondeterministic_multi_qubit_with_sampling(self): allow_sampling=True) targets = ref_measure.multiqubit_measure_counts_nondeterministic(shots) qobj = assemble(circuits, QasmSimulator(), shots=shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -171,7 +171,7 @@ def test_measure_nondeterministic_multi_qubit_without_sampling(self): allow_sampling=False) targets = ref_measure.multiqubit_measure_counts_nondeterministic(shots) qobj = assemble(circuits, QasmSimulator(), shots=shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -186,7 +186,7 @@ def test_conditional_1bit(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_conditionals.conditional_counts_1bit(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -198,7 +198,7 @@ def test_conditional_2bit(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_conditionals.conditional_counts_2bit(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -213,7 +213,7 @@ def test_h_gate_deterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_1q_clifford.h_gate_counts_deterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -225,7 +225,7 @@ def test_h_gate_nondeterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_1q_clifford.h_gate_counts_nondeterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -240,7 +240,7 @@ def test_x_gate_deterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_1q_clifford.x_gate_counts_deterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -255,7 +255,7 @@ def test_z_gate_deterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_1q_clifford.z_gate_counts_deterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -270,7 +270,7 @@ def test_y_gate_deterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_1q_clifford.y_gate_counts_deterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -285,7 +285,7 @@ def test_s_gate_deterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_1q_clifford.s_gate_counts_deterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -297,7 +297,7 @@ def test_s_gate_nondeterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_1q_clifford.s_gate_counts_nondeterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -312,7 +312,7 @@ def test_sdg_gate_deterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_1q_clifford.sdg_gate_counts_deterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -324,7 +324,7 @@ def test_sdg_gate_nondeterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_1q_clifford.sdg_gate_counts_nondeterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -339,7 +339,7 @@ def test_cx_gate_deterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_2q_clifford.cx_gate_counts_deterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -351,7 +351,7 @@ def test_cx_gate_nondeterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_2q_clifford.cx_gate_counts_nondeterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -366,7 +366,7 @@ def test_cz_gate_deterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_2q_clifford.cz_gate_counts_deterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -378,7 +378,7 @@ def test_cz_gate_nondeterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_2q_clifford.cz_gate_counts_nondeterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -393,7 +393,7 @@ def test_swap_gate_deterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_2q_clifford.swap_gate_counts_deterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) @@ -405,7 +405,7 @@ def test_swap_gate_nondeterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_2q_clifford.swap_gate_counts_nondeterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS_SAMPLING) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS_SAMPLING) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -420,7 +420,7 @@ def test_t_gate_deterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_non_clifford.t_gate_counts_deterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.1 * shots) @@ -434,7 +434,7 @@ def test_t_gate_nondeterministic_default_basis_gates(self): targets = ref_non_clifford.t_gate_counts_nondeterministic(shots) opts = self.BACKEND_OPTS.copy() opts["extended_stabilizer_mixing_time"] = 50 - job = QasmSimulator().run(qobj, backend_options=opts) + job = QasmSimulator().run(qobj, **opts) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.1 * shots) @@ -449,7 +449,7 @@ def test_tdg_gate_deterministic_default_basis_gates(self): final_measure=True) qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_non_clifford.tdg_gate_counts_deterministic(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) @@ -464,7 +464,7 @@ def test_tdg_gate_nondeterministic_default_basis_gates(self): targets = ref_non_clifford.tdg_gate_counts_nondeterministic(shots) opts = self.BACKEND_OPTS.copy() opts["extended_stabilizer_mixing_time"] = 50 - job = QasmSimulator().run(qobj, backend_options=opts) + job = QasmSimulator().run(qobj, **opts) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.1 * shots) @@ -481,7 +481,7 @@ def test_ccx_gate_deterministic_default_basis_gates(self): targets = ref_non_clifford.ccx_gate_counts_deterministic(shots) opts = self.BACKEND_OPTS.copy() opts["extended_stabilizer_mixing_time"] = 100 - job = QasmSimulator().run(qobj, backend_options=opts) + job = QasmSimulator().run(qobj, **opts) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) @@ -495,7 +495,7 @@ def test_ccx_gate_nondeterministic_default_basis_gates(self): targets = ref_non_clifford.ccx_gate_counts_nondeterministic(shots) opts = self.BACKEND_OPTS.copy() opts["extended_stabilizer_mixing_time"] = 100 - job = QasmSimulator().run(qobj, backend_options=opts) + job = QasmSimulator().run(qobj, **opts) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.10 * shots) @@ -512,7 +512,7 @@ def test_grovers_default_basis_gates(self): targets = ref_algorithms.grovers_counts(shots) opts = self.BACKEND_OPTS.copy() opts["extended_stabilizer_mixing_time"] = 100 - job = QasmSimulator().run(qobj, backend_options=opts) + job = QasmSimulator().run(qobj, **opts) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.1 * shots) @@ -523,7 +523,7 @@ def test_teleport_default_basis_gates(self): circuits = ref_algorithms.teleport_circuit() qobj = assemble(circuits, QasmSimulator(), shots=shots) targets = ref_algorithms.teleport_counts(shots) - job = QasmSimulator().run(qobj, backend_options=self.BACKEND_OPTS) + job = QasmSimulator().run(qobj, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) diff --git a/test/terra/backends/unitary_simulator/unitary_basics.py b/test/terra/backends/unitary_simulator/unitary_basics.py index 187e84bc7c..1ec3109af8 100644 --- a/test/terra/backends/unitary_simulator/unitary_basics.py +++ b/test/terra/backends/unitary_simulator/unitary_basics.py @@ -42,7 +42,7 @@ def test_h_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -56,7 +56,7 @@ def test_h_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -70,7 +70,7 @@ def test_h_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -83,7 +83,7 @@ def test_h_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -97,7 +97,7 @@ def test_h_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -111,7 +111,7 @@ def test_h_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -127,7 +127,7 @@ def test_x_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -141,7 +141,7 @@ def test_x_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -155,7 +155,7 @@ def test_x_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -171,7 +171,7 @@ def test_z_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -185,7 +185,7 @@ def test_z_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -199,7 +199,7 @@ def test_z_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -215,7 +215,7 @@ def test_y_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -229,7 +229,7 @@ def test_y_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -243,7 +243,7 @@ def test_y_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -259,7 +259,7 @@ def test_s_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -273,7 +273,7 @@ def test_s_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -287,7 +287,7 @@ def test_s_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -300,7 +300,7 @@ def test_s_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -314,7 +314,7 @@ def test_s_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -328,7 +328,7 @@ def test_s_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -344,7 +344,7 @@ def test_sdg_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -358,7 +358,7 @@ def test_sdg_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -372,7 +372,7 @@ def test_sdg_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -385,7 +385,7 @@ def test_sdg_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -399,7 +399,7 @@ def test_sdg_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -413,7 +413,7 @@ def test_sdg_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -429,7 +429,7 @@ def test_cx_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -443,7 +443,7 @@ def test_cx_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -457,7 +457,7 @@ def test_cx_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -470,7 +470,7 @@ def test_cx_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -484,7 +484,7 @@ def test_cx_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -498,7 +498,7 @@ def test_cx_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -514,7 +514,7 @@ def test_cz_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -528,7 +528,7 @@ def test_cz_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -542,7 +542,7 @@ def test_cz_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -555,7 +555,7 @@ def test_cz_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -569,7 +569,7 @@ def test_cz_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -583,7 +583,7 @@ def test_cz_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -600,7 +600,7 @@ def test_cu1_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -614,7 +614,7 @@ def test_cu1_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -628,7 +628,7 @@ def test_cu1_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -644,7 +644,7 @@ def test_cu3_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -658,7 +658,7 @@ def test_cu3_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -672,7 +672,7 @@ def test_cu3_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -688,7 +688,7 @@ def test_cswap_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary( @@ -705,7 +705,7 @@ def test_swap_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -719,7 +719,7 @@ def test_swap_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -733,7 +733,7 @@ def test_swap_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -746,7 +746,7 @@ def test_swap_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -760,7 +760,7 @@ def test_swap_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -774,7 +774,7 @@ def test_swap_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -790,7 +790,7 @@ def test_t_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -804,7 +804,7 @@ def test_t_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -818,7 +818,7 @@ def test_t_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -831,7 +831,7 @@ def test_t_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -845,7 +845,7 @@ def test_t_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -859,7 +859,7 @@ def test_t_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -875,7 +875,7 @@ def test_tdg_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -889,7 +889,7 @@ def test_tdg_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -903,7 +903,7 @@ def test_tdg_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -916,7 +916,7 @@ def test_tdg_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -930,7 +930,7 @@ def test_tdg_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -944,7 +944,7 @@ def test_tdg_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -960,7 +960,7 @@ def test_ccx_gate_deterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -974,7 +974,7 @@ def test_ccx_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -988,7 +988,7 @@ def test_ccx_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -1001,7 +1001,7 @@ def test_ccx_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -1015,7 +1015,7 @@ def test_ccx_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -1029,7 +1029,7 @@ def test_ccx_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -1045,7 +1045,7 @@ def test_unitary_gate(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -1058,7 +1058,7 @@ def test_diagonal_gate(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -1072,7 +1072,7 @@ def test_cswap_gate_deterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -1086,7 +1086,7 @@ def test_cswap_gate_deterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -1099,7 +1099,7 @@ def test_cswap_gate_nondeterministic_default_basis_gates(self): job = execute(circuits, self.SIMULATOR, shots=1, - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -1113,7 +1113,7 @@ def test_cswap_gate_nondeterministic_minimal_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -1127,7 +1127,7 @@ def test_cswap_gate_nondeterministic_waltz_basis_gates(self): self.SIMULATOR, shots=1, basis_gates=['u1', 'u2', 'u3', 'cx'], - backend_options=self.BACKEND_OPTS) + **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_unitary(result, circuits, targets) @@ -1144,7 +1144,7 @@ def test_qobj_global_phase(self): targets = ref_1q_clifford.h_gate_unitary_nondeterministic() qobj = assemble(transpile(circuits, self.SIMULATOR), - shots=1, backend_options=self.BACKEND_OPTS) + shots=1, **self.BACKEND_OPTS) # Set global phases for i, _ in enumerate(circuits): global_phase = (-1) ** i * (pi / 4) diff --git a/test/terra/backends/unitary_simulator/unitary_fusion.py b/test/terra/backends/unitary_simulator/unitary_fusion.py index dbee2645b3..5b4f4af319 100644 --- a/test/terra/backends/unitary_simulator/unitary_fusion.py +++ b/test/terra/backends/unitary_simulator/unitary_fusion.py @@ -50,7 +50,7 @@ def test_fusion_theshold(self): circuit = transpile(circuit, self.SIMULATOR) qobj = assemble([circuit], shots=1) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) @@ -61,7 +61,7 @@ def test_fusion_theshold(self): circuit = transpile(circuit, self.SIMULATOR) qobj = assemble([circuit], shots=1) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) @@ -72,7 +72,7 @@ def test_fusion_theshold(self): circuit = transpile(circuit, self.SIMULATOR) qobj = assemble([circuit], shots=1) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) @@ -88,7 +88,7 @@ def test_fusion_disable(self): with self.subTest(msg='test fusion enable'): backend_options = self.fusion_options(enabled=True, threshold=1) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) @@ -97,7 +97,7 @@ def test_fusion_disable(self): with self.subTest(msg='test fusion disable'): backend_options = self.fusion_options(enabled=False, threshold=1) result = self.SIMULATOR.run( - qobj, backend_options=backend_options).result() + qobj, **backend_options).result() meta = self.fusion_metadata(result) self.assertSuccess(result) @@ -112,12 +112,12 @@ def test_fusion_output(self): options_disabled = self.fusion_options(enabled=False, threshold=1) result_disabled = self.SIMULATOR.run( - qobj, backend_options=options_disabled).result() + qobj, **options_disabled).result() self.assertSuccess(result_disabled) options_enabled = self.fusion_options(enabled=True, threshold=1) result_enabled = self.SIMULATOR.run( - qobj, backend_options=options_enabled).result() + qobj, **options_enabled).result() self.assertSuccess(result_enabled) unitary_no_fusion = Operator(result_disabled.get_unitary(0)) diff --git a/test/terra/backends/unitary_simulator/unitary_snapshot.py b/test/terra/backends/unitary_simulator/unitary_snapshot.py index 1f43c3dfc1..9f7af08186 100644 --- a/test/terra/backends/unitary_simulator/unitary_snapshot.py +++ b/test/terra/backends/unitary_simulator/unitary_snapshot.py @@ -28,17 +28,19 @@ class UnitarySnapshotTests: def test_unitary_snap(self): """Test Unitary matrix snaps on a random circuit""" backend = UnitarySimulator() - backend_opts = {} + target = qi.random_unitary(2 ** 4, seed=111) circ = QuantumCircuit(4) - circ.append(qi.random_unitary(2 ** 4), [0, 1, 2, 3]) + circ.append(target, [0, 1, 2, 3]) circ.append(Snapshot("final", "unitary", 4), [0, 1, 2, 3]) - qobj = assemble(circ, backend=backend) - aer_input = backend._format_qobj(qobj, self.BACKEND_OPTS, None) - aer_output = backend._controller(aer_input) - self.assertIsInstance(aer_output, dict) - self.assertTrue(aer_output['success']) - snaps = aer_output['results'][0]['data']['snapshots']['unitary']['final'] - self.assertTrue(all([isinstance(arr, np.ndarray) for arr in snaps])) + qobj = assemble(circ, backend=backend, shots=1) + job = backend.run(qobj) + result = job.result() + self.assertSuccess(result) + snaps = result.data(0)['snapshots']['unitary']['final'] + for arr in snaps: + self.assertTrue(isinstance(arr, np.ndarray)) + self.assertEqual(qi.Operator(arr), target) + if __name__ == '__main__': unittest.main() diff --git a/test/terra/decorators.py b/test/terra/decorators.py index 8825d2d9f9..26d0734d8f 100644 --- a/test/terra/decorators.py +++ b/test/terra/decorators.py @@ -36,7 +36,7 @@ def is_method_available(backend, method): qobj = assemble(dummy_circ, optimization_level=0) backend_options = {"method": method} try: - job = backend.run(qobj, backend_options=backend_options) + job = backend.run(qobj, **backend_options) result = job.result() error_msg = 'not supported on this system' if not result.success and error_msg in result.results[0].status: diff --git a/test/terra/extensions/test_wrappers.py b/test/terra/extensions/test_wrappers.py index fd068125b7..7b863b34f6 100644 --- a/test/terra/extensions/test_wrappers.py +++ b/test/terra/extensions/test_wrappers.py @@ -49,8 +49,8 @@ def _create_qobj(self, backend, noise_model=None): circuit.x(list(range(num_qubits))) qobj = assemble(transpile(circuit, backend), backend) opts = {'max_parallel_threads': 1} - fqobj = backend._format_qobj(qobj, backend_options=opts, noise_model=noise_model) - return fqobj + fqobj = backend._format_qobj(qobj, **opts, noise_model=noise_model) + return fqobj.to_dict() def _map_and_test(self, cfunc, qobj): n = 2 diff --git a/test/terra/pulse/test_system_models.py b/test/terra/pulse/test_system_models.py index e390e80d42..5caa2aafe9 100644 --- a/test/terra/pulse/test_system_models.py +++ b/test/terra/pulse/test_system_models.py @@ -63,7 +63,6 @@ def _simple_system_model(self, v0=5.0, v1=5.1, j=0.01, r=0.02, alpha0=-0.33, alp dt = 1. return PulseSystemModel(hamiltonian=ham_model, - qubit_freq_est=self._default_qubit_lo_freq, u_channel_lo=self._u_channel_lo, subsystem_list=subsystem_list, dt=dt) @@ -113,27 +112,6 @@ def test_control_channel_labels_from_backend(self): self.assertEqual(system_model.control_channel_labels, expected) - def test_qubit_lo_default(self): - """Test drawing of defaults form a backend.""" - test_model = self._simple_system_model() - default_qubit_lo_freq = self._default_qubit_lo_freq - default_u_lo_freq = self._compute_u_lo_freqs(default_qubit_lo_freq) - - # test output of default qubit_lo_freq - freqs = test_model.calculate_channel_frequencies() - self.assertAlmostEqual(freqs['D0'], default_qubit_lo_freq[0]) - self.assertAlmostEqual(freqs['D1'], default_qubit_lo_freq[1]) - self.assertAlmostEqual(freqs['U0'], default_u_lo_freq[0]) - self.assertAlmostEqual(freqs['U1'], default_u_lo_freq[1]) - - # test defaults again, but with non-default hamiltonian - test_model = self._simple_system_model(v0=5.1, v1=4.9, j=0.02) - freqs = test_model.calculate_channel_frequencies() - self.assertAlmostEqual(freqs['D0'], default_qubit_lo_freq[0]) - self.assertAlmostEqual(freqs['D1'], default_qubit_lo_freq[1]) - self.assertAlmostEqual(freqs['U0'], default_u_lo_freq[0]) - self.assertAlmostEqual(freqs['U1'], default_u_lo_freq[1]) - def test_qubit_lo_from_hamiltonian(self): """Test computation of qubit_lo_freq from the hamiltonian itself.""" test_model = self._simple_system_model() @@ -155,6 +133,7 @@ def test_qubit_lo_from_hamiltonian(self): self.assertAlmostEqual(freqs['U1'], -0.203960780543) def test_qubit_lo_from_configurable_backend(self): + """Test computation of qubit_lo_freq from configurable backend.""" backend = FakeArmonk() test_model = PulseSystemModel.from_backend(backend) qubit_lo_from_hamiltonian = test_model.hamiltonian.get_qubit_lo_from_drift() diff --git a/test/terra/test_python_to_cpp.py b/test/terra/test_python_to_cpp.py index 7e60aec6cc..f8f820d470 100644 --- a/test/terra/test_python_to_cpp.py +++ b/test/terra/test_python_to_cpp.py @@ -25,7 +25,6 @@ class TestPythonToCpp(QiskitAerTestCase): """ Test Pyhton C API wrappers we have for dealing with Python data structures in C++ code. """ - def test_py_list_to_cpp_vec(self): arg = [1., 2., 3.] self.assertTrue(test_py_list_to_cpp_vec(arg)) diff --git a/tools/verify_wheels.py b/tools/verify_wheels.py index d0197d2878..da1f9f62d4 100644 --- a/tools/verify_wheels.py +++ b/tools/verify_wheels.py @@ -16,7 +16,7 @@ from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.providers.aer.pulse.system_models.duffing_model_generators import duffing_system_model -from qiskit.pulse import (Schedule, Play, Acquire, SamplePulse, DriveChannel, AcquireChannel, +from qiskit.pulse import (Schedule, Play, Acquire, Waveform, DriveChannel, AcquireChannel, MemorySlot) from qiskit.providers.aer import QasmSimulator @@ -428,7 +428,7 @@ def model_and_pi_schedule(): dt=1.0) # note: parameters set so that area under curve is 1/4 - sample_pulse = SamplePulse(np.ones(50)) + sample_pulse = Waveform(np.ones(50)) # construct schedule schedule = Schedule(name='test_sched') @@ -478,7 +478,7 @@ def model_and_pi_schedule(): meas_level=1, meas_return='avg', shots=1) - results = backend_sim.run(qobj, system_model).result() + results = backend_sim.run(qobj, system_model=system_model).result() state = results.get_statevector(0) assertAlmostEqual(state[0], 0, delta=10**-3) assertAlmostEqual(state[1], -1j, delta=10**-3)