Skip to content

qruise-toolset

qruise.toolset.hamiltonian

Docstring for the hamiltonian.py module.

Anything that is related to the definition of the Hamiltonian of a quantum system.

Hamiltonian

Declaring the Hamiltonian of a system of interest.

This instantiates a Hamiltonian object with time-indepedent part specified by H0 and time-dependent parts drives passed as a list of tuples with the first element the basis and the second element as its time-dependent coefficient.

Parameters:

Name Type Description Default
H0 Array | Qobj

JAX matrix or a Qobj representing the time-independent part of the Hamiltonion.

None
Ht List[Tuple[Array | Qobj, Callable]]

List of tuples with the first element being the basis and the second being the time-dependent coefficient.

None

Attributes:

Name Type Description
H0 Array

JAX array signifying the time-independent part of the Hamiltonian.

coeffs List[Callable]

List of callable functions defining the coefficients of the time-dependent part of the Hamiltonian.

hamils List[Array]

List of JAX arrays which in combination with coeffs specifies the operators of the time-depenedent parts of the Hamiltonian.

Methods:

Name Description
add_term

add a time-dependent part to the Hamiltonian

inactive_params property

Return the set of frozen parameter keys from all signal chain coefficients.

Returns:

Type Description
Set[str]

Union of inactive_params from every coefficient that exposes the attribute (i.e. every SignalChainComponent in coeffs).

__call__(t, params)

Return the Hamiltonian at a given instance of time.

Parameters:

Name Type Description Default
t float | Array

An instance of time.

required
params Dict[str, float]

Dictiorary of parameters that is passed to the envelopes of the Hamiltonian's terms.

required

Returns:

Type Description
Array

The Hamiltonian matrix.

add_term(hamil, coeff)

Method to add extra terms to the base Hamiltonian.

Given the basis hamil and its coefficient coeff a new time-depenedent part will be added to the Hamiltonian.

Parameters:

Name Type Description Default
hamil Array | Qobj

Hamiltonian matrix operator.

required
coeff Callable

Callable function as the coefficient of the Hamiltonian channel hamil, usually time-dependent.

required

qruise.toolset.control_stack

Docstring for the control_stack.py module.

Module for defining the functional behaviour of different control electronics in a control stack.

Every component falls into two categories: (i) it is either a source, i.e. it produces a signal, or (ii) it transforms the input signal from a source. These components can be represented by a function. The reason we use classes here is due to the fact that some transformations are non-local in time. Therefore some memory kernels or internal states must be tracked.

ADC

Bases: SignalChainComponent

Analogue-to-Digital component.

It discretise the input up to a precision indicated by the number of bits. The ADC component is limited to a range of operation voltage, namely \(V_{min}\) and \(V_{max}\). Mathematically, it transforms an input signal \(f(t)\) via

\[ \begin{gather} \delta = \frac{V_{max} - V_{min}}{2^n - 1}\\ f_{d}(t) = V_{min} + \Big[\frac{f(t) - V_{min}}{\delta}\Big] \delta \end{gather} \]

where \(n\) is the number of bits, and \(f_d(t)\) is the digitised representation of the function \(f(t)\).

Gaussian

Bases: SignalChainComponent

AWG component generating Gaussian pulse.

The mathematical expression is given by

\[ \frac{a}{\sigma\sqrt{2\pi}} \exp [-\frac{(t-\mu)^2}{2\sigma^2}] \]

where \(a\) is a factor that scales the maximum value of the pulse, \(\sigma\) is the standard deviation and \(\mu\) is the mean value.

Heaviside

Bases: SignalChainComponent

AWG component generating a Heaviside pulse.

The definition is given by

\[ H(t) = \left\lbrace \begin{aligned} &0\,,\; &t \lt 0 \\ &0\,,\; &t = 0 \\ &1\,,\; &t \gt 0 \end{aligned} \right. \]

LocalOscillator

Bases: SignalChainComponent

AWG component generating pure sine pulse.

The mathematical expression is given by

\[ A \sin(\omega t + \phi) \]

where \(A\) is the amplitude, \(\omega\) is the frequency, and \(\phi\) is a constant phase.

PWCPulse

Bases: SignalChainComponent

Piece-wise constant pulse.

Outputs a piece-wise constant pulse at a certain time instance t on a given time interval [t0, t1] and a given time differential dt, provided that the array of the pulse is known. Mathematically,

\[ n = \lfloor \frac{t - t_0}{dt} \rfloor\\ \mathrm{env}[n] \]

where \(\mathrm{env}\) is the pulse profile and \([n]\) shows the index n of the pulse profile.

Rectangular

Bases: SignalChainComponent

AWG component generating a rectangular pulse.

The definition is given by

\[ \mathrm{rect}(t, \tau_1, \tau_2) = \Theta(t - \tau_1) - \Theta(t - \tau_2) \]

where \(\Theta(t)\) is the Heaviside function. If \(\tau_1 > \tau_2\) then the rectangular pulse has a positive range where as if \(\tau_1 < \tau_2\), the function has a negative range.

SignalChainComponent

Abstract signal chain component.

Parameters:

Name Type Description Default
name str

Name of the component.

required
params Dict[str, ArrayOrFloat]

Component parameters.

required
source Callable | None

The component signifying an external component asthe input source if the component is not a source itself.

None
**kwargs Dict

Keyworded arguments.

{}

Attributes:

Name Type Description
params Dict[str, ArrayOrFloat]

Default values for a subset of parameters associated with the component.

inactive_params Set[str]

Set of strings used to let JAX know which parameters do not contribute to the gradient when differentiated.

SlepianPulse

Bases: SignalChainComponent

Slepian (DPSS) pulse generator.

