Skip to content

Commit

Permalink
make type annotations compatible with numpy 2
Browse files Browse the repository at this point in the history
  • Loading branch information
richrines1 committed Oct 10, 2024
1 parent 60c1b76 commit 5959b49
Show file tree
Hide file tree
Showing 11 changed files with 39 additions and 40 deletions.
10 changes: 5 additions & 5 deletions cirq-superstaq/cirq_superstaq/ops/qubit_gates.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def __init__(self, theta: cirq.TParamVal) -> None:
def _num_qubits_(self) -> int:
return 2

def _unitary_(self) -> npt.NDArray[np.complex_] | None:
def _unitary_(self) -> npt.NDArray[np.complex128] | None:
if self._is_parameterized_():
return None
return np.array(
Expand Down Expand Up @@ -126,7 +126,7 @@ def _resolve_parameters_(self, resolver: cirq.ParamResolver, recursive: bool) ->
def _has_unitary_(self) -> bool:
return not self._is_parameterized_()

def _apply_unitary_(self, args: cirq.ApplyUnitaryArgs) -> npt.NDArray[np.complex_]:
def _apply_unitary_(self, args: cirq.ApplyUnitaryArgs) -> npt.NDArray[np.complex128]:
zo = args.subspace_index(0b01)
oz = args.subspace_index(0b10)
args.available_buffer[zo] = args.target_tensor[zo]
Expand Down Expand Up @@ -184,7 +184,7 @@ class ZXPowGate(cirq.EigenGate):
"""

def _eigen_components(self) -> list[tuple[float, npt.NDArray[np.float_]]]:
def _eigen_components(self) -> list[tuple[float, npt.NDArray[np.float64]]]:
return [
(
0.0,
Expand Down Expand Up @@ -914,7 +914,7 @@ def rz_rads(self) -> cirq.TParamVal:
def _num_qubits_(self) -> int:
return 2

def _unitary_(self) -> npt.NDArray[np.complex_] | None:
def _unitary_(self) -> npt.NDArray[np.complex128] | None:
if self._is_parameterized_():
return None
return np.diag(
Expand Down Expand Up @@ -990,7 +990,7 @@ def _json_dict_(self) -> dict[str, Any]:
class DDPowGate(cirq.EigenGate):
r"""The Dipole-Dipole gate for EeroQ hardware"""

def _eigen_components(self) -> list[tuple[float, npt.NDArray[np.float_]]]:
def _eigen_components(self) -> list[tuple[float, npt.NDArray[np.float64]]]:
return [
(
-0.5,
Expand Down
12 changes: 6 additions & 6 deletions cirq-superstaq/cirq_superstaq/ops/qudit_gates.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def _equal_up_to_global_phase_(self, other: Any, atol: float) -> bool | None:
def _has_unitary_(self) -> bool:
return True

def _apply_unitary_(self, args: cirq.ApplyUnitaryArgs) -> npt.NDArray[np.complex_] | None:
def _apply_unitary_(self, args: cirq.ApplyUnitaryArgs) -> npt.NDArray[np.complex128] | None:
for i in range(self._dimension):
for j in range(i):
idx0 = args.subspace_index(i * self._dimension + j)
Expand Down Expand Up @@ -118,7 +118,7 @@ def _swapped_state_indices(self) -> tuple[int, int]:
def _eigen_shifts(self) -> list[float]:
return [0.0, 0.5, -0.5]

def _eigen_components(self) -> list[tuple[float, npt.NDArray[np.float_]]]:
def _eigen_components(self) -> list[tuple[float, npt.NDArray[np.float64]]]:
idx0, idx1 = self._swapped_state_indices()

d = self.dimension**2
Expand Down Expand Up @@ -191,7 +191,7 @@ def dimension(self) -> int:
def _qid_shape_(self) -> tuple[int, int]:
return self.dimension, self.dimension

def _eigen_components(self) -> list[tuple[float, npt.NDArray[np.float_]]]:
def _eigen_components(self) -> list[tuple[float, npt.NDArray[np.float64]]]:
eigen_components = []
exponents = np.kron(range(self.dimension), range(self.dimension)) % self.dimension
for x in sorted(set(exponents)):
Expand Down Expand Up @@ -304,7 +304,7 @@ def _with_exponent(self, exponent: cirq.TParamVal) -> VirtualZPowGate:
global_shift=self._global_shift,
)

def _eigen_components(self) -> list[tuple[float, npt.NDArray[np.float_]]]:
def _eigen_components(self) -> list[tuple[float, npt.NDArray[np.float64]]]:
projector_phase = np.zeros(self._dimension)
projector_phase[self._level :] = 1
projector_rest = 1 - projector_phase
Expand Down Expand Up @@ -370,7 +370,7 @@ def _target_state(self) -> int:
def _qid_shape_(self) -> tuple[int]:
return (3,)

def _eigen_components(self) -> list[tuple[float, npt.NDArray[np.float_]]]:
def _eigen_components(self) -> list[tuple[float, npt.NDArray[np.float64]]]:
d = self._qid_shape_()[0]
projector_phase = np.zeros((d, d))
projector_phase[self._target_state, self._target_state] = 1
Expand Down Expand Up @@ -542,7 +542,7 @@ def _resolve_parameters_(
def _has_unitary_(self) -> bool:
return cirq.has_unitary(self._sub_gate)

def _apply_unitary_(self, args: cirq.ApplyUnitaryArgs) -> npt.NDArray[np.complex_] | None:
def _apply_unitary_(self, args: cirq.ApplyUnitaryArgs) -> npt.NDArray[np.complex128] | None:
if not cirq.has_unitary(self._sub_gate):
return NotImplemented

Expand Down
10 changes: 5 additions & 5 deletions cirq-superstaq/cirq_superstaq/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ def aqt_compile_eca(
target: str = "aqt_keysight_qpu",
atol: float | None = None,
gate_defs: None | (
Mapping[str, npt.NDArray[np.complex_] | cirq.Gate | cirq.Operation | None]
Mapping[str, npt.NDArray[np.number[Any]] | cirq.Gate | cirq.Operation | None]
) = None,
**kwargs: Any,
) -> css.compiler_output.CompilerOutput:
Expand Down Expand Up @@ -483,7 +483,7 @@ def aqt_compile(
random_seed: int | None = None,
atol: float | None = None,
gate_defs: None | (
Mapping[str, npt.NDArray[np.complex_] | cirq.Gate | cirq.Operation | None]
Mapping[str, npt.NDArray[np.number[Any]] | cirq.Gate | cirq.Operation | None]
) = None,
gateset: Mapping[str, Sequence[Sequence[int]]] | None = None,
pulses: object = None,
Expand Down Expand Up @@ -816,7 +816,7 @@ def _get_compile_request_json(

def supercheq(
self, files: list[list[int]], num_qubits: int, depth: int
) -> tuple[list[cirq.Circuit], npt.NDArray[np.float_]]:
) -> tuple[list[cirq.Circuit], npt.NDArray[np.float64]]:
"""Returns the randomly generated circuits and the fidelity matrix for inputted files.
Args:
Expand Down Expand Up @@ -1123,7 +1123,7 @@ def process_cb(self, job_id: str, counts: list[dict[str, int]] | None = None) ->

def _objective(
x: np.typing.NDArray[np.int_], A: float, p: float
) -> np.typing.NDArray[np.float_]:
) -> np.typing.NDArray[np.float64]:
return A * p**x

