Skip to content

Commit

Permalink
Fix result mypy errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Randl committed Apr 5, 2023
1 parent c0e4141 commit 1591d70
Show file tree
Hide file tree
Showing 17 changed files with 191 additions and 158 deletions.
10 changes: 5 additions & 5 deletions qiskit/pulse/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,7 +678,7 @@ def get_context(self) -> ScheduleBlock:
"""
return self._context_stack[-1]

@property
@property # type: ignore
@_requires_backend
def num_qubits(self):
"""Get the number of qubits in the backend."""
Expand All @@ -689,7 +689,7 @@ def transpiler_settings(self) -> Mapping:
"""The builder's transpiler settings."""
return self._transpiler_settings

@transpiler_settings.setter
@transpiler_settings.setter # type: ignore
@_compile_lazy_circuit_before
def transpiler_settings(self, settings: Mapping):
self._compile_lazy_circuit()
Expand All @@ -700,7 +700,7 @@ def circuit_scheduler_settings(self) -> Mapping:
"""The builder's circuit to pulse scheduler settings."""
return self._circuit_scheduler_settings

@circuit_scheduler_settings.setter
@circuit_scheduler_settings.setter # type: ignore
@_compile_lazy_circuit_before
def circuit_scheduler_settings(self, settings: Mapping):
self._compile_lazy_circuit()
Expand Down Expand Up @@ -907,7 +907,7 @@ def _(
)

@_requires_backend
def call_gate(self, gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True):
def call_gate(self, gate: circuit.Gate, qubits: Union[int, Tuple[int, ...]], lazy: bool = True):
"""Call the circuit ``gate`` in the pulse program.
The qubits are assumed to be defined on physical qubits.
Expand Down Expand Up @@ -2528,7 +2528,7 @@ def delay_qubits(duration: int, *qubits: Union[int, Iterable[int]]):


# Gate instructions
def call_gate(gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True):
def call_gate(gate: circuit.Gate, qubits: Union[int, Tuple[int, ...]], lazy: bool = True):
"""Call a gate and lazily schedule it to its corresponding
pulse instruction.
Expand Down
28 changes: 15 additions & 13 deletions qiskit/pulse/calibration_entries.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@
# that they have been altered from the originals.

"""Internal format of calibration data in target."""
from __future__ import annotations
import inspect
from abc import ABCMeta, abstractmethod
from collections.abc import Sequence, Callable
from enum import IntEnum
from typing import Callable, List, Union, Optional, Sequence, Any
from typing import Any

from qiskit.pulse.exceptions import PulseError
from qiskit.pulse.schedule import Schedule, ScheduleBlock
Expand Down Expand Up @@ -79,7 +81,7 @@ def get_signature(self) -> inspect.Signature:
pass

@abstractmethod
def get_schedule(self, *args, **kwargs) -> Union[Schedule, ScheduleBlock]:
def get_schedule(self, *args, **kwargs) -> Schedule | ScheduleBlock:
"""Generate schedule from entry definition.
If the pulse program is templated with :class:`.Parameter` objects,
Expand Down Expand Up @@ -114,7 +116,7 @@ class ScheduleDef(CalibrationEntry):
"""

def __init__(self, arguments: Optional[Sequence[str]] = None):
def __init__(self, arguments: Sequence[str] | None = None):
"""Define an empty entry.
Args:
Expand All @@ -129,9 +131,9 @@ def __init__(self, arguments: Optional[Sequence[str]] = None):
arguments = list(arguments)
self._user_arguments = arguments

self._definition = None
self._definition: Callable | Schedule | None = None
self._signature = None
self._user_provided = None
self._user_provided: bool | None = None

@property
def user_provided(self) -> bool:
Expand Down Expand Up @@ -168,7 +170,7 @@ def _parse_argument(self):

def define(
self,
definition: Union[Schedule, ScheduleBlock],
definition: Schedule | ScheduleBlock,
user_provided: bool = True,
):
self._definition = definition
Expand All @@ -178,7 +180,7 @@ def define(
def get_signature(self) -> inspect.Signature:
return self._signature

def get_schedule(self, *args, **kwargs) -> Union[Schedule, ScheduleBlock]:
def get_schedule(self, *args, **kwargs) -> Schedule | ScheduleBlock:
if not args and not kwargs:
out = self._definition
else:
Expand Down Expand Up @@ -252,7 +254,7 @@ def define(
def get_signature(self) -> inspect.Signature:
return self._signature

def get_schedule(self, *args, **kwargs) -> Union[Schedule, ScheduleBlock]:
def get_schedule(self, *args, **kwargs) -> Schedule | ScheduleBlock:
try:
# Python function doesn't allow partial bind, but default value can exist.
to_bind = self._signature.bind(*args, **kwargs)
Expand Down Expand Up @@ -294,9 +296,9 @@ class PulseQobjDef(ScheduleDef):

def __init__(
self,
arguments: Optional[Sequence[str]] = None,
converter: Optional[QobjToInstructionConverter] = None,
name: Optional[str] = None,
arguments: Sequence[str] | None = None,
converter: QobjToInstructionConverter | None = None,
name: str | None = None,
):
"""Define an empty entry.
Expand All @@ -322,7 +324,7 @@ def _build_schedule(self):