Generates a discrete-time Slepian (Discrete Prolate Spheroidal Sequence, DPSS) envelope over the interval [t0, t1] with step d t. Let N = ⌊(t1 - t0)/d t⌋ and sample times t_n = t0 + n·d t for n = 0,…,N−1. The DPSS v_k[n] (k = 0,1,…) are the length-N sequences that maximize spectral concentration in the baseband [−W, W] cycles/sample (with 0 < W < 1/2). They satisfy the discrete Slepian eigenproblem

\[ \sum_{m=0}^{N-1} D_{n-m}(W)\, v_k[m] = \lambda_k\, v_k[n], \qquad n=0,\ldots,N-1, \]

where

\[ D_\ell(W) = \begin{cases} \dfrac{\sin\!\big(2\pi W \ell\big)}{\pi \ell}, & \ell \neq 0,\\[6pt] 2W, & \ell = 0, \end{cases} \]

and \(\lambda_k \in [0,1]\) is the in-band energy concentration. The time–bandwidth product is \(NW = N W\), so you may parameterize via either \(NW\) or \(W = NW/N\).

Parameters:

Name Type Description Default
name str

Name of the component.

required
params Dict[str, ArrayOrFloat]

Component parameters. SlepianPulse has two parameters to tune its behaviour. NW is the time-bandwidth product, and amplitude is a 1D array of length Kmax specifying the amplitude of each taper.

required
source Callable | None

The component signifying an external component as the input source if the component is not a source itself.

None
**kwargs Dict

Keyworded arguments. SlepianPulse has five keyworded arguments to tune its behaviour. M is the length of the sequence, t0 is the starting time of the pulse, dt is the time step, Kmax is the number of tapers to use, and sym specifies whether to use symmetric (True) or periodic (False) extension of the sequence.

{}

Attributes:

Name Type Description
params Dict[str, ArrayOrFloat]

Default values for a subset of parameters associated with the component.

inactive_params Set[str]

Set of strings used to let JAX know which parameters do not contribute to the gradient when differentiated.

Notes
  • The zeroth taper (\(k=0\)) is maximally concentrated and is commonly used alone as the “Slepian pulse”.
  • Using multiple tapers (\(K>1\)) can tailor time/frequency roll-off by choosing the coefficients \(c_k\).
References
  • D. Slepian, "Prolate Spheroidal Wave Functions, Fourier Analysis, and Uncertainty—V," Bell Syst. Tech. J. 57, 1371–1430 (1978).
  • D. J. Thomson, "Spectrum estimation and harmonic analysis," Proc. IEEE 70, 1055–1096 (1982).
  • D. B. Percival and A. T. Walden, Spectral Analysis for Physical Applications (1993).

TransferFunc

Bases: SignalChainComponent

Transfer Function modelled in its space-state representation.

State-space representation of transfer function, also known as Rosenbrock system matrix, for dynamical system of the form

\[ \begin{aligned} \dot{x}(t) &= Ax(t) + Bu(t)\\ y(t) &= Cx(t) + Du(t) \end{aligned} \]

is given by the Rosenbrock system matrix as follows

\[ \begin{aligned} P(s) = \begin{pmatrix} sI - A & -B\\ C & D \end{pmatrix}. \end{aligned} \]

As a linear time-invariant systems, transfer functions have state-space reperestation[1].

Parameters:

Name Type Description Default
name str

Name of the component.

required
params Dict[str, ArrayOrFloat]

Component parameters.

required
source Callable | None

The component signifying an external component asthe input source if the component is not a source itself.

None
**kwargs Dict

Keyworded arguments. TransferFunc has two keyworded arguments to tune its behaviour. One is n_max which specifies how finely we create the time grid and second max_squarings which species the maximum power the expm scaling-and-squaring order.

{}

Attributes:

Name Type Description
params Dict[str, ArrayOrFloat]

Default values for a subset of parameters associated with the component.

inactive_params Set[str]

Set of strings used to let JAX know which parameters do not contribute to the gradient when differentiated.

Notes

[1] De Schutter, B., 2000. Minimal state-space realization in linear system theory: an overview. Journal of computational and applied mathematics, 121(1-2), pp.331-354.

freeze_params(freeze_keys)

Decorator to set a set a set of varibales as inactive parameters.

Parameters:

Name Type Description Default
freeze_keys Set

Set of keys to be set as inactive variables.

required

Returns:

Type Description
Callable

Decorated function with certain variables set as inactive.

qruise.toolset.parameter

Docstring for the parameter.py module.

The intention is to enable the user to effectively and efficiently keeps track of the parameters involved in the simulation of a quantum system. The only and single source of truth on which the user can rely to get current value of the parameters after any mutable operation. This allows other parts of qruise-toolset to remain static.

ParameterCollection

A collection of parameters.

A single source of truth to keep track of parameters to be optimised or parsed anytime anywhere.

Attributes:

Name Type Description
params Dict[str, float]

A dictionary of parameters.

Methods:

Name Description
add_param

Add a key-value pair to the collection.

get_val

Get the value of a given key.

add_dict

Adding an input dictionary as a batch of key-pair values.

get_collection

Returns the collection of parameters.

__repr__()

Print nicely all the parameters in the collection.

Returns:

Type Description
str

Nicely formatted string listing all the parameters.

add_dict(source_dict)

Add a set of key-value pairs in a batch mode.

Parameters:

Name Type Description Default
source_dict Dict[str, float]

A dictionary of key-value pairs.

required

add_param(key, val)

Add a single key-value pair to the parameter collection.

Parameters:

Name Type Description Default
key str

A string specifying the name of the parameter.

required
val float

Value associated with the key.

required

