The math module

J

Symplectic form.

Xmat

The matrix \(X_n = \begin{bmatrix}0 & I_n\\ I_n & 0\end{bmatrix}.\).

Zmat

The matrix \(Z_n = \begin{bmatrix}I_n & 0\\ 0 & -I_n\end{bmatrix}.\).

abs

The absolute value of array.

all

Returns True if all elements of array are True, False otherwise.

all_diagonals

Returns all the diagonals of a density matrix.

allclose

Whether two arrays are equal within tolerance.

angle

The complex phase of array.

any

Returns True if any element of array is True, False otherwise.

arange

Returns an array of evenly spaced values within a given interval.

asnumpy

Converts an array to a numpy array.

astensor

Converts a scalar or array-like input to a tensor.

atleast_nd

Returns an array with at least n dimensions.

beamsplitter

Creates a beamsplitter matrix with given cutoffs using a Fock lattice strategy.

block

Returns a matrix made from the given blocks.

broadcast_arrays

Broadcast arrays to a common shape.

broadcast_to

Broadcasts an array to a new shape.

cast

Casts array to dtype.

change_backend

Changes the backend to a different one.

clip

Clips array to the interval [a_min, a_max].

complex_gaussian_integral_1

Computes the complex Gaussian integral.

complex_gaussian_integral_2

Computes the complex Gaussian integral.

concat

Concatenates values along the given axis.

conj

The complex conjugate of array.

cos

The cosine of an array.

cosh

The hyperbolic cosine of array.

conditional

Executes true_fn if cond is True, otherwise false_fn.

dagger

The adjoint of array.

det

The determinant of matrix.

diag

The array made by inserting the given array along the \(k\)-th diagonal.

diag_part

The array of the main diagonal of array.

diagonal

Return specified diagonals of array.

displacement

Creates a single mode displacement matrix using a Fock lattice strategy.

eigvals

The eigenvalues of a tensor.

eigh

The eigenvalues and eigenvectors of a matrix.

einsum

The result of the Einstein summation convention on the operands.

equal

Returns the element-wise equality of two arrays.

error_if

Raises an error if condition is True.

euclidean_to_symplectic

Convert the Euclidean gradient to a Riemannian gradient on the tangent bundle of the symplectic manifold.

euclidean_to_unitary

Convert the Euclidean gradient to a Riemannian gradient on the tangent bundle of the unitary manifold.

exp

The exponential of array element-wise.

expand_dims

The array with an additional dimension inserted at the given axis.

expm

The matrix exponential of matrix.

eye

The identity matrix of size.

eye_like

The identity matrix of the same shape and dtype as array.

full

Returns an array of given shape filled with fill_value.

gather

The values of the array at the given indices.

get_backend

Returns the backend with the given name.

hermite_renormalized

Renormalized multidimensional Hermite polynomial given by the "exponential" Taylor series of \(exp(c + bx + 1/2*Ax^2)\) at zero, where the series has \(sqrt(n!)\) at the denominator rather than \(n!\).

hermite_renormalized_1leftoverMode

Compute the conditional density matrix of mode 0, with all the other modes detected with PNR detectors up to the given photon numbers.

hermite_renormalized_binomial

Renormalized multidimensional Hermite polynomial given by the "exponential" Taylor series of \(exp(C + Bx + 1/2*Ax^2)\) at zero, where the series has \(sqrt(n!)\) at the denominator rather than \(n!\).

hermite_renormalized_diagonal

Renormalized multidimensional Hermite polynomial given by the "exponential" Taylor series of \(exp(C + Bx - Ax^2)\) at zero, where the series has \(sqrt(n!)\) at the denominator rather than \(n!\).

homodyne_projector

Creates a homodyne projector matrix.

imag

The imaginary part of array.

infinity_like

Returns an array of infinities with the same shape as array.

inv

The inverse of tensor.

iscomplexobj

Whether the given object is complex.

isnan

Whether the given array contains any NaN values.

issubdtype

Whether the arg1 is a typecode lower/equal in type hierarchy to arg2.

kron

The Kroenecker product of the given tensors.

lgamma

The natural logarithm of the gamma function of x.

log

The natural logarithm of x.

make_complex

Given two real tensors representing the real and imaginary part of a complex number, this operation returns a complex tensor.

map_fn

Transforms elems by applying fn to each element unstacked on axis 0.

matmul

The matrix product of the given matrices.

matvec

The matrix vector product of a (matrix) and b (vector).

max

The maximum value of an array.

maximum

The element-wise maximum of a and b.

minimum

The element-wise minimum of a and b.

mod

Returns the element-wise remainder of division.

moveaxis

Moves the axes of an array to a new position.

norm

The norm of array.

ones

Returns an array of ones with the given shape and dtype.

ones_like

Returns an array of ones with the same shape and dtype as array.

outer

The outer product of array1 and array2.

pad

The padded array.

pinv

The pseudo-inverse of matrix.

pow

Returns \(x^y\).

prod

The product of all elements in array.

random_orthogonal

A random orthogonal matrix in \(O(N)\).

random_symplectic

A random symplectic matrix in Sp(2*num_modes).

random_unitary

A random unitary matrix in \(U(N)\).

real

The real part of array.

reshape

The reshaped array.

rotmat

Rotation matrix from quadratures to complex amplitudes.

shape

The shape of an array.

sin

The sine of array.

sinh

The hyperbolic sine of array.

solve

The solution of the linear system \(Ax = b\).

sort

Sort the array along an axis.

sqrt

The square root of x.

sqrtm

The matrix square root.

squeezed

Creates a single mode squeezed state matrix using a Fock lattice strategy.

squeezer

Creates a single mode squeezer matrix using a Fock lattice strategy.

stack

Stack arrays in sequence along a new axis.

sum

The sum of array.

swapaxes

Swap two axes of an array.

tensordot

The tensordot product of a and b.

tile

The tiled array.

trace

The trace of array.

transpose

The transposed arrays.