fit_data: defaultdict[str, float] = defaultdict(float)
Expand Down Expand Up @@ -1167,7 +1167,7 @@ def plot(self, circuits_and_metadata: dict[str, Any]) -> None:

def _objective(
x: np.typing.NDArray[np.int_], A: float, p: float
) -> np.typing.NDArray[np.float_]:
) -> np.typing.NDArray[np.float64]:
return A * p**x

e_f = 0.0
Expand Down
2 changes: 1 addition & 1 deletion qiskit-superstaq/qiskit_superstaq/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def json_encoder(val: object) -> dict[str, object]:
raise TypeError(f"Object of type {type(val)} is not JSON serializable.")


def json_resolver(val: T) -> T | npt.NDArray[np.complex_]:
def json_resolver(val: T) -> T | npt.NDArray[np.complex128]:
"""Hook to deserialize objects that were serialized via `json_encoder()`.
Args:
Expand Down
2 changes: 1 addition & 1 deletion qiskit-superstaq/qiskit_superstaq/superstaq_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def aqt_compile(
num_eca_circuits: int | None = None,
random_seed: int | None = None,
atol: float | None = None,
gate_defs: Mapping[str, str | npt.NDArray[np.complex_] | None] | None = None,
gate_defs: Mapping[str, str | npt.NDArray[np.number[Any]] | None] | None = None,
gateset: Mapping[str, Sequence[Sequence[int]]] | None = None,
pulses: object = None,
variables: object = None,
Expand Down
6 changes: 3 additions & 3 deletions qiskit-superstaq/qiskit_superstaq/superstaq_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def aqt_compile(
num_eca_circuits: int | None = None,
random_seed: int | None = None,
atol: float | None = None,
gate_defs: Mapping[str, str | npt.NDArray[np.complex_] | None] | None = None,
gate_defs: Mapping[str, str | npt.NDArray[np.number[Any]] | None] | None = None,
gateset: Mapping[str, Sequence[Sequence[int]]] | None = None,
pulses: object = None,
variables: object = None,
Expand Down Expand Up @@ -252,7 +252,7 @@ def aqt_compile_eca(
random_seed: int | None = None,
target: str = "aqt_keysight_qpu",
atol: float | None = None,
gate_defs: Mapping[str, str | npt.NDArray[np.complex_] | None] | None = None,
gate_defs: Mapping[str, str | npt.NDArray[np.number[Any]] | None] | None = None,
**kwargs: Any,
) -> qss.compiler_output.CompilerOutput:
"""Compiles and optimizes the given circuit(s) for the Advanced Quantum Testbed (AQT) at
Expand Down Expand Up @@ -458,7 +458,7 @@ def cq_compile(

def supercheq(
self, files: list[list[int]], num_qubits: int, depth: int
) -> tuple[list[qiskit.QuantumCircuit], npt.NDArray[np.float_]]:
) -> tuple[list[qiskit.QuantumCircuit], npt.NDArray[np.float64]]:
"""Returns Supercheq randomly generated circuits and the corresponding fidelity matrices.
References:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@ def _get_expectation_value_from_probs(self, probabilities: Mapping[str, float])
expectation_value += probability * self._get_energy_for_bitstring(bitstring)
return expectation_value

def _get_opt_angles(self) -> tuple[npt.NDArray[np.float_], float]:
def f(params: npt.NDArray[np.float_]) -> float:
def _get_opt_angles(self) -> tuple[npt.NDArray[np.float64], float]:
def f(params: npt.NDArray[np.float64]) -> float:
"""The objective function to minimize.
Args:
Expand All @@ -143,7 +143,7 @@ def f(params: npt.NDArray[np.float_]) -> float:

return out["x"], out["fun"]

def _gen_angles(self) -> npt.NDArray[np.float_]:
def _gen_angles(self) -> npt.NDArray[np.float64]:
# Classically simulate the variational optimization 5 times,
# return the parameters from the best performing simulation
best_params, best_cost = np.zeros(2), 0.0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ def _get_expectation_value_from_probs(self, probabilities: Mapping[str, float])
expectation_value += probability * self._get_energy_for_bitstring(bitstring)
return expectation_value

def _get_opt_angles(self) -> tuple[npt.NDArray[np.float_], float]:
def f(params: npt.NDArray[np.float_]) -> float:
def _get_opt_angles(self) -> tuple[npt.NDArray[np.float64], float]:
def f(params: npt.NDArray[np.float64]) -> float:
"""The objective function to minimize.
Args:
Expand All @@ -118,7 +118,7 @@ def f(params: npt.NDArray[np.float_]) -> float:

return out["x"], out["fun"]

def _gen_angles(self) -> npt.NDArray[np.float_]:
def _gen_angles(self) -> npt.NDArray[np.float64]:
# Classically simulate the variational optimization 5 times,
# return the parameters from the best performing simulation
best_params, best_cost = np.zeros(2), 0.0
Expand Down
8 changes: 4 additions & 4 deletions supermarq-benchmarks/supermarq/benchmarks/vqe_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def _gen_tfim_hamiltonian(self) -> list[tuple[str, int | tuple[int, int], int]]:
hamiltonian.append(("ZZ", (self.num_qubits - 1, 0), 1))
return hamiltonian

def _gen_ansatz(self, params: npt.NDArray[np.float_]) -> list[cirq.Circuit]:
def _gen_ansatz(self, params: npt.NDArray[np.float64]) -> list[cirq.Circuit]:
qubits = cirq.LineQubit.range(self.num_qubits)
z_circuit = cirq.Circuit()

Expand Down Expand Up @@ -117,8 +117,8 @@ def _get_expectation_value_from_probs(

return avg_energy

def _get_opt_angles(self) -> tuple[npt.NDArray[np.float_], float]:
def f(params: npt.NDArray[np.float_]) -> float:
def _get_opt_angles(self) -> tuple[npt.NDArray[np.float64], float]:
def f(params: npt.NDArray[np.float64]) -> float:
"""The objective function to minimize.
Args:
Expand All @@ -141,7 +141,7 @@ def f(params: npt.NDArray[np.float_]) -> float:

return out["x"], out["fun"]

def _gen_angles(self) -> npt.NDArray[np.float_]:
def _gen_angles(self) -> npt.NDArray[np.float64]:
"""Classically simulate the variational optimization and return
the final parameters.
"""
Expand Down
8 changes: 4 additions & 4 deletions supermarq-benchmarks/supermarq/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ def plot_benchmark(


def heatmap(
data: npt.NDArray[np.float_],
data: npt.NDArray[np.floating[Any]],
ax: matplotlib.axes.Axes,
row_labels: list[str],
col_labels: list[str],
Expand Down Expand Up @@ -306,7 +306,7 @@ def heatmap(

def annotate_heatmap(
im: matplotlib.image.AxesImage,
data: npt.NDArray[np.float_] | None = None,
data: npt.NDArray[np.floating[Any]] | None = None,
valfmt: Any = "{x:.2f}",
textcolors: tuple[str, str] = ("black", "white"),
threshold: float | None = None,
Expand Down Expand Up @@ -360,7 +360,7 @@ def annotate_heatmap(
return texts


def radar_factory(num_vars: int) -> npt.NDArray[np.float_]:
def radar_factory(num_vars: int) -> npt.NDArray[np.float64]:
"""Create a radar chart with `num_vars` axes.
(https://matplotlib.org/stable/gallery/specialty_plots/radar_chart.html) This function
Expand Down Expand Up @@ -398,7 +398,7 @@ class RadarAxesMeta(PolarAxes):

def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Initializes the `RadarAxesMeta` class."""
self.theta: npt.NDArray[np.float_]
self.theta: npt.NDArray[np.float64]
self.num_vars: int
self.frame: str

Expand Down
9 changes: 4 additions & 5 deletions supermarq-benchmarks/supermarq/qcvv/irb.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import cirq
import cirq.circuits
import numpy as np
import numpy.typing as npt
import pandas as pd
import scipy
import seaborn as sns
Expand Down Expand Up @@ -637,7 +638,7 @@ def analyze_results(self, plot_results: bool = True) -> IRBResults | RBResults:

def _fit_decay(
self, experiment: str = "RB"
) -> tuple[np.typing.NDArray[np.float_], np.typing.NDArray[np.float_]]:
) -> tuple[np.typing.NDArray[np.float64], np.typing.NDArray[np.float64]]:
"""Fits the exponential decay function to either the RB or IRB results.
Args:
Expand All @@ -662,9 +663,7 @@ def _fit_decay(
return popt, np.sqrt(np.diag(pcov))

@staticmethod
def exp_decay(
x: np.typing.NDArray[np.float_], A: float, alpha: float, B: float
) -> np.typing.NDArray[np.float_]:
def exp_decay(x: npt.ArrayLike, A: float, alpha: float, B: float) -> npt.ArrayLike:
r"""Exponential decay of the form
.. math::
Expand All @@ -680,4 +679,4 @@ def exp_decay(
Returns:
Exponential decay applied to x.
"""
return A * (alpha**x) + B
return A * (np.asarray(alpha) ** x) + B

0 comments on commit 5959b49

Please sign in to comment.