get_collection()

Return all the parameters in the collection.

Returns:

Type Description
Dict[str, float]

Dictionary of key-value pairs of the parameters in the collection.

get_val(key)

Get the value of a parameter.

Parameters:

Name Type Description Default
key str

The name of the parameter.

required

Returns:

Type Description
float

The value of the parameter.

qruise.toolset.transforms

Docstring for the transforms.py module.

The sole purpose of this module so to provide the user with utilities to handle optimal control problem efficiently by providing the initial and target states. It provides checks and tools to ensure those states are defined in a sane manner.

Transform

Specify the initial and target states of the Quantum Optimal Control Problem.

Parameters:

Name Type Description Default
input_state Qobj | Array

The initial state.

required
output_state Qobj | Array

The target state.

required

Attributes:

Name Type Description
input_state Qobj | Array

The initial state.

output_state Qobj | Array

The target state.

dims Tuple

Dimension of the initial and target states.

Methods:

Name Description
get_y0_yt

Get the initial state and the target state as a tuple.

get_y0_yt()

Helper method to get the initial and target states.

Returns:

Type Description
Tuple[Array, Array]:

Tuple of two elements. The first is the initial state and the second is the target state.

qruise.toolset.problem

Docstring for the problem.py module.

A Problem defines a set of ordinary differential equations to solve the dynamics of a quantum system given its Hamiltonian. Generally speaking, if the Hamiltonian of a system is known, one can solve the dynamics of a closed quantum system using the Schrödinger equation, or if one deals with an open quantum system, the von Neumann equation or Lindblad equation is the right choice.

EnsembleProblem

Bases: Problem

An ensemble problem.

Parameters:

Name Type Description Default
hamiltonian Hamiltonion

The Hamiltonian of interest.

required
y0 EnsembleArray | Array

List of initial state vectors or density matrices.

required
params Dict[str, EnsembleArrayF | ArrayF]

Simulation parameters with values either passed as a list of values or a single value.

required
time_span Tuple[EnsembleFloat | float, EnsembleFloat | float]

Simulation time span indicating the starting and ending times. Each element can be either a list of scalars or a single scalar.

required
c_ops List[Qobj | Array] | None

Collapse operators for open-system (Lindblad) evolution. Each operator must be a square matrix of size matching the Hamiltonian dimension. Defaults to None (closed system).

None

Attributes:

Name Type Description
hamiltonian Hamiltonian

System's Hamiltonian.

y0 EnsembleArray | Array

The initial quantum state(s).

params Dict[str, EnsembleArrayF | ArrayF]

Simulation parameters

time_span Tuple[EnsembleFloat | float, EnsembleFloat | float]

Simulation time span; tuple of starting and ending times. Can be either a list of scalar values or a single scalar.

problem()

Provide an AbstractSolver with necessary inputs for a simulation.

Returns:

Name Type Description
Tuple Tuple[Array, Dict[str, ArrayF | EnsembleArrayF], Tuple[float | EnsembleFloat, float | EnsembleFloat], InAxes]

A tuple with the first element as the initial quantum state, the second as a dictionary of parameters, the third as a simulation time span and the last as the axes description for JAX vectorisation map.

remake(**kwargs)

Create a new ensemble problem with a new set of variables.

Parameters:

Name Type Description Default
**kwargs Dict

Dictionary of key-value pairs. The keys can be 'hamiltonian', 'y0', 'params', 'time_span', or 'c_ops'.

{}

Returns:

Type Description
EnsembleProblem

A new ensemble problem that uses variables from an already instantiated EnsembleProblem if not mentioned in the kwargs.

Problem

Generic class for specifying a quantum simulation problem.

Parameters:

Name Type Description Default
hamiltonian Hamiltonian

The Hamiltonian of interest.

required
y0 Array

The initial state of the quantum system.

required
params Dict[str, ArrayF]

Parameters that uniquely define the Hamiltonian.

required
time_span Tuple[float, float]

Time interval over which the problem is defined. Basically, the start and end of the simulation.

required
c_ops List[Qobj | Array] | None

Collapse operators for open quantum system evolution. Each operator must be a (d, d) matrix where d is the Hilbert space dimension. Stored as self.c_ops and used by lindblad(), lindbladpwc(), and lindbladpwc_trotter(). Defaults to an empty list.

None

Attributes:

Name Type Description
hamiltonian Hamiltonian

Hamiltonian of the system.

y0 Array

Initial quantum state.

time_span Tuple[float, float]

Simulation starting and ending times.

dimension Int

Size of the Hilbert space.

Methods:

Name Description
problem

Return a tuple of initial condition, parameters and simulation time span.

schroedinger

System of ODEs for the Schrödinger equation.

von_neumann

System of ODEs for the von Neumann master equation.

lindblad

System of ODEs for the Lindblad equation.

sepwc

System of equations for piece-wise constant Schrödinger equation.

mepwc

System of equations for piece-wise constant master equation.

inactive_params property

Return the set of frozen parameter keys from the Hamiltonian.

Returns:

Type Description
Set[str]

Delegates to self.hamiltonian.inactive_params.

lindblad()

Return the Lindblad master equation.

The Lindblad master equation is given by

\[ i\frac{\partial}{\partial t}\rho_t = [H_t, \rho_t] + \sum_i \gamma_i \left(L_i \rho_t L_i^\dagger - \frac{1}{2}\left\{L_i^\dagger L_i, \rho_t \right\}\right), \]

where \(i\) is the imaginary number, \(\rho_t\) is the density matrix of the system at time \(t\), and \(H_t\) is the Hamiltonian of the system. The notion \([., .]\) stands on the commutation relation, whereas \(\{., .\}\) stands on anti-commutation. The operators \(L_i\) are called collapse operators. We used the convention of setting \(\hbar = 1\).

