Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix mypy errors (providers) #8265

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 22 additions & 20 deletions qiskit/providers/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,21 @@
# pylint: disable=invalid-name

"""Backend abstract interface for providers."""
from __future__ import annotations


import typing
from abc import ABC
from abc import abstractmethod
import datetime
from typing import List, Union, Iterable, Tuple
from collections.abc import Iterable

from qiskit.providers.provider import Provider
from qiskit.providers.models.backendstatus import BackendStatus
from qiskit.circuit.gate import Instruction

if typing.TYPE_CHECKING:
from qiskit.providers.models import BackendConfiguration, BackendProperties


class Backend:
"""Base common type for all versioned Backend abstract classes.
Expand All @@ -34,7 +38,7 @@ class Backend:
directly.
"""

version = 0
version: str | int = 0


class BackendV1(Backend, ABC):
Expand Down Expand Up @@ -69,9 +73,9 @@ class BackendV1(Backend, ABC):
.. automethod:: _default_options
"""

version = 1
version: str | int = 1

def __init__(self, configuration, provider=None, **fields):
def __init__(self, configuration: BackendConfiguration, provider=None, **fields):
"""Initialize a backend class
Args:
Expand Down Expand Up @@ -138,15 +142,15 @@ def set_options(self, **fields):
raise AttributeError("Options field %s is not valid for this backend" % field)
self._options.update_options(**fields)

def configuration(self):
def configuration(self) -> BackendConfiguration:
"""Return the backend configuration.
Returns:
BackendConfiguration: the configuration for the backend.
"""
return self._configuration