def define(
self,
definition: List[PulseQobjInstruction],
definition: list[PulseQobjInstruction],
user_provided: bool = False,
):
# This doesn't generate signature immediately, because of lazy schedule build.
Expand All @@ -334,7 +336,7 @@ def get_signature(self) -> inspect.Signature:
self._build_schedule()
return super().get_signature()

def get_schedule(self, *args, **kwargs) -> Union[Schedule, ScheduleBlock]:
def get_schedule(self, *args, **kwargs) -> Schedule | ScheduleBlock:
if self._definition is None:
self._build_schedule()
return super().get_schedule(*args, **kwargs)
Expand Down
14 changes: 9 additions & 5 deletions qiskit/pulse/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,13 @@
.. autoclass:: Channel
"""
from __future__ import annotations
from abc import ABCMeta
from typing import Any, Set, Union
from typing import Any

import numpy as np

from qiskit.circuit import Parameter
from qiskit.circuit.parameterexpression import ParameterExpression
from qiskit.pulse.exceptions import PulseError

Expand All @@ -75,7 +77,7 @@ class Channel(metaclass=ABCMeta):
for the ``prefix`` class attribute.
"""

prefix = None # type: Optional[str]
prefix: str | None = None
"""A shorthand string prefix for characterizing the channel type."""

# pylint: disable=unused-argument
Expand All @@ -99,7 +101,7 @@ def __init__(self, index: int):
self._hash = hash((self.__class__.__name__, self._index))

@property
def index(self) -> Union[int, ParameterExpression]:
def index(self) -> int | ParameterExpression:
"""Return the index of this channel. The index is a label for a control signal line
typically mapped trivially to a qubit index. For instance, ``DriveChannel(0)`` labels
the signal line driving the qubit labeled with index 0.
Expand All @@ -125,7 +127,7 @@ def _validate_index(self, index: Any) -> None:
raise PulseError("Channel index must be a nonnegative integer")

@property
def parameters(self) -> Set:
def parameters(self) -> set[Parameter]:
"""Parameters which determine the channel index."""
if isinstance(self.index, ParameterExpression):
return self.index.parameters
Expand All @@ -143,7 +145,7 @@ def name(self) -> str:
def __repr__(self):
return f"{self.__class__.__name__}({self._index})"

def __eq__(self, other: "Channel") -> bool:
def __eq__(self, other: object) -> bool:
"""Return True iff self and other are equal, specifically, iff they have the same type
and the same index.
Expand All @@ -153,6 +155,8 @@ def __eq__(self, other: "Channel") -> bool:
Returns:
True iff equal.
"""
if not isinstance(other, Channel):
return NotImplemented
return type(self) is type(other) and self._index == other._index

def __hash__(self):
Expand Down
33 changes: 18 additions & 15 deletions qiskit/pulse/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@
"""
Configurations for pulse experiments.
"""
from typing import Dict, Union, Tuple, Optional
from __future__ import annotations

from .channels import PulseChannel, DriveChannel, MeasureChannel
from .channels import DriveChannel, MeasureChannel
from .exceptions import PulseError


Expand All @@ -24,7 +24,7 @@ class Kernel:
into IQ points.
"""

def __init__(self, name: Optional[str] = None, **params):
def __init__(self, name: str | None = None, **params):
"""Create new kernel.
Args:
Expand All @@ -47,7 +47,7 @@ class Discriminator:
into 0/1 state results.
"""