Collapse operators are taken from self.c_ops, which is set at construction time via Problem.__init__.

Returns:

Type Description
Callable

ODE defining the Lindblad master equation.

Raises:

Type Description
ValueError

If y0 is not a square density matrix whose dimension matches the Hamiltonian.

lindbladpwc()

Compile an equation for solving a (piecewise-constant) Lindblad master equation.

Collapse operators are taken from self.c_ops, which is set at construction time via Problem.__init__.

Returns:

Name Type Description
Callable Callable

A function (t, dt, y, args) -> rho_next for one piecewise-constant step.

Raises:

Type Description
ValueError

If y0 is not a square density matrix whose dimension matches the Hamiltonian.

lindbladpwc_trotter()

Compile a piecewise-constant Lindblad equation solver using Trotter splitting.

Collapse operators are taken from self.c_ops, which is set at construction time via Problem.__init__.

Returns:

Name Type Description
Callable Callable

A function (t, dt, y, args) -> rho_next for one piecewise-constant step.

Raises:

Type Description
ValueError

If y0 is not a square density matrix whose dimension matches the Hamiltonian.

Warnings

The first-order Trotter splitting can violate complete positivity for large time steps. Consider using lindbladpwc if you face accuracy issues.

Notes

This method is significantly faster than lindbladpwc() for larger systems because it avoids exponentiating the full d²×d² Liouvillian superoperator. Instead, it: 1. Applies unitary evolution by exponentiating the d×d Hamiltonian 2. Applies dissipation directly on the density matrix via an explicit Euler step

Complexity: O(d³) vs O(d⁶) for standard lindbladpwc() Accuracy: First-order in dt (Lie–Trotter + Euler discretization)

Mathematical approach: - Standard lindbladpwc: ρ(t+dt) = exp(L·dt) ρ(t), where L is d²×d² superoperator - This method: ρ(t+dt) ≈ exp(L_H·dt) [ρ(t) + dt·D(ρ(t))], i.e. a Lie–Trotter split with exact Hamiltonian evolution and a first-order approximation to exp(L_D·dt).

For most practical applications with small dt, this method provides similar accuracy to lindbladpwc() but runs much faster. Use lindbladpwc() if you need maximum numerical precision or are working with very large time steps.

Examples:

>>> prob = Problem(H, rho_0, params, (t0, tfinal), c_ops=[c_op])
>>> solver = PWCSolver(n=grid_size, store=True)
>>> solver.set_system(prob.lindbladpwc_trotter())
>>> _, rhos = solver.evolve(*prob.problem())

mepwc()

Compile an equation for solving a quantum master equation.

Returns:

Name Type Description
Callable Callable

A callable function that solves unitary evolution of a quantum density matrix.

Raises:

Type Description
ValueError

If y0 is not a square density matrix whose dimension matches the Hamiltonian.

problem(**kwargs)

Return the initial condition, parameters and the time span.

Parameters:

Name Type Description Default
**kwargs Dict

Dictionary of key-value paris. The keys can be the following: 'y0', 'params' and 'time_span'.

{}

Returns:

Type Description
Tuple[Array, Dict[str, float], Tuple[float, float]]:

Tuple with the first element as a initial condition, the second element as the parameter dictionary and the last as a tuple of time span.

remake(**kwargs)

Create a new problem with new set of variables.

Parameters:

Name Type Description Default
**kwargs Dict

Dictionary of key-value pairs. The keys can be 'hamiltonian', 'y0', 'params', 'time_span', or 'c_ops'.

{}

Returns:

Type Description
Problem

A new problem that uses variables from an already instantiated Problem if not mentioned in the kwargs.

schroedinger()

Return the Schrödinger equation.

The Schrödinger is given by

\[ i\frac{\partial}{\partial t}|\psi(t)\rangle = H(t)|\psi(t)\rangle, \]

where \(i\) is the imaginary number, \(|\psi(t)\rangle\) is the wave-function of the system at time \(t\), and \(H(t)\) is the Hamiltonian of the system. We used the convention of setting \(\hbar = 1\).

Returns:

Type Description
Callable

ODE defining the Schrödinger equation.

sepwc()

Compile an equation for solving the Schrödinger equation.

Returns:

Name Type Description
Callable Callable

A callable function that solves unitary evolution of a quantum state vector.

von_neumann()

Return the von Neumann equation.

The von Neumann master equation is given by

\[ i\frac{\partial}{\partial t}\rho(t) = [H(t), \rho(t)], \]

where \(i\) is the imaginary number, \(\rho(t)\) is the density matrix of the system at time \(t\), and \(H(t)\) is the Hamiltonian of the system. The notion \([., .]\) stands on the commutation relation. We used the convention of setting \(\hbar = 1\).

Returns:

Type Description
Callable

ODE defining the von Neumann master equation.

Raises:

Type Description
ValueError

If y0 is not a square density matrix whose dimension matches the Hamiltonian.

QOCProblem

Bases: Problem

Specify a Quantum Optimal Control problem.

Parameters:

Name Type Description Default
hamiltonian Hamiltonian

The Hamiltonian of interest.

required
y0 Array | Qobj

The initial state of the quantum system.

required
params Dict[str, float]

Parameters that uniquely define the Hamiltonian.

required
time_span Tuple[float, float]

Time interval over which the problem is defined. Basically, the start and end of the simulation.

required
yt Array | Qobj

The desired target state.

required
loss Callable

Loss function used for the minimisation problem.

required
c_ops List[Qobj | Array] | None

Collapse operators for open quantum system evolution. Each operator must be a (d, d) matrix where d is the Hilbert space dimension. Stored as self.c_ops and used by lindblad(), lindbladpwc(), and lindbladpwc_trotter(). Defaults to an empty list.

None

Attributes:

Name Type Description
yt Array | Qobj

The desired target state.

loss Callable

Loss function used for the minimisation problem.

problem(**kwargs)

Return values required as the inputs of an optimiser.

Parameters:

Name Type Description Default
**kwargs Dict

Dictionary of key-value pairs. The keys can be the following: 'y0', 'params', 'time_span' and 'yt'.

{}

Returns:

Type Description
Tuple[Arr, Dict[str, float], Tuple[float, float], Array]:

Tuple of four elements. The first is the initial state, the second is the set of parameters, the third is the simulation time span and the last is the target state.

remake(**kwargs)

Create a new quantum optimal control problem with new set of variables.

Parameters:

Name Type Description Default
**kwargs Dict

Dictionary of key-value pairs. The keys can be 'hamiltonian', 'y0', 'params', 'time_span', 'c_ops', 'yt' and 'loss'.

{}

Returns:

Type Description
Problem

A new quantum optimal control problem that uses variables from an already instantiated Problem if not mentioned in the kwargs.

qruise.toolset.solvers.abstract_solver

Abstract solvers and abstract minimisers module.

Contains declaration of two major classes for abstract solvers and optimisers.

AbstractSolver

Bases: ABC

Abstract Solver.

Parameters:

Name Type Description Default
eq Callable

Defines the equation governing the dynamics.

None

Methods:

Name Description
set_system

Set the equation governing the dynamics.

evolve

Evolve the dynamics of the system.

ensemble_evolve

Evolve the dynamics of an ensemble of systems.

ensemble_evolve(y0, params, t_span, in_axes, cartesian=False, compile=False)

Simulate an ensemble problem.

The ensemble simulation can take place over either an ensemble of initial conditions, parameters or simulation time spans.

Parameters:

Name Type Description Default
y0 Array

A JAX array, a tensor of rank 1, 2 or 3. If the rank is 1, no parallelisation takes place.

required
params Dict[str, ArrayOrFloat]

Dictionary of parameters with values passed as either JAX arrays or floats.

required
t_span Tuple[ArrayOrFloat, ArrayOrFloat]

Tuple of the simulation starting and ending points. Passed as either JAX arrays or floats.

required
in_axes InAxes

Tuple of axes that provides jax.vmap method with a pytree structure for an ensemble simulation.

required
cartesian bool

If set to true, compiles a vectorised map function to simulate an ensemble problem and return the result as a an array for a set yielded by the Cartesian product of all the parameters , initial conditions and simulation time spans.

False
compile bool

If the pytree structure of in_axes changes, set to True to compile a new jitted JAX vmapped function that is compatible.

False

Returns:

Name Type Description
Array Array | Solution

Return an \(n\)-dimensional JAX array solution.

evolve(y0, params, t_span) abstractmethod

Solve for the dynamics of a given system.

For a given equation describing the dynamics, this method evolves the state of the system given its initial condition, input parameters and the interval over which the dynamics must be simulated.

Parameters:

Name Type Description Default
y0 Array

Array specifying the initial condition.

required
params Dict[str, float]:

Set of parameters.

required
t_span Tuple[float, float]

Tuple indicating the starting and ending times of the simulation.

required

Returns:

Type Description
Tuple[Array, Array] | Solution:

Result of the dynamics returned as a JAX array or a diffrax solution. The first element of the tuple is the time grid.

set_system(eq)

Set the equation describing the dynamics of the system.

Parameters:

Name Type Description Default
eq Callable

The equation governing the dynamics of the system.

required

qruise.toolset.solvers.solvers

Solvers Module.

Class definitions for Ordinary Differential Equations and Piece-Wise Constant solvers.

The module is compatible with diffrax for solving ODE'. Piece-wise constant solver used in extreme cases when ODE solvers fail to converge (which is quite rare). It uses matrix exponentiation of the Hamiltonian to generates unitaries that are infinitesimal generators of the system's dynamics.

ODESolver

Bases: AbstractSolver

Solve an ODE equation.

Parameters:

Name Type Description Default
solver AbstractSolver

A diffrax ODE solver.

required
eq Callable

An ODE governing the dynamics.

None
**kwargs Dict

Keyworded arguments used to set the ODE solver parameters such as relative, absolute tolerance, and etc. See diffrax API documentation for diffeqsolve.

{}

Attributes:

Name Type Description
solver AbstractSolver

A diffrax ODE solver.

kwargs Dict

Keyworded arguments used to set the ODE solver parameters such as relative, absolute tolerance, and etc.

Methods:

Name Description
set_system

Register the system of ODE's to be solved.

evolve

Solve an ODE for a given initial condition y0 and a set of parameters given by params evaluated at timestamps t_span.

evolve(y0, params, t_span)

Solve for the ODE equation.

Simulate the dynamical system given the initial condition y and the time interval t_eval.

Parameters:

Name Type Description Default
y0 Array

The initial condition.

required
params Dict[str, float] | Dict[str, Array]

A dictionary of parameters where the values can be a scalar or a JAX array. The array form provides the user with the possibility to parallelise for an ensemble simulation.

required
t_span Tuple[float, float]

The starting and ending time instances.

required

Returns:

Type Description
Tuple[Array, Array | Solution]

The first element of the tuple is the timestamps. The second element is the solution to the ODE equation. If "saveat" keyword has an array type for keyword "ts" the output is a JAX array. Otherwise, the output is an interpolated solution.

PWCSolver

Bases: AbstractSolver

Piece-wise constant solver.

Parameters:

Name Type Description Default
n int

Size of the time grid.

required
store bool

Specify whether to store the result at each timestamp.

False
eq Callable

Set of equations describing the unitary evolution of the system.

None

Attributes:

Name Type Description
n int

Size of the time grid. Setting this property resets cached JIT-compiled functions.

Methods:

Name Description
set_system

Set the desired set of equations used to evolve the initial state of the system.

evolve

Simulate a quantum dynamics problem.

n property writable

Get the size of the time grid.

Returns:

Type Description
int

The size of the time grid.

evolve(y0, params, t_span)

Propagate the the initial state vector.

Parameters:

Name Type Description Default
y0 Array

JAX array specifying the initial state.

required
params Dict[str, float]

Simulation parameters.

required
t_span Tuple[float, float]

Tuple of size two with indicating the starting and ending times of the simulation.

required

Returns:

Type Description
Tuple[Array, Array]

The first element is the timestamps and the second is the state vector(s) or density matrix(ces).

set_system(eq)

Specify the unitary equation to be solved by the solver.

Parameters:

Name Type Description Default
eq Callable

The unitary equation of interest.

required

qruise.toolset.optimisers.optimisers

Optimisers module.

A set of optimisers such as ODEOptimisers or PWCOptimisers that are compatible with their corresponding solvers. These are used to solve a quantum optimal control problem, but not limitted.

EnsembleOptimiser

Ensemble optimiser.

Optimises control parameters of a quantum system to be robust across an ensemble of physical parameters defined in an EnsembleProblem.

Parameters:

Name Type Description Default
minimiser Minimiser

A minimiser algorithm.

required
solver AbstractSolver

Solver for evolving the dynamics.

required
loss Callable

Loss function used for the minimisation.

None

Attributes:

Name Type Description
minimiser Minimiser

A minimiser algorithm.

solver AbstractSolver

Solver that evolves the system's dynamics.

optimise(y0, params, t_span, in_axes, y_t, cartesian=False, control_param_keys=None, freeze_keys=None, **kwargs)

Optimise control parameters to be robust across an ensemble.

Optimises the control parameters (those broadcast across the ensemble, i.e. with in_axes value None) to minimise the mean loss over all ensemble members.

Parameters:

Name Type Description Default
y0 Array

Initial state vector.

required
params Dict[str, Any]

Dictionary of all parameters. Parameters with in_axes value None are optimised (control params); those with in_axes value 0 are held fixed (ensemble params).

required
t_span Tuple[float, float]

Time interval containing the starting and ending times of the simulation.

required
in_axes InAxes

Vmap axes specification from EnsembleProblem.problem().

required
y_t Array

Desired target state vector.

required
cartesian bool

If True, takes the Cartesian product of ensemble dimensions. Default is False.

False
control_param_keys List[str] or None

Explicit list of parameter keys to optimise. When provided, all other parameters are treated as fixed (held constant during optimisation), regardless of their in_axes value. Default is None (use in_axes to infer control parameters).

.. note:: Keys listed here must have an in_axes value of None (i.e. scalar or array control parameters, not ensemble list parameters). Including a key whose in_axes value is not None will cause jax.vmap to fail with a shape error.

None
freeze_keys Set[str] or None

Set of control parameter keys to exclude from optimisation. Frozen control parameters are held constant and merged back into the returned result unchanged. Default is None (all control parameters are optimised).

None
**kwargs Dict

Extra arguments passed to the minimiser.

{}

Returns:

Type Description
Tuple[Dict[str, Any], Any]

The first element is the optimised control parameters merged with any frozen control parameters (those in freeze_keys). The second element is the summary output of the minimiser.

set_optimisation(loss)

Provide the optimiser with a loss function.

Parameters:

Name Type Description Default
loss Callable

Loss function.

required

Optimiser

Abstract optimiser.

Parameters:

Name Type Description Default
minimiser Minimiser

A minimiser algorithm.

required
solver AbstractSolver

Solver for evolving the dynamics.

required
loss Callable

Loss function used for the minimisation.

None

Attributes:

Name Type Description
minimiser Minimiser

A minimiser algorithm.

solver AbstractSolver

Solver that evolves the system's dynamics.

optimise(y0, params, t_span, y_t, freeze_keys=None, **kwargs)

Optimise a set of parameters to meet the target state.

Optimise a quantum optimal control problem given an initial state vector y0 and a target state y_t for a given set of parameters.

Parameters:

Name Type Description Default
y0 Array

Initial state vector.

required
params Dict[str, float]

Dictionary of parameters to be optimised.

required
t_span Tuple[float, float]

Time interval containing the starting and ending times of the simulation.

required
y_t Array

Desired target state vector.

required
freeze_keys set or None

Set of parameter keys to exclude from optimisation. Frozen parameters are held constant and merged back into the returned result unchanged. Default is None (all parameters are optimised).

None
**kwargs Dict

Extra arguments used for optimistix.minimise or scipy.optimize.minimize method.

{}

Returns:

Type Description
Tuple[Dict[str, Array], Any]

The first element is the optimised set of parameters given by a dictionary. The second element is the summary output of the optimiser.

set_optimisation(loss)

Provide the optimiser with a loss function.

Parameters:

Name Type Description Default
loss Callable

Loss function.

required

qruise.toolset.optimisers.minimisers

Minimiser module.

Provides an interface for providing different minimisation strategies provided by different optimisation libraries such as scipy.optimize or optimistix.

Minimiser

Bases: ABC

Abstract minimisation strategy.

Parameters:

Name Type Description Default
method Any

Minimisation algorithm.

required
maxiter int | None

Unified maximum iteration count using scipy terminology. Subclasses map this to their native parameter. Default is None.

None
tol float | None

Unified convergence tolerance using scipy terminology. Subclasses map this to their native parameter. Default is None.

None
**kwargs Any

Arguments for the minimisation algorithm.

{}

Attributes:

Name Type Description
method Any

Minimisation algorithm.

maxiter int | None

Unified maximum iteration count.

tol float | None

Unified convergence tolerance.

Methods:

Name Description
minimise

Minimise an objective given the initial guess of parameters.

minimise(objective, params, args) abstractmethod

Minimise an objective function.

Parameters:

Name Type Description Default
objective Callable

An objective function to be minimised with the signature f(x, args).

required
params Dict[str, float]

Dictionary of parameters.

required
args Tuple[PyTree, ...]

Tulpe of objects passed to the objective function.

required

Returns:

Type Description
Tuple[Dict[str, float], Any]

The first element is a dictionary with optimised parameters, the second is the result summary of the minimiser strategy.

OptimistixMinimiser

Bases: Minimiser

Optimistix minimisation strategy.

Parameters:

Name Type Description Default
method _ModuleMeta

Minimisation algorithm. Its instantiation must yield an AbstractMinimiser.

required
maxiter int | None

Unified maximum iteration count. Maps to max_steps in optimistix.minimise. Cannot be combined with max_steps=. Default is None.

None
tol float | None

Unified convergence tolerance. Sets both rtol and atol on the method instance. Cannot be combined with rtol= or atol=. Default is None.

None
max_steps int | None

Native optimistix maximum iteration count. Cannot be combined with maxiter=. Default is None (resolved to 1000 when neither maxiter= nor max_steps= is provided).

None
**kwargs Any

Arguments for the minimisation algorithm. Used to instantiate optimistix.AbstractMinimiser objects.

{}

Attributes:

Name Type Description
method _ModuleMeta

Minimisation algorithm. Its instantiation must yield an AbstractMinimiser.

maxiter int | None

Unified maximum iteration count (None when not specified).

tol float | None

Unified convergence tolerance (None when not specified).

max_steps int

Maximum number of solver iterations (resolved from maxiter, max_steps, or the default 1000).

Methods:

Name Description
minimise

Minimise an objective given the initial guess of parameters. This uses optimistix.minimise method.

Notes

When tol= is provided it is mapped to both rtol and atol on the underlying optimistix solver, which means the relative and absolute tolerances are set to the same value. Use rtol= and atol= directly when independent control over the two tolerances is required.

minimise(objective, params, args)

Minimise an objective function.

The method uses optimistix.minimise to minimise an objective function given the initial guess for the parameters.

Parameters:

Name Type Description Default
objective Callable

An objective function to be minimised with the signature f(x, args).

required
params Dict[str, float]

Dictionary of parameters.

required
args Tuple[PyTree, ...]

Tuple of objects passed to the objective function.

required

Returns:

Type Description
Tuple[Dict[str, float], Any | None]

The first element is a dictionary with optimised parameters, the second is the optimistix.minimise result summary.

Notes

If params is empty (e.g. all parameters are frozen), the method returns (params, None) immediately without calling optimistix.minimise.

ScipyMinimiser

Bases: Minimiser

Scipy minimisation strategy.

Parameters:

Name Type Description Default
method str

Minimisation algorithm.

required
log_progress bool

If True, log the loss value and gradient norm at each iteration via the standard Python logging module at INFO level. Equivalent to the deprecated disp=True / iprint options that were removed from L-BFGS-B in scipy 1.15. Default is False. When normalise=True, logged gradient norms correspond to the normalised coordinate system and are scaled by (hi - lo) per element relative to the original parameter space.

False
log_interval int

Log a progress line every log_interval iterations. Analogous to the deprecated iprint parameter: set to 1 (default) for every iteration, 5 for every fifth, etc. Only has an effect when log_progress=True.

1
maxiter int | None

Unified maximum iteration count. Injected into options={"maxiter": maxiter} when calling scipy.optimize.minimize. Cannot be combined with options={"maxiter": ...}. Default is None.

None
tol float | None

Unified convergence tolerance. Forwarded directly as the tol argument to scipy.optimize.minimize. Default is None.

None
normalise bool

If True, each parameter is linearly mapped to [0, 1] within its bounds before scipy sees it, and mapped back to the original scale after optimisation. Requires bounds to be provided; a UserWarning is emitted and normalisation is skipped when no bounds are given. Unbounded ((None, None)), non-finite (±inf), or degenerate (lo == hi) entries are left unchanged. Note that scipy internally operates in normalised coordinates, so the xk argument passed to any user callback and logged gradient norms correspond to the normalised parameterisation. OptimizeResult.x and the returned parameter dict are both denormalised to the original scale before being returned. Default is False.

False
**kwargs Any

Additional arguments forwarded to scipy.optimize.minimize, e.g. options, callback. Note: bounds is extracted from kwargs and stored as _raw_bounds; it is processed lazily in minimise() to support active-only parameter subsets.

{}

Attributes:

Name Type Description
method str

Minimisation algorithm.

log_progress bool

Whether iteration progress is logged.

log_interval int

Logging frequency in number of iterations.

maxiter int | None

Unified maximum iteration count.

tol float | None

Unified convergence tolerance.

normalise bool

Whether parameter normalisation to [0, 1] is applied.

Methods:

Name Description
minimise

Minimise an objective given the initial guess of parameters. This uses scipy.optimize.minimize method.

minimise(objective, params, args)

Minimise an objective function.

The method uses scipy.optimise.minimize method to minimise an objective function given the initial guess for the parameters.

Parameters:

Name Type Description Default
objective Callable

An objective function to be minimised with the signature f(x, args).

required
params Dict[str, float]

Dictionary of parameters.

required
args Tuple[PyTree, ...]

Tulpe of objects passed to the objective function.

required

Returns:

Type Description
Tuple[Dict[str, float], OptimizeResult | None]

The first element is a dictionary with optimised parameters, the second is the scipy.optimize.minimize result summary.

Notes

If params is empty (e.g. all parameters are frozen), the method returns (params, None) immediately without calling scipy.optimize.minimize.

qruise.toolset.plots

PlotUtil

A utility class for enhancing the plotting experience. It uses the Bokeh library as its backend

Attributes:

Name Type Description
canvas Plot | None

an instance of the Bokeh Plot object

notebook bool

specifies whether the plots are drawn in a notebook or not

**kwargs

keyworded arguments for the Bokeh figure method

init_canvas(**kwargs)

Initialise the Plot object

plot(x, y, labels, line_dash=None)

plots set of arrays given a one- or two-dimensional input array

Parameters:

Name Type Description Default
x Array

a one-dimensional array indexing the x-axis

required
y Array

a one- or two-dimensional array of relevant time-series

required
labels List[str]

a list of strings specifying the label of each individual time-series

required
line_dash str | List[str] | None

Bokeh dash style ("solid", "dashed", "dotted", etc.) or list of styles. Defaults to "solid".

None

show_canvas()

shows the canvas

qruise.toolset.utils

anti_commutation(A, B)

Anti-commutation between operators A and B.

Parameters:

Name Type Description Default
A Array

Matrix operator.

required
B Array

Matrix operator.

required

Returns:

Name Type Description
Array

The anti-commutation of the two input operators.

Examples:

>>> A = jnp.array([[1, 2], [3, 4]])
>>> B = jnp.array([[9, 8], [7, 6]])
>>> anti_commutation(A, B)
Array([[56, 70],
       [80, 86]], dtype=int64)

closest_vec2eigvec(eigenvecs, vecs)

Find the index of the closest eigenvector to a given vector.

Parameters:

Name Type Description Default
eigenvecs Array

An array of eigenvectors given by a matrix where each column is a single eigenvector.

required
vecs List | Array

A list or an array of vectors. In the latter case it is a matrix which each column is a single vector of interest.

required

Returns:

Type Description
Array

An array of eigenvalues associated with the list of input vectors.

Examples:

>>> H = Hamiltonian(sigmaz() + sigmay())
>>> eigvals, eigvecs = jnp.linalg.eigh(H.H0)
>>> basis, labels = computational_basis([2])
>>> closest_vec2eigvec(eigvecs, basis)

commutation(A, B)

Commutation between operators A and B.

Parameters:

Name Type Description Default
A Array

Matrix operator.

required
B Array

Matrix operator.

required

Returns:

Name Type Description
Array

The commutation of the two input operators.

Examples:

>>> A = jnp.array([[1, 2], [3, 4]])
>>> B = jnp.array([[9, 8], [7, 6]])
>>> commutation(A, B)
Array([[-10, -30],
       [ 30,  10]], dtype=int64)

computational_basis(system_n)

Generate the computational basis and the corresponding state labels.

Parameters:

Name Type Description Default
system_n List[int]

List containing numbers each indicating the number of levels each system has in a many-body problem.

required

Returns:

Type Description
Tuple[List[Array], List[Tuple[int, int]]

A tuple with two elements: - basis: List of basis vectors for the computational basis. - labels: List of tuples representing the computational basis states.

Examples:

>>> # Three two-level system.
>>> basis, labels = computational_basis([2, 2, 2])
>>> labels
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
 (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

compute_rise_time_gaussian_coeffs(rise_time, n_order=3, fraction=0.6)

Compute the absolute coefficients of a Gaussian filter for a given rise time.

Parameters:

Name Type Description Default
rise_time float

The rise time in seconds.

required
n_order int

The order of the Gaussian filter. Defaults to 3.

3
fraction float

The fraction of the total amplitude used to calculate sigma. Defaults to 0.6.

0.6

Returns:

Type Description
ndarray

The absolute coefficients of the Gaussian filter.

get_population(arr)

get the population density of all levels given the raw simulation data

Parameters:

Name Type Description Default
arr Array

JAX array containing the raw simulation data

required

Returns:

Type Description
Array

two-dimensional array with the first dimension referring to the level and the second dimension referring to the indices of the population time-series

op_expectation(op, rho)

Expetation value of a given operator.

Parameters:

Name Type Description Default
op Qobj | Array

A quantum operator given as a QuTiP object or a JAx array represented by a square matrix.

required
rho Array

Density matrix.

required

Returns:

Name Type Description
Array

The expecation value of the quantum operator

Examples:

>>> import jax.numpy as jnp
>>> from qutip import sigmax
>>> rho = jnp.eye(2, dtype=jnp.complex128)
>>> op = sigmax()
>>> op_expectation(op, rho)
Array(0., dtype=float64)

project_op(operator, basis)

Projects a given operator onto the (sub)space spanned by a given basis.

Parameters:

Name Type Description Default
operator Array

A square matrix representation of an operator.

required
basis List[Array]

List of basis spanning the sub-space space.

required

Returns:

Type Description
Array

Matrix of the projected operator.

transform_basis(state, basis, check_unitary=False)

Transform a given state given a new basis.

Parameters:

Name Type Description Default
state Array

The state to be transformed.

required
basis List[Array] | Array

A list of vectors or matrix array that defines the transformation in the new basis.

required
check_unitary bool

Check if the new basis defines a unitary tarnsformation.

False

Returns:

Name Type Description
Array Array

Transformed state described in the new basis.