Skip to content

Commit

Permalink
Fix transpiler mypy errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Randl committed Dec 31, 2023
1 parent a9b3881 commit 6a2329b
Show file tree
Hide file tree
Showing 56 changed files with 352 additions and 249 deletions.
2 changes: 1 addition & 1 deletion qiskit/transpiler/basepasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def execute(
self,
passmanager_ir: PassManagerIR,
state: PassManagerState,
callback: Callable = None,
callback: Callable | None = None,
) -> tuple[PassManagerIR, PassManagerState]:
new_dag, state = super().execute(
passmanager_ir=passmanager_ir,
Expand Down
30 changes: 17 additions & 13 deletions qiskit/transpiler/coupling.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@
CNOT gates. The object has a distance function that can be used to map quantum circuits
onto a device with this coupling.
"""
from __future__ import annotations

import math
from typing import List
from collections.abc import Sequence

import numpy as np
import rustworkx as rx
from rustworkx.visualization import graphviz_draw

Expand All @@ -46,7 +48,9 @@ class CouplingMap:
"_is_symmetric",
)

def __init__(self, couplinglist=None, description=None):
def __init__(
self, couplinglist: Sequence[Sequence[int]] | None = None, description: str | None = None
):
"""
Create coupling graph. By default, the generated coupling has no nodes.
Expand All @@ -61,23 +65,23 @@ def __init__(self, couplinglist=None, description=None):
# the coupling map graph
self.graph = rx.PyDiGraph()
# a dict of dicts from node pairs to distances
self._dist_matrix = None
self._dist_matrix: np.ndarray | None = None
# a sorted list of physical qubits (integers) in this coupling map
self._qubit_list = None
# number of qubits in the graph
self._size = None
self._size: int | None = None
self._is_symmetric = None

if couplinglist is not None:
self.graph.extend_from_edge_list([tuple(x) for x in couplinglist])

def size(self):
def size(self) -> int:
"""Return the number of physical qubits in this graph."""
if self._size is None:
self._size = len(self.graph)
return self._size

def get_edges(self):
def get_edges(self) -> list[tuple[int, int]]:
"""
Gets the list of edges in the coupling graph.
Expand Down Expand Up @@ -108,7 +112,7 @@ def add_physical_qubit(self, physical_qubit):
self._qubit_list = None # invalidate
self._size = None # invalidate

def add_edge(self, src, dst):
def add_edge(self, src: int, dst: int):
"""
Add directed edge to coupling graph.
Expand All @@ -130,7 +134,7 @@ def physical_qubits(self):
self._qubit_list = self.graph.node_indexes()
return self._qubit_list

def is_connected(self):
def is_connected(self) -> bool:
"""
Test if the graph is connected.
Expand All @@ -150,7 +154,7 @@ def neighbors(self, physical_qubit):
return self.graph.neighbors(physical_qubit)

@property
def distance_matrix(self):
def distance_matrix(self) -> np.ndarray:
"""Return the distance matrix for the coupling map.
For any qubits where there isn't a path available between them the value
Expand All @@ -174,7 +178,7 @@ def compute_distance_matrix(self):
self.graph, as_undirected=True, null_value=math.inf
)

def distance(self, physical_qubit1, physical_qubit2):
def distance(self, physical_qubit1: int, physical_qubit2: int) -> int:
"""Returns the undirected distance between physical_qubit1 and physical_qubit2.
Args:
Expand Down Expand Up @@ -251,7 +255,7 @@ def _check_symmetry(self):
"""
return self.graph.is_symmetric()

def reduce(self, mapping, check_if_connected=True):
def reduce(self, mapping: list[int], check_if_connected=True):
"""Returns a reduced coupling map that
corresponds to the subgraph of qubits
selected in the mapping.
Expand All @@ -269,7 +273,7 @@ def reduce(self, mapping, check_if_connected=True):
CouplingError: Reduced coupling map must be connected.
"""

inv_map = [None] * (max(mapping) + 1)
inv_map: list[int] = [None] * (max(mapping) + 1)
for idx, val in enumerate(mapping):
inv_map[val] = idx

Expand Down Expand Up @@ -401,7 +405,7 @@ def largest_connected_component(self):
"""Return a set of qubits in the largest connected component."""
return max(rx.weakly_connected_components(self.graph), key=len)

def connected_components(self) -> List["CouplingMap"]:
def connected_components(self) -> list["CouplingMap"]:
"""Separate a :Class:`~.CouplingMap` into subgraph :class:`~.CouplingMap`
for each connected component.
Expand Down
13 changes: 8 additions & 5 deletions qiskit/transpiler/instruction_durations.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@

"""Durations of instructions, one of transpiler configurations."""
from __future__ import annotations
from typing import Optional, List, Tuple, Union, Iterable

from typing import Iterable, Optional, Tuple, List, Union

import qiskit.circuit
from qiskit.circuit import Barrier, Delay
Expand All @@ -36,7 +37,9 @@ class InstructionDurations:
"""

