Skip to content

Commit

Permalink
fix lint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
hhorii committed Feb 13, 2023
1 parent d83ea88 commit 3c0e6cc
Show file tree
Hide file tree
Showing 10 changed files with 93 additions and 69 deletions.
12 changes: 6 additions & 6 deletions qiskit_aer/backends/aer_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,7 @@ def __repr__(self):
if noise_model is None or noise_model.is_ideal():
return display
pad = ' ' * (len(self.__class__.__name__) + 1)
return '{}\n{}noise_model={})'.format(display[:-1], pad, repr(noise_model))
return f'{display[:-1]}\n{pad}noise_model={repr(noise_model)})'

def name(self):
"""Format backend name string for simulator"""
Expand Down Expand Up @@ -682,7 +682,7 @@ def from_backend(cls, backend, **options):

# Customize configuration name
name = configuration.backend_name
configuration.backend_name = 'aer_simulator({})'.format(name)
configuration.backend_name = f'aer_simulator({name})'
else:
raise TypeError(
"The backend argument requires a BackendV2 or BackendV1 object, "
Expand Down Expand Up @@ -730,10 +730,10 @@ def configuration(self):
config.backend_name = self.name()
return config

def _execute_direct(self, circuits, noise_model, config):
def _execute_direct(self, aer_circuits, noise_model, config):
"""Execute circuits on the backend.
"""
return cpp_execute_direct(self._controller, circuits, noise_model, config)
return cpp_execute_direct(self._controller, aer_circuits, noise_model, config)

def _execute(self, qobj):
"""Execute a qobj on the backend.
Expand All @@ -753,8 +753,8 @@ def set_option(self, key, value):
if key == "method":
if (value is not None and value not in self.available_methods()):
raise AerError(
"Invalid simulation method {}. Available methods"
" are: {}".format(value, self.available_methods()))
f"Invalid simulation method {value}. Available methods"
f" are: {self.available_methods()}")
self._set_method_config(value)
super().set_option(key, value)
if key in ["method", "noise_model", "basis_gates"]:
Expand Down
24 changes: 13 additions & 11 deletions qiskit_aer/backends/aerbackend.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,13 @@
import logging
import time
import uuid
import warnings
from abc import ABC, abstractmethod

from qiskit.circuit import QuantumCircuit, ParameterExpression, Delay
from qiskit.compiler import assemble
from qiskit.providers import BackendV1 as Backend
from qiskit.providers.models import BackendStatus
from qiskit.pulse import Schedule, ScheduleBlock
from qiskit.qobj import QasmQobj, PulseQobj
from qiskit.result import Result
from ..aererror import AerError
from ..jobs import AerJob, AerJobSet, AerJobDirect, split_qobj
Expand Down Expand Up @@ -163,12 +161,14 @@ def run(self,
if isinstance(circuits, (QuantumCircuit, Schedule, ScheduleBlock)):
circuits = [circuits]
if not isinstance(circuits, list):
raise AerError("bad input to run() function; circuits must be either circuits or schedules")
raise AerError("bad input to run() function; " +
"circuits must be either circuits or schedules")

if all(isinstance(circ, QuantumCircuit) for circ in circuits):
if (('executor' in run_options and run_options['executor']) or
('executor' in self.options.__dict__ and self.options.__dict__['executor']) or
validate):
executor = run_options.get('executor', None)
if executor is None and 'executor' in self.options.__dict__:
executor = 'executor' in self.options.__dict__
if executor or validate:
# This path remains for DASK execution to split a qobj insttance
# into sub-qobj instances. This will be replaced with _run_circuits path
# in the near releases
Expand All @@ -178,7 +178,8 @@ def run(self,
elif all(isinstance(circ, (ScheduleBlock, Schedule)) for circ in circuits):
return self._run_qobj(circuits, validate, parameter_binds, **run_options)
else:
raise AerError("bad input to run() function; circuits must be either circuits or schedules")
raise AerError("bad input to run() function;" +
"circuits must be either circuits or schedules")

def _run_circuits(self,
circuits,
Expand Down Expand Up @@ -375,7 +376,7 @@ def _run_direct(self, circuits, noise_model, config, job_id='', format_result=Tr
# Start timer
start = time.time()

# Take metadata from headers of experiments to work around JSON serialization error
# Take metadata from headers of experiments to work around JSON serialization error
metadata_list = []
metadata_index = 0
for circ in circuits:
Expand All @@ -386,7 +387,7 @@ def _run_direct(self, circuits, noise_model, config, job_id='', format_result=Tr
if "id" in metadata_copy:
circ._header.metadata["id"] = metadata_copy["id"]
circ._header.metadata["metadata_index"] = metadata_index
metadata_index += 1
metadata_index += 1

# Run simulation
output = self._execute_direct(circuits, noise_model, config)
Expand Down Expand Up @@ -583,13 +584,14 @@ def _execute(self, qobj):
"""
pass


@abstractmethod
def _execute_direct(self, aer_circuits, noise_model, config):
"""Execute aer circuits on the backend.
Args:
aer_circuits (List of AerCircuit): simulator input.
noise_model (NoiseModel): noise model
config (Dict): configuration for simulation
Returns:
dict: return a dictionary of results.
Expand Down Expand Up @@ -625,7 +627,7 @@ def set_option(self, key, value):
self._set_defaults_option(key, value)
else:
if not hasattr(self._options, key):
raise AerError("Invalid option %s" % key)
raise AerError(f"Invalid option {key}")
if value is not None:
# Only add an option if its value is not None
setattr(self._options, key, value)
Expand Down
7 changes: 6 additions & 1 deletion qiskit_aer/backends/backend_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ def cpp_execute(controller, qobj):

return controller(qobj)


def cpp_execute_direct(controller, aer_circuits, noise_model, config):
"""Execute aer circuits on C++ controller wrapper"""

Expand All @@ -138,6 +139,7 @@ def cpp_execute_direct(controller, aer_circuits, noise_model, config):

return controller.execute(native_circuits, noise_model, config)


def available_methods(controller, methods, devices):
"""Check available simulation methods by running a dummy circuit."""
# Test methods are available using the controller
Expand Down Expand Up @@ -201,24 +203,27 @@ def add_final_save_op(aer_circs, state):

for aer_circ in aer_circs:
num_qubits = aer_circ.num_qubits
getattr(aer_circ, f"save_{state}")(list(range(num_qubits)),f"{state}","single")
getattr(aer_circ, f"save_{state}")(list(range(num_qubits)), f"{state}", "single")

return aer_circs


def map_legacy_method_options(qobj):
"""Map legacy method names of qasm simulator to aer simulator options"""
method = getattr(qobj.config, "method", None)
if method in LEGACY_METHOD_MAP:
qobj.config.method, qobj.config.device = LEGACY_METHOD_MAP[method]
return qobj


def map_legacy_method_config(config):
"""Map legacy method names of qasm simulator to aer simulator options"""
method = config["method"] if "method" in config else None
if method in LEGACY_METHOD_MAP:
config["method"], config["device"] = LEGACY_METHOD_MAP[method]
return config


def format_save_type(data, save_type, save_subtype):
"""Format raw simulator result data based on save type."""
init_fns = {
Expand Down
3 changes: 1 addition & 2 deletions qiskit_aer/backends/pulse_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,11 +278,10 @@ def _execute(self, qobj):
qobj.config.qubit_freq_est = self.defaults().qubit_freq_est
return pulse_controller(qobj)

def _execute_direct(self, circuits, noise_model, config):
def _execute_direct(self, aer_circuits, noise_model, config):
"""Execute circuits on the backend.
"""
raise AerError("not implemented yet")
# return cpp_execute_direct(self._controller, circuits, noise_model, config)

def set_option(self, key, value):
"""Set pulse simulation options and update backend."""
Expand Down
18 changes: 10 additions & 8 deletions qiskit_aer/backends/qasm_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
from ..version import __version__
from ..aererror import AerError
from .aerbackend import AerBackend
from .backend_utils import (cpp_execute, available_methods,
from .backend_utils import (cpp_execute,
cpp_execute_direct,
available_methods,
MAX_QUBITS_STATEVECTOR,
LEGACY_METHOD_MAP,
map_legacy_method_options,
Expand Down Expand Up @@ -393,11 +395,11 @@ def __repr__(self):

method = getattr(self.options, 'method', None)
if method not in [None, 'automatic']:
display += ",\n{}method='{}'".format(pad, method)
display += f",\n{pad}method='{method}'"

noise_model = getattr(self.options, 'noise_model', None)
if noise_model is not None and not noise_model.is_ideal():
display += ',\n{}noise_model={})'.format(pad, repr(noise_model))
display += f',\n{pad}noise_model={repr(noise_model)})'

display += ")"
return display
Expand Down Expand Up @@ -469,7 +471,7 @@ def from_backend(cls, backend, **options):

# Customize configuration name
name = configuration.backend_name
configuration.backend_name = 'qasm_simulator({})'.format(name)
configuration.backend_name = f'qasm_simulator({name})'

# Use automatic noise model if none is provided
if 'noise_model' not in options:
Expand Down Expand Up @@ -518,11 +520,11 @@ def _execute(self, qobj):
qobj = map_legacy_method_options(qobj)
return cpp_execute(self._controller, qobj)

def _execute_direct(self, circuits, noise_model, config):
def _execute_direct(self, aer_circuits, noise_model, config):
"""Execute circuits on the backend.
"""
config = map_legacy_method_config(config)
return cpp_execute_direct(self._controller, circuits, noise_model, config)
return cpp_execute_direct(self._controller, aer_circuits, noise_model, config)

def set_option(self, key, value):
if key == "custom_instructions":
Expand All @@ -534,8 +536,8 @@ def set_option(self, key, value):
self.set_option("device", device)
if (value is not None and value not in self.available_methods()):
raise AerError(
"Invalid simulation method {}. Available methods"
" are: {}".format(value, self.available_methods()))
f"Invalid simulation method {value}. Available methods"
f" are: {self.available_methods()}")
self._set_method_config(value)
super().set_option(key, value)
if key in ["method", "noise_model", "basis_gates"]:
Expand Down
6 changes: 3 additions & 3 deletions qiskit_aer/backends/statevector_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,12 +269,12 @@ def _execute(self, qobj):
qobj = map_legacy_method_options(qobj)
return cpp_execute(self._controller, qobj)

def _execute_direct(self, circuits, noise_model, config):
def _execute_direct(self, aer_circuits, noise_model, config):
"""Execute circuits on the backend.
"""
circuits = add_final_save_op(circuits, "statevector")
aer_circuits = add_final_save_op(aer_circuits, "statevector")
config = map_legacy_method_config(config)
return cpp_execute_direct(self._controller, circuits, noise_model, config)
return cpp_execute_direct(self._controller, aer_circuits, noise_model, config)

def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas.
Expand Down
14 changes: 7 additions & 7 deletions qiskit_aer/backends/unitary_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,12 +267,12 @@ def _execute(self, qobj):
qobj = map_legacy_method_options(qobj)
return cpp_execute(self._controller, qobj)

def _execute_direct(self, circuits, noise_model, config):
def _execute_direct(self, aer_circuits, noise_model, config):
"""Execute circuits on the backend.
"""
circuits = add_final_save_op(circuits, "unitary")
aer_circuits = add_final_save_op(aer_circuits, "unitary")
config = map_legacy_method_config(config)
return cpp_execute_direct(self._controller, circuits, noise_model, config)
return cpp_execute_direct(self._controller, aer_circuits, noise_model, config)

def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas.
Expand All @@ -283,15 +283,15 @@ def _validate(self, qobj):
"""
name = self.name()
if getattr(qobj.config, 'noise_model', None) is not None:
raise AerError("{} does not support noise.".format(name))
raise AerError(f"{name} does not support noise.")

n_qubits = qobj.config.n_qubits
max_qubits = self.configuration().n_qubits
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'])))
f'Number of qubits ({n_qubits}) is greater than '
f'max ({max_qubits}) for "{name}" with '
f"{int(local_hardware_info()['memory'])} GB system memory.")
if qobj.config.shots != 1:
logger.info('"%s" only supports 1 shot. Setting shots=1.', name)
qobj.config.shots = 1
Expand Down
Loading

0 comments on commit 3c0e6cc

Please sign in to comment.