Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use builtin types #144

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions notebooks/textbook/notebook_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,20 @@
# language governing permissions and limitations under the License.

import math
from typing import Dict, List

import matplotlib.pyplot as plt


# 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.
Expand All @@ -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}"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

Expand All @@ -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)
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

Expand All @@ -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)
Expand All @@ -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]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Tuple

from braket.circuits import Circuit, circuit


Expand Down Expand Up @@ -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

Expand All @@ -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
Expand Down
40 changes: 20 additions & 20 deletions src/braket/experimental/algorithms/qc_qmc/classical_qmc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(
Expand All @@ -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:
Expand All @@ -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)

Expand Down Expand Up @@ -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)


Expand All @@ -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:
Expand All @@ -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"))
Expand All @@ -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:
Expand All @@ -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)
Expand Down Expand Up @@ -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.
Expand All @@ -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.
"""
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading