diff --git a/notebooks/textbook/notebook_plotting.py b/notebooks/textbook/notebook_plotting.py index b86aa399..c73a450b 100644 --- a/notebooks/textbook/notebook_plotting.py +++ b/notebooks/textbook/notebook_plotting.py @@ -12,7 +12,6 @@ # language governing permissions and limitations under the License. import math -from typing import Dict, List import matplotlib.pyplot as plt @@ -20,13 +19,13 @@ # deutsch jozsa # bernstein vazirani def plot_bitstrings( - probabilities: Dict[str, float], + probabilities: dict[str, float], title: str = None, ) -> None: """Plot the measurement results. Args: - probabilities (Dict[str, float]): Measurement probabilities. + probabilities (dict[str, float]): Measurement probabilities. title (str): Title for the plot. xlabel (str): xlabel for the plot. ylabel (str): ylabel for the plot. @@ -39,11 +38,11 @@ def plot_bitstrings( # grovers and quantum fourier transform -def plot_bitstrings_formatted(probabilities: List[float]) -> None: +def plot_bitstrings_formatted(probabilities: list[float]) -> None: """Format the bistring and plot the measure results. Args: - probabilities (List[float]): Probabilities of measuring each bitstring. + probabilities (list[float]): Probabilities of measuring each bitstring. """ num_qubits = int(math.log2(len(probabilities))) format_bitstring = "{0:0" + str(num_qubits) + "b}" diff --git a/src/braket/experimental/algorithms/bells_inequality/bells_inequality.py b/src/braket/experimental/algorithms/bells_inequality/bells_inequality.py index ed794fad..abea5c5b 100644 --- a/src/braket/experimental/algorithms/bells_inequality/bells_inequality.py +++ b/src/braket/experimental/algorithms/bells_inequality/bells_inequality.py @@ -10,8 +10,8 @@ # 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 collections import Counter -from typing import List, Tuple import numpy as np from braket.circuits import Circuit, Qubit, circuit @@ -25,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. @@ -38,7 +38,7 @@ def create_bell_inequality_circuits( maximum violation of Bell's inequality. Returns: - List[Circuit]: Three circuits circAB, circAC, circBC. + list[Circuit]: Three circuits circAB, circAC, circBC. """ circAB = bell_singlet_rotated_basis(qubit0, qubit1, angle_A, angle_B) circAC = bell_singlet_rotated_basis(qubit0, qubit1, angle_A, angle_C) @@ -47,35 +47,35 @@ 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: - circuits (List[Circuit]): Three Bell inequality circuits in order circAB, circAC, circBC. + circuits (list[Circuit]): Three Bell inequality circuits in order circAB, circAC, circBC. device (Device): Quantum device or simulator. shots (int): Number of shots. Defaults to 1_000. Returns: - List[QuantumTask]: List of quantum tasks. + list[QuantumTask]: List of quantum tasks. """ tasks = [device.run(circ, shots=shots) for circ in circuits] return tasks 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: - tasks (List[QuantumTask]): List of quantum tasks. + tasks (list[QuantumTask]): List of quantum tasks. verbose (bool): Controls printing of the inequality result. Defaults to True. Returns: - Tuple[List[Counter], float, float, float]: results, pAB, pAC, pBC + tuple[list[Counter], float, float, float]: results, pAB, pAC, pBC """ results = [task.result().result_types[0].value for task in tasks] # probability result type prob_same = np.array([d[0] + d[3] for d in results]) # 00 and 11 states diff --git a/src/braket/experimental/algorithms/bernstein_vazirani/bernstein_vazirani.py b/src/braket/experimental/algorithms/bernstein_vazirani/bernstein_vazirani.py index c7816611..326e2e27 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 from braket.circuits import Circuit @@ -60,14 +59,14 @@ 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: task (QuantumTask): Quantum task to process. Returns: - Dict[str, float]: Results as a dictionary of bitstrings + dict[str, float]: Results as a dictionary of bitstrings """ probabilities = task.result().result_types[0].value diff --git a/src/braket/experimental/algorithms/chsh_inequality/chsh_inequality.py b/src/braket/experimental/algorithms/chsh_inequality/chsh_inequality.py index 77f4e349..e5a79373 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 from braket.circuits import Circuit, Qubit @@ -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. @@ -45,7 +44,7 @@ def create_chsh_inequality_circuits( b2 (float): Second basis rotation angle for second qubit. Returns: - List[Circuit]: List of quantum circuits. + list[Circuit]: List of quantum circuits. """ circ_a1b1 = bell_singlet_rotated_basis(qubit0, qubit1, a1, b1) circ_a1b2 = bell_singlet_rotated_basis(qubit0, qubit1, a1, b2) @@ -55,35 +54,35 @@ 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: - circuits (List[Circuit]): Four CHSH inequality circuits to run. + circuits (list[Circuit]): Four CHSH inequality circuits to run. device (Device): Quantum device or simulator. shots (int): Number of shots. Defaults to 1_000. Returns: - List[QuantumTask]: List of quantum tasks. + list[QuantumTask]: List of quantum tasks. """ tasks = [device.run(circ, shots=shots) for circ in circuits] return tasks 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: - tasks (List[QuantumTask]): List of quantum tasks. + tasks (list[QuantumTask]): List of quantum tasks. verbose (bool): Controls printing of the inequality result. Defaults to True. Returns: - Tuple[float, List[Counter], float, float, float]: The chsh_value, list of results, + tuple[float, list[Counter], float, float, float]: The chsh_value, list of results, and the four probabilities: E_a1b1, E_a1b2, E_a2b1, E_a2b2. """ results = [task.result().result_types[0].value for task in tasks] diff --git a/src/braket/experimental/algorithms/deutsch_jozsa/deutsch_jozsa.py b/src/braket/experimental/algorithms/deutsch_jozsa/deutsch_jozsa.py index 46334c99..520a2dde 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 from braket.circuits import Circuit, circuit @@ -108,14 +107,14 @@ 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: task (QuantumTask): Quantum task to process. Returns: - Dict[str, float]: Results as a dictionary of bitstrings + dict[str, float]: Results as a dictionary of bitstrings """ probabilities = task.result().result_types[0].value probabilities = np.round(probabilities, 10) # round off floating-point errors diff --git a/src/braket/experimental/algorithms/grovers_search/grovers_search.py b/src/braket/experimental/algorithms/grovers_search/grovers_search.py index e8fa6e59..7e83a9b6 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 @@ -109,7 +107,7 @@ def multi_control_not_constructor( is_outermost_call (bool): Whether the call is the outermost call from external functions. Returns: - Tuple[Circuit, int]: the multi-contol Not circuit and the number of ancilla in the circuit + tuple[Circuit, int]: the multi-contol Not circuit and the number of ancilla in the circuit """ if n_qubit == 1: n_ancilla = 1 diff --git a/src/braket/experimental/algorithms/qc_qmc/classical_qmc.py b/src/braket/experimental/algorithms/qc_qmc/classical_qmc.py index 39a8292b..b0c76106 100644 --- a/src/braket/experimental/algorithms/qc_qmc/classical_qmc.py +++ b/src/braket/experimental/algorithms/qc_qmc/classical_qmc.py @@ -2,7 +2,7 @@ import multiprocessing as mp import os from dataclasses import dataclass -from typing import Callable, List, Tuple +from typing import Callable 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: @@ -43,7 +43,7 @@ def classical_qmc( max_pool (int): Max workers. Defaults to 8. Returns: - Tuple[float, float]: Energies + tuple[float, float]: Energies """ e_hf = hartree_fock_energy(trial, prop) @@ -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: @@ -108,7 +108,7 @@ def full_imag_time_evolution( weight (float): weight for sampling. Returns: - Tuple[List[float], float]: energy_list, weights + tuple[list[float], float]: energy_list, weights """ # random seed for multiprocessing np.random.seed(int.from_bytes(os.urandom(4), byteorder="little")) @@ -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: @@ -141,7 +141,7 @@ def imag_time_propogator( e_shift (float): Reference energy, i.e. Hartree-Fock energy Returns: - Tuple[float, ndarray, float]: e_loc, new_walker, new_weight + tuple[float, ndarray, float]: e_loc, new_walker, new_weight """ # First compute the bias force using the expectation value of L operators num_fields = len(prop.v_gamma) @@ -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. @@ -212,7 +212,7 @@ def reortho(A: np.ndarray) -> Tuple[np.ndarray, float]: A (ndarray): MxN matrix. Returns: - Tuple[ndarray, float]: (Q, detR) + tuple[ndarray, float]: (Q, detR) Q (ndarray): Orthogonal matrix. A = QR. detR (float): Determinant of upper triangular matrix (R) from QR decomposition. """ @@ -309,28 +309,28 @@ 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. Args: x (ndarray): auxiliary fields - v_0 (List[ndarray]): modified one-body term from reordering the two-body + v_0 (list[ndarray]): modified one-body term from reordering the two-body operator + mean-field subtraction. - v_gamma (List[ndarray]): Cholesky vectors stored in list (L, num_spin_orbitals, + v_gamma (list[ndarray]): Cholesky vectors stored in list (L, num_spin_orbitals, num_spin_orbitals), without mf_shift. mf_shift (ndarray): mean-field shift \Bar{v}_{\gamma} stored in np.array format dtau (float): imaginary time step size trial (ndarray): trial state as np.ndarray, e.g., for h2 HartreeFock state, it is np.array([[1,0], [0,1], [0,0], [0,0]]) walker (ndarray): walker state as np.ndarray, others are the same as trial - green_funcs (List[ndarray]): one-body Green's function + green_funcs (list[ndarray]): one-body Green's function Returns: ndarray: new walker for next time step diff --git a/src/braket/experimental/algorithms/qc_qmc/qc_qmc.py b/src/braket/experimental/algorithms/qc_qmc/qc_qmc.py index 4823886c..bafc5c3e 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 typing import Callable import numpy as np import pennylane as qml @@ -29,7 +29,7 @@ def qc_qmc( trial_state_circuit: Callable, dev: qml.Device, max_pool: int = 8, -) -> Tuple[List[float], List[float]]: +) -> tuple[list[float], list[float]]: """Quantum assisted Auxiliary-Field Quantum Monte Carlo. Args: @@ -44,7 +44,7 @@ def qc_qmc( max_pool (int): Max workers. Defaults to 8. Returns: - Tuple[List[float], List[float]]: quantum and classical energies + tuple[list[float], list[float]]: quantum and classical energies """ e_hf = hartree_fock_energy(trial, prop) walkers = [trial] * num_walkers @@ -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.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: @@ -117,7 +117,7 @@ def q_full_imag_time_evolution( for quantum device; Returns: - Tuple[List[float],List[float],List[float],List[float]]: energy_list, weights, qs, cs + tuple[list[float], list[float], list[float], list[float]]: energy_list, weights, qs, cs """ # random seed for mutliprocessing np.random.seed(int.from_bytes(os.urandom(4), byteorder="little")) @@ -150,7 +150,7 @@ def imag_time_propogator_qaee( e_shift: float, trial_state_circuit: Callable, dev: qml.Device, -) -> Tuple[float, float, float, np.ndarray, float]: +) -> tuple[float, float, float, np.ndarray, float]: """Imaginary time propogator with quantum energy evaluations. Args: @@ -165,7 +165,7 @@ def imag_time_propogator_qaee( dev (qml.Device): Pennylane device Returns: - Tuple[float, float, float, ndarray, float]: propogatpr results + tuple[float, float, float, ndarray, float]: propogatpr results e_loc: local energy e_loc_q / c_ovlp: numerator q_ovlp / c_ovlp: denominator for evaluation of total energy @@ -284,11 +284,11 @@ 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: - givens (Tuple): (i, j, \theta, \varphi) + givens (tuple): (i, j, \theta, \varphi) """ (i, j, theta, varphi) = givens @@ -304,11 +304,11 @@ 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: - circuit_description (List[Tuple]): list of tuples containing Givens rotation + circuit_description (list[tuple]): list of tuples containing Givens rotation (i, j, theta, phi) in reversed order. """ @@ -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 @@ -454,7 +454,7 @@ def pauli_real( q_state (ndarray): orthonormalized walker state trial_state_circuit (Callable): quantum trial state u_matrix (ndarray): unitary transformation to change the Pauli into Z basis - pauli (List[int]): list that stores the position of the Z gate, e.g., [0,1] + pauli (list[int]): list that stores the position of the Z gate, e.g., [0,1] represents 'ZZII'. Returns: @@ -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 @@ -479,7 +479,7 @@ def pauli_imag( q_state (ndarray): orthonormalized walker state trial_state_circuit (Callable): quantum trial state u_matrix (ndarray): unitary transformation to change the Pauli into Z basis - pauli (List[int]): list that stores the position of the Z gate, e.g., [0,1] + pauli (list[int]): list that stores the position of the Z gate, e.g., [0,1] represents 'ZZII'. Returns: @@ -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$. @@ -508,7 +508,7 @@ def pauli_estimate( orthonormalized. trial_state_circuit (Callable): circuit unitary to prepare the quantum trial state u_matrix (ndarray): eigenvector of Cholesky vectors, $L = U \\lambda U^{\\dagger}$ - pauli (List[int]): list of 0 and 1 as the representation of a Pauli string, + pauli (list[int]): list of 0 and 1 as the representation of a Pauli string, e.g., [0,1] represents 'ZZII'. dev (qml.device): `qml.device('lightning.qubit', wires=wires)` for simulator; or `qml.device('braket.aws.qubit', device_arn=device_arn, wires=wires, shots=shots)` 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 2d212331..0a12f9e0 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 @@ -11,9 +11,6 @@ # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. - -from typing import List - import numpy as np from braket.circuits import Circuit, FreeParameter, Observable, circuit from braket.devices import Device @@ -25,7 +22,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. @@ -35,7 +32,7 @@ def cost_function( device (Device): Braket device to run on. circ (Circuit): QAOA circuit to run. coeffs (ndarray): The coefficients of the cost Hamiltonian. - cost_history (List[float]): History of cost evaluations. + cost_history (list[float]): History of cost evaluations. shots (int): Number of shots. Defaults to 0. Returns: 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 84d223c4..8f64c441 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 from braket.devices import Device @@ -148,7 +146,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:: @@ -157,7 +155,7 @@ def _compute_kernel(px: np.ndarray, py: np.ndarray, sigma_list: List[float] = [0 Args: px (ndarray): Probability distribution py (ndarray): Target probability distribution - sigma_list (List[float]): Standard deviations of distribution. Defaults to [0.1, 1]. + sigma_list (list[float]): Standard deviations of distribution. Defaults to [0.1, 1]. Returns: float: Value of the Gaussian RBF function for kernel(px, py). @@ -169,7 +167,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 @@ -190,7 +188,7 @@ def mmd_loss(px: np.ndarray, py: np.ndarray, sigma_list: List[float] = [0.1, 1]) Args: px (ndarray): Probability distribution py (ndarray): Target probability distribution - sigma_list (List[float]): Standard deviations of distribution. Defaults to [0.1, 1]. + sigma_list (list[float]): Standard deviations of distribution. Defaults to [0.1, 1]. Returns: float: Value of the MMD loss @@ -204,13 +202,13 @@ 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. Args: - neighbors (List[Tuple[int,int]]): List of qubit pairs. - parameters (List[List[List[FreeParameter]]]): List of FreeParameters. First index is + neighbors (list[tuple[int,int]]): List of qubit pairs. + parameters (list[list[list[FreeParameter]]]): List of FreeParameters. First index is n_layers, second is n_qubits, and third is [0,1,2] Returns: @@ -227,11 +225,11 @@ 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: - neighbors (List[Tuple[int,int]]): Neighbors for CNots to connect + neighbors (list[tuple[int,int]]): Neighbors for CNots to connect Returns: Circuit: CNot entangling layer @@ -243,11 +241,11 @@ 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: - parameters (List[List[FreeParameter]]): Parameters for rotation layers. + parameters (list[list[FreeParameter]]): Parameters for rotation layers. Returns: Circuit: Rotation layer 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 a51efda3..c7261f16 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,7 @@ import math from collections import Counter -from typing import Any, Callable, Dict, List, Tuple +from typing import Any, Callable import numpy as np from braket.circuits import Circuit, circuit @@ -125,7 +125,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. @@ -136,7 +136,7 @@ def get_quantum_phase_estimation_results( verbose (bool) : If True, prints aggregate results (default is False) Returns: - Dict[str, Any]: aggregate measurement results + dict[str, Any]: aggregate measurement results """ result = task.result() @@ -210,7 +210,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. @@ -219,7 +219,7 @@ def _get_quantum_phase_estimation_phases( precision_qubits (QubitSetInput): Qubits defining the precision register Returns: - Tuple[List[float], Dict[str, int]]: decimal phase estimates, precision results + tuple[list[float], dict[str, int]]: decimal phase estimates, precision results """ # Aggregate the results (i.e., ignore/trace out the query register qubits): diff --git a/src/braket/experimental/algorithms/quantum_walk/quantum_walk.py b/src/braket/experimental/algorithms/quantum_walk/quantum_walk.py index 8246d459..118ec004 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 from braket.circuits import Circuit @@ -107,7 +107,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: @@ -116,7 +116,7 @@ def run_quantum_walk( shots (int): Number of measurement shots. Default is 1000. Returns: - Dict[str, Any]: measurements and results from running Quantum Phase Estimation + dict[str, Any]: measurements and results from running Quantum Phase Estimation """ # Add results_types diff --git a/src/braket/experimental/algorithms/shors/shors.py b/src/braket/experimental/algorithms/shors/shors.py index 8cc5ed3e..a55b82ee 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 from braket.circuits import Circuit, circuit @@ -70,19 +70,19 @@ 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. Args: circuit (Circuit): Shor's algorithm circuit device (Device): Braket device backend - shots (Optional[int]) : Number of measurement shots (default is 1000). + shots (int | None) : Number of measurement shots (default is 1000). 0 shots results in no measurement. Returns: - Dict[str, Any]: measurements and results from running Shors's algorithm + dict[str, Any]: measurements and results from running Shors's algorithm """ task = device.run(circuit, shots=shots) @@ -179,23 +179,23 @@ 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 Args: - results (Dict[str, Any]): Results associated with quantum phase estimation run as produced + results (dict[str, Any]): Results associated with quantum phase estimation run as produced by run_shors_algorithm integer_N (int) : The integer to be factored integer_a (int) : Any integer that satisfies 1 < a < N and gcd(a, N) = 1. verbose (bool) : If True, prints aggregate results (default is False) Returns: - Dict[str, Any]: Factors of the integer N + dict[str, Any]: Factors of the integer N """ # unpack results @@ -234,14 +234,14 @@ 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 Args: measurement_counts (Counter) : measurement results from a device run Returns: - List[float] : decimal phase estimates + list[float] : decimal phase estimates """ # Aggregate the results (i.e., ignore/trace out the query register qubits): diff --git a/src/braket/experimental/algorithms/simons/simons.py b/src/braket/experimental/algorithms/simons/simons.py index b0e67f95..bb8f0cc8 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 braket.circuits import Circuit @@ -80,15 +80,13 @@ 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: oracle (Circuit): The oracle encoding the secret string device (Device): Braket device backend - shots (Optional[int]) : Number of measurement shots (default is None). + shots (int | None) : Number of measurement shots (default is None). The default number of shots is set to twice the arity of the oracle. shots must be a strictly positive integer. @@ -108,14 +106,14 @@ 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: task (QuantumTask): Task for Simon's algorithm. Returns: - Dict[str, Any]: Dict containing the secret string and marginalized output states + dict[str, Any]: Dict containing the secret string and marginalized output states """ task_result = task.result() @@ -138,7 +136,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: @@ -150,7 +148,7 @@ def _get_secret_string(measurement_counts: Counter) -> Tuple[str, Counter]: measurement_counts (Counter): Counter with all measured bistrings Returns: - Tuple[str, Counter]: the secret string and the marginalized output states + tuple[str, Counter]: the secret string and the marginalized output states """ nb_base_qubits = len(list(measurement_counts.keys())[0]) // 2 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..221487d9 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. @@ -19,9 +18,9 @@ def random_circuit( Args: num_qubits (int): Number of qubits in the circuit. num_gates (int): Number of instructions (gates) in the circuit. - gate_set (Optional[List[Gate]]): List of basis gates for the random circuit + gate_set (list[Gate] | None): List of basis gates for the random circuit (default is None). - seed (Optional[int]): Random seed for reproducibility (default is None). + seed (int | None): Random seed for reproducibility (default is None). Returns: Circuit: random quantum circuit.