The math module¶
Symplectic form. |
|
The matrix \(X_n = \begin{bmatrix}0 & I_n\\ I_n & 0\end{bmatrix}.\). |
|
The matrix \(Z_n = \begin{bmatrix}I_n & 0\\ 0 & -I_n\end{bmatrix}.\). |
|
The absolute value of array. |
|
Returns |
|
Returns all the diagonals of a density matrix. |
|
Whether two arrays are equal within tolerance. |
|
The complex phase of |
|
Returns |
|
Returns an array of evenly spaced values within a given interval. |
|
Converts an array to a numpy array. |
|
Converts a scalar or array-like input to a tensor. |
|
Returns an array with at least n dimensions. |
|
Creates a beamsplitter matrix with given cutoffs using a Fock lattice strategy. |
|
Returns a matrix made from the given blocks. |
|
Broadcast arrays to a common shape. |
|
Broadcasts an array to a new shape. |
|
Casts |
|
Changes the backend to a different one. |
|
Clips array to the interval |
|
Computes the complex Gaussian integral. |
|
Computes the complex Gaussian integral. |
|
Concatenates values along the given axis. |
|
The complex conjugate of array. |
|
The cosine of an array. |
|
The hyperbolic cosine of array. |
|
Executes |
|
The adjoint of |
|
The determinant of matrix. |
|
The array made by inserting the given array along the \(k\)-th diagonal. |
|
The array of the main diagonal of array. |
|
Return specified diagonals of array. |
|
Creates a single mode displacement matrix using a Fock lattice strategy. |
|
The eigenvalues of a tensor. |
|
The eigenvalues and eigenvectors of a matrix. |
|
The result of the Einstein summation convention on the operands. |
|
Returns the element-wise equality of two arrays. |
|
Raises an error if |
|
Convert the Euclidean gradient to a Riemannian gradient on the tangent bundle of the symplectic manifold. |
|
Convert the Euclidean gradient to a Riemannian gradient on the tangent bundle of the unitary manifold. |
|
The exponential of array element-wise. |
|
The array with an additional dimension inserted at the given axis. |
|
The matrix exponential of matrix. |
|
The identity matrix of size. |
|
The identity matrix of the same shape and dtype as array. |
|
Returns an array of given shape filled with |
|
The values of the array at the given indices. |
|
Returns the backend with the given name. |
|
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!\). |
|
Compute the conditional density matrix of mode 0, with all the other modes detected with PNR detectors up to the given photon numbers. |
|
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!\). |
|
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!\). |
|
Creates a homodyne projector matrix. |
|
The imaginary part of array. |
|
Returns an array of infinities with the same shape as |
|
The inverse of tensor. |
|
Whether the given object is complex. |
|
Whether the given array contains any NaN values. |
|
Whether the |
|
The Kroenecker product of the given tensors. |
|
The natural logarithm of the gamma function of |
|
The natural logarithm of |
|
Given two real tensors representing the real and imaginary part of a complex number, this operation returns a complex tensor. |
|
Transforms elems by applying fn to each element unstacked on axis 0. |
|
The matrix product of the given matrices. |
|
The matrix vector product of |
|
The maximum value of an array. |
|
The element-wise maximum of |
|
The element-wise minimum of |
|
Returns the element-wise remainder of division. |
|
Moves the axes of an array to a new position. |
|
The norm of array. |
|
Returns an array of ones with the given |
|
Returns an array of ones with the same shape and |
|
The outer product of |
|
The padded array. |
|
The pseudo-inverse of matrix. |
|
Returns \(x^y\). |
|
The product of all elements in |
|
A random orthogonal matrix in \(O(N)\). |
|
A random symplectic matrix in |
|
A random unitary matrix in \(U(N)\). |
|
The real part of |
|
The reshaped array. |
|
Rotation matrix from quadratures to complex amplitudes. |
|
The shape of an array. |
|
The sine of |
|
The hyperbolic sine of |
|
The solution of the linear system \(Ax = b\). |
|
Sort the array along an axis. |
|
The square root of |
|
The matrix square root. |
|
Creates a single mode squeezed state matrix using a Fock lattice strategy. |
|
Creates a single mode squeezer matrix using a Fock lattice strategy. |
|
Stack arrays in sequence along a new axis. |
|
The sum of array. |
|
Swap two axes of an array. |
|
The tensordot product of |
|
The tiled array. |
|
The trace of array. |
|
The transposed arrays. |
|
Maps a unitary matrix (or batch of unitary matrices) into an orthogonal matrix (or batch) of twice the size. |
|
Updates a tensor in place by adding the given values. |
|
The loss and gradients of the given cost function. |
|
Returns |
|
Returns an array of zeros with the given shape and |
|
Returns an array of zeros with the same shape and |
A class to manage the different backends supported by Mr Mustard.
- mrmustard.math.cast(array, dtype=None)¶
Casts
arraytodtype.- 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:
- 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:
- 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:
- 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:
- 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:
- mrmustard.math.all(array)¶
Returns
Trueif all elements of array areTrue,Falseotherwise.- Parameters:
array (ArrayLike) – The array to check.
- Returns:
Trueif all elements of array areTrue,Falseotherwise.- 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:
- 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:
- mrmustard.math.any(array)¶
Returns
Trueif any element of array isTrue,Falseotherwise.- Parameters:
array (ArrayLike) – The array to check.
- Returns:
Trueif any element of array isTrue,Falseotherwise.- 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:
- 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:
- 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 typefloat.
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- mrmustard.math.conditional(cond, true_fn, false_fn, *args)¶
Executes
true_fnifcondisTrue, otherwisefalse_fn.- Parameters:
cond (ArrayLike) – The condition to check.
true_fn (Callable) – The function to execute if
condisTrue.false_fn (Callable) – The function to execute if
condisFalse.*args (Any) – The arguments to pass to
true_fnandfalse_fn.
- Returns:
The result of
true_fnifcondisTrue, otherwisefalse_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:
- 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:
- 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
arrayinserted into thek-th diagonal.- Return type:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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, ..., outputwherelabelsare 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 indicesiandk. 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_OPTIMIZEis 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:
- Similar to
- 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:
- mrmustard.math.error_if(array, condition, msg)¶
Raises an error if
conditionisTrue.- 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
conditionisTrue.
- Raises:
ValueError – If at least one element of
conditionisTrue.- 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:
- 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:
- 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:
- 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:
- 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:
- 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 typefloat.
- Returns:
The identity matrix.
- Return type:
- 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:
- mrmustard.math.full(shape, fill_value, dtype=None)¶
Returns an array of given shape filled with
fill_value.
- 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:
- 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, usessettings.STABLE_FOCK_CONVERSION. ExplicitTrue/Falsetakes 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:
- 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:
- 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:
- 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:
- mrmustard.math.homodyne_projector(fock_dim, A, b, c, out=None)¶
Creates a homodyne projector matrix.
- Parameters:
fock_dim (int) – The Fock dimension.
A (ComplexMatrix) – The A matrix.
b (ComplexVector) – The b vector.
c (ComplexScalar) – The c scalar.
out (Tensor | None) – The output tensor.
- Returns:
The homodyne projector matrix.
- Return type:
- 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:
- 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:
- 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:
- 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:
- mrmustard.math.issubdtype(arg1, arg2)¶
Whether the
arg1is a typecode lower/equal in type hierarchy toarg2.- 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:
- 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:
- 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:
- 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:
- 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.
funcwill be applied to the nested sequence of the resulting slices.
- Returns:
The result of applying
fnonelements.- Return type:
- mrmustard.math.matmul(*matrices)¶
The matrix product of the given matrices.
- Parameters:
matrices (ArrayLike) – The matrices to multiply.
- Returns:
The matrix product
- Return type:
- mrmustard.math.matvec(a, b)¶
The matrix vector product of
a(matrix) andb(vector).
- 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:
- mrmustard.math.maximum(a, b)¶
The element-wise maximum of
aandb.- 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
aandb- Return type:
- mrmustard.math.minimum(a, b)¶
The element-wise minimum of
aandb.- 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
aandb- Return type:
- 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:
- 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:
- 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:
- mrmustard.math.ones(shape, dtype=None)¶
Returns an array of ones with the given
shapeanddtype.- Parameters:
shape (Sequence[int]) – The shape of the array
dtype (DTypeLike | None) – The dtype of the array.
- Returns:
The array of ones
- Return type:
- mrmustard.math.ones_like(array)¶
Returns an array of ones with the same shape and
dtypeasarray.- Parameters:
array (ArrayLike) – The array to take the shape and dtype of
- Returns:
The array of ones
- Return type:
- mrmustard.math.outer(array1, array2)¶
The outer product of
array1andarray2.- 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:
- 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:
- 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:
- mrmustard.math.pow(x, y)¶
Returns \(x^y\). Broadcasts
xandyif necessary.- Parameters:
x (ArrayLike) – The base.
y (ArrayLike) – The exponent.
- Returns:
The \(x^y\).
- Return type:
- 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 inarray.
- Returns:
The product of the elements in
array.- Return type:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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) –
dtypeof the output array.
- Returns:
The square root of
x.- Return type:
- 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
dtypeof the output tensor. IfNone, the output is of typemath.complex128.
- Returns:
The square root of
x.- Return type:
- 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:
- 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:
- 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:
- 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:
- mrmustard.math.tensordot(a, b, axes)¶
The tensordot product of
aandb.- 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
aandb.- Return type:
- 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:
- mrmustard.math.trace(array, dtype=None)¶
The trace of array.
- Parameters:
array (ArrayLike) – The array to take the trace of.
dtype (DTypeLike | None) –
dtypeof the output array.
- Returns:
The trace of array.
- Return type:
- 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:
- 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:
- 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:
- mrmustard.math.value_and_gradients(cost_fn, parameters)¶
The loss and gradients of the given cost function.
- Parameters:
cost_fn (Callable[[...], mrmustard.utils.typing.Scalar]) – Cost function to compute the loss and gradients of.
parameters (dict[str, list[mrmustard.utils.typing.Trainable]]) – Parameters to compute the loss and gradients of.
- 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
0ifx == 0elementwise andx * log(y)otherwise.- Parameters:
x (ArrayLike) – The first array.
y (ArrayLike) – The second array.
- Returns:
The result of the xlogy operation.
- Return type:
- 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: