Skip to content

Commit

Permalink
Fix circuit mypy errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Randl committed Jun 29, 2022
1 parent 1082240 commit a179720
Show file tree
Hide file tree
Showing 28 changed files with 138 additions and 104 deletions.
2 changes: 1 addition & 1 deletion qiskit/circuit/controlflow/control_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
class ControlFlowOp(Instruction, ABC):
"""Abstract class to encapsulate all control flow operations."""

@property
@property # type: ignore
@abstractmethod
def blocks(self) -> Tuple[QuantumCircuit, ...]:
"""Tuple of QuantumCircuits which may be executed as part of the
Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/controlledgate.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def __init__(
self.num_ctrl_qubits = num_ctrl_qubits
self.definition = copy.deepcopy(definition)
self._ctrl_state = None
self.ctrl_state = ctrl_state
self.ctrl_state: Optional[Union[int, str]] = ctrl_state
self._name = name

@property
Expand Down
10 changes: 5 additions & 5 deletions qiskit/circuit/gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

"""Unitary gate."""

from typing import List, Optional, Union, Tuple
from typing import List, Optional, Union, Tuple, Any, Iterator
import numpy as np

from qiskit.circuit.parameterexpression import ParameterExpression
Expand Down Expand Up @@ -52,7 +52,7 @@ def to_matrix(self) -> np.ndarray:
"""
if hasattr(self, "__array__"):
# pylint: disable=no-member
return self.__array__(dtype=complex)
return self.__array__(dtype=complex) # type: ignore[attr-defined]
raise CircuitError(f"to_matrix not defined for this {type(self)}")

def power(self, exponent: float):
Expand Down Expand Up @@ -118,7 +118,7 @@ def control(
return add_control(self, num_ctrl_qubits, label, ctrl_state)

@staticmethod
def _broadcast_single_argument(qarg: List) -> List:
def _broadcast_single_argument(qarg: List) -> Iterator[Tuple[List[Any], List[Any]]]:
"""Expands a single argument.
For example: [q[0], q[1]] -> [q[0]], [q[1]]
Expand All @@ -129,7 +129,7 @@ def _broadcast_single_argument(qarg: List) -> List:
yield [arg0], []

@staticmethod
def _broadcast_2_arguments(qarg0: List, qarg1: List) -> List:
def _broadcast_2_arguments(qarg0: List, qarg1: List) -> Iterator[Tuple[List[Any], List[Any]]]:
if len(qarg0) == len(qarg1):
# [[q[0], q[1]], [r[0], r[1]]] -> [q[0], r[0]]
# -> [q[1], r[1]]
Expand All @@ -151,7 +151,7 @@ def _broadcast_2_arguments(qarg0: List, qarg1: List) -> List:
)

@staticmethod
def _broadcast_3_or_more_args(qargs: List) -> List:
def _broadcast_3_or_more_args(qargs: List) -> Iterator[Tuple[List[Any], List[Any]]]:
if all(len(qarg) == len(qargs[0]) for qarg in qargs):
for arg in zip(*qargs):
yield list(arg), []
Expand Down
4 changes: 2 additions & 2 deletions qiskit/circuit/instructionset.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import functools
import warnings
from typing import Callable, Optional, Tuple, Union
from typing import Callable, Optional, Tuple, Union, List

from qiskit.circuit.exceptions import CircuitError
from .instruction import Instruction
Expand Down Expand Up @@ -124,7 +124,7 @@ def __init__(self, circuit_cregs=None, *, resource_requester: Optional[Callable]
CircuitError: if both ``resource_requester`` and ``circuit_cregs`` are passed. Only one
of these may be passed, and it should be ``resource_requester``.
"""
self._instructions = []
self._instructions: List[CircuitInstruction] = []
if circuit_cregs is not None:
if resource_requester is not None:
raise CircuitError("Cannot pass both 'circuit_cregs' and 'resource_requester'.")
Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/library/arithmetic/piecewise_chebyshev.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def __init__(
self._degree = degree if degree is not None else 1
self._breakpoints = breakpoints if breakpoints is not None else [0]

self._polynomials = None
self._polynomials: Optional[List[List[float]]] = None

self.num_state_qubits = num_state_qubits

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

"""Piecewise-linearly-controlled rotation."""

from typing import List, Optional
from typing import List, Optional, Union
import numpy as np

from qiskit.circuit import QuantumRegister, AncillaRegister, QuantumCircuit
Expand Down Expand Up @@ -48,8 +48,8 @@ def __init__(
self,
num_state_qubits: Optional[int] = None,
breakpoints: Optional[List[int]] = None,
slopes: Optional[List[float]] = None,
offsets: Optional[List[float]] = None,
slopes: Optional[Union[List[float], np.ndarray]] = None,
offsets: Optional[Union[List[float], np.ndarray]] = None,
basis: str = "Y",
name: str = "pw_lin",
) -> None:
Expand Down Expand Up @@ -96,7 +96,7 @@ def breakpoints(self, breakpoints: List[int]) -> None:
self._reset_registers(self.num_state_qubits)

@property
def slopes(self) -> List[int]:
def slopes(self) -> List[float]:
"""The breakpoints of the piecewise linear function.
The function is linear in the intervals ``[point_i, point_{i+1}]`` where the last
Expand Down Expand Up @@ -134,7 +134,7 @@ def offsets(self, offsets: List[float]) -> None:
self._offsets = offsets

@property
def mapped_slopes(self) -> List[float]:
def mapped_slopes(self) -> np.ndarray:
"""The slopes mapped to the internal representation.
Returns:
Expand All @@ -147,7 +147,7 @@ def mapped_slopes(self) -> List[float]:
return mapped_slopes

@property
def mapped_offsets(self) -> List[float]:
def mapped_offsets(self) -> np.ndarray:
"""The offsets mapped to the internal representation.
Returns:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"""Polynomially controlled Pauli-rotations."""

import warnings
from typing import List, Optional, Dict, Sequence
from typing import List, Optional, Dict, Tuple

from itertools import product

Expand Down Expand Up @@ -255,7 +255,7 @@ def _check_configuration(self, raise_on_failure: bool = True) -> bool:

return valid

def _get_rotation_coefficients(self) -> Dict[Sequence[int], float]:
def _get_rotation_coefficients(self) -> Dict[Tuple[int, ...], float]:
"""Compute the coefficient of each monomial.
Returns:
Expand All @@ -269,15 +269,15 @@ def _get_rotation_coefficients(self) -> Dict[Sequence[int], float]:
if 0 < sum(combination) <= self.degree:
valid_combinations += [combination]

rotation_coeffs = {control_state: 0 for control_state in valid_combinations}
rotation_coeffs = {control_state: 0.0 for control_state in valid_combinations}

# compute the coefficients for the control states
for i, coeff in enumerate(self.coeffs[1:]):
i += 1 # since we skip the first element we need to increase i by one

# iterate over the multinomial coefficients
for comb, num_combs in _multinomial_coefficients(self.num_state_qubits, i).items():
control_state = ()
control_state: Tuple[int, ...] = ()
power = 1
for j, qubit in enumerate(comb):
if qubit > 0: # means we control on qubit i
Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/library/arithmetic/quadratic_form.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ def required_result_qubits(

bounds = [] # bounds = [minimum value, maximum value]
for condition in [lambda x: x < 0, lambda x: x > 0]:
bound = 0
bound = 0.0
bound += sum(sum(q_ij for q_ij in q_i if condition(q_ij)) for q_i in quadratic)
bound += sum(l_i for l_i in linear if condition(l_i))
bound += offset if condition(offset) else 0
Expand Down
9 changes: 5 additions & 4 deletions qiskit/circuit/library/blueprintcircuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@

"""Blueprint circuit object."""

from typing import Optional
from typing import Optional, List
from abc import ABC, abstractmethod
from qiskit.circuit import QuantumCircuit

from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit.parametertable import ParameterTable, ParameterView


Expand All @@ -32,8 +33,8 @@ class BlueprintCircuit(QuantumCircuit, ABC):
def __init__(self, *regs, name: Optional[str] = None) -> None:
"""Create a new blueprint circuit."""
super().__init__(*regs, name=name)
self._qregs = []
self._cregs = []
self._qregs: List[QuantumRegister] = []
self._cregs: List[ClassicalRegister] = []
self._qubits = []
self._qubit_indices = {}
self._is_built = False
Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/library/generalized_gates/diagonal.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ class Diagonal(QuantumCircuit):
`arXiv:0406176 <https://arxiv.org/pdf/quant-ph/0406176.pdf>`_
"""

def __init__(self, diag: Union[List, np.array]) -> None:
def __init__(self, diag: Union[List, np.ndarray]) -> None:
"""Create a new Diagonal circuit.
Args:
Expand Down
1 change: 1 addition & 0 deletions qiskit/circuit/library/generalized_gates/mcmt.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@ def _ccx_v_chain_rule(
Raises:
QiskitError: If an insufficient number of ancilla qubits was provided.
"""
# TODO: should it actually return anyting?
if len(ancilla_qubits) == 0:
return

Expand Down
4 changes: 2 additions & 2 deletions qiskit/circuit/library/generalized_gates/permutation.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

"""Permutation circuit."""

from typing import List, Optional
from typing import List, Optional, Union

import numpy as np

Expand All @@ -26,7 +26,7 @@ class Permutation(QuantumCircuit):
def __init__(
self,
num_qubits: int,
pattern: Optional[List[int]] = None,
pattern: Optional[Union[List[int], np.ndarray]] = None,
seed: Optional[int] = None,
) -> None:
"""Return an n_qubit permutation circuit implemented using SWAPs.
Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/library/graph_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class GraphState(QuantumCircuit):
`arXiv:1512.07892 <https://arxiv.org/pdf/1512.07892.pdf>`_
"""

def __init__(self, adjacency_matrix: Union[List, np.array]) -> None:
def __init__(self, adjacency_matrix: Union[List, np.ndarray]) -> None:
"""Create graph state preparation circuit.
Args:
Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/library/iqp.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class IQP(QuantumCircuit):
`arXiv:1504.07999 <https://arxiv.org/abs/1504.07999>`_
"""

def __init__(self, interactions: Union[List, np.array]) -> None:
def __init__(self, interactions: Union[List, np.ndarray]) -> None:
"""Create IQP circuit.
Args:
Expand Down
21 changes: 12 additions & 9 deletions qiskit/circuit/library/n_local/n_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

"""The n-local circuit class."""

from typing import Union, Optional, List, Any, Tuple, Sequence, Set, Callable
from typing import Union, Optional, List, Any, Tuple, Sequence, Set, Callable, Mapping
from itertools import combinations
import warnings

Expand Down Expand Up @@ -119,12 +119,12 @@ def __init__(
self._num_qubits = None
self._insert_barriers = insert_barriers
self._reps = reps
self._entanglement_blocks = []
self._rotation_blocks = []
self._prepended_blocks = []
self._prepended_entanglement = []
self._appended_blocks = []
self._appended_entanglement = []
self._entanglement_blocks: List[Instruction] = []
self._rotation_blocks: List[Instruction] = []
self._prepended_blocks: List[QuantumCircuit] = []
self._prepended_entanglement: List[List[int]] = []
self._appended_blocks: List[QuantumCircuit] = []
self._appended_entanglement: List[List[int]] = []
self._entanglement = None
self._entangler_maps = None
self._ordered_parameters = ParameterVector(name=parameter_prefix)
Expand Down Expand Up @@ -784,7 +784,10 @@ def add_layer(

def assign_parameters(
self,
parameters: Union[dict, List[float], List[Parameter], ParameterVector],
parameters: Union[
Mapping[Parameter, Union[ParameterExpression, float]],
Sequence[Union[ParameterExpression, float]],
],
inplace: bool = False,
) -> Optional[QuantumCircuit]:
"""Assign parameters to the n-local circuit.
Expand Down Expand Up @@ -982,7 +985,7 @@ def get_parameters(block: Union[QuantumCircuit, Instruction]) -> List[Parameter]

def get_entangler_map(
num_block_qubits: int, num_circuit_qubits: int, entanglement: str, offset: int = 0
) -> List[Sequence[int]]:
) -> List[Tuple[int, ...]]:
"""Get an entangler map for an arbitrary number of qubits.
Args:
Expand Down
4 changes: 2 additions & 2 deletions qiskit/circuit/library/n_local/pauli_two_design.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

"""The Random Pauli circuit class."""

from typing import Optional
from typing import Optional, List, Dict
import numpy as np

from qiskit.circuit import QuantumCircuit
Expand Down Expand Up @@ -81,7 +81,7 @@ def __init__(
self._rng = np.random.default_rng(seed)

# store a dict to keep track of the random gates
self._gates = {}
self._gates: Dict[int, List[str]] = {}

super().__init__(
num_qubits,
Expand Down
4 changes: 2 additions & 2 deletions qiskit/circuit/library/n_local/qaoa_ansatz.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,11 @@ def __init__(

self._cost_operator = None
self._reps = reps
self._initial_state = initial_state
self._initial_state: Optional[QuantumCircuit] = initial_state
self._mixer = mixer_operator

# set this circuit as a not-built circuit
self._bounds = None
self._bounds: Optional[List[Tuple[Optional[float], Optional[float]]]] = None

# store cost operator and set the registers if the operator is not None
self.cost_operator = cost_operator
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,6 @@ def mcrz(
)


QuantumCircuit.mcrx = mcrx
QuantumCircuit.mcry = mcry
QuantumCircuit.mcrz = mcrz
QuantumCircuit.mcrx = mcrx # type: ignore[attr-defined]
QuantumCircuit.mcry = mcry # type: ignore[attr-defined]
QuantumCircuit.mcrz = mcrz # type: ignore[attr-defined]
4 changes: 2 additions & 2 deletions qiskit/circuit/library/standard_gates/x.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

"""X, CX, CCX and multi-controlled X gates."""

from typing import Optional, Union
from typing import Optional, Union, Dict, Type
from math import ceil
import numpy
from qiskit.circuit.controlledgate import ControlledGate
Expand Down Expand Up @@ -895,7 +895,7 @@ def __new__(
"""
# The CXGate and CCXGate will be implemented for all modes of the MCX, and
# the C3XGate and C4XGate will be implemented in the MCXGrayCode class.
explicit = {1: CXGate, 2: CCXGate}
explicit: Dict[int, Type[ControlledGate]] = {1: CXGate, 2: CCXGate}
if num_ctrl_qubits in explicit:
gate_class = explicit[num_ctrl_qubits]
gate = gate_class.__new__(gate_class, label=label, ctrl_state=ctrl_state)
Expand Down
5 changes: 4 additions & 1 deletion qiskit/circuit/library/templates/rzx/rzx_cy.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,15 @@
q_1: ┤ X ├┤ RY(ϴ) ├┤ X ├┤ RY(-ϴ) ├┤ RZ(-π/2) ├┤ RX(ϴ) ├┤1 ├┤ RZ(π/2) ├
└───┘└───────┘└───┘└────────┘└──────────┘└───────┘└──────────┘└─────────┘
"""
from typing import Optional

import numpy as np

from qiskit.circuit import Parameter, QuantumCircuit
from qiskit.circuit.parameterexpression import ParameterValueType


def rzx_cy(theta: float = None):
def rzx_cy(theta: Optional[ParameterValueType] = None):
"""Template for CX - RYGate - CX."""
if theta is None:
theta = Parameter("ϴ")
Expand Down
Loading

0 comments on commit a179720

Please sign in to comment.