def properties(self):
def properties(self) -> BackendProperties | None:
"""Return the backend properties.
Returns:
Expand Down Expand Up @@ -323,11 +327,11 @@ class BackendV2(Backend, ABC):

def __init__(
self,
provider: Provider = None,
name: str = None,
description: str = None,
online_date: datetime.datetime = None,
backend_version: str = None,
provider: Provider | None = None,
name: str | None = None,
description: str | None = None,
online_date: datetime.datetime | None = None,
backend_version: str | None = None,
**fields,
):
"""Initialize a BackendV2 based backend
Expand Down Expand Up @@ -373,17 +377,17 @@ def __init__(
self._coupling_map = None

@property
def instructions(self) -> List[Tuple[Instruction, Tuple[int]]]:
def instructions(self) -> list[tuple[Instruction, tuple[int, ...]]]:
"""A list of Instruction tuples on the backend of the form ``(instruction, (qubits)``"""
return self.target.instructions

@property
def operations(self) -> List[Instruction]:
def operations(self) -> list[Instruction]:
"""A list of :class:`~qiskit.circuit.Instruction` instances that the backend supports."""
return list(self.target.operations)

@property
def operation_names(self) -> List[str]:
def operation_names(self) -> list[str]:
"""A list of instruction names that the backend supports."""
return list(self.target.operation_names)

Expand Down Expand Up @@ -440,7 +444,7 @@ def _default_options(cls):
pass

@property
def dt(self) -> Union[float, None]:
def dt(self) -> float | None:
"""Return the system time resolution of input signals
This is required to be implemented if the backend supports Pulse
Expand All @@ -466,7 +470,7 @@ def dtm(self) -> float:
raise NotImplementedError

@property
def meas_map(self) -> List[List[int]]:
def meas_map(self) -> list[list[int]]:
"""Return the grouping of measurements which are multiplexed
This is required to be implemented if the backend supports Pulse
Expand All @@ -487,9 +491,7 @@ def instruction_schedule_map(self):
instructions defined in this backend's target."""
return self.target.instruction_schedule_map()

def qubit_properties(
self, qubit: Union[int, List[int]]
) -> Union[QubitProperties, List[QubitProperties]]:
def qubit_properties(self, qubit: int | list[int]) -> QubitProperties | list[QubitProperties]:
"""Return QubitProperties for a given qubit.
If there are no defined or the backend doesn't support querying these
Expand Down
32 changes: 19 additions & 13 deletions qiskit/providers/backend_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@

from __future__ import annotations
import logging
from typing import List, Iterable, Any, Dict, Optional, Tuple
import typing
from collections.abc import Iterable
from typing import Any

from qiskit.providers.backend import BackendV1, BackendV2
from qiskit.providers.backend import QubitProperties
Expand All @@ -25,17 +27,21 @@
from qiskit.providers.options import Options
from qiskit.providers.exceptions import BackendPropertyError

if typing.TYPE_CHECKING:
from qiskit.pulse import Instruction
from qiskit.transpiler.target import Target

logger = logging.getLogger(__name__)


def convert_to_target(
configuration: BackendConfiguration,
properties: BackendProperties = None,
defaults: PulseDefaults = None,
custom_name_mapping: Optional[Dict[str, Any]] = None,
properties: BackendProperties | None = None,
defaults: PulseDefaults | None = None,
custom_name_mapping: dict[str, Any] | None = None,
add_delay: bool = True,
filter_faulty: bool = True,
):
) -> Target:
"""Decode transpiler target from backend data set.

This function generates ``Target`` instance from intermediate
Expand Down Expand Up @@ -95,8 +101,8 @@ def convert_to_target(
# Create instruction property placeholder from backend configuration
basis_gates = set(getattr(configuration, "basis_gates", []))
gate_configs = {gate.name: gate for gate in configuration.gates}
inst_name_map = {} # type: Dict[str, Instruction]
prop_name_map = {} # type: Dict[str, Dict[Tuple[int, ...], InstructionProperties]]
inst_name_map: dict[str, Instruction] = {}
prop_name_map: dict[str, dict[tuple[int, ...], InstructionProperties]] = {}
all_instructions = set.union(basis_gates, set(required))

faulty_ops = set()
Expand Down Expand Up @@ -268,11 +274,11 @@ def convert_to_target(

def qubit_props_list_from_props(
properties: BackendProperties,
) -> List[QubitProperties]:
) -> list[QubitProperties]:
"""Uses BackendProperties to construct
and return a list of QubitProperties.
"""
qubit_props: List[QubitProperties] = []
qubit_props: list[QubitProperties] = []
for qubit, _ in enumerate(properties.qubits):
try:
t_1 = properties.t1(qubit)
Expand Down Expand Up @@ -324,7 +330,7 @@ class should only be used if you need a :class:`~.BackendV2` and still need
def __init__(
self,
backend: BackendV1,
name_mapping: Optional[Dict[str, Any]] = None,
name_mapping: dict[str, Any] | None = None,
add_delay: bool = True,
filter_faulty: bool = True,
):
Expand Down Expand Up @@ -364,13 +370,13 @@ def __init__(
if hasattr(self._backend, "defaults"):
self._defaults = self._backend.defaults()

self._target = None
self._target: Target | None = None
self._name_mapping = name_mapping
self._add_delay = add_delay
self._filter_faulty = filter_faulty

@property
def target(self):
def target(self) -> Target:
"""A :class:`qiskit.transpiler.Target` object for the backend.

:rtype: Target
Expand Down Expand Up @@ -399,7 +405,7 @@ def dtm(self) -> float:
return self._config.dtm

@property
def meas_map(self) -> List[List[int]]:
def meas_map(self) -> list[list[int]]:
return self._config.meas_map

def drive_channel(self, qubit: int):
Expand Down
6 changes: 4 additions & 2 deletions qiskit/providers/basicaer/basicaertools.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,21 @@
"""Contains functions used by the basic aer simulators.
"""
from __future__ import annotations

from string import ascii_uppercase, ascii_lowercase
from typing import List, Optional

import numpy as np

import qiskit.circuit.library.standard_gates as gates
from qiskit.circuit import Gate
from qiskit.exceptions import QiskitError

# Single qubit gates supported by ``single_gate_params``.
SINGLE_QUBIT_GATES = ("U", "u", "h", "p", "u1", "u2", "u3", "rz", "sx", "x")


def single_gate_matrix(gate: str, params: Optional[List[float]] = None):
def single_gate_matrix(gate: str, params: list[float] | None = None):
"""Get the matrix for a single qubit.
Args:
Expand All @@ -41,6 +42,7 @@ def single_gate_matrix(gate: str, params: Optional[List[float]] = None):
if params is None:
params = []

gc: type[Gate]
if gate == "U":
gc = gates.UGate
elif gate == "u3":
Expand Down
10 changes: 5 additions & 5 deletions qiskit/providers/fake_provider/fake_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@
"""
Base class for dummy backends.
"""
from __future__ import annotations

import warnings
import collections
import json
import os
import re

from typing import List, Iterable
from collections.abc import Iterable

from qiskit import circuit
from qiskit.providers.models import BackendProperties, BackendConfiguration, PulseDefaults
Expand All @@ -42,7 +42,7 @@


class _Credentials:
def __init__(self, token="123456", url="https://"):
def __init__(self, token: str = "123456", url: str = "https://"):
self.token = token
self.url = url
self.hub = "hub"
Expand Down Expand Up @@ -98,7 +98,7 @@ def _parse_channels(self, channels):
}
identifier_pattern = re.compile(r"\D+(?P<index>\d+)")

channels_map = {
channels_map: dict[str, dict[tuple, list]] = {
"acquire": collections.defaultdict(list),
"drive": collections.defaultdict(list),
"measure": collections.defaultdict(list),
Expand Down Expand Up @@ -220,7 +220,7 @@ def dtm(self) -> float:
return None

@property
def meas_map(self) -> List[List[int]]:
def meas_map(self) -> list[list[int]]:
"""Return the grouping of measurements which are multiplexed
This is required to be implemented if the backend supports Pulse
scheduling.
Expand Down
7 changes: 4 additions & 3 deletions qiskit/providers/fake_provider/fake_qasm_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"""
Fake backend abstract class for mock backends.
"""
from __future__ import annotations

import json
import os
Expand All @@ -30,15 +31,15 @@
class FakeQasmBackend(FakeBackend):
"""A fake OpenQASM backend."""

dirname = None
dirname: str = None
conf_filename = None
props_filename = None
backend_name = None

def __init__(self):
configuration = self._get_conf_from_json()
self._defaults = None
self._properties = None
self._properties: BackendProperties | None = None
super().__init__(configuration)

def properties(self):
Expand All @@ -63,7 +64,7 @@ def _set_props_from_json(self):
decode_backend_properties(props)
self._properties = BackendProperties.from_dict(props)

def _load_json(self, filename):
def _load_json(self, filename) -> dict:
with open(os.path.join(self.dirname, filename)) as f_json:
the_json = json.load(f_json)
return the_json
Expand Down
14 changes: 11 additions & 3 deletions qiskit/providers/fake_provider/utils/backend_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
Utilities for constructing Target object from configuration, properties and
pulse defaults json files
"""
from __future__ import annotations

from collections.abc import Mapping
from typing import Any

from qiskit.transpiler.target import Target, InstructionProperties
from qiskit.providers.backend import QubitProperties
Expand All @@ -27,7 +31,11 @@
from qiskit.providers.models.pulsedefaults import PulseDefaults


def convert_to_target(conf_dict: dict, props_dict: dict = None, defs_dict: dict = None) -> Target:
def convert_to_target(
conf_dict: Mapping[str, Any],
props_dict: Mapping[str, Any] | None = None,
defs_dict: Mapping[str, Any] | None = None,
) -> Target:
"""Uses configuration, properties and pulse defaults dicts
to construct and return Target class.
"""
Expand All @@ -47,7 +55,7 @@ def convert_to_target(conf_dict: dict, props_dict: dict = None, defs_dict: dict
# Parse from properties if it exsits
if props_dict is not None:
# Parse instructions
gates = {}
gates: dict[str, dict[tuple, InstructionProperties]] = {}
for gate in props_dict["gates"]:
name = gate["gate"]
if name in name_mapping:
Expand Down Expand Up @@ -132,7 +140,7 @@ def convert_to_target(conf_dict: dict, props_dict: dict = None, defs_dict: dict
return target


def qubit_props_from_props(properties: dict) -> list:
def qubit_props_from_props(properties: dict) -> list[QubitProperties]:
"""Returns a dictionary of `qiskit.providers.backend.QubitProperties` using
a backend properties dictionary created by loading props.json payload.
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
# that they have been altered from the originals.

"""Configurable backend."""
from __future__ import annotations

import itertools
from datetime import datetime
from typing import Optional, List, Union
Expand Down Expand Up @@ -38,7 +40,7 @@ def __init__(
self,
name: str,
n_qubits: int,
version: Optional[str] = None,
version: str | None = None,
coupling_map: Optional[List[List[int]]] = None,
basis_gates: Optional[List[str]] = None,
qubit_t1: Optional[Union[float, List[float]]] = None,
Expand Down
Loading