From 28e504efc5538ea32abe55af3896b479db07f2b1 Mon Sep 17 00:00:00 2001 From: Cody Wang Date: Fri, 12 Jun 2026 15:55:14 -0700 Subject: [PATCH] fix: Python 3.11 syntax --- pyproject.toml | 2 +- .../adaptive_allocator.py | 30 ++++++++----------- .../adaptive_allocator_braket_helpers.py | 8 ++--- .../bells_inequality/bells_inequality.py | 11 ++++--- .../bernstein_vazirani/bernstein_vazirani.py | 3 +- .../chsh_inequality/chsh_inequality.py | 11 ++++--- .../algorithms/deutsch_jozsa/deutsch_jozsa.py | 3 +- .../grovers_search/grovers_search.py | 4 +-- src/braket/experimental/algorithms/hhl/hhl.py | 8 ++--- .../algorithms/qc_qmc/classical_qmc.py | 26 ++++++++-------- .../experimental/algorithms/qc_qmc/qc_qmc.py | 20 ++++++------- .../quantum_approximate_optimization.py | 4 +-- .../quantum_circuit_born_machine/qcbm.py | 12 ++++---- .../quantum_counting/quantum_counting.py | 22 +++++++------- .../quantum_phase_estimation.py | 7 +++-- .../algorithms/quantum_walk/quantum_walk.py | 4 +-- .../experimental/algorithms/shors/shors.py | 12 ++++---- .../experimental/algorithms/simons/simons.py | 10 +++---- .../random_circuit/random_circuit.py | 5 ++-- 19 files changed, 91 insertions(+), 111 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 0f3a72e4..f947bb51 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -89,7 +89,7 @@ target-version = "py311" line-length = 100 [tool.ruff.lint] -extend-select = ["I", "PERF"] +extend-select = ["I", "PERF", "UP"] preview = false #TODO: set back to true [tool.ruff.lint.isort] diff --git a/src/braket/experimental/algorithms/adaptive_shot_allocation/adaptive_allocator.py b/src/braket/experimental/algorithms/adaptive_shot_allocation/adaptive_allocator.py index 0780e281..6ccab2fa 100644 --- a/src/braket/experimental/algorithms/adaptive_shot_allocation/adaptive_allocator.py +++ b/src/braket/experimental/algorithms/adaptive_shot_allocation/adaptive_allocator.py @@ -1,7 +1,7 @@ import random import warnings +from collections.abc import Callable from functools import partial -from typing import Callable, Dict, List, Tuple, Union import matplotlib.pyplot as plt import networkx as nx @@ -9,7 +9,7 @@ from networkx.algorithms import approximation # Type alias for measurement data structure (see AdaptiveShotAllocator.measurements) -MeasurementData = List[List[Dict[Tuple[int, int], int]]] +MeasurementData = list[list[dict[tuple[int, int], int]]] """ Helper functions for Pauli operator commutation and Bayesian statistics calculations. @@ -48,9 +48,7 @@ def commute(a: str, b: str, qwc: bool = True) -> bool: # BAYESIAN STATISTICS (closed formulas from Appendix B of arXiv:2110.15339v6) -def term_variance_estimate( - term_idx: int, measurements: Union[MeasurementData, None] = None -) -> float: +def term_variance_estimate(term_idx: int, measurements: MeasurementData | None = None) -> float: """ Estimate variance for a single Pauli term. See Eq 14 in Appendix B of "Adaptive Estimation of Quantum Observables (arXiv:2110.15339v6) @@ -69,9 +67,7 @@ def term_variance_estimate( return 4 * ((x0 + 1) * (x1 + 1)) / ((x0 + x1 + 2) * (x0 + x1 + 3)) -def terms_covariance_estimate( - i: int, j: int, measurements: Union[MeasurementData, None] = None -) -> float: +def terms_covariance_estimate(i: int, j: int, measurements: MeasurementData | None = None) -> float: """ Estimate covariance between two Pauli terms. See Eq 25-6 in Appendix B of "Adaptive Estimation of Quantum Observables (arXiv:2110.15339v6) @@ -139,14 +135,14 @@ class AdaptiveShotAllocator: """ num_terms: int - paulis: List[str] - coeffs: List[float] + paulis: list[str] + coeffs: list[float] graph: nx.Graph - cliq: List[List[int]] + cliq: list[list[int]] measurements: MeasurementData - shots: Union[List[int], None] + shots: list[int] | None - def __init__(self, paulis: List[str], coeffs: List[float]) -> None: + def __init__(self, paulis: list[str], coeffs: list[float]) -> None: """ Initialize the AdaptiveShotAllocator with Pauli terms and their coefficients. @@ -327,7 +323,7 @@ def _update_graph_weights(self) -> None: ) self.graph[i][j]["weight"] = weight - def incremental_shot_allocation(self, num_shots: int) -> List[int]: + def incremental_shot_allocation(self, num_shots: int) -> list[int]: """ Propose allocation of measurement shots to cliques using greedy minimization of the estimated error. @@ -415,9 +411,7 @@ def error_estimate(self) -> float: return np.sqrt(variance_estimate) - def expectation_from_measurements( - self, measurements: Union[MeasurementData, None] = None - ) -> float: + def expectation_from_measurements(self, measurements: MeasurementData | None = None) -> float: """ Calculate the energy expectation value from measurement results for the different Pauli string observables. @@ -515,7 +509,7 @@ def _validate_measurements(self, measurements: MeasurementData) -> bool: ) return True - def shots_from_measurements(self, measurements: MeasurementData) -> List[int]: + def shots_from_measurements(self, measurements: MeasurementData) -> list[int]: """ Extract the number of shots allocated to each clique from measurement data. diff --git a/src/braket/experimental/algorithms/adaptive_shot_allocation/adaptive_allocator_braket_helpers.py b/src/braket/experimental/algorithms/adaptive_shot_allocation/adaptive_allocator_braket_helpers.py index ea8f2125..d444851d 100644 --- a/src/braket/experimental/algorithms/adaptive_shot_allocation/adaptive_allocator_braket_helpers.py +++ b/src/braket/experimental/algorithms/adaptive_shot_allocation/adaptive_allocator_braket_helpers.py @@ -3,8 +3,6 @@ experiments on Amazon Braket. """ -from typing import List, Union - from braket.aws import AwsDevice from braket.circuits import Circuit, Observable from braket.devices import LocalSimulator @@ -29,10 +27,10 @@ def observable_from_string(pauli_string: str) -> Observable: def run_fixed_allocation( - device: Union[LocalSimulator, AwsDevice], + device: LocalSimulator | AwsDevice, circuit: Circuit, estimator: AdaptiveShotAllocator, - shot_allocation: List[int], + shot_allocation: list[int], ) -> MeasurementData: """ Run experiment with a specific shot allocation. @@ -96,7 +94,7 @@ def run_fixed_allocation( def run_adaptive_allocation( - device: Union[LocalSimulator, AwsDevice], + device: LocalSimulator | AwsDevice, circuit: Circuit, estimator: AdaptiveShotAllocator, shots_per_round: int, diff --git a/src/braket/experimental/algorithms/bells_inequality/bells_inequality.py b/src/braket/experimental/algorithms/bells_inequality/bells_inequality.py index 8dfa9d49..d9326701 100644 --- a/src/braket/experimental/algorithms/bells_inequality/bells_inequality.py +++ b/src/braket/experimental/algorithms/bells_inequality/bells_inequality.py @@ -11,7 +11,6 @@ # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. from collections import Counter -from typing import List, Tuple import numpy as np @@ -26,7 +25,7 @@ def create_bell_inequality_circuits( angle_A: float = 0, angle_B: float = np.pi / 3, angle_C: float = 2 * np.pi / 3, -) -> List[Circuit]: +) -> list[Circuit]: """Create the three circuits for Bell's inequality. Default angles will give maximum violation of Bell's inequality. @@ -48,10 +47,10 @@ def create_bell_inequality_circuits( def run_bell_inequality( - circuits: List[Circuit], + circuits: list[Circuit], device: Device, shots: int = 1_000, -) -> List[QuantumTask]: +) -> list[QuantumTask]: """Submit three Bell circuits to a device. Args: @@ -67,8 +66,8 @@ def run_bell_inequality( def get_bell_inequality_results( - tasks: List[QuantumTask], verbose: bool = True -) -> Tuple[List[Counter], float, float, float]: + tasks: list[QuantumTask], verbose: bool = True +) -> tuple[list[Counter], float, float, float]: """Return Bell task results after post-processing. Args: diff --git a/src/braket/experimental/algorithms/bernstein_vazirani/bernstein_vazirani.py b/src/braket/experimental/algorithms/bernstein_vazirani/bernstein_vazirani.py index 7f4b6aba..55867ca9 100644 --- a/src/braket/experimental/algorithms/bernstein_vazirani/bernstein_vazirani.py +++ b/src/braket/experimental/algorithms/bernstein_vazirani/bernstein_vazirani.py @@ -10,7 +10,6 @@ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. -from typing import Dict import numpy as np @@ -61,7 +60,7 @@ def bernstein_vazirani_circuit(hidden_string: str) -> Circuit: return bv_circuit -def get_bernstein_vazirani_results(task: QuantumTask) -> Dict[str, float]: +def get_bernstein_vazirani_results(task: QuantumTask) -> dict[str, float]: """Return the probabilities and corresponding bitstrings. Args: diff --git a/src/braket/experimental/algorithms/chsh_inequality/chsh_inequality.py b/src/braket/experimental/algorithms/chsh_inequality/chsh_inequality.py index 98cc0725..b3889368 100644 --- a/src/braket/experimental/algorithms/chsh_inequality/chsh_inequality.py +++ b/src/braket/experimental/algorithms/chsh_inequality/chsh_inequality.py @@ -12,7 +12,6 @@ # language governing permissions and limitations under the License. from collections import Counter -from typing import List, Tuple import numpy as np @@ -32,7 +31,7 @@ def create_chsh_inequality_circuits( a2: float = 0, b1: float = np.pi / 4, b2: float = 3 * np.pi / 4, -) -> List[Circuit]: +) -> list[Circuit]: """Create the four circuits for CHSH inequality. Default angles will give maximum violation of the inequality. @@ -55,10 +54,10 @@ def create_chsh_inequality_circuits( def run_chsh_inequality( - circuits: List[Circuit], + circuits: list[Circuit], device: Device, shots: int = 1_000, -) -> List[QuantumTask]: +) -> list[QuantumTask]: """Submit four CHSH circuits to a device. Args: @@ -74,8 +73,8 @@ def run_chsh_inequality( def get_chsh_results( - tasks: List[QuantumTask], verbose: bool = True -) -> Tuple[float, List[Counter], float, float, float]: + tasks: list[QuantumTask], verbose: bool = True +) -> tuple[float, list[Counter], float, float, float]: """Return CHSH task results after post-processing. Args: diff --git a/src/braket/experimental/algorithms/deutsch_jozsa/deutsch_jozsa.py b/src/braket/experimental/algorithms/deutsch_jozsa/deutsch_jozsa.py index a33bd6d4..65f3cde9 100644 --- a/src/braket/experimental/algorithms/deutsch_jozsa/deutsch_jozsa.py +++ b/src/braket/experimental/algorithms/deutsch_jozsa/deutsch_jozsa.py @@ -10,7 +10,6 @@ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. -from typing import Dict import numpy as np @@ -109,7 +108,7 @@ def deutsch_jozsa(oracle: Circuit) -> Circuit: return circ -def get_deutsch_jozsa_results(task: QuantumTask) -> Dict[str, float]: +def get_deutsch_jozsa_results(task: QuantumTask) -> dict[str, float]: """Return the probabilities and corresponding bitstrings. Args: diff --git a/src/braket/experimental/algorithms/grovers_search/grovers_search.py b/src/braket/experimental/algorithms/grovers_search/grovers_search.py index e8fa6e59..464b685a 100644 --- a/src/braket/experimental/algorithms/grovers_search/grovers_search.py +++ b/src/braket/experimental/algorithms/grovers_search/grovers_search.py @@ -1,5 +1,3 @@ -from typing import Tuple - from braket.circuits import Circuit, circuit @@ -99,7 +97,7 @@ def multi_control_not_constructor( n_qubit: int, decompose_ccnot: bool, is_outermost_call: bool = True, -) -> Tuple[Circuit, int]: +) -> tuple[Circuit, int]: """Recursive constructor of a multi-contol Not circuit (generalized Toffoli gate). Ref: https://arxiv.org/abs/1904.01671 diff --git a/src/braket/experimental/algorithms/hhl/hhl.py b/src/braket/experimental/algorithms/hhl/hhl.py index f3afb23d..19c5c416 100644 --- a/src/braket/experimental/algorithms/hhl/hhl.py +++ b/src/braket/experimental/algorithms/hhl/hhl.py @@ -23,7 +23,7 @@ [2] Wikipedia: https://en.wikipedia.org/wiki/HHL_algorithm """ -from typing import Any, Dict, List, Optional +from typing import Any import numpy as np from qiskit.circuit import QuantumCircuit @@ -47,7 +47,7 @@ def hhl_circuit( matrix: np.ndarray, b_vector: np.ndarray, num_clock_qubits: int = 2, - scaling_factor: Optional[float] = None, + scaling_factor: float | None = None, ) -> Circuit: """Construct the full HHL circuit for solving Ax = b. @@ -147,7 +147,7 @@ def get_hhl_results( b_vector: np.ndarray, num_clock_qubits: int = 2, verbose: bool = False, -) -> Dict[str, Any]: +) -> dict[str, Any]: """Post-process results from an HHL run. Extracts the solution state by post-selecting on the ancilla qubit @@ -330,7 +330,7 @@ def _compute_hamiltonian_simulation(matrix: np.ndarray, t: float) -> np.ndarray: def _decompose_controlled_unitary( unitary: np.ndarray, - targets: List[int], + targets: list[int], ) -> Circuit: """Decompose a controlled-U gate into native 1q/2q gates via Qiskit transpilation. diff --git a/src/braket/experimental/algorithms/qc_qmc/classical_qmc.py b/src/braket/experimental/algorithms/qc_qmc/classical_qmc.py index 4c757137..a1aab225 100644 --- a/src/braket/experimental/algorithms/qc_qmc/classical_qmc.py +++ b/src/braket/experimental/algorithms/qc_qmc/classical_qmc.py @@ -1,8 +1,8 @@ import copy import multiprocessing as mp import os +from collections.abc import Callable from dataclasses import dataclass -from typing import Callable, List, Tuple import pennylane as qml from openfermion.circuits.low_rank import low_rank_two_body_decomposition @@ -17,11 +17,11 @@ class ChemicalProperties: nuclear_repulsion: float # nuclear repulsion energy v_0: np.ndarray # one-body term stored as np.ndarray with mean-field subtraction h_chem: np.ndarray # one-body term stored as np.ndarray, without mean-field subtraction - v_gamma: List[np.ndarray] # 1j * l_gamma - l_gamma: List[np.ndarray] # Cholesky vector decomposed from two-body terms + v_gamma: list[np.ndarray] # 1j * l_gamma + l_gamma: list[np.ndarray] # Cholesky vector decomposed from two-body terms mf_shift: np.ndarray # mean-field shift - lambda_l: List[np.ndarray] # eigenvalues of Cholesky vectors - u_l: List[np.ndarray] # eigenvectors of Cholesky vectors + lambda_l: list[np.ndarray] # eigenvalues of Cholesky vectors + u_l: list[np.ndarray] # eigenvectors of Cholesky vectors def classical_qmc( @@ -31,7 +31,7 @@ def classical_qmc( trial: np.ndarray, prop: ChemicalProperties, max_pool: int = 8, -) -> Tuple[float, float]: +) -> tuple[float, float]: """Classical Auxiliary-Field Quantum Monte Carlo. Args: @@ -82,7 +82,7 @@ def hartree_fock_energy(trial: np.ndarray, prop: ChemicalProperties) -> float: return e_hf -def full_imag_time_evolution_wrapper(args: Tuple) -> Callable: +def full_imag_time_evolution_wrapper(args: tuple) -> Callable: return full_imag_time_evolution(*args) @@ -94,7 +94,7 @@ def full_imag_time_evolution( e_shift: float, walker: np.ndarray, weight: float, -) -> Tuple[List[float], float]: +) -> tuple[list[float], float]: """Imaginary time evolution of a single walker. Args: @@ -128,7 +128,7 @@ def imag_time_propogator( weight: float, prop: ChemicalProperties, e_shift: float, -) -> Tuple[float, np.ndarray, float]: +) -> tuple[float, np.ndarray, float]: """Propagate a walker by one time step. Args: @@ -203,7 +203,7 @@ def local_energy(h1e: np.ndarray, eri: np.ndarray, green_funcs: np.ndarray, enuc return e1 + e2 + enuc -def reortho(A: np.ndarray) -> Tuple[np.ndarray, float]: +def reortho(A: np.ndarray) -> tuple[np.ndarray, float]: """Reorthogonalise a MxN matrix A. Performs a QR decomposition of A. Note that for consistency elsewhere we want to preserve detR > 0 which is not guaranteed. We thus factor the signs of the diagonal of R into Q. @@ -309,13 +309,13 @@ def chemistry_preparation( def propagate_walker( x: np.ndarray, - v_0: List[np.ndarray], - v_gamma: List[np.ndarray], + v_0: list[np.ndarray], + v_gamma: list[np.ndarray], mf_shift: np.ndarray, dtau: float, trial: np.ndarray, walker: np.ndarray, - green_funcs: List[np.ndarray], + green_funcs: list[np.ndarray], ) -> np.ndarray: r"""Update the walker forward in imaginary time. diff --git a/src/braket/experimental/algorithms/qc_qmc/qc_qmc.py b/src/braket/experimental/algorithms/qc_qmc/qc_qmc.py index fbedd0dd..c2c0c013 100644 --- a/src/braket/experimental/algorithms/qc_qmc/qc_qmc.py +++ b/src/braket/experimental/algorithms/qc_qmc/qc_qmc.py @@ -1,6 +1,6 @@ import multiprocessing as mp import os -from typing import Callable, List, Tuple +from collections.abc import Callable import numpy as np import pennylane as qml @@ -29,7 +29,7 @@ def qc_qmc( trial_state_circuit: Callable, dev: qml.devices.Device, max_pool: int = 8, -) -> Tuple[List[float], List[float]]: +) -> tuple[list[float], list[float]]: """Quantum assisted Auxiliary-Field Quantum Monte Carlo. Args: @@ -83,7 +83,7 @@ def qc_qmc( return quantum_energies, energies -def q_full_imag_time_evolution_wrapper(args: Tuple) -> Callable: +def q_full_imag_time_evolution_wrapper(args: tuple) -> Callable: return q_full_imag_time_evolution(*args) @@ -98,7 +98,7 @@ def q_full_imag_time_evolution( weight: float, trial_state_circuit: Callable, dev: qml.devices.Device, -) -> Tuple[List[float], List[float], List[float], List[float]]: +) -> tuple[list[float], list[float], list[float], list[float]]: """Imaginary time evolution of a single walker. Args: @@ -150,7 +150,7 @@ def imag_time_propogator_qaee( e_shift: float, trial_state_circuit: Callable, dev: qml.devices.Device, -) -> Tuple[float, float, float, np.ndarray, float]: +) -> tuple[float, float, float, np.ndarray, float]: """Imaginary time propogator with quantum energy evaluations. Args: @@ -284,7 +284,7 @@ def local_energy_quantum( # noqa: C901 return energy -def givens_block_circuit(givens: Tuple) -> None: +def givens_block_circuit(givens: tuple) -> None: r"""This function defines the Givens rotation circuit from a single givens tuple. Args: @@ -304,7 +304,7 @@ def givens_block_circuit(givens: Tuple) -> None: qml.CNOT(wires=[j, i]) -def prepare_slater_circuit(circuit_description: List[Tuple]) -> None: +def prepare_slater_circuit(circuit_description: list[tuple]) -> None: """Creating Givens rotation circuit to prepare arbitrary Slater determinant. Args: @@ -446,7 +446,7 @@ def u_circuit(u_matrix: np.ndarray) -> None: def pauli_real( - q_state: np.ndarray, trial_state_circuit: Callable, u_matrix: np.ndarray, pauli: List[int] + q_state: np.ndarray, trial_state_circuit: Callable, u_matrix: np.ndarray, pauli: list[int] ) -> Callable: """Construct the the vacuum reference circuit for measuring expectation value of a pauli real part @@ -471,7 +471,7 @@ def pauli_real( def pauli_imag( - q_state: np.ndarray, trial_state_circuit: Callable, u_matrix: np.ndarray, pauli: List[int] + q_state: np.ndarray, trial_state_circuit: Callable, u_matrix: np.ndarray, pauli: list[int] ) -> Callable: """Construct the the vacuum reference circuit for measuring expectation value of a pauli imaginary part @@ -499,7 +499,7 @@ def pauli_estimate( q_state: np.ndarray, trial_state_circuit: Callable, u_matrix: np.ndarray, - pauli: List[int], + pauli: list[int], dev: qml.device, ) -> float: """This function returns the expectation value of $\\langle \\Psi_q_state|pauli|\\phi_l\rangle$. diff --git a/src/braket/experimental/algorithms/quantum_approximate_optimization/quantum_approximate_optimization.py b/src/braket/experimental/algorithms/quantum_approximate_optimization/quantum_approximate_optimization.py index 0d37d306..60576390 100644 --- a/src/braket/experimental/algorithms/quantum_approximate_optimization/quantum_approximate_optimization.py +++ b/src/braket/experimental/algorithms/quantum_approximate_optimization/quantum_approximate_optimization.py @@ -12,8 +12,6 @@ # language governing permissions and limitations under the License. -from typing import List - import numpy as np from braket.circuits import Circuit, FreeParameter, Observable, circuit @@ -26,7 +24,7 @@ def cost_function( device: Device, circ: Circuit, coeffs: np.ndarray, - cost_history: List[float], + cost_history: list[float], shots: int = 0, ) -> float: """Cost function and append to loss history list. diff --git a/src/braket/experimental/algorithms/quantum_circuit_born_machine/qcbm.py b/src/braket/experimental/algorithms/quantum_circuit_born_machine/qcbm.py index dd136149..5b73d950 100644 --- a/src/braket/experimental/algorithms/quantum_circuit_born_machine/qcbm.py +++ b/src/braket/experimental/algorithms/quantum_circuit_born_machine/qcbm.py @@ -12,8 +12,6 @@ # language governing permissions and limitations under the License. -from typing import List, Tuple - import numpy as np from braket.circuits import Circuit, FreeParameter, circuit @@ -149,7 +147,7 @@ def gradient(self, params: np.ndarray) -> np.ndarray: return grad -def _compute_kernel(px: np.ndarray, py: np.ndarray, sigma_list: List[float] = [0.1, 1]) -> float: +def _compute_kernel(px: np.ndarray, py: np.ndarray, sigma_list: list[float] = [0.1, 1]) -> float: r"""Gaussian radial basis function (RBF) kernel. .. math:: @@ -170,7 +168,7 @@ def _compute_kernel(px: np.ndarray, py: np.ndarray, sigma_list: List[float] = [0 return kernel -def mmd_loss(px: np.ndarray, py: np.ndarray, sigma_list: List[float] = [0.1, 1]) -> float: +def mmd_loss(px: np.ndarray, py: np.ndarray, sigma_list: list[float] = [0.1, 1]) -> float: r"""Maximum Mean Discrepancy loss (MMD). MMD determines if two distributions are equal by looking at the difference between @@ -205,7 +203,7 @@ def mmd_loss(px: np.ndarray, py: np.ndarray, sigma_list: List[float] = [0.1, 1]) @circuit.subroutine(register=True) def qcbm_layers( - neighbors: List[Tuple[int, int]], parameters: List[List[List[FreeParameter]]] + neighbors: list[tuple[int, int]], parameters: list[list[list[FreeParameter]]] ) -> Circuit: """QCBM layers. @@ -228,7 +226,7 @@ def qcbm_layers( @circuit.subroutine(register=True) -def entangler(neighbors: List[Tuple[int, int]]) -> Circuit: +def entangler(neighbors: list[tuple[int, int]]) -> Circuit: """Add CNot gates to circuit. Args: @@ -244,7 +242,7 @@ def entangler(neighbors: List[Tuple[int, int]]) -> Circuit: @circuit.subroutine(register=True) -def rotation_layer(parameters: List[List[FreeParameter]]) -> Circuit: +def rotation_layer(parameters: list[list[FreeParameter]]) -> Circuit: """Add rotation layers to circuit. Args: diff --git a/src/braket/experimental/algorithms/quantum_counting/quantum_counting.py b/src/braket/experimental/algorithms/quantum_counting/quantum_counting.py index 6ffc73fb..b84eeb1c 100644 --- a/src/braket/experimental/algorithms/quantum_counting/quantum_counting.py +++ b/src/braket/experimental/algorithms/quantum_counting/quantum_counting.py @@ -10,7 +10,7 @@ """ import math -from typing import Any, Dict, List, Tuple +from typing import Any import numpy as np @@ -23,7 +23,7 @@ def build_oracle_circuit( n_qubits: int, - marked_states: List[int], + marked_states: list[int], decompose_ccnot: bool = False, ) -> Circuit: """Build an oracle circuit that flips the phase of marked states. @@ -60,7 +60,7 @@ def build_oracle_circuit( def build_grover_circuit( n_qubits: int, - marked_states: List[int], + marked_states: list[int], decompose_ccnot: bool = False, ) -> Circuit: """Build the Grover operator G = D ยท O as a circuit. @@ -88,7 +88,7 @@ def build_grover_circuit( def _controlled_oracle_circuit( control: int, search_qubits: QubitSetInput, - marked_states: List[int], + marked_states: list[int], decompose_ccnot: bool = False, ) -> Circuit: """Build a controlled oracle circuit using gate-level primitives. @@ -202,7 +202,7 @@ def _add_controlled_h(circ: Circuit, control: int, target: int) -> None: def controlled_grover_circuit( control: int, search_qubits: QubitSetInput, - marked_states: List[int], + marked_states: list[int], power: int = 1, decompose_ccnot: bool = False, ) -> Circuit: @@ -270,7 +270,7 @@ def quantum_counting_circuit( counting_circ: Circuit, counting_qubits: QubitSetInput, search_qubits: QubitSetInput, - marked_states: List[int], + marked_states: list[int], decompose_ccnot: bool = False, ) -> Circuit: """Create the full quantum counting circuit with result types. @@ -298,7 +298,7 @@ def quantum_counting_circuit( def quantum_counting( counting_qubits: QubitSetInput, search_qubits: QubitSetInput, - marked_states: List[int], + marked_states: list[int], decompose_ccnot: bool = False, ) -> Circuit: """Build the core quantum counting circuit using QPE on the Grover operator. @@ -367,7 +367,7 @@ def get_quantum_counting_results( counting_qubits: QubitSetInput, search_qubits: QubitSetInput, verbose: bool = False, -) -> Dict[str, Any]: +) -> dict[str, Any]: """Post-process quantum counting results to estimate the number of marked items. After measuring the counting qubits, the most likely outcome y gives @@ -397,7 +397,7 @@ def get_quantum_counting_results( N = 2**n_search # Aggregate results on counting register (trace out search qubits) - counting_register_results: Dict[str, int] = {} + counting_register_results: dict[str, int] = {} if measurement_counts: for key in measurement_counts.keys(): counting_bits = key[:n_counting] @@ -446,10 +446,10 @@ def get_quantum_counting_results( def _get_counting_estimates( - counting_register_results: Dict[str, int], + counting_register_results: dict[str, int], n_counting: int, N: int, -) -> Tuple[List[float], List[float]]: +) -> tuple[list[float], list[float]]: """Convert counting register bitstrings to phase and count estimates. Args: diff --git a/src/braket/experimental/algorithms/quantum_phase_estimation/quantum_phase_estimation.py b/src/braket/experimental/algorithms/quantum_phase_estimation/quantum_phase_estimation.py index 4e0e7e55..0a8ef532 100644 --- a/src/braket/experimental/algorithms/quantum_phase_estimation/quantum_phase_estimation.py +++ b/src/braket/experimental/algorithms/quantum_phase_estimation/quantum_phase_estimation.py @@ -13,7 +13,8 @@ import math from collections import Counter -from typing import Any, Callable, Dict, List, Tuple +from collections.abc import Callable +from typing import Any import numpy as np @@ -126,7 +127,7 @@ def get_quantum_phase_estimation_results( precision_qubits: QubitSetInput, query_qubits: QubitSetInput, verbose: bool = False, -) -> Dict[str, Any]: +) -> dict[str, Any]: """Function to postprocess results returned by run_quantum_phase_estimation and pretty print results. @@ -211,7 +212,7 @@ def _binary_to_decimal(binary: str) -> float: def _get_quantum_phase_estimation_phases( measurement_counts: Counter, precision_qubits: QubitSetInput -) -> Tuple[List[float], Dict[str, int]]: +) -> tuple[list[float], dict[str, int]]: """Get Quantum Phase Estimates phase estimate from measurement_counts for given number of precision qubits. diff --git a/src/braket/experimental/algorithms/quantum_walk/quantum_walk.py b/src/braket/experimental/algorithms/quantum_walk/quantum_walk.py index b297109d..92cc34f2 100644 --- a/src/braket/experimental/algorithms/quantum_walk/quantum_walk.py +++ b/src/braket/experimental/algorithms/quantum_walk/quantum_walk.py @@ -1,4 +1,4 @@ -from typing import Any, Dict +from typing import Any import numpy as np @@ -108,7 +108,7 @@ def run_quantum_walk( circ: Circuit, device: Device, shots: int = 1000, -) -> Dict[str, Any]: +) -> dict[str, Any]: """Function to run quantum random walk algorithm and return measurement counts. Args: diff --git a/src/braket/experimental/algorithms/shors/shors.py b/src/braket/experimental/algorithms/shors/shors.py index 4a0ced2e..7af1096b 100644 --- a/src/braket/experimental/algorithms/shors/shors.py +++ b/src/braket/experimental/algorithms/shors/shors.py @@ -14,7 +14,7 @@ import math from collections import Counter from fractions import Fraction -from typing import Any, Dict, List, Optional +from typing import Any import numpy as np @@ -71,8 +71,8 @@ def shors_algorithm(integer_N: int, integer_a: int) -> Circuit: def run_shors_algorithm( circuit: Circuit, device: Device, - shots: Optional[int] = 1000, -) -> Dict[str, Any]: + shots: int | None = 1000, +) -> dict[str, Any]: """ Function to run Shor's algorithm and return measurement counts. @@ -180,11 +180,11 @@ def modular_exponentiation_amod15( def get_factors_from_results( - results: Dict[str, Any], + results: dict[str, Any], integer_N: int, integer_a: int, verbose: bool = True, -) -> Dict[str, Any]: +) -> dict[str, Any]: """ Function to postprocess dictionary returned by run_shors_algorithm and pretty print results @@ -235,7 +235,7 @@ def get_factors_from_results( return aggregate_results -def _get_phases(measurement_counts: Counter) -> List[float]: +def _get_phases(measurement_counts: Counter) -> list[float]: """ Get phase estimate from measurement_counts using top half qubits diff --git a/src/braket/experimental/algorithms/simons/simons.py b/src/braket/experimental/algorithms/simons/simons.py index f906f12b..a8c7e631 100644 --- a/src/braket/experimental/algorithms/simons/simons.py +++ b/src/braket/experimental/algorithms/simons/simons.py @@ -12,7 +12,7 @@ # language governing permissions and limitations under the License. from collections import Counter -from typing import Any, Dict, Optional, Tuple +from typing import Any import numpy as np from sympy import Matrix @@ -81,9 +81,7 @@ def simons_algorithm(oracle: Circuit) -> Circuit: return Circuit().h(range(nb_base_qubits)).add(oracle).h(range(nb_base_qubits)) -def run_simons_algorithm( - oracle: Circuit, device: Device, shots: Optional[int] = None -) -> QuantumTask: +def run_simons_algorithm(oracle: Circuit, device: Device, shots: int | None = None) -> QuantumTask: """Function to run Simon's algorithm and return the secret string. Args: @@ -109,7 +107,7 @@ def run_simons_algorithm( return task -def get_simons_algorithm_results(task: QuantumTask) -> Dict[str, Any]: +def get_simons_algorithm_results(task: QuantumTask) -> dict[str, Any]: """Get and print classically post-processed results from Simon's algorithm execution. Args: @@ -139,7 +137,7 @@ def get_simons_algorithm_results(task: QuantumTask) -> Dict[str, Any]: return output -def _get_secret_string(measurement_counts: Counter) -> Tuple[str, Counter]: +def _get_secret_string(measurement_counts: Counter) -> tuple[str, Counter]: """Classical post-processing to recover the secret string. The measurement counter contains k bitstrings which correspond to k equations: diff --git a/src/braket/experimental/auxiliary_functions/random_circuit/random_circuit.py b/src/braket/experimental/auxiliary_functions/random_circuit/random_circuit.py index 0f5d0af6..76cb3998 100644 --- a/src/braket/experimental/auxiliary_functions/random_circuit/random_circuit.py +++ b/src/braket/experimental/auxiliary_functions/random_circuit/random_circuit.py @@ -1,7 +1,6 @@ import inspect import math import random -from typing import List, Optional from braket.circuits import Circuit, Gate, Instruction from braket.circuits.gates import CNot, H, S, T @@ -10,8 +9,8 @@ def random_circuit( num_qubits: int, num_gates: int, - gate_set: Optional[List[Gate]] = None, - seed: Optional[int] = None, + gate_set: list[Gate] | None = None, + seed: int | None = None, ) -> Circuit: """ Generates a random quantum circuit.