Skip to content

qruise-toolset

qruise.toolset.hamiltonian

Hamiltonian dataclass

Dataclass for Hamiltonian.

Parameters:

Name Type Description Default
h0 Array | SpArray | Qobj

Stationary part of the Hamiltonian.

required
hts_drvs List[Tuple[Drive, Array | SpArray | Qobj]]

Sequence of tuples each containing the time-dependent quantum channel and the corresponding drive.

required

Attributes:

Name Type Description
H0 CSRMatrix

Stationary part of the Hamiltonian in compressed sparse column matrix.

Hts Tuple[CSRMatrix, ...]

Tuple of time-dependent quantum channels.

drvs Tuple[Drive, ...]

Tuple of time-dependent drives.

n int

Number of time-dependent quantum channels.

qruise.toolset.problem

The Problem module.

It allows the user to define a quantum simulation problem as a dataclass and manipulate the required inputs to be compatible with the desired equation.

Problem dataclass

Dataclass defining a quantum simulation problem.

Parameters:

Name Type Description Default
eq str

The name of the PDE equation to be solved. Can be either Schroedinger, `MasterEquation'.

required
H Hamiltonian

The Hamiltonian of the quantum simulation problem.

required
u0 Array

The initial condition of the PDE. A vector state or a density matrix.

required
tspan Tuple[float, float]

The time interval over which the PDE must be solved.

required
ps Parameters

The parameter space.

required
c_ops Tuple[CSRMatrix, ...]

Set of collapse operators for the Lindblad equation.

()
sim bool

Flag to indicate whether to perform simulation or not.

True

Attributes:

Name Type Description
eq str
H Hamiltonian
u0 Array
tspan Tuple[float, float]
c_ops Tuple[CSRMatrix, ...]
sim bool

remake(B, **D)

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 eq, H, u0, tspan, ps and c_ops.

required

Returns:

Type Description
Problem

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

QOCProblem dataclass

Bases: Problem

Dataclass defining a quantum optimal control problem.

Parameters:

Name Type Description Default
eq str

The name of the PDE equation to be solved. Can be either Schroedinger, VonNeumann or Lindblad.

required
H Hamiltonian

The Hamiltonion of the quantum simulation problem.

required
u0 Array | Qobj

The initial condition of the PDE. A vector state or a density matrix.

required
tspan Tuple[float, float]

The time interval over which the PDE must be solved.

required
ps Parameters

The parameter space.

required
ut Array | Qobj

The desired target state.

required
loss str

The measure used to quantify the state overlap.

required
c_ops Tuple[CSRMatrix, ...]

Set of collapse operators for the Lindblad equation.

()

Attributes:

Name Type Description
eq str
H Hamiltonian
u0 Array
tspan Tuple[float, float]
ps Parameters
ut Array
loss str
c_ops Tuple[CSRMatrix, ...]

qruise.toolset.ensemble_problem

Module for ensemble problems.

EnsembleProblem dataclass

Dataclass for defining an ensemble of quantum simulation problems.

Parameters:

Name Type Description Default
eq str

Equation describing the dynamics. Can be either Schroedinger or MasterEquation.

required
H Hamiltonian | List[Hamiltonian]

A collection of Hamiltonians or a single element Hamiltonian of the quantum system.

required
u0 Array | Qobj | List[Array | Qobj]

A collection of initial conditions or a single initial condition.

required
tspan Tuple[float, float] | List[Tuple[float, float]]

A collection of the simulation timespans or a single element timespan.

required
ps Parameters | List[Parameters]

A collection of parameter spaces or a single parameter space.

required
c_ops Tuple | List[Tuple] | Tuple[()]

A collection of tuples of collapse operators or a tuple of collapse operators.

[()]
sim bool

Flag to indicate whether to perform simulation or not.

True

Attributes:

Name Type Description
eq str

Equation describing the dynamics. Can be either Schroedinger or MasterEquation.

H List[Hamiltonian]

A collection of Hamiltonians.

u0 List[Array]

A collection of initial conditions.

tspan List[Tuple[float, float]]

A collection of the simulation timespans.

ps List[Parameters]

A collection of parameter spaces.

c_ops List[Tuple[CSRMatrix, ...]] | Tuple[()]

A collection of tuples of collapse operators.

sim bool

Flag to indicate whether to perform simulation or not.

EnsembleQOCProblem dataclass

Bases: EnsembleProblem

Dataclass defining an ensemble quantum optimal control problem.

Inherits from :class:EnsembleProblem and reuses its sanity checks for eq, H, u0, tspan, ps, and c_ops. Adds validation for ut (target states) and loss.

This is used for gate optimisation where a single set of control parameters must optimise performance across multiple initial states simultaneously (e.g. |0> and |1> for a single-qubit gate), or for robust optimal control over different time spans or parameter sets.

TODO: Revisit u0/ut pairing for robust optimal control with multiple ps, tspan, or H.

Parameters:

Name Type Description Default
eq str

The name of the PDE equation to be solved. Can be either Schroedinger or MasterEquation.

required
H Hamiltonian | List[Hamiltonian]

The Hamiltonian(s) of the quantum simulation problem.

required
u0 Array | Qobj | List[Array | Qobj]

Initial condition(s) (one per trajectory).

required
tspan Tuple[float, float] | List[Tuple[float, float]]

The time interval(s) over which the PDE must be solved.

required
ps Parameters | List[Parameters]

The parameter space(s).

required
ut List[Array | Qobj]

List of target states.

required
loss str

The measure used to quantify the state overlap.

required
c_ops Tuple | List[Tuple] | Tuple[()]

Set of collapse operators for the Lindblad equation.

[()]

Attributes:

Name Type Description
eq str
H List[Hamiltonian]
u0 List[Array]
tspan List[Tuple[float, float]]
ps List[Parameters]
ut List[Array]
loss str
c_ops List[Tuple[CSRMatrix, ...]] | Tuple[()]
sim bool

qruise.toolset.parameters

Parameters module.

Designed as a data container for the set of parameters that parametrise the quantum simulation problem uniquely.

BoundError

Bases: Exception

Exception handling for lower and upper bounds.

LengthMismatch

Bases: Exception

Exception handling of length mismatches.

Parameters dataclass

Dataclass to store the simulation parameters.

Parameters:

Name Type Description Default
ps Dict[str, Union[float, NDArray, Tuple, Tuple]]

Relational structure establishing the relation between the drive scope and its parameters. See the function's type hint for the full input's type. If any leaf value is a list (or a tuple of lists), the dict is treated as an ensemble of parameter spaces and constructing Parameters from it returns a List[Parameters] instead of a single instance.

required

Attributes:

Name Type Description
ps NDArray

Flat array of parameters.

lb NDArray

Lower bounds of the parameters.

ub NDArray

Upper bounds of the parameters.

keys Tuple[str, ...]

Names associated with each parameter.

ranges Tuple[range, ...]

Intervals specifying the segments related to a specific parameter.

shapes Tuple[int, ...]

The array shape of each parameter.

ps_num int

Total number of parameter names.

__copy__(A)

Shallow-copy the Parameters instance.

Returns:

Type Description
Parameters

A new Parameters instance sharing the same underlying field values as self.

__deepcopy__(A, memo)

Deep-copy the Parameters instance.

Parameters:

Name Type Description Default
memo Dict

Memoisation dict used by copy.deepcopy.

required

Returns:

Type Description
Parameters

A new Parameters instance with its own copies of the underlying arrays.

__init__(ps, lb, ub, keys, ranges, shapes)

Construct Parameters directly from already-flattened arrays and metadata, bypassing the dict-parsing logic.

Parameters:

Name Type Description Default
ps NDArray

Flat array of parameters.

required
lb NDArray

Lower bounds of the parameters.

required
ub NDArray

Upper bounds of the parameters.

required
keys Tuple[str, ...]

Names associated with each parameter.

required
ranges Tuple[range, ...]

Intervals specifying the segments related to a specific parameter.

required
shapes Tuple[Tuple[int, ...], ...]

The array shape of each parameter.

required

__new__(ps, lb, ub, keys, ranges, shapes)

Raw-array construction of a Parameters instance.

Parameters:

Name Type Description Default
ps NDArray

Flat array of parameters.

required
lb NDArray

Lower bounds of the parameters.

required
ub NDArray

Upper bounds of the parameters.

required
keys Tuple[str, ...]

Names associated with each parameter.

required
ranges Tuple[range, ...]

Intervals specifying the segments related to a specific parameter.

required
shapes Tuple[Tuple[int, ...], ...]

The array shape of each parameter.

required

Returns:

Type Description
Parameters

A new, uninitialised Parameters instance.

__str__(A)

String representation of Parameters.

Returns:

Type Description
str

Parameters string representation.

to_dict(A, x=_B)

Map a flat parameter array back to its nested dict.

Parameters:

Name Type Description Default
x NDArray

Flat array with the same shape as self.ps. Defaults to self.ps if None.

_B

Returns:

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

The nested dict structure, keyed by component name then parameter name, with each value a (value, lower_bound, upper_bound) tuple reshaped back to its original array shape.

ShapeMismatch

Bases: Exception

Exception handling of shape mismatches.

qruise.toolset.components

Module for component-based modelling.

Allows the user to define connectivity between different QPUs and the drive channels and their respective sources. It compiles the Hamiltonian of the system by simply providing the connectivities between the components.

AbstractQPU dataclass

Dataclass for an abstract QPU.

Attributes:

Name Type Description
name str

The name of the QPU.

h_dim int

The Hilbert space dimension.

__matmul__(B, other)

Overloading the @ operator for AbstractQPU.

Adds an AbstractQPU to a ModelBuilder object.

Parameters:

Name Type Description Default
other ModelBuilder

A ModelBuilder object for a component-based modelling using graphs.

required

__or__(B, other)

Overloading the | operator for AbstractQPU.

Chains an AbstractQPU to a Qobj operator.

Parameters:

Name Type Description Default
other Qobj

Quantum channel as QuTiP Qobj.

required

Returns:

Type Description
_CouplingChain

An updated object of _CouplingChain.

Drive dataclass

Dataclass for drives.

Parameters:

Name Type Description Default
cname str

Scope name of the drive.

required
func Callable

A pure annotated python function.

required

Attributes:

Name Type Description
cname str

Scope name of the drive.

func CFunc

A numba cfunc callable function.

funcname str

Function's name.

scalar_argnames Tuple[str, ...]

Names space for the scalar arguments.

scalar_argtypes Tuple[str, ...]

Primitive C types for the scalar arguments.

scalar_argname int

Number of scalar argument.

arr_argnames Tuple[str, ...]

Name space for the array arguments.

arr_argtypes Tuple[str, ...]

Primitive C types for the array arguments.

arr_argnum int

Number of array arguments.

rettype str

Primitive C type for the return type.

__matmul__(other)

Overloading the @ operator for Drive.

Adds a Drive object to the model.

Parameters:

Name Type Description Default
other ModelBuilder

A model for a component-based modelling using graphs.

required

__rshift__(other)

Overloading the >> operoter for Drive.

Chains a Drive object to a quantum channel.

Parameters:

Name Type Description Default
other Qobj

Quantum channel as a QuTiP Qobj.

required

Returns:

Type Description
_DriveChain

An updated object of _DriveChain.

FailedCFuncCompilation

Bases: Exception

Abstract Exception class.

Used to raise execption for failure in compilation of a C function from a pure python function.

ModelBuilder

Basically a undirected Graph.

Attributes:

Name Type Description
qpu_ind int

Counts the number of QPU nodes in the graph. Used for indexing the QPUs.

g Graph

Networkx.Graph object. For defining the connectivities between the components.

hamiltonian(A)

Get the stationary and time-dependent parts of the Hamiltonian.

Returns:

Type Description
Tuple[Qobj, Iterable[Tuple[Drive, Qobj]]]

Tuple with the first element as the stationary part of the Hamiltonian and the second as an iterable of tuples of drive and the coupling quantum channel.

Qubit dataclass

Bases: AbstractQPU

Qubit dataclass.

A Qubit component which is a two-level system with a natural frequency freq.

Parameters:

Name Type Description Default
name str

The name of the Qubit.

required
freq float

The natural frequency of the Qubit.

required
op Qobj

The quantum operator specifying the stationary Hamiltonian of the Qubit.

required

Attributes:

Name Type Description
freq float

The natural frequency of the Qubit.

op Qobj

The quantum operator specifying the stationary Hamiltonian of the Qubit.

qruise.toolset.session

Session Module.

Establish a live Julia session.

This will instantiate a Julia session in the background. The sole purpose of this module is to enable user to pass Python objects required for the simulation of a quantum system to native Julia type and structures and simulate the dynamics using the Julia backend.

Session

Run a Julia session in background.

Attributes:

Name Type Description
session ModuleValue

A juliacall.Module value.

jlconvert Callable

Convert python types to native Julia types.

i32 TypeValue

Julia Int32.

i64 TypeValue

Julia Int64.

f32 TypeValue

Julia Float32.

f64 TypeValue

Julia Float64.

c32 TypeValue

Julia ComplexF32.

c64 TypeValue

Julia ComplexF64.

val TypeValue

Julia Val.

symb TypeValue

Julia Symbol.

Methods:

Name Description
evolve

Simulate the dynamics of a given quantum system.

instantiate

Instantiate the Julia solver, problem and parameter space.

ensemble_evolve(A, alg=_K, ensemblealg='EnsembleThreads', xarray=_A, **J)

Evolve the ensemble quantum simulation problem.

After instantiating the quantum simulation problem, i.e by calling Session.qsprob_init, this method can be used to get the evolution of the dynamics of a quantum simulation problem.

Parameters:

Name Type Description Default
alg str

The ODE algorithm for numerically solving the problem. Default to Tsit5.

_K
ensemblealg str

Algorithm used for the ensemble simulation.

'EnsembleThreads'
xarray bool

Indicates whether to return the result as an xarray.Dataset object.

_A
**kwargs Dict

Keyworded-arguments to fine-tune the behaviour of the the ODE solver.

required

Returns:

Type Description
Tuple[Array, Array] | Dataset

If xarray=False time instances and the quantum states of the system are returned as numpy arrays. Otherwise, an xarray.Dataset is returned with qstates storing the quantum states of the system over the sim_index and time_index coordinates (with per-simulation time values in time). qstates has a row dimension (plus col for matrices), left without coordinate values since their meaning depends on the problem (ket, density matrix, or propagator columns); use ds.rename(...) / ds.assign_coords(...) to label them for your specific problem.

ensemble_qocprob_init(A, prob, alg=_K)

Instantiate an Ensemble Quantum Optimal Control problem.

The total number of trajectories is the Cartesian product of the individual dimensions::

len(H) * len(c_ops) * len(ps) * len(u0) * len(tspan)

u0 and ut are paired by index: target state ut[k] is used for every trajectory whose u0 index is k.

TODO: Revisit u0/ut pairing for robust optimal control with multiple ps, tspan, or H.

Parameters:

Name Type Description Default
prob EnsembleQOCProblem

The ensemble quantum optimal control problem.

required
alg str

The ODE algorithm for the quantum simulation.

_K

ensemble_qsprob_init(A, prob)

Instantiate the Julia EnsembleProblem structure.

Parameters:

Name Type Description Default
prob EnsembleProblem

An ensemble of quantum simulation problems.

required

evolve(A, alg=_K, xarray=_A, **F)

Evolve the quantum simulation problem.

After instantiating the quantum simulation problem, i.e by calling Session.qsprob_init, this method can be used to get the evolution of the dynamics of a quantum simulation problem.

Parameters:

Name Type Description Default
alg str

The ODE algorithm for numerically solving the problem. Default to Tsit5.

_K
xarray bool

Indicates whether to return the result as an xarray.Dataset object.

_A
**kwargs Dict

Keyworded-arguments to fine-tune the behaviour of the the ODE solver.

required

Returns:

Type Description
Tuple[Array, Array] | Dataset

If xarray=False time instances and the quantum states of the system are returned as numpy arrays. Otherwise, an xarray.Dataset is returned with qstates storing the quantum states of the system over the time coordinate. qstates has a row dimension (plus col for matrices), left without coordinate values since their meaning depends on the problem (ket, density matrix, or propagator columns); use ds.rename(...) / ds.assign_coords(...) to label them for your specific problem.

optimise(A, alg, as_dict=_A, **D)

Run the optimisation simulation.

It optimises the set of parameters provided by the user when the simulation problem was instantiated. Supports both single QOCProblem (via qocprob_init) and EnsembleQOCProblem (via ensemble_qocprob_init).

Parameters:

Name Type Description Default
alg str

The optimisation algorithm.

required
as_dict bool

Indicates whether to return the result mapped back to its nested dict structure instead of a flat array. Default to True.

_A
**kwargs Dict

Keyworded-arguments for controlling optimisation behaviour.

  • maxiters (int): maximum number of optimiser iterations passed to Optimization.solve.
  • reltol (float): relative tolerance for the ODE solver used inside the gradient computation (forward and adjoint solves).
  • abstol (float): absolute tolerance for the ODE solver used inside the gradient computation (forward and adjoint solves).
required

Returns:

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

A flat array of optimised parameters. If as_dict, the nested dict structure is returned.

qocprob_init(A, prob, alg=_K)

Instantiate a Quantum Optimal Control problem.

It implicitly instantiates the Quantum Simulation problem associated to the Quantum Optimal Control problem.

Parameters:

Name Type Description Default
prob Problem

The quantum simulation problem.

required
alg str

The algorithm used for the quantum simulation problem.

_K

qsprob_init(A, prob)

Instantiate the Julia Problem structure.

The Problem live in _qr module. This reduces overhead to simulate the problem given a solver. This furthers allows to keep the Main module clean and indirectly accessible in case one requires debugging the Hamiltonian, drives and the parameter space.

Parameters:

Name Type Description Default
prob Problem

The quantum simulation problem.

required

qruise.toolset.types

Module for primitive data types.

AbstractArray

Bases: AbstractType

Abstract array type.

Attributes:

Name Type Description
eltype Number

Type of array's elements.

ndim int

The rank of the array.

n int

Total number of arguments in the LLVM representation.

AbstractFloat

Bases: Number

Abstract float data type.

AbstractInt

Bases: Number

Abstract integer data type.

AbstractType

Abstract Data types.

Attributes:

Name Type Description
c_prmtv_type str

The C primitive type associated to the type.

Float32

Bases: AbstractFloat

Float32 data type.

__new__(A)

Create a new Numba float32 data type.

Returns:

Type Description
float32

Numba float32 data type.

Float64

Bases: AbstractFloat

Float64 data type.

__new__(A)

Create a new Numba float64 data type.

Returns:

Type Description
float64

Numba float64 data type.

Int32

Bases: AbstractInt

Int32 data type.

__new__(A)

Create a new Numba int32 data type.

Returns:

Type Description
int32

Numba int32 data type.

Int64

Bases: AbstractInt

Int64 data type.

__new__(A)

Create a new Numba int64 data type.

Returns:

Type Description
int64

Numba int64 data type.

Number

Bases: AbstractType

Abstract number type.

Incorporates integeres and floats.

Array1D(T)

Create a Metaclass for creating one-dimensional array.

Parameters:

Name Type Description Default
T Number

Data type of elements of the array.

required

Returns:

Type Description
type

Dynamically created type for an one-dimensional array with a given element type.

Array2D(T)

Create a Metaclass for creating one-dimensional array.

Parameters:

Name Type Description Default
T Number

Data type of elements of the array.

required

Returns:

Type Description
type

Dynamically created type for an two-dimensional array with a given element type.

ArrayND(T, ndim)

Create a Metaclass for creating array data type.

Parameters:

Name Type Description Default
T AbstractType

Data type of elements of the array.

required
ndim int

The dimension of the array.

required

Returns:

Type Description
type

Dynamically created type for an n-dimensional array with a given element type.

qruise.toolset.prob_utils