unitary_to_orthogonal

Maps a unitary matrix (or batch of unitary matrices) into an orthogonal matrix (or batch) of twice the size.

update_add_tensor

Updates a tensor in place by adding the given values.

value_and_gradients

The loss and gradients of the given cost function.

xlogy

Returns 0 if x == 0 elementwise and x * log(y) otherwise.

zeros

Returns an array of zeros with the given shape and dtype.

zeros_like

Returns an array of zeros with the same shape and dtype as array.

A class to manage the different backends supported by Mr Mustard.

mrmustard.math.cast(array, dtype=None)

Casts array to dtype.

Parameters:
  • array (ArrayLike) – The array to cast.

  • dtype (DTypeLike | None) – The data type to cast to. If None, the returned array is the same as the given one.

Returns:

The array cast to dtype.

Return type:

Tensor

mrmustard.math.J(num_modes)

Symplectic form.

Parameters:

num_modes (int) – A positive integer representing the number of modes.

Returns:

The symplectic form.

Return type:

RealTensor

mrmustard.math.Xmat(num_modes)

The matrix \(X_n = \begin{bmatrix}0 & I_n\\ I_n & 0\end{bmatrix}.\).

Parameters:

num_modes (int) – A positive integer representing the number of modes.

Returns:

The \(2N\times 2N\) array.

Return type:

RealTensor

mrmustard.math.Zmat(num_modes)

The matrix \(Z_n = \begin{bmatrix}I_n & 0\\ 0 & -I_n\end{bmatrix}.\).

Parameters:

num_modes (int) – A positive integer representing the number of modes.

Returns:

The \(2N\times 2N\) array.

Return type:

RealTensor

mrmustard.math.abs(array)

The absolute value of array.

Parameters:

array (ArrayLike) – The array to take the absolute value of.

Returns:

The absolute value of the given array.

Return type:

RealTensor

mrmustard.math.all(array)

Returns True if all elements of array are True, False otherwise.

Parameters:

array (ArrayLike) – The array to check.

Returns:

True if all elements of array are True, False otherwise.

Return type:

bool

mrmustard.math.all_diagonals(rho, real)

Returns all the diagonals of a density matrix.

Parameters:
  • rho (ArrayLike) – The density matrix.

  • real (bool) – Whether to return the real part of the diagonals.

Returns:

The diagonals of the density matrix.

Return type:

Tensor

mrmustard.math.allclose(array1, array2, atol=1e-09, rtol=1e-05)

Whether two arrays are equal within tolerance.

The two arrays are compaired element-wise.

Parameters:
  • array1 (ArrayLike) – An array.

  • array2 (ArrayLike) – Another array.

  • atol (float) – The absolute tolerance.

  • rtol (float) – The relative tolerance.

Returns:

Whether two arrays are equal within tolerance.

Raises:

ValueError – If the shape of the two arrays do not match.

Return type:

bool

mrmustard.math.angle(array)

The complex phase of array.

Parameters:

array (ArrayLike) – The array to take the complex phase of.

Returns:

The complex phase of array.

Return type:

RealScalarValue | RealTensor

mrmustard.math.any(array)

Returns True if any element of array is True, False otherwise.

Parameters:

array (ArrayLike) – The array to check.

Returns:

True if any element of array is True, False otherwise.

Return type:

bool

mrmustard.math.arange(start, limit=None, delta=1, dtype=None)

Returns an array of evenly spaced values within a given interval.

Parameters:
  • start (int) – The start of the interval.

  • limit (int | None) – The end of the interval.

  • delta (int) – The step size.

  • dtype (Any) – The dtype of the returned array.

Returns:

The array of evenly spaced values.

Return type:

IntTensor

mrmustard.math.asnumpy(tensor)

Converts an array to a numpy array.

Parameters:

tensor (ArrayLike) – The tensor to convert.

Returns:

The corresponding numpy array.

Return type:

Tensor

mrmustard.math.astensor(array, dtype=None)

Converts a scalar or array-like input to a tensor.

Parameters:
  • array – The scalar or array-like input to convert.

  • dtype – The dtype of the tensor. If None, the returned tensor is of type float.

Returns:

The tensor with dtype.

mrmustard.math.atleast_nd(array, n, dtype=None)

Returns an array with at least n dimensions. Note that dimensions are prepended to meet the minimum number of dimensions.

Parameters:
  • array (ArrayLike) – The array to convert.

  • n (int) – The minimum number of dimensions.

  • dtype (DTypeLike | None) – The data type of the array. If None, the returned array is of the same type as the given one.

Returns:

The array with at least n dimensions.

Return type:

Tensor

mrmustard.math.beamsplitter(theta, phi, shape, method)

Creates a beamsplitter matrix with given cutoffs using a Fock lattice strategy.

Parameters:
  • theta (RealScalar) – Transmittivity angle of the beamsplitter.

  • phi (RealScalar) – Phase angle of the beamsplitter.

  • shape (tuple[int, int, int, int]) – Output shape of the two modes.

  • method (Literal['vanilla', 'schwinger', 'stable']) – Method to compute the beamsplitter (“vanilla”, “schwinger” or “stable”).

Returns:

The matrix representing the beamsplitter gate.

Raises:

ValueError – If the method is not “vanilla”, “schwinger” or “stable”.

Return type:

ComplexTensor

mrmustard.math.block(blocks, axes=(-2, -1))

Returns a matrix made from the given blocks.

Parameters:
  • blocks (list[list[ArrayLike]]) – A list of lists of compatible blocks.

  • axes (tuple[int, ...]) – The axes to stack the blocks along.

Returns:

The matrix made of blocks.

Return type:

Tensor

mrmustard.math.broadcast_arrays(*arrays)

Broadcast arrays to a common shape.

Parameters:

*arrays (list[ArrayLike]) – The arrays to broadcast.

Returns:

A list of broadcasted arrays.

Return type:

list[mrmustard.utils.typing.Tensor]

mrmustard.math.broadcast_to(array, shape)

Broadcasts an array to a new shape.

Parameters:
  • array (ArrayLike) – The array to broadcast.

  • shape (tuple[int, ...]) – The shape to broadcast to.

Returns:

The broadcasted array.

Return type:

Tensor

mrmustard.math.change_backend(name)

Changes the backend to a different one.

Parameters:

name (str) – The name of the new backend.

Return type:

None

mrmustard.math.clip(array, a_min=None, a_max=None)

Clips array to the interval [a_min, a_max].

Parameters:
  • array (ArrayLike) – The array to clip.

  • a_min (ArrayLike | None) – The minimum value.

  • a_max (ArrayLike | None) – The maximum value.

Returns:

The clipped array.

Return type:

Tensor

mrmustard.math.complex_gaussian_integral_1(A, b, idx12, A_out=None, b_out=None, log_c_out=None)

Computes the complex Gaussian integral.

In particular,

\[\int_{C^m} d\mu(z) \exp(\frac{1}{2}(z,z^*,\beta)^T A (z,z^*,\beta) + (z,z^*,\beta)^T b),\]

where \(z\in\mathbb{C}^{m}\), \(\beta\in\mathbb{C}^{N}\) and the integration measure is given by \(d\mu(z) = \exp(-|z|^2) \frac{d^{2m}z}{\pi^m} = \frac{1}{\pi^m}\exp(-|z|^2) d\mathrm{Re}(z) d\mathrm{Im}(z)\).

If we partition A and b into idx12 blocks and the remaining blocks:

\[\begin{split}A = \begin{pmatrix} B & C^T \\ C & D \end{pmatrix},\quad b = \begin{pmatrix} g \\ h \end{pmatrix},\end{split}\]

the result is given by:

\[\begin{split}A_{\mathrm{out}} = D - C M^{-1} C^T, \\ b_{\mathrm{out}} = h - C M^{-1} g, \\ \log c_{\mathrm{out}} = -\frac{1}{2} g^T M^{-1} g + \frac{1}{2} \log(\det(iM^{-1}))\end{split}\]

where \(M = B - X\), \(X\) is the block with zeros on the diagonal and identities on the off-diagonal.

This function supports broadcasted/batched inputs, however note that this function is about one order of magnitude faster when the inputs are not batched versus being batched with size 1, so it’s recommended to squeeze the batch dimension before calling this function.

Parameters:
  • A (ComplexMatrix) – The A matrix.

  • b (ComplexVector) – The b vector.

  • idx12 (ArrayLike) – the indices of the z variables to integrate over. The first half is the z variables and the second half is the z* variables.

  • A_out (ComplexMatrix | None) – The (optional) output A matrix.

  • b_out (ComplexVector | None) – The (optional) output b vector.

  • log_c_out (ComplexTensor | None) – The (optional) output log_c vector.

Returns:

The (A_out, b_out, log_c_out) triple which parametrizes the result of the integral with eventual batch dimensions.

Return type:

tuple[ComplexMatrix, ComplexVector, ComplexTensor]

mrmustard.math.complex_gaussian_integral_2(A1, b1, A2, b2, idx1, idx2, A_out=None, b_out=None, log_c_out=None)

Computes the complex Gaussian integral.

In particular:

\[\int_{C^m} d\mu(z) \exp\!\left(\tfrac{1}{2}(z,\beta)^T A_1 (z,\beta) + (z,\beta)^T b_1\right) \exp\!\left(\tfrac{1}{2}(z^*,\gamma)^T A_2 (z^*,\gamma) + (z^*,\gamma)^T b_2\right),\]

where \(z\in\mathbb{C}^{m}\), \(\beta\in\mathbb{C}^{N_1}\), \(\gamma\in\mathbb{C}^{N_2}\) and the integration measure is given by \(d\mu(z) = \exp(-|z|^2) \frac{d^{2m}z}{\pi^m} = \frac{1}{\pi^m}\exp(-|z|^2) d\mathrm{Re}(z) d\mathrm{Im}(z)\).

If we partition \(A_1, b_1\) and \(A_2, b_2\) into \(\mathrm{idx1}, \mathrm{idx2}\) blocks and the remaining blocks:

\[\begin{split}A_1 = \begin{pmatrix} A & C^T \\ C & B \end{pmatrix},\quad b_1 = \begin{pmatrix} g \\ h \end{pmatrix},\qquad A_2 = \begin{pmatrix} D & F^T \\ F & E \end{pmatrix},\quad b_2 = \begin{pmatrix} i \\ j \end{pmatrix},\end{split}\]

the result is given by:

\[\begin{split}A_{\mathrm{out}} = \begin{pmatrix} B - C\,D\,L\,C^T & -F\,L\,C^T \\ -F\,L\,C^T & E - F\,L\,A\,F^T \end{pmatrix}, \\ b_{\mathrm{out}} = \begin{pmatrix} h - C\,(D\,L^T g + L\, i) \\ j - F\,(A\,L\, i + L^T g) \end{pmatrix}, \\ \log c_{\mathrm{out}} = -\frac{1}{2}\big[g^T D L^T g + 2 g^T L i + i^T A L i\big] + \frac{1}{2} \log(\det(-L)),\end{split}\]

where \(L = (A D - I)^{-1}\).

This function supports broadcasted/batched inputs, however note that this function is about one order of magnitude faster when the inputs are not batched versus being batched with size 1, so it’s recommended to squeeze the batch dimension before calling this function.

Parameters:
  • A1 (ComplexMatrix) – The first A matrix.

  • b1 (ComplexVector) – The first b vector.

  • A2 (ComplexMatrix) – The second A matrix.

  • b2 (ComplexVector) – The second b vector.

  • idx1 (ArrayLike) – The indices in the first tuple to integrate over. The first half is the z variables and the second half is the z* variables.

  • idx2 (ArrayLike) – The indices in the second tuple to integrate over. The first half is the z variables and the second half is the z* variables.

  • A_out (ComplexMatrix | None) – The (optional) output A matrix.

  • b_out (ComplexVector | None) – The (optional) output b vector.

  • log_c_out (ComplexTensor | None) – The (optional) output log_c vector.