def __init__(
self, instruction_durations: "InstructionDurationsType" | None = None, dt: float = None
self,
instruction_durations: "InstructionDurationsType" | None = None,
dt: float | None = None,
):
self.duration_by_name: dict[str, tuple[float, str]] = {}
self.duration_by_name_qubits: dict[tuple[str, tuple[int, ...]], tuple[float, str]] = {}
Expand Down Expand Up @@ -96,7 +99,7 @@ def from_backend(cls, backend: Backend):

return InstructionDurations(instruction_durations, dt=dt)

def update(self, inst_durations: "InstructionDurationsType" | None, dt: float = None):
def update(self, inst_durations: "InstructionDurationsType" | None, dt: float | None = None):
"""Update self with inst_durations (inst_durations overwrite self).
Args:
Expand Down Expand Up @@ -165,7 +168,7 @@ def update(self, inst_durations: "InstructionDurationsType" | None, dt: float =
def get(
self,
inst: str | qiskit.circuit.Instruction,
qubits: int | list[int],
qubits: int | Iterable[int],
unit: str = "dt",
parameters: list[float] | None = None,
) -> float:
Expand Down Expand Up @@ -208,7 +211,7 @@ def get(
def _get(
self,
name: str,
qubits: list[int],
qubits: Iterable[int],
to_unit: str,
parameters: Iterable[float] | None = None,
) -> float:
Expand Down
19 changes: 9 additions & 10 deletions qiskit/transpiler/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
Physical (qu)bits are integers.
"""
from __future__ import annotations
from typing import List
from dataclasses import dataclass

from qiskit import circuit
Expand All @@ -36,8 +35,8 @@ def __init__(self, input_dict=None):
"""construct a Layout from a bijective dictionary, mapping
virtual qubits to physical qubits"""
self._regs = []
self._p2v = {}
self._v2p = {}
self._p2v: dict[int, circuit.Qubit] = {}
self._v2p: dict[circuit.Qubit, int] = {}
if input_dict is not None:
if not isinstance(input_dict, dict):
raise LayoutError("Layout constructor takes a dict")
Expand Down Expand Up @@ -202,14 +201,14 @@ def get_registers(self):
"""
return set(self._regs)

def get_virtual_bits(self):
def get_virtual_bits(self) -> dict[circuit.Qubit, int]:
"""
Returns the dictionary where the keys are virtual (qu)bits and the
values are physical (qu)bits.
"""
return self._v2p

def get_physical_bits(self):
def get_physical_bits(self) -> dict[int, circuit.Qubit]:
"""
Returns the dictionary where the keys are physical (qu)bits and the
values are virtual (qu)bits.
Expand Down Expand Up @@ -479,7 +478,7 @@ class TranspileLayout:
input_qubit_mapping: dict[circuit.Qubit, int]
final_layout: Layout | None = None
_input_qubit_count: int | None = None
_output_qubit_list: List[Qubit] | None = None
_output_qubit_list: list[Qubit] | None = None

def initial_virtual_layout(self, filter_ancillas: bool = False) -> Layout:
"""Return a :class:`.Layout` object for the initial layout.
Expand All @@ -506,7 +505,7 @@ def initial_virtual_layout(self, filter_ancillas: bool = False) -> Layout:
}
)

def initial_index_layout(self, filter_ancillas: bool = False) -> List[int]:
def initial_index_layout(self, filter_ancillas: bool = False) -> list[int]:
"""Generate an initial layout as an array of integers
Args:
Expand All @@ -520,7 +519,7 @@ def initial_index_layout(self, filter_ancillas: bool = False) -> List[int]:

virtual_map = self.initial_layout.get_virtual_bits()
if filter_ancillas:
output = [None] * self._input_qubit_count
output: list[int | None] = [None] * self._input_qubit_count
else:
output = [None] * len(virtual_map)
for index, (virt, phys) in enumerate(virtual_map.items()):
Expand All @@ -530,7 +529,7 @@ def initial_index_layout(self, filter_ancillas: bool = False) -> List[int]:
output[pos] = phys
return output

def routing_permutation(self) -> List[int]:
def routing_permutation(self) -> list[int]:
"""Generate a final layout as an array of integers
If there is no :attr:`.final_layout` attribute present then that indicates
Expand All @@ -547,7 +546,7 @@ def routing_permutation(self) -> List[int]:
virtual_map = self.final_layout.get_virtual_bits()
return [virtual_map[virt] for virt in self._output_qubit_list]

def final_index_layout(self, filter_ancillas: bool = True) -> List[int]:
def final_index_layout(self, filter_ancillas: bool = True) -> list[int]:
"""Generate the final layout as an array of integers
This method will generate an array of final positions for each qubit in the output circuit.
Expand Down
12 changes: 10 additions & 2 deletions qiskit/transpiler/passes/basis/basis_translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@


"""Translates gates to a target basis using a given equivalence library."""
from __future__ import annotations

import time
import logging
Expand All @@ -21,6 +22,7 @@
from collections import defaultdict

import rustworkx
from qiskit.transpiler import Target

from qiskit.circuit import (
Gate,
Expand Down Expand Up @@ -102,7 +104,13 @@ class BasisTranslator(TransformationPass):
:ref:`custom_basis_gates` for details on adding custom equivalence rules.
"""

def __init__(self, equivalence_library, target_basis, target=None, min_qubits=0):
def __init__(
self,
equivalence_library,
target_basis: list[str],
target: Target | None = None,
min_qubits=0,
):
"""Initialize a BasisTranslator instance.
Args:
Expand All @@ -120,7 +128,7 @@ def __init__(self, equivalence_library, target_basis, target=None, min_qubits=0)
self._target_basis = target_basis
self._target = target
self._non_global_operations = None
self._qargs_with_non_global_operation = {}
self._qargs_with_non_global_operation: dict[tuple, set[str]] = {}
self._min_qubits = min_qubits
if target is not None:
self._non_global_operations = self._target.get_non_global_operation_names()
Expand Down
6 changes: 4 additions & 2 deletions qiskit/transpiler/passes/basis/decompose.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
# that they have been altered from the originals.

"""Expand a gate in a circuit using its decomposition rules."""
from typing import Type, Union, List, Optional
from __future__ import annotations

from collections.abc import Sequence
from fnmatch import fnmatch

from qiskit.transpiler.basepasses import TransformationPass
Expand All @@ -25,7 +27,7 @@ class Decompose(TransformationPass):

def __init__(
self,
gates_to_decompose: Optional[Union[Type[Gate], List[Type[Gate]], List[str], str]] = None,
gates_to_decompose: type[Gate] | Sequence[type[Gate]] | Sequence[str] | str | None = None,
) -> None:
"""Decompose initializer.
Expand Down
11 changes: 5 additions & 6 deletions qiskit/transpiler/passes/calibration/pulse_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
# that they have been altered from the originals.

"""Instruction schedule map reference pass."""

from typing import List, Union
from __future__ import annotations

from qiskit.circuit import Instruction as CircuitInst
from qiskit.pulse import Schedule, ScheduleBlock
Expand Down Expand Up @@ -49,8 +48,8 @@ class PulseGates(CalibrationBuilder):

def __init__(
self,
inst_map: InstructionScheduleMap = None,
target: Target = None,
inst_map: InstructionScheduleMap | None = None,
target: Target | None = None,
):
"""Create new pass.
Expand All @@ -70,7 +69,7 @@ def __init__(
target.update_from_instruction_schedule_map(inst_map)
self.target = target

def supported(self, node_op: CircuitInst, qubits: List) -> bool:
def supported(self, node_op: CircuitInst, qubits: list) -> bool:
"""Determine if a given node supports the calibration.
Args:
Expand All @@ -82,7 +81,7 @@ def supported(self, node_op: CircuitInst, qubits: List) -> bool:
"""
return self.target.has_calibration(node_op.name, tuple(qubits))

def get_calibration(self, node_op: CircuitInst, qubits: List) -> Union[Schedule, ScheduleBlock]:
def get_calibration(self, node_op: CircuitInst, qubits: list) -> Schedule | ScheduleBlock:
"""Gets the calibrated schedule for the given instruction and qubits.
Args:
Expand Down
6 changes: 3 additions & 3 deletions qiskit/transpiler/passes/calibration/rx_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
# that they have been altered from the originals.

"""Add single-pulse RX calibrations that are bootstrapped from the SX calibration."""
from __future__ import annotations

from typing import Union
from functools import lru_cache
import numpy as np

Expand Down Expand Up @@ -77,7 +77,7 @@ class RXCalibrationBuilder(CalibrationBuilder):

def __init__(
self,
target: Target = None,
target: Target | None = None,
):
"""Bootstrap single-pulse RX gate calibrations from the
(hardware-calibrated) SX gate calibration.
Expand Down Expand Up @@ -109,7 +109,7 @@ def supported(self, node_op: Instruction, qubits: list) -> bool:
== "Drag"
)

def get_calibration(self, node_op: Instruction, qubits: list) -> Union[Schedule, ScheduleBlock]:
def get_calibration(self, node_op: Instruction, qubits: list) -> Schedule | ScheduleBlock:
"""
Generate RX calibration for the rotation angle specified in node_op.
"""
Expand Down
4 changes: 2 additions & 2 deletions qiskit/transpiler/passes/calibration/rzx_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,9 @@ class RZXCalibrationBuilder(CalibrationBuilder):

def __init__(
self,
instruction_schedule_map: InstructionScheduleMap = None,
instruction_schedule_map: InstructionScheduleMap | None = None,
verbose: bool = True,
target: Target = None,
target: Target | None = None,
):
"""
Initializes a RZXGate calibration builder.
Expand Down

0 comments on commit 6a2329b

Please sign in to comment.