def __init__(self, name: Optional[str] = None, **params):
def __init__(self, name: str | None = None, **params):
"""Create new discriminator.
Args:
Expand Down Expand Up @@ -118,8 +118,8 @@ class LoConfig:

def __init__(
self,
channel_los: Optional[Dict[PulseChannel, float]] = None,
lo_ranges: Optional[Dict[PulseChannel, Union[LoRange, Tuple[int]]]] = None,
channel_los: dict[DriveChannel | MeasureChannel, float] | None = None,
lo_ranges: dict[DriveChannel | MeasureChannel, LoRange | tuple[int]] | None = None,
):
"""Lo channel configuration data structure.
Expand All @@ -131,9 +131,9 @@ def __init__(
PulseError: If channel is not configurable or set lo is out of range.
"""
self._q_lo_freq = {}
self._m_lo_freq = {}
self._lo_ranges = {}
self._q_lo_freq: dict[DriveChannel, float] = {}
self._m_lo_freq: dict[MeasureChannel, float] = {}
self._lo_ranges: dict[DriveChannel, LoRange] = {}

lo_ranges = lo_ranges if lo_ranges else {}
for channel, freq in lo_ranges.items():
Expand All @@ -143,7 +143,7 @@ def __init__(
for channel, freq in channel_los.items():
self.add_lo(channel, freq)

def add_lo(self, channel: Union[DriveChannel, MeasureChannel], freq: float):
def add_lo(self, channel: DriveChannel | MeasureChannel, freq: float):
"""Add a lo mapping for a channel."""
if isinstance(channel, DriveChannel):
# add qubit_lo_freq
Expand All @@ -156,7 +156,7 @@ def add_lo(self, channel: Union[DriveChannel, MeasureChannel], freq: float):
else:
raise PulseError("Specified channel %s cannot be configured." % channel.name)

def add_lo_range(self, channel: DriveChannel, lo_range: Union[LoRange, Tuple[int]]):
def add_lo_range(self, channel: DriveChannel, lo_range: LoRange | tuple[int]):
"""Add lo range to configuration.
Args:
Expand All @@ -168,22 +168,25 @@ def add_lo_range(self, channel: DriveChannel, lo_range: Union[LoRange, Tuple[int
lo_range = LoRange(*lo_range)
self._lo_ranges[channel] = lo_range

def check_lo(self, channel: Union[DriveChannel, MeasureChannel], freq: float) -> bool:
def check_lo(self, channel: DriveChannel | MeasureChannel, freq: float) -> bool:
"""Check that lo is valid for channel.
Args:
channel: Channel to validate lo for
freq: lo frequency
Raises:
PulseError: If freq is outside of channels range
Returns:
True if lo is valid for channel
"""
lo_ranges = self._lo_ranges
if channel in lo_ranges:
lo_range = lo_ranges[channel]
if not lo_range.includes(freq):
raise PulseError(f"Specified LO freq {freq:f} is out of range {lo_range}")
return True

def channel_lo(self, channel: Union[DriveChannel, MeasureChannel]) -> float:
def channel_lo(self, channel: DriveChannel | MeasureChannel) -> float:
"""Return channel lo.
Args:
Expand All @@ -204,11 +207,11 @@ def channel_lo(self, channel: Union[DriveChannel, MeasureChannel]) -> float:
raise PulseError("Channel %s is not configured" % channel)

@property
def qubit_los(self) -> Dict:
def qubit_los(self) -> dict[DriveChannel, float]:
"""Returns dictionary mapping qubit channels (DriveChannel) to los."""
return self._q_lo_freq

@property
def meas_los(self) -> Dict:
def meas_los(self) -> dict[MeasureChannel, float]:
"""Returns dictionary mapping measure channels (MeasureChannel) to los."""
return self._m_lo_freq
2 changes: 1 addition & 1 deletion qiskit/pulse/instructions/acquire.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def channel(self) -> AcquireChannel:
return self.operands[1]

@property
def channels(self) -> Tuple[Union[AcquireChannel, MemorySlot, RegisterSlot]]:
def channels(self) -> Tuple[Union[AcquireChannel, MemorySlot, RegisterSlot], ...]:
"""Returns the channels that this schedule uses."""
return tuple(self.operands[ind] for ind in (1, 2, 3) if self.operands[ind] is not None)

Expand Down
18 changes: 11 additions & 7 deletions qiskit/pulse/instructions/instruction.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
sched = Schedule()
sched += Delay(duration, channel) # Delay is a specific subclass of Instruction
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Collection
from typing import Callable, Iterable, List, Optional, Set, Tuple

from qiskit.circuit import Parameter
Expand Down Expand Up @@ -51,9 +53,9 @@ def __init__(
operands: The argument list.
name: Optional display name for this instruction.
"""
self._operands = operands
self._operands: Tuple = operands
self._name = name
self._hash = None
self._hash: int | None = None
self._validate()

def _validate(self):
Expand Down Expand Up @@ -81,7 +83,7 @@ def operands(self) -> Tuple:
"""Return instruction operands."""
return self._operands

@property
@property # type: ignore
@abstractmethod
def channels(self) -> Tuple[Channel]:
"""Returns the channels that this schedule uses."""
Expand All @@ -103,12 +105,12 @@ def duration(self) -> int:
raise NotImplementedError

@property
def _children(self) -> Tuple["Instruction"]:
def _children(self) -> Tuple["Instruction", ...]:
"""Instruction has no child nodes."""
return ()

@property
def instructions(self) -> Tuple[Tuple[int, "Instruction"]]:
def instructions(self) -> Tuple[Tuple[int, "Instruction"], ...]:
"""Iterable for getting instructions from Schedule tree."""
return tuple(self._instructions())

Expand All @@ -129,7 +131,7 @@ def ch_start_time(self, *channels: List[Channel]) -> int:
"""
return 0

def ch_stop_time(self, *channels: List[Channel]) -> int:
def ch_stop_time(self, *channels: Collection[Channel]) -> int:
"""Return maximum start time for supplied channels.
Args:
Expand Down Expand Up @@ -292,11 +294,13 @@ def draw(
image.show()
return image

def __eq__(self, other: "Instruction") -> bool:
def __eq__(self, other: object) -> bool:
"""Check if this Instruction is equal to the `other` instruction.
Equality is determined by the instruction sharing the same operands and channels.
"""
if not isinstance(other, Instruction):
return NotImplemented
return isinstance(other, type(self)) and self.operands == other.operands

def __hash__(self) -> int:
Expand Down
Loading

0 comments on commit 1591d70

Please sign in to comment.