Returns:

The (A_out, b_out, log_c_out) triple which parametrizes the result of the integral with eventual batch dimensions.

Return type:

tuple[ComplexMatrix, ComplexVector, ComplexTensor]

mrmustard.math.concat(values, axis=0)

Concatenates values along the given axis.

Parameters:
  • values (Sequence[ArrayLike]) – The values to concatenate.

  • axis (int) – The axis along which to concatenate.

Returns:

The concatenated values.

Return type:

Tensor

mrmustard.math.conj(array)

The complex conjugate of array.

Parameters:

array (ArrayLike) – The array to take the complex conjugate of.

Returns:

The complex conjugate of the given array.

Return type:

Tensor

mrmustard.math.cos(array)

The cosine of an array.

Parameters:

array (ArrayLike) – The array to take the cosine of.

Returns:

The cosine of array.

Return type:

Tensor

mrmustard.math.cosh(array)

The hyperbolic cosine of array.

Parameters:

array (ArrayLike) – The array to take the hyperbolic cosine of.

Returns:

The hyperbolic cosine of array.

Return type:

Tensor

mrmustard.math.conditional(cond, true_fn, false_fn, *args)

Executes true_fn if cond is True, otherwise false_fn.

Parameters:
  • cond (ArrayLike) – The condition to check.

  • true_fn (Callable) – The function to execute if cond is True.

  • false_fn (Callable) – The function to execute if cond is False.

  • *args (Any) – The arguments to pass to true_fn and false_fn.

Returns:

The result of true_fn if cond is True, otherwise false_fn.

Return type:

Any

mrmustard.math.dagger(array)

The adjoint of array. This operation swaps the first and second half of the indexes and then conjugates the matrix.

Parameters:

array (ArrayLike) – The array to take the adjoint of

Returns:

The adjoint of array

Return type:

Tensor

mrmustard.math.det(matrix)

The determinant of matrix.

Parameters:

matrix (ArrayLike) – The matrix to take the determinant of

Returns:

The determinant of matrix.

Return type:

ScalarValue | Tensor

mrmustard.math.diag(array, k=0)

The array made by inserting the given array along the \(k\)-th diagonal.

Parameters:
  • array (ArrayLike) – The array to insert.

  • k (int) – The k-th diagonal to insert array into.

Returns:

The array with array inserted into the k-th diagonal.

Return type:

Tensor

mrmustard.math.diag_part(array, k=0)

The array of the main diagonal of array.

Parameters:
  • array (ArrayLike) – The array to extract the main diagonal of.

  • k (int) – The diagonal to extract.

Returns:

The array of the main diagonal of array.

Return type:

Tensor

mrmustard.math.diagonal(array, offset=0, axis1=0, axis2=1)

Return specified diagonals of array.

Parameters:
  • array (ArrayLike) – The array to take the diagonal of.

  • offset (int) – The offset of the diagonal.

  • axis1 (int) – The first axis to take the diagonal of.

  • axis2 (int) – The second axis to take the diagonal of.

Returns:

The diagonal of array.

Return type:

Tensor

mrmustard.math.displacement(alpha, shape)

Creates a single mode displacement matrix using a Fock lattice strategy.

Parameters:
  • alpha (ComplexScalar) – The displacement.

  • shape (tuple[int, int]) – The shape of the displacement matrix.

Returns:

The matrix representing the displacement gate.

Return type:

ComplexTensor

mrmustard.math.eigvals(tensor)

The eigenvalues of a tensor.

Parameters:

tensor (ArrayLike) – The tensor to calculate the eigenvalues of.

Returns:

The eigenvalues of tensor.

Return type:

Tensor

mrmustard.math.eigh(tensor)

The eigenvalues and eigenvectors of a matrix.

Parameters:

tensor (ArrayLike) – The tensor to calculate the eigenvalues and eigenvectors of.

Returns:

The eigenvalues and eigenvectors of tensor.

Return type:

Tensor

mrmustard.math.einsum(*operands, optimize='greedy', memory_limit=None, backend=None)

The result of the Einstein summation convention on the operands.

Similar to np.einsum, two signatures are supported:
  • Subscript style:

    The first operand is a string where the subscripts for summation are a comma separated list of subscript labels with explicit output indices following a -> indicator.

  • Sublist style:

    The operands must be in the form tensor0, labels0, tensor1, labels1, ..., output where labels are a list of integers labeling indices for the preceding tensor in the list of operands and output is a list of integers labeling output indices for the resulting tensor.

Note

In subscript style, parentheses are supported in the output string to group indices that should be vectorized/flattened. For example, "ij,jk->h(ik)" will vectorize indices i and k. Ellipsis notation (...) cannot be combined with parenthesized groups.

Parameters:
  • operands (str | ArrayLike | list[int]) – The operands to perform the Einstein summation on in either subscript style or sublist style.

  • optimize (OptimizeKind) – Optional flag whether to optimize the contraction order. Allowed values are True, False, “greedy”, “optimal” or “auto”. Note the TF backend does not support False and converts it to “greedy”. If None, settings.EINSUM_OPTIMIZE is used.

  • memory_limit (int | Literal['max_input'] | None) – The memory limit for the contraction. If None, the memory limit is set to the default value.

  • backend (BackendType | None) – The name of the backend to use. If None, the set backend is used.

Returns:

The result of the Einstein summation convention.

Return type:

Tensor

mrmustard.math.equal(a, b)

Returns the element-wise equality of two arrays.

Parameters:
  • a (ArrayLike) – The first array.

  • b (ArrayLike) – The second array.

Returns:

The element-wise equality of two arrays.

Return type:

BoolScalar

mrmustard.math.error_if(array, condition, msg)

Raises an error if condition is True.

