Utils#
Operators#
This module contains functions for generating common operators used to generate hamiltonians and unitary transformations.
gates.py are more predefined in terms of dimensions I think?
- feedback_grape.utils.operators.cosm(a: Array) Array#
Cosine of a matrix.
- feedback_grape.utils.operators.create(n: int, dtype: ~numpy.dtype = <class 'jax.numpy.complex128'>) Array#
n-dimensional creation operator
- feedback_grape.utils.operators.destroy(n: int, dtype: ~numpy.dtype = <class 'jax.numpy.complex128'>) Array#
n-dimensional destruction operator
- feedback_grape.utils.operators.identity(dimensions, *, dtype=<class 'jax.numpy.complex128'>)#
Identity operator.
- Parameters:
dimensions (int) – Dimensions of the identity operator.
dtype (dtype) – Data type of the identity operator.
- Returns:
Identity operator of given dimensions and dtype.
- Return type:
jnp.ndarray
- feedback_grape.utils.operators.jaxify(a: Qobj) Array#
Convert a QuTiP Qobj to a JAX array.
- Parameters:
a (qt.Qobj) – The QuTiP Qobj to convert.
- Returns:
The JAX array representation of the Qobj.
- Return type:
jnp.ndarray
- feedback_grape.utils.operators.sigmam(dtype=<class 'jax.numpy.complex128'>)#
Lowering operator.
- feedback_grape.utils.operators.sigmap(dtype=<class 'jax.numpy.complex128'>)#
Raising operator.
- feedback_grape.utils.operators.sigmax(dtype=<class 'jax.numpy.complex128'>)#
Pauli X operator.
- feedback_grape.utils.operators.sigmay(dtype=<class 'jax.numpy.complex128'>)#
Pauli Y operator.
- feedback_grape.utils.operators.sigmaz(dtype=<class 'jax.numpy.complex128'>)#
Pauli Z operator.
- feedback_grape.utils.operators.sinm(a: Array) Array#
Sine of a matrix.
Gates#
This module define some basic quantum gates and their matrix representations.
- feedback_grape.utils.gates.cnot()#
Controlled NOT gate.
- feedback_grape.utils.gates.hadamard()#
Hadamard transform operator.
Superoperators#
- feedback_grape.utils.superoperator.sprepost(a, b)#
Create a superoperator that represents the action a * rho * b.dagger()
- Parameters:
a – Left operator
b – Right operator
- Returns:
Superoperator that maps rho -> a * rho * b.dagger()
- Return type:
E
States#
This module contains functions to implement some basic quantum states
- feedback_grape.utils.states.basis(n, k=0)#
Basis state in n-dimensional Hilbert space.
- feedback_grape.utils.states.coherent(n: int, alpha: complex) Array#
coherent state; ie: eigenstate of a lowering operator.
- Parameters:
n (int)
alpha (float/complex) – Eigenvalue of coherent state.
- Returns:
Coherent state in n-dimensional Hilbert space.
- Return type:
jnp.ndarray
Notes
The state |n⟩ represents the energy eigenstate (or number state) of the quantum harmonic oscillator with exactly n excitations (or n quanta/particles). This is also known as the Fock state. (where if 0th index is 1 then ground state, 1st index is 1 then 1 energy quanta (or photon in a cavity), etc.)
- feedback_grape.utils.states.fock(dimension: int, n: int) Array#
Creates a Fock state |n⟩ in an n_cav-dimensional Hilbert space.
Tensor#
Module to create composite quantum objects via tensor product.
Definition according to Nelsen and Chuang: The tensor product is a way of putting vector spaces together to form larger vector spaces. This construction is crucial to understanding the quantum mechanics of multi- particle systems.
- feedback_grape.utils.tensor.tensor(*args: Array) Array#
Compute the tensor/Kronecker product of two or more quantum objects.
- Parameters:
*args (jnp.ndarray) – Arrays to be tensored together.
- Returns:
The resulting quantum object after applying the tensor product.
- Return type:
jnp.ndarray
Fidelity#
- feedback_grape.utils.fidelity.fidelity(*, C_target, U_final, evo_type='unitary')#
Computes the fidelity between the final and target state/operator/density matrix.
- Parameters:
C_target (jnp.ndarray) – Target operator, state, or density matrix.
U_final (jnp.ndarray) – Final operator, state, or density matrix after evolution.
evo_type (str, optional) –
Type of fidelity calculation. Must be one of:
”unitary”: Uses normalized overlap for operators.
”state”: Uses normalized overlap for state vectors.
”density”: Uses Uhlmann fidelity for density matrices.
- Returns:
fidelity – Fidelity value in [0, 1].
- Return type:
float
Notes
- For
evo_type="unitary"or"state", fidelity is the squared magnitude of the normalized overlap: \(|\langle C_\mathrm{target} | U_\mathrm{final} \rangle|^2\)
- For
- For
evo_type="density", fidelity is computed using the Uhlmann formula: \(\left(\mathrm{Tr}\left[\sqrt{\sqrt{\rho}\, \sigma\, \sqrt{\rho}}\right]\right)^2\) where \(\rho\) and \(\sigma\) are density matrices.
- For
Note that, for the same initial and target states/density matrices, the fidelity of state and density may differ slightly due to the computation method.
- feedback_grape.utils.fidelity.is_positive_semi_definite(A, tol=1e-15)#
Check if a matrix is positive semi-definite.
- Parameters:
A (jnp.ndarray) – The matrix to check.
tol (float, optional) – Tolerance for numerical stability, default is 1e-8.
- Returns:
True if A is positive semi-definite, False otherwise.
- Return type:
bool
- feedback_grape.utils.fidelity.isbra(a: Array) bool#
Check if the input is a bra (row vector). :param A: Input array.
- Returns:
True if A is a bra, False otherwise.
- Return type:
bool
- feedback_grape.utils.fidelity.isket(a: Array) bool#
Check if the input is a ket (column vector). :param A: Input array.
- Returns:
True if A is a ket, False otherwise.
- Return type:
bool
- feedback_grape.utils.fidelity.ket2dm(a: Array) Array#
Convert a ket to a density matrix. :param a: Input ket (column vector).
- Returns:
Density matrix corresponding to the input ket.
- Return type:
dm
- feedback_grape.utils.fidelity.sqrtm_eig(A)#
GPU-friendly matrix square root using eigendecomposition.
Purity#
- feedback_grape.utils.purity.purity(*, rho)#
Computes the purity of a density matrix.
- Parameters:
rho – Density matrix.
- Returns:
Purity value.
- Return type:
purity
Optimizers#
- feedback_grape.utils.optimizers.optimize_L_BFGS(loss_fn, control_amplitudes, max_iter, convergence_threshold, learning_rate, progress, early_stop)#
Uses L-BFGS to optimize the control amplitudes.
- Parameters:
loss_fn – loss function to optimize.
control_amplitudes – Initial control amplitudes.
max_iter – Maximum number of iterations.
convergence_threshold – Convergence threshold for optimization.
learning_rate – Learning rate for the optimizer.
progress – If True, prints the progress of the optimization (for debugging - significantly slows optimization).
early_stop – If True, stops the optimization if the loss does not change significantly (if convergence threshold is reached).
- Returns:
Optimized control amplitudes. final_iter_idx: Number of iterations in the optimization. reward_history: Reward (fidelity, in [0, 1]) at each iteration. The
L-BFGS line search requires a scalar-valued
loss_fn(optax does not supporthas_auxhere), so the reward is recovered from the loss as-loss(loss =-fidelity).- Return type:
control_amplitudes
- feedback_grape.utils.optimizers.optimize_adam(loss_fn, control_amplitudes, max_iter, learning_rate, convergence_threshold, progress, early_stop)#
Uses Adam optimizer to optimize the control amplitudes. No stachasticity is used between iterations.
- Parameters:
loss_fn – loss function to optimize.
control_amplitudes – Initial control amplitudes.
max_iter – Maximum number of iterations.
learning_rate – Learning rate for the optimizer.
convergence_threshold – Convergence threshold for optimization.
progress – If True, prints the progress of the optimization.
early_stop – If True, stops the optimization if the loss does not change significantly (if convergence threshold is reached).
- Returns:
Optimized control amplitudes. final_iter_idx: Number of iterations in the optimization. reward_history: Reward (e.g. fidelity, in [0, 1]) at each iteration, as
returned by the auxiliary output of
loss_fn.- Return type:
control_amplitudes
- feedback_grape.utils.optimizers.optimize_adam_feedback(loss_fn, control_amplitudes, max_iter, learning_rate, convergence_threshold, key, progress, early_stop, window=50, patience=3)#
Uses Adam optimizer to optimize the control amplitudes.
The reward is a stochastic estimate (it is averaged over
batch_sizesampled trajectories), so consecutive rewards differ by an amount that does not decay as the optimization converges. Convergence is therefore measured by comparing the mean reward over the lastwindowiterations against the mean over thewindowiterations before those. Averaging suppresses the sampling noise, and keeping the two windows disjoint stops the comparison from collapsing back into a single-sample difference.- Parameters:
loss_fn – loss function to optimize.
control_amplitudes – Initial control amplitudes.
max_iter – Maximum number of iterations.
learning_rate – Learning rate for the optimizer.
convergence_threshold – Smallest improvement in mean reward, over
windowiterations, that is still considered progress. Must be set above the noise floor of the reward (roughlystd(reward) * sqrt(2 / window)once the reward has plateaued) or it can never be reached.key – JAX random key for stochastic operations (so that each iteration has is different).
progress – If True, prints the progress of the optimization.
early_stop – If True, stops the optimization once the reward has stopped improving by more than
convergence_threshold.window – Number of iterations averaged into each of the two compared windows. Larger values suppress more noise but delay the earliest possible stop, which is
2 * windowiterations.patience – Number of consecutive comparisons that must fall below
convergence_thresholdbefore stopping. Guards against a single comparison landing low by chance.
- Returns:
Optimized control amplitudes. final_iter_idx: Number of iterations in the optimization. reward_history: Reward (e.g. mean fidelity/purity, in [0, 1]) at each
iteration, as returned by the auxiliary output of
loss_fn.- Return type:
control_amplitudes
POVM#
- feedback_grape.utils.povm.povm(rho_cav, povm_measure_operator, initial_povm_params, gate_param_constraints, rng_key, evo_type)#
Perform a POVM measurement on the given state. Gets called when user provides measurement_flag=True in one of the Gate NamedTuples.
- Parameters:
rho_cav (jnp.ndarray) – The density matrix of the cavity.
povm_measure_operator (callable) – The POVM measurement operator. - It should take a measurement outcome and list of parameters as input. - The measurement outcome options are either 1 or -1
initial_povm_params (list) – Initial parameters for the POVM measurement operator.
gate_param_constraints (list) – Constraints for the gate parameters.
rng_key (jax.random.PRNGKey) – Random number generator key for stochastic operations.
evo_type (str) – Evolution type, either ‘state’ or ‘density_matrix’.
- Returns:
A tuple containing the post-measurement state, the measurement result, and the log probability of the measurement outcome.
- Return type:
tuple
Solver#
Module for solving the time-dependent Schrödinger equation and master equation
- feedback_grape.utils.solver.mesolve(*, jump_ops, rho0, H=None, tsave=Array([0., 1.], dtype=float64))#
- Parameters:
H – List of Hamiltonians for each time interval.
Hamiltonian) ((time-dependent)
jump_ops – List of collapse operators.
rho0 – Initial density matrix.
tsave – List of time intervals.
- Returns:
Evolved density matrix after applying the time-dependent Hamiltonians.
- Return type:
rho_final
- feedback_grape.utils.solver.sesolve(Hs, initial_state, delta_ts, evo_type='density')#
- Parameters:
Hs – List of Hamiltonians for each time interval.
Hamiltonian) ((time-dependent)
initial_state – Initial state.
delta_ts – List of time intervals.
- Returns:
Evolved state after applying the time-dependent Hamiltonians.
- Return type:
U
QubitCavity (Modeling API)#
- class feedback_grape.utils.modeling.Cavity(index, dim, dims)#
Bases:
object- __init__(index, dim, dims)#
- property a#
- property adag#
- property identity#
- class feedback_grape.utils.modeling.Qubit(index, dims)#
Bases:
object- __init__(index, dims)#
- property cnot#
- property hadamard#
- property identity#
- property sigmam#
- property sigmap#
- property sigmax#
- property sigmay#
- property sigmaz#
- class feedback_grape.utils.modeling.QubitCavity(num_qubits: int, *cavity_dims: int)#
Bases:
object- __init__(num_qubits: int, *cavity_dims: int)#
Qubit comes first in the Hilbert space, followed by cavities.
- Parameters:
num_qubits (int) – Number of qubits.
*cavity_dims (int) – Dimensions of each cavity.
- feedback_grape.utils.modeling.embed(op, idx, dims)#
Embed operator op at position idx in total Hilbert space of dims.