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 transpiler mypy errors #11468

Open
wants to merge 5 commits 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions qiskit/synthesis/unitary/aqc/approximate.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"""Base classes for an approximate circuit definition."""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Optional, SupportsFloat
from typing import SupportsFloat
import numpy as np

from qiskit.circuit.quantumcircuit import QuantumCircuit
Expand All @@ -21,7 +21,7 @@
class ApproximateCircuit(QuantumCircuit, ABC):
"""A base class that represents an approximate circuit."""

def __init__(self, num_qubits: int, name: Optional[str] = None) -> None:
def __init__(self, num_qubits: int, name: str | None = None) -> None:
"""
Args:
num_qubits: number of qubit this circuit will span.
Expand Down
5 changes: 2 additions & 3 deletions qiskit/synthesis/unitary/aqc/cnot_unit_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
to be parametrized and used for approximate compiling optimization.
"""
from __future__ import annotations
from typing import Optional

import numpy as np

Expand All @@ -28,8 +27,8 @@ def __init__(
self,
num_qubits: int,
cnots: np.ndarray,
tol: Optional[float] = 0.0,
name: Optional[str] = None,
tol: float | None = 0.0,
name: str | None = None,
) -> None:
"""
Args:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
Utility functions in the fast gradient implementation.
"""
from __future__ import annotations
from typing import Union
import numpy as np


Expand All @@ -36,7 +35,7 @@ def is_permutation(x: np.ndarray) -> bool:
)


def reverse_bits(x: Union[int, np.ndarray], nbits: int, enable: bool) -> Union[int, np.ndarray]:
def reverse_bits(x: int | np.ndarray, nbits: int, enable: bool) -> int | np.ndarray:
"""
Reverses the bit order in a number of ``nbits`` length.
If ``x`` is an array, then operation is applied to every entry.
Expand Down
5 changes: 2 additions & 3 deletions qiskit/synthesis/unitary/aqc/fast_gradient/layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
"""
from __future__ import annotations
from abc import abstractmethod, ABC
from typing import Optional
import numpy as np
from .fast_grad_utils import (
bit_permutation_1q,
Expand Down Expand Up @@ -62,7 +61,7 @@ class Layer1Q(LayerBase):
interleaves with the identity ones.
"""

def __init__(self, num_qubits: int, k: int, g2x2: Optional[np.ndarray] = None):
def __init__(self, num_qubits: int, k: int, g2x2: np.ndarray | None = None):
"""
Args:
num_qubits: number of qubits.
Expand Down Expand Up @@ -102,7 +101,7 @@ class Layer2Q(LayerBase):
interleaves with the identity ones.
"""

def __init__(self, num_qubits: int, j: int, k: int, g4x4: Optional[np.ndarray] = None):
def __init__(self, num_qubits: int, j: int, k: int, g4x4: np.ndarray | None = None):
"""
Args:
num_qubits: number of qubits.
Expand Down
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 cls(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
25 changes: 12 additions & 13 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 @@ -368,7 +367,7 @@ def from_qubit_list(qubit_list, *qregs):
out.add_register(qreg)
return out

def compose(self, other: Layout, qubits: List[Qubit]) -> Layout:
def compose(self, other: Layout, qubits: list[Qubit]) -> Layout:
"""Compose this layout with another layout.

If this layout represents a mapping from the P-qubits to the positions of the Q-qubits,
Expand All @@ -388,7 +387,7 @@ def compose(self, other: Layout, qubits: List[Qubit]) -> Layout:
other_v2p = other.get_virtual_bits()
return Layout({virt: other_v2p[qubits[phys]] for virt, phys in self._v2p.items()})

def inverse(self, source_qubits: List[Qubit], target_qubits: List[Qubit]):
def inverse(self, source_qubits: list[Qubit], target_qubits: list[Qubit]):
"""Finds the inverse of this layout.

This is possible when the layout is a bijective mapping, however the input
Expand All @@ -415,7 +414,7 @@ def inverse(self, source_qubits: List[Qubit], target_qubits: List[Qubit]):
}
)

def to_permutation(self, qubits: List[Qubit]):
def to_permutation(self, qubits: list[Qubit]):
"""Creates a permutation corresponding to this layout.

This is possible when the layout is a bijective mapping with the same
Expand Down Expand Up @@ -551,7 +550,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 @@ -578,7 +577,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 @@ -592,7 +591,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 @@ -602,7 +601,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 @@ -618,7 +617,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 input circuit.
Expand Down