Parameters:
  • array (ArrayLike) – The array to check.

  • condition (BoolScalar) – The condition to check; should only use array elements in the condition.

  • msg (str) – The message to raise if condition is True.

Raises:

ValueError – If at least one element of condition is True.

Return type:

None

mrmustard.math.euclidean_to_symplectic(S, dS_euclidean)

Convert the Euclidean gradient to a Riemannian gradient on the tangent bundle of the symplectic manifold.

Implemented from:

Wang J, Sun H, Fiori S. A Riemannian‐steepest‐descent approach for optimization on the real symplectic group. Mathematical Methods in the Applied Sciences. 2018 Jul 30;41(11):4273-86.

Parameters:
  • S (ArrayLike) – Symplectic matrix.

  • dS_euclidean (ArrayLike) – Euclidean gradient tensor.

Returns:

The symplectic gradient tensor.

Return type:

Tensor

mrmustard.math.euclidean_to_unitary(U, dU_euclidean)

Convert the Euclidean gradient to a Riemannian gradient on the tangent bundle of the unitary manifold.

Implemented from:

Y Yao, F Miatto, N Quesada - arXiv preprint arXiv:2209.06069, 2022.

Parameters:
  • U (ArrayLike) – Unitary matrix.

  • dU_euclidean (ArrayLike) – Euclidean gradient tensor.

Returns:

The unitary gradient tensor.

Return type:

Tensor

mrmustard.math.exp(array)

The exponential of array element-wise.

Parameters:

array (ArrayLike) – The array to take the exponential of.

Returns:

The exponential of array.

Return type:

Tensor

mrmustard.math.expand_dims(array, axis)

The array with an additional dimension inserted at the given axis.

Parameters:
  • array (ArrayLike) – The array to expand.

  • axis (int) – The axis to insert the new dimension.

Returns:

The array with an additional dimension inserted at the given axis.

Return type:

Tensor

mrmustard.math.expm(matrix)

The matrix exponential of matrix.

Parameters:

matrix (ArrayLike) – The matrix to take the exponential of.

Returns:

The exponential of matrix.

Return type:

Tensor

mrmustard.math.eye(size, dtype=None)

The identity matrix of size.

Parameters:
  • size (int) – The size of the identity matrix

  • dtype (DTypeLike | None) – The data type of the identity matrix. If None, the returned matrix is of type float.

Returns:

The identity matrix.

Return type:

Tensor

mrmustard.math.eye_like(array)

The identity matrix of the same shape and dtype as array.

Parameters:

array (ArrayLike) – The array to create the identity matrix of.

Returns:

The identity matrix.

Return type:

Tensor

mrmustard.math.full(shape, fill_value, dtype=None)

Returns an array of given shape filled with fill_value.

Parameters:
  • shape (Sequence[int]) – The shape of the array.

  • fill_value (Scalar) – The value to fill the array with.

  • dtype (DTypeLike | None) – The dtype of the array. If None, the returned array is of type inferred from fill_value.

Returns:

The array filled with fill_value.

Return type:

Tensor

mrmustard.math.gather(array, indices, axis=None)

The values of the array at the given indices.

Parameters:
  • array (ArrayLike) – The array to gather values from.

  • indices (IntArrayLike) – The indices to gather values from.

  • axis (int | None) – The axis to gather values from.

Returns:

The values of the array at the given indices.

Return type:

Tensor

mrmustard.math.get_backend(name=None)

Returns the backend with the given name.

Parameters:

name (str | None) – The name of the backend.

Returns:

The backend with the given name.

Raises:

ValueError – If the backend name is not a supported one.

Return type:

BackendBase

mrmustard.math.hermite_renormalized(A, b, c, shape, stable=None, out=None)

Renormalized multidimensional Hermite polynomial given by the “exponential” Taylor series of \(exp(c + bx + 1/2*Ax^2)\) at zero, where the series has \(sqrt(n!)\) at the denominator rather than \(n!\). It computes all the amplitudes within the tensor of given shape.

This method automatically selects the appropriate calculation method based on input dimensions: 1. If A.ndim = 2, b.ndim = 1, c is scalar: Uses vanilla strategy (unbatched) 2. If A.ndim = 2, b.ndim > 1, c is scalar: Uses vanilla_full_batch strategy with broadcasting 3. If A.ndim > 2, b.ndim > 1, c.ndim > 0: Uses vanilla_full_batch strategy (fully batched)

Parameters:
  • A (ArrayLike) – The A matrix. Can be unbatched (shape D×D) or batched (shape B×D×D).

  • b (ArrayLike) – The b vector. Can be unbatched (shape D) or batched (shape B×D).

  • c (ArrayLike) – The c scalar. Can be scalar or batched (shape B).

  • shape (tuple[int, ...]) – The shape of the final tensor (excluding batch dimensions).

  • stable (bool | None) – Whether to use the numerically stable version of the algorithm (also slower). If None, uses settings.STABLE_FOCK_CONVERSION. Explicit True/False takes precedence over the setting.

  • out (ComplexTensor | None) – If provided, the result will be stored in this tensor.

Returns:

The renormalized Hermite polynomial of given shape preserving the batch dimensions.

Return type:

ComplexTensor

mrmustard.math.hermite_renormalized_1leftoverMode(A, b, c, output_cutoff, pnr_cutoffs, reorderedAB=True)

Compute the conditional density matrix of mode 0, with all the other modes detected with PNR detectors up to the given photon numbers.

Parameters:
  • A (ArrayLike) – The A matrix.

  • b (ArrayLike) – The b vector.

  • c (ArrayLike) – The c scalar.

  • output_cutoff (int) – Upper boundary of photon numbers in mode 0.

  • pnr_cutoffs (tuple[int, ...]) – Upper boundary of photon numbers in the other modes.

  • reorderedAB (bool) – Whether to reorder A and B parameters match conventions in mrmustard.math.numba.compactFock~.

Returns:

The conditional density matrix of mode 0. The final shape is (output_cutoff + 1, output_cutoff + 1, *pnr_cutoffs + 1).

Return type:

ComplexTensor

mrmustard.math.hermite_renormalized_binomial(A, B, C, shape, max_l2, global_cutoff)

Renormalized multidimensional Hermite polynomial given by the “exponential” Taylor series of \(exp(C + Bx + 1/2*Ax^2)\) at zero, where the series has \(sqrt(n!)\) at the denominator rather than \(n!\). The computation fills a tensor of given shape up to a given L2 norm or global cutoff, whichever applies first. The max_l2 value, if not provided, is set to the default value of the AUTOSHAPE_PROBABILITY setting.

Parameters:
  • A (ArrayLike) – The A matrix.

  • B (ArrayLike) – The B vector.

  • C (ArrayLike) – The C scalar.

  • shape (tuple[int, ...]) – The shape of the final tensor (local cutoffs).

  • max_l2 (float | None) – The maximum squared L2 norm of the tensor.

  • global_cutoff (int | None) – The global cutoff.

Returns:

The renormalized Hermite polynomial of given shape.

Return type:

ComplexTensor

mrmustard.math.hermite_renormalized_diagonal(A, b, c, cutoffs, reorderedAB=True)

Renormalized multidimensional Hermite polynomial given by the “exponential” Taylor series of \(exp(C + Bx - Ax^2)\) at zero, where the series has \(sqrt(n!)\) at the denominator rather than \(n!\). Note the minus sign in front of A.

Calculates the diagonal of the Fock representation (i.e. the PNR detection probabilities of all modes) by applying the recursion relation in a selective manner.

Note: This function supports batching of different B’s.

Parameters:
  • A (ArrayLike) – The A matrix.

  • b (ArrayLike) – The b vector.

  • c (ArrayLike) – The c scalar.

  • cutoffs (tuple[int, ...]) – upper boundary of photon numbers in each mode

  • reorderedAB (bool) – Whether to reorder A and B parameters match conventions in mrmustard.math.numba.compactFock~.

Returns:

The renormalized Hermite polynomial.

Return type:

ComplexTensor

mrmustard.math.homodyne_projector(fock_dim, A, b, c, out=None)

Creates a homodyne projector matrix.

Parameters:
Returns:

The homodyne projector matrix.

Return type:

ComplexTensor

mrmustard.math.imag(array)

The imaginary part of array.

Parameters:

array (ArrayLike) – The scalar or array-like input to take the imaginary part of.

Returns:

The imaginary part of array

Return type:

RealTensor

mrmustard.math.infinity_like(array)

Returns an array of infinities with the same shape as array.

Parameters:

array (ArrayLike) – The array to take the shape of.

Returns:

An array of infinities with the same shape as array.

Return type:

Tensor

mrmustard.math.inv(tensor)

The inverse of tensor.

Parameters:

tensor (ArrayLike) – The tensor to take the inverse of

Returns:

The inverse of tensor

Return type:

Tensor

mrmustard.math.iscomplexobj(x)

Whether the given object is complex.

Parameters:

x (Any) – The object to check.

Returns:

Whether the given array is a complex object.

Return type:

bool

mrmustard.math.isnan(array)

Whether the given array contains any NaN values.

Parameters:

array (ArrayLike) – The array to check for NaN values.

Returns:

Whether the given array contains any NaN values.

Return type:

BoolScalar

mrmustard.math.issubdtype(arg1, arg2)

Whether the arg1 is a typecode lower/equal in type hierarchy to arg2.

Parameters:
  • arg1 (DTypeLike) – The object to be tested

  • arg2 (DTypeLike) – The object to be compared against

Returns:

Whether arg1 is a subdtype of arg2.

Return type:

bool

mrmustard.math.kron(tensor1, tensor2)

The Kroenecker product of the given tensors.

Parameters:
  • tensor1 (ArrayLike) – A tensor.

  • tensor2 (ArrayLike) – Another tensor.

Returns:

The Kroenecker product.

Return type:

Tensor

mrmustard.math.lgamma(x)

The natural logarithm of the gamma function of x.

Parameters:

x (ArrayLike) – The array to take the natural logarithm of the gamma function of.

Returns:

The natural logarithm of the gamma function of x.

Return type:

Tensor

mrmustard.math.log(x)

The natural logarithm of x.

Parameters:

x (ArrayLike) – The array to take the natural logarithm of

Returns:

The natural logarithm of x

Return type:

Tensor

mrmustard.math.make_complex(real, imag)

Given two real tensors representing the real and imaginary part of a complex number, this operation returns a complex tensor. The input tensors must have the same shape.

Parameters:
  • real (ArrayLike) – The real part of the complex number.

  • imag (ArrayLike) – The imaginary part of the complex number.

Returns:

The complex array real + 1j * imag.

Return type:

ComplexTensor

mrmustard.math.map_fn(fn, elements)

Transforms elems by applying fn to each element unstacked on axis 0.

Parameters:
  • fn (Callable) – The callable to be performed. It accepts one argument, which will have the same (possibly nested) structure as elems.

  • elements (ArrayLike) – A tensor or (possibly nested) sequence of tensors, each of which will be unstacked along their first dimension. func will be applied to the nested sequence of the resulting slices.

Returns:

The result of applying fn on elements.

Return type:

Tensor

mrmustard.math.matmul(*matrices)

The matrix product of the given matrices.

Parameters:

matrices (ArrayLike) – The matrices to multiply.

Returns:

The matrix product

Return type:

Tensor

mrmustard.math.matvec(a, b)

The matrix vector product of a (matrix) and b (vector).

Parameters:
  • a (Matrix) – The matrix to multiply

  • b (Vector) – The vector to multiply

Returns:

The matrix vector product of a and b

Return type:

Tensor

mrmustard.math.max(array)

The maximum value of an array.

Parameters:

array (ArrayLike) – The array to take the maximum value of.

Returns:

The maximum value of the array.

Return type:

ScalarValue

mrmustard.math.maximum(a, b)

The element-wise maximum of a and b.

Parameters:
  • a (ArrayLike) – The first array to take the maximum of.

  • b (ArrayLike) – The second array to take the maximum of.

Returns:

The element-wise maximum of a and b

Return type:

Tensor

mrmustard.math.minimum(a, b)

The element-wise minimum of a and b.

Parameters:
  • a (ArrayLike) – The first array to take the minimum of.

  • b (ArrayLike) – The second array to take the minimum of.

Returns:

The element-wise minimum of a and b

Return type:

Tensor

mrmustard.math.mod(a, b)

Returns the element-wise remainder of division.

Parameters:
  • a (ArrayLike) – The dividend array.

  • b (ArrayLike) – The divisor array.

Returns:

The element-wise remainder of division.

Return type:

Tensor

mrmustard.math.moveaxis(array, old, new)

Moves the axes of an array to a new position.

Parameters:
  • array (ArrayLike) – The array to move the axes of.

  • old (int | Sequence[int]) – The old index position

  • new (int | Sequence[int]) – The new index position

Returns:

The updated array

Return type:

Tensor

mrmustard.math.norm(array, axis=None, keepdims=False)

The norm of array.

Parameters:
  • array (ArrayLike) – The array to take the norm of

  • axis (int | Sequence[int] | None) – The axis or axes to norm over. If None, the norm is computed over all axes.

  • keepdims (bool) – Whether to keep the dimensions of the array.

Returns:

The norm of array.

Return type:

Tensor

mrmustard.math.ones(shape, dtype=None)

Returns an array of ones with the given shape and dtype.

Parameters:
  • shape (Sequence[int]) – The shape of the array

  • dtype (DTypeLike | None) – The dtype of the array.

Returns:

The array of ones

Return type:

Tensor

mrmustard.math.ones_like(array)

Returns an array of ones with the same shape and dtype as array.

Parameters:

array (ArrayLike) – The array to take the shape and dtype of

Returns:

The array of ones

Return type:

Tensor

mrmustard.math.outer(array1, array2)

The outer product of array1 and array2.

Parameters:
  • array1 (ArrayLike) – The first array to take the outer product of

  • array2 (ArrayLike) – The second array to take the outer product of

Returns:

The outer product of array1 and array2

Return type:

Tensor

mrmustard.math.pad(array, paddings, mode='CONSTANT', constant_values=0)

The padded array.

Parameters:
  • array (ArrayLike) – The array to pad.

  • paddings (Sequence[tuple[int, int]]) – Paddings to apply.

  • mode – Mode to apply the padding.

  • constant_values – Constant values to use for padding.

Returns:

The padded array

Return type:

Tensor

mrmustard.math.pinv(matrix)

The pseudo-inverse of matrix.

Parameters:

matrix (ArrayLike) – The matrix to take the pseudo-inverse of.

Returns:

The pseudo-inverse of matrix

Return type:

Tensor

mrmustard.math.pow(x, y)

Returns \(x^y\). Broadcasts x and y if necessary.

Parameters:
  • x (ArrayLike) – The base.

  • y (ArrayLike) – The exponent.

Returns:

The \(x^y\).

Return type:

Tensor

mrmustard.math.prod(array, axis=None)

The product of all elements in array.

Parameters:
  • array (ArrayLike) – The array of elements to calculate the product of.

  • axis (int | tuple[int, ...] | None) – The axis along which a product is performed. If None, it calculates the product of all elements in array.

Returns:

The product of the elements in array.

Return type:

ScalarValue | Tensor

mrmustard.math.random_orthogonal(N, seed=None, batch_shape=())

A random orthogonal matrix in \(O(N)\).

Parameters:
  • N (int) – The dimension of the matrix.

  • seed (int | None) – The random seed. If None, the global seed is used.

  • batch_shape (tuple[int, ...]) – The batch shape for generating multiple random matrices.

Return type:

Tensor

mrmustard.math.random_symplectic(num_modes, max_r=1.0, seed=None, batch_shape=())

A random symplectic matrix in Sp(2*num_modes).

Squeezing is sampled uniformly from 0.0 to max_r (1.0 by default).

Parameters:
  • num_modes (int) – The number of modes.

  • max_r (float) – The maximum squeezing value.

  • seed (int | None) – The random seed. If None, the global seed is used.

  • batch_shape (tuple[int, ...]) – The batch shape for generating multiple random matrices.

Return type:

Tensor

mrmustard.math.random_unitary(N, seed=None, batch_shape=())

A random unitary matrix in \(U(N)\).

Parameters:
  • N (int) – The dimension of the matrix.

  • seed (int | None) – The random seed. If None, the global seed is used.

  • batch_shape (tuple[int, ...]) – The batch shape for generating multiple random matrices.

Return type:

Tensor

mrmustard.math.real(array)

The real part of array.

Parameters:

array (ArrayLike) – The scalar or array-like input to take the real part of.

Returns:

The real part of array

Return type:

RealTensor

mrmustard.math.reshape(array, shape)

The reshaped array.

Parameters:
  • array (ArrayLike) – The array to reshape.

  • shape (int | Sequence[int]) – Shape to reshape the array to.

Returns:

The reshaped array.

Return type:

Tensor

mrmustard.math.rotmat(num_modes)

Rotation matrix from quadratures to complex amplitudes.

Parameters:

num_modes (int) – A positive integer representing the number of modes.

Returns:

The rotation matrix.

Return type:

ComplexTensor

mrmustard.math.shape(array)

The shape of an array.

Parameters:

array (ArrayLike) – The array to take the shape of.

Returns:

The shape of the array.

Return type:

tuple[int, …]

mrmustard.math.sin(array)

The sine of array.

Parameters:

array (ArrayLike) – The array to take the sine of.

Returns:

The sine of array.

Return type:

Tensor

mrmustard.math.sinh(array)

The hyperbolic sine of array.

Parameters:

array (ArrayLike) – The array to take the hyperbolic sine of.

Returns:

The hyperbolic sine of array.

Return type:

Tensor

mrmustard.math.solve(matrix, rhs)

The solution of the linear system \(Ax = b\).

Parameters:
  • matrix (ArrayLike) – The matrix \(A\).

  • rhs (ArrayLike) – The vector \(b\).

Returns:

The solution \(x\).

Return type:

Tensor

mrmustard.math.sort(array, axis=-1)

Sort the array along an axis.

Parameters:
  • array (ArrayLike) – The array to sort.

  • axis (int) – The axis to sort along.

Returns:

A sorted version of the array in ascending order.

Return type:

Tensor

mrmustard.math.sqrt(x, dtype=None)

The square root of x.

Parameters:
  • x (ArrayLike) – The scalar or array-like input to take the square root of.

  • dtype (DTypeLike | None) – dtype of the output array.

Returns:

The square root of x.

Return type:

Tensor

mrmustard.math.sqrtm(tensor, dtype=None)

The matrix square root.

Parameters:
  • tensor (ArrayLike) – The tensor to take the matrix square root of.

  • dtype (DTypeLike | None) – The dtype of the output tensor. If None, the output is of type math.complex128.

Returns:

The square root of x.

Return type:

Tensor

mrmustard.math.squeezed(r, phi, shape)

Creates a single mode squeezed state matrix using a Fock lattice strategy.

Parameters:
  • r (RealScalar) – Squeezing magnitude.

  • phi (RealScalar) – Squeezing angle.

  • shape (tuple[int]) – Output shape of the mode.

Returns:

The matrix representing the squeezed state.

Return type:

ComplexTensor

mrmustard.math.squeezer(r, phi, shape)

Creates a single mode squeezer matrix using a Fock lattice strategy.

Parameters:
  • r (RealScalar) – Squeezing magnitude.

  • phi (RealScalar) – Squeezing angle.

  • shape (tuple[int, int]) – Output shape of the two modes.

Returns:

The matrix representing the squeezer.

Return type:

ComplexTensor

mrmustard.math.stack(arrays, axis=0)

Stack arrays in sequence along a new axis.

Parameters:
  • arrays (Sequence[ArrayLike]) – Sequence of tensors to stack.

  • axis (int) – The axis along which to stack the arrays.

Returns:

The stacked array.

Return type:

Tensor

mrmustard.math.sum(array, axis=None)

The sum of array.

Parameters:
  • array (ArrayLike) – The array to take the sum of.

  • axis (int | Sequence[int] | None) – The axis/axes to sum over.

Returns:

The sum of array.

mrmustard.math.swapaxes(array, axis1, axis2)

Swap two axes of an array.

Parameters:
  • array (ArrayLike) – The array to swap axes of.

  • axis1 (int) – The first axis to swap.

  • axis2 (int) – The second axis to swap.

Returns:

The array with the axes swapped.

Return type:

Tensor

mrmustard.math.tensordot(a, b, axes)

The tensordot product of a and b.

Parameters:
  • a (ArrayLike) – The first array to take the tensordot product of.

  • b (ArrayLike) – The second array to take the tensordot product of.

  • axes (Sequence[int]) – The axes to take the tensordot product over.

Returns:

The tensordot product of a and b.

Return type:

Tensor

mrmustard.math.tile(array, repeats)

The tiled array.

Parameters:
  • array (ArrayLike) – The array to tile.

  • repeats (Sequence[int]) – Number of times to tile the array along each axis.

Returns:

The tiled array.

Return type:

Tensor

mrmustard.math.trace(array, dtype=None)

The trace of array.

Parameters:
  • array (ArrayLike) – The array to take the trace of.

  • dtype (DTypeLike | None) – dtype of the output array.

Returns:

The trace of array.

Return type:

Tensor

mrmustard.math.transpose(a, perm=None)

The transposed arrays.

Parameters:
  • a (ArrayLike) – The array to transpose.

  • perm (Sequence[int] | None) – Permutation to apply to the array.

Returns:

The transposed array.

Return type:

Tensor

mrmustard.math.unitary_to_orthogonal(U)

Maps a unitary matrix (or batch of unitary matrices) into an orthogonal matrix (or batch) of twice the size.

Parameters:

U (ArrayLike) – A unitary matrix of shape (…, N, N) where … represents optional batch dimensions.

Returns:

An orthogonal matrix of shape (…, 2N, 2N).

Return type:

Tensor

mrmustard.math.update_add_tensor(tensor, indices, values)

Updates a tensor in place by adding the given values.

Parameters:
  • tensor (ArrayLike) – The tensor to update.

  • indices (ArrayLike) – The indices to update.

  • values (ArrayLike) – The values to add.

Returns:

The updated tensor.

Return type:

Tensor

mrmustard.math.value_and_gradients(cost_fn, parameters)

The loss and gradients of the given cost function.

Parameters:
Returns:

The loss and gradients of the given cost function.

Return type:

tuple[mrmustard.utils.typing.Tensor, dict[str, list[mrmustard.utils.typing.Tensor]]]

mrmustard.math.xlogy(x, y)

Returns 0 if x == 0 elementwise and x * log(y) otherwise.

Parameters:
  • x (ArrayLike) – The first array.

  • y (ArrayLike) – The second array.

Returns:

The result of the xlogy operation.

Return type:

Tensor

mrmustard.math.zeros(shape, dtype=None)

Returns an array of zeros with the given shape and dtype.

Parameters:
  • shape (int | Sequence[int]) – The shape of the array.

  • dtype (DTypeLike | None) – The dtype of the array.

Returns:

The array of zeros.

Return type:

Tensor

mrmustard.math.zeros_like(array)

Returns an array of zeros with the same shape and dtype as array.

Parameters:

array (ArrayLike) – The array to take the shape and dtype of.

Returns:

The array of zeros.

Return type:

Tensor