Table of Contents

Class DefaultLinalgEngine

Namespace
NumSharp.Backends
Assembly
NumSharp.dll

NumSharp's LinalgEngine, the default of Linalg: NumPy's numpy/linalg/_linalg.py statements in NumPy's order - the argument checks (_assert_stacked_2d, _assert_stacked_square, _assert_finite), the dtype rule (_commonType), the text refusals of the _umath_linalg gufuncs' input casts and each function's tail - over ten protected virtual kernels that stand for those gufuncs (CholeskyKernel(NDArray, bool), DetKernel(NDArray), SlogdetKernel(NDArray), EigKernel(NDArray, bool), EighKernel(NDArray, char, bool), InvKernel(NDArray), SolveKernel(NDArray, NDArray, bool), LstsqKernel(NDArray, NDArray, double), QrKernel(NDArray, string), SvdKernel(NDArray, bool, bool)).

public class DefaultLinalgEngine : LinalgEngine
Inheritance
DefaultLinalgEngine
Inherited Members

Remarks

The kernels. Each answers an empty operand (an empty matrix or a zero-size batch) itself, without LAPACK (NumSharp.Backends.LinAlgEmpty), then asks the operand engine's Blas, then falls back: the LU four (det, slogdet, inv, solve) to the managed LU (NumSharp.Backends.ManagedLu, allclose to NumPy), the other six to OpenBlasMissingBackendException. So the bundled OpenBLAS of NumSharp.Interop.OpenBLAS reaches them through Blas, and no subclass is needed for it.

Deriving. Override a kernel to compute a factorisation another way (MKL, a GPU, a solver of your own): the public members keep running NumPy's statements around it, so the override receives validated operands already cast to the loop dtype (float32, float64 or complex128) and its result goes through NumPy's collapse, casts and result layouts. Call the base kernel for the operands it does not serve (an empty one, another dtype). Assign the instance to Linalg of the cached engine.

Nested calls. A member never calls back up into a public np.* facade: where NumPy's statement calls another numpy.linalg function (inv, svdvals, norm, solve, ...) or a sibling (pinv's and matrix_rank's svd, the hermitian svd's eigh), it calls this engine's own virtual member, so a subclass that overrides one computes it for every caller; where it calls a main-namespace function (sum, matmul, abs, ...), it calls the member that function's facade dispatches to - the operand engine's TensorEngine member, or the array object's (NDArray / UnmanagedStorage) for the allocations, copies and views. The operands are plain arrays: every np.linalg facade is woven and hands a subclass operand in as its plain view, so a facade's subclass path would never run on these calls. The exceptions are np.outer and np.tensordot, whose statements are still their facades' own (no engine member until the np-layer dtype plan's phase P8): their three calls are pinned in ratchet R2's allowlist (np-layer dtype plan, P6b).

The statements were the internal operation class LinalgEngine (the np-layer dtype plan's P2) and the kernels the ten TensorEngine members of the same names (0.70.0); phase PE's E2 made the class this public sub-engine, and P6b made its statements call members instead of np.* facades. The kernels are Backends/Default/LinearAlgebra/DefaultLinalgEngine.Kernels.cs.

Methods

Cholesky(NDArray, bool)

NumPy's np.linalg.cholesky(a, upper=False): the Cholesky factor of a Hermitian positive-definite matrix, or of each matrix in a stack.

public override NDArray Cholesky(NDArray a, bool upper = false)

Parameters

a NDArray

The matrix or stack (the last two axes, square). Only the lower triangle is read, so a non-Hermitian operand is factorised as its own reflection rather than rejected.

upper bool

False (NumPy's default) for the lower factor L with a = L L*; true for the upper U with a = U* U.

Returns

NDArray

The triangular factor, a fresh array of the loop dtype (float64 for bool / integer operands).

Remarks

NumPy's statements: _assert_stacked_square, _commonType, the text refusal of the cholesky_lo / cholesky_up gufunc's input cast, then CholeskyKernel(NDArray, bool) at the loop dtype.

Exceptions

LinAlgError

Fewer than two axes, a non-square operand, or a matrix that is not positive definite (Matrix is not positive definite).

TypeError

A float16, decimal or char operand (array type float16 is unsupported in linalg).

TypeError

A text operand (NumPy's gufunc input-cast refusal, a UFuncTypeError).

OpenBlasMissingBackendException

A non-empty operand that no matrix backend serves (an empty operand or a zero-size batch needs none).

CholeskyKernel(NDArray, bool)

The cholesky_lo / cholesky_up gufunc: OpenBLAS potrf through the operand engine's Blas; an empty operand is Cholesky(NDArray), with or without a backend.

protected virtual NDArray CholeskyKernel(NDArray a, bool upper)

Parameters

a NDArray

The Hermitian positive-definite matrix or stack, validated (square, at least two axes) and cast to the loop dtype (float32, float64 or complex128) by Cholesky(NDArray, bool).

upper bool

Return the upper factor (NumPy's upper=True) rather than the lower one.

Returns

NDArray

The triangular factor, a fresh array of a's dtype and shape.

Remarks

An override replaces the factorisation for every np.linalg.cholesky call of the engine whose Linalg it is; it receives empty operands too (the base kernel answers them).

Exceptions

LinAlgError

A matrix that is not positive definite (Matrix is not positive definite, from the factorisation).

OpenBlasMissingBackendException

A non-empty operand that no backend serves: Core carries no managed Cholesky.

Cond(NDArray, object)

NumPy's np.linalg.cond(x, p=None): the condition number of a matrix in the given norm, or of each matrix in a stack.

public override NDArray Cond(NDArray x, object p = null)

Parameters

x NDArray

The matrix or stack.

p object

The order: null (NumPy's default) and ±2 from the singular values; ±1, ±inf and "fro" / "nuc" as norm(x, p) * norm(inv(x), p).

Returns

NDArray

The condition number, real: a 0-d array for one matrix (NumPy's scalar), one per matrix of a stack; inf for a singular matrix, NaN only where the matrix itself holds a NaN.

Remarks

The inverse runs in float64 (complex128 for a complex operand) whatever the result dtype, and a singular matrix's inverse is NaN rather than an error, as NumPy computes it under errstate(all='ignore').

Exceptions

LinAlgError

An empty operand (cond is not defined on empty arrays), a non-square one for an inverse-based order, or the nuclear norm of a singular matrix (the SVD of its NaN inverse: SVD did not converge).

TypeError

An array or list order (NumPy's p in {2, -2} hashes it: unhashable type: 'numpy.ndarray' / 'list'); a float16, decimal or char operand.

ValueError

An order the norm refuses (Invalid norm order for matrices.).

TypeError

A text operand (NumPy's gufunc input-cast refusal).

OpenBlasMissingBackendException

An SVD-based order (null, ±2, "nuc") over a non-empty operand that no matrix backend serves. The inverse-based orders need none: the managed LU inverts.

Cross(NDArray, NDArray, int)

NumPy's np.linalg.cross(x1, x2, axis=-1), the Array-API cross product: stricter than cross(NDArray, NDArray, int, int, int, int?), it takes 3-vectors only, over one axis shared by both operands and the result.

public override NDArray Cross(NDArray x1, NDArray x2, int axis = -1)

Parameters

x1 NDArray

The first operand.

x2 NDArray

The second operand.

axis int

The axis holding the three components, in both operands and in the result (negative counts from the end).

Returns

NDArray

np.cross's result: promote_types(x1.dtype, x2.dtype) (a strong promotion), a view of a fresh C-ordered array whose component axis is moved to axis.

Remarks

NumPy 2.5's one statement return _core_cross(x1, x2, axis=axis), which is cross(NDArray, NDArray, int, int, int, int?), computed by the member its facade dispatches to, Cross(NDArray, NDArray, int, int, int, int?) of x1's engine: the 3-component check is np.cross's own (the same text), and an axis out of range is its AxisError (axisa: axis 3 is out of bounds for array of dimension 3), where NumPy 2.4 checked the lengths first by tuple indexing (an IndexError). The core cross promotes the two dtypes STRONGLY (an int8 matrix against an int32 row is int32, a bool one int32 too) and fills a fresh array whose component axis it moves to the requested axis last, so the result is a view in NumPy's layout (C order for the last axis, F order for the first axis of a matrix).

Exceptions

IndexError

axis is out of range for either operand (tuple index out of range: NumPy indexes x1.shape[axis] first).

ValueError

The component axis of either operand does not have length 3, or the other axes do not broadcast.

TypeError

Either operand holds text (the multiply has no string loop).

Det(NDArray)

NumPy's np.linalg.det(a): the determinant of a matrix, or of each matrix in a stack, from an LU factorisation (getrf), so a large or ill-conditioned matrix can overflow where Slogdet(NDArray) stays finite.

public override NDArray Det(NDArray a)

Parameters

a NDArray

The square matrix or stack.

Returns

NDArray

The determinant in the loop dtype: NumPy's scalar (a read-only 0-d array) for one matrix, one value per matrix of a stack.

Remarks

Needs no backend: without one the managed LU computes it, allclose to NumPy's blocked LAPACK (a matrix whose zero pivot appears only after several eliminations can give a tiny value where LAPACK gives 0).

Exceptions

LinAlgError

Fewer than two axes, or a non-square operand.

TypeError

A float16, decimal or char operand.

TypeError

A text operand (NumPy's gufunc input-cast refusal).

DetKernel(NDArray)

The det gufunc: OpenBLAS getrf through the operand engine's Blas, or NumSharp's managed LU (NumSharp.Backends.ManagedLu) when no backend serves the operand.

protected virtual NDArray DetKernel(NDArray a)

Parameters

a NDArray

The square matrix or stack, validated and cast to the loop dtype by Det(NDArray).

Returns

NDArray

The determinant: for one matrix NumPy's scalar (a read-only 0-d array, the gufunc's return step), for a stack a writeable array of one determinant per matrix.

Remarks

NumPy's det is the gufunc _umath_linalg.det, and the ufunc machinery returns a 0-d output as a numpy scalar; NumSharp.NDArray.PyArray_Return() is that step for both routes (a no-op for a stack's 1-d or larger result). The managed LU is allclose to NumPy's blocked LAPACK, not bit-exact: a matrix whose zero pivot only appears after several eliminations can give a tiny determinant where LAPACK cancels to 0.

Eig(NDArray)

NumPy's np.linalg.eig(a): the eigenvalues and right eigenvectors of a general (not necessarily symmetric) matrix, or of each matrix in a stack.

public override (NDArray eigenvalues, NDArray eigenvectors) Eig(NDArray a)

Parameters

a NDArray

The square matrix or stack; it must hold no inf or NaN.

Returns

(NDArray Lhs, NDArray Rhs)

(eigenvalues, eigenvectors), the columns of the second being the vectors. Always complex128 (NumPy 2.5: a real matrix with real eigenvalues gives zero imaginary parts, where NumPy 2.4 returned a real dtype); a float32 operand's result carries NumPy's complex64 values.

Remarks

NumPy's statements: _assert_stacked_square, _assert_finite, _commonType, EigKernel(NDArray, bool) at the loop dtype, then the results in the operand's complex type (ComplexEigResult(NDArray, NDArray, NPTypeCode)): always complex since NumPy 2.5, a real matrix with real eigenvalues too.

Exceptions

LinAlgError

Fewer than two axes, a non-square operand, an operand holding inf / NaN (Array must not contain infs or NaNs), or no convergence.

TypeError

A text operand (isfinite has no string loop), or a float16, decimal or char operand.

OpenBlasMissingBackendException

A non-empty operand that no matrix backend serves.

EigKernel(NDArray, bool)

The eig / eigvals gufunc: OpenBLAS geev through the operand engine's Blas, always complex128 (and so is Eig(NDArray)'s result); an empty operand is Eig(NDArray, bool), with or without a backend.

protected virtual (NDArray eigenvalues, NDArray eigenvectors) EigKernel(NDArray a, bool computeVectors)

Parameters

a NDArray

The square matrix or stack, validated (finite included) and cast to the loop dtype.

computeVectors bool

Whether the eigenvectors are wanted; the second slot is null otherwise.

Returns

(NDArray Lhs, NDArray Rhs)

The complex128 eigenvalues and, when computeVectors is set, the eigenvectors (the columns).

Exceptions

LinAlgError

The eigenvalue iteration did not converge (Eigenvalues did not converge).

OpenBlasMissingBackendException

A non-empty operand that no backend serves: Core carries no managed eigensolver.

Eigh(NDArray, char)

NumPy's np.linalg.eigh(a, UPLO='L'): the eigenvalues and eigenvectors of a real symmetric or complex Hermitian matrix, or of each matrix in a stack. Faster than Eig(NDArray) and always real.

public override (NDArray eigenvalues, NDArray eigenvectors) Eigh(NDArray a, char UPLO = 'L')

Parameters

a NDArray

The symmetric / Hermitian matrix or stack.

UPLO char

The triangle that holds the data, 'L' (NumPy's default) or 'U', either case. The other triangle is NOT read, so a non-symmetric operand is interpreted as its own reflection.

Returns

(NDArray Lhs, NDArray Rhs)

(eigenvalues, eigenvectors): the eigenvalues ascending and real (the real counterpart dtype for a complex operand).

Remarks

NumPy's statements: the UPLO check (before the operand is read), _assert_stacked_square, _commonType, the text refusal of the eigh_lo / eigh_up gufunc's input cast, then EighKernel(NDArray, char, bool) at the loop dtype.

Exceptions

ValueError

UPLO is neither 'L' nor 'U' (UPLO argument must be 'L' or 'U', checked before the operand).

LinAlgError

Fewer than two axes, a non-square operand, or no convergence.

TypeError

A float16, decimal or char operand.

TypeError

A text operand (NumPy's gufunc input-cast refusal).

OpenBlasMissingBackendException

A non-empty operand that no matrix backend serves.

EighKernel(NDArray, char, bool)

The eigh / eigvalsh gufunc: OpenBLAS syevd (real symmetric) or heevd (complex Hermitian) through the operand engine's Blas; an empty operand is Eigh(NDArray, bool), with or without a backend.

protected virtual (NDArray eigenvalues, NDArray eigenvectors) EighKernel(NDArray a, char uplo, bool computeVectors)

Parameters

a NDArray

The symmetric / Hermitian matrix or stack, validated and cast to the loop dtype.

uplo char

The triangle read, 'L' or 'U' (upper-cased by Eigh(NDArray, char)).

computeVectors bool

Whether the eigenvectors are wanted; the second slot is null otherwise.

Returns

(NDArray Lhs, NDArray Rhs)

The real eigenvalues, ascending, and (when computeVectors is set) the eigenvectors.

Exceptions

LinAlgError

The eigenvalue iteration did not converge.

OpenBlasMissingBackendException

A non-empty operand that no backend serves.

Eigvals(NDArray)

NumPy's np.linalg.eigvals(a): Eig(NDArray)'s eigenvalues without the eigenvectors.

public override NDArray Eigvals(NDArray a)

Parameters

a NDArray

The square matrix or stack; it must hold no inf or NaN.

Returns

NDArray

The eigenvalues, always complex128 (NumPy 2.5), as Eig(NDArray)'s.

Remarks

Eig(NDArray)'s statements without the eigenvectors (the kernel computes none).

Exceptions

LinAlgError

Fewer than two axes, a non-square operand, an operand holding inf / NaN, or no convergence.

TypeError

A text operand, or a float16, decimal or char operand.

OpenBlasMissingBackendException

A non-empty operand that no matrix backend serves.

Eigvalsh(NDArray, char)

NumPy's np.linalg.eigvalsh(a, UPLO='L'): Eigh(NDArray, char)'s eigenvalues without the eigenvectors. LAPACK computes them another way when it computes no vectors, so they can differ from Eigh's in the last bits, in NumPy as here.

public override NDArray Eigvalsh(NDArray a, char UPLO = 'L')

Parameters

a NDArray

The symmetric / Hermitian matrix or stack.

UPLO char

The triangle that holds the data, 'L' or 'U', either case.

Returns

NDArray

The eigenvalues, ascending and real.

Remarks

Eigh(NDArray, char)'s statements without the eigenvectors (the eigvalsh_lo / eigvalsh_up gufunc; the kernel computes no vectors).

Exceptions

ValueError

UPLO is neither 'L' nor 'U'.

LinAlgError

Fewer than two axes, a non-square operand, or no convergence.

TypeError

A float16, decimal or char operand.

TypeError

A text operand (NumPy's gufunc input-cast refusal).

OpenBlasMissingBackendException

A non-empty operand that no matrix backend serves.

Inv(NDArray)

NumPy's np.linalg.inv(a): the multiplicative inverse of a matrix, or of each matrix in a stack, by solving a x = I (gesv), so a singular operand raises from the factorisation, not from a determinant test.

public override NDArray Inv(NDArray a)

Parameters

a NDArray

The square matrix or stack.

Returns

NDArray

The inverse, a fresh array of the loop dtype (float64 for bool / integer operands).

Remarks

Needs no backend: without one the managed LU computes it.

Exceptions

LinAlgError

Fewer than two axes, a non-square operand, or a singular matrix (Singular matrix).

TypeError

A float16, decimal or char operand.

TypeError

A text operand (NumPy's gufunc input-cast refusal).

InvKernel(NDArray)

The inv gufunc: OpenBLAS gesv against the identity through the operand engine's Blas, or NumSharp's managed LU (NumSharp.Backends.ManagedLu) when no backend serves the operand.

protected virtual NDArray InvKernel(NDArray a)

Parameters

a NDArray

The square matrix or stack, validated and cast to the loop dtype.

Returns

NDArray

The inverse, a fresh array of a's dtype and shape.

Remarks

Cond(NDArray, object) calls this kernel too, per matrix, and turns a singular one into NaN as NumPy's errstate(all='ignore') does: an override must keep the Singular matrix text of its LinAlgError for that to work.

Exceptions

LinAlgError

A singular matrix (Singular matrix, from the factorisation, as NumPy's gesv reports it: no determinant test).

Lstsq(NDArray, NDArray, double?)

NumPy's np.linalg.lstsq(a, b, rcond=None): the least-squares solution to a x = b. It takes a single matrix, not a stack.

public override (NDArray Solution, NDArray Residuals, NDArray Rank, NDArray SingularValues) Lstsq(NDArray a, NDArray b, double? rcond = null)

Parameters

a NDArray

The coefficient matrix (M, N), exactly two-dimensional.

b NDArray

The ordinate values, (M,) or (M, K).

rcond double?

Singular values below rcond times the largest are treated as zero; null for NumPy's eps * max(M, N) (float64's eps, the compute type's).

Returns

(NDArray, NDArray, NDArray, NDArray)

NumPy's four-tuple (solution, residuals, rank, singularValues): the residuals EMPTY unless the system is overdetermined and of full rank; the rank NumPy's scalar.

Remarks

NumPy's statements: the 1-D b promotion, _assert_2d, the row check, _commonType, the text refusal of the lstsq gufunc's input casts, the default cutoff, the nrhs == 0 padding, LstsqKernel(NDArray, NDArray, double), and NumPy's tail (the squeeze, the discarded residuals, the casts). The promotion, the allocations and the squeeze are the array object's members (np.expand_dims', np.zeros' and np.reshape's), not their facades.

Exceptions

LinAlgError

An operand that is not two-dimensional (after a 1-D b became a column), b's rows differ from a's (Incompatible dimensions), or no convergence.

TypeError

A float16, decimal or char operand.

TypeError

A text operand (NumPy's gufunc input-cast refusal).

OpenBlasMissingBackendException

A non-empty operand that no matrix backend serves.

LstsqKernel(NDArray, NDArray, double)

The lstsq gufunc: OpenBLAS gelsd through the operand engine's Blas; an empty coefficient matrix is Lstsq(NDArray, NDArray), with or without a backend.

protected virtual (NDArray Solution, NDArray Residuals, NDArray Rank, NDArray SingularValues) LstsqKernel(NDArray a, NDArray b, double rcond)

Parameters

a NDArray

The coefficient matrix (M, N), cast to the loop dtype.

b NDArray

The right-hand sides (M, K), K >= 1 (Lstsq(NDArray, NDArray, double?) pads K == 0), cast to the loop dtype.

rcond double

The singular-value cutoff ratio (NumPy's default already applied).

Returns

(NDArray, NDArray, NDArray, NDArray)

The solution, the residuals, the rank and the singular values, before Lstsq(NDArray, NDArray, double?)'s casts; the rank is NumPy's scalar (a read-only 0-d array, the gufunc's return step).

Remarks

NumPy's lstsq calls the gufunc _umath_linalg.lstsq, whose 0-d rank output the ufunc machinery returns as a numpy scalar (np.intc); NumSharp.NDArray.PyArray_Return() is that step for both routes. Since NumPy 2.5 the gufunc checks the coefficient matrix before gelsd (all_finite, gh-32719): LAPACK's SVD drivers can loop forever on an inf, so a non-finite a is a failed factorisation. The check is NumPy's code, not LAPACK's, so it runs with or without a backend; the right-hand sides are not checked (a NaN in b solves to NaN).

Exceptions

LinAlgError

The SVD did not converge, or the coefficient matrix holds an inf or a NaN (SVD did not converge in Linear Least Squares).

OpenBlasMissingBackendException

A non-empty, finite coefficient matrix that no backend serves.

Matmul(NDArray, NDArray)

NumPy's np.linalg.matmul(x1, x2), the Array-API spelling of matmul(NDArray, NDArray, NDArray, int[][], int?, bool?, DType, string, char): the same operation with every keyword at its default.

public override NDArray Matmul(NDArray x1, NDArray x2)

Parameters

x1 NDArray

The left operand (at least one-dimensional).

x2 NDArray

The right operand (at least one-dimensional).

Returns

NDArray

np.matmul's product: a fresh array that owns its data, NumPy's 0-d scalar stand-in for two vectors.

Remarks

NumPy's one statement return _core_matmul(x1, x2): the member matmul(NDArray, NDArray, NDArray, int[][], int?, bool?, DType, string, char) dispatches to, Matmul(NDArray, NDArray, NDArray, int[][], int?, bool?, DType, string, char) of x1's engine, with every keyword at np.matmul's default (no out, axes, axis, keepdims or dtype; casting="same_kind", order='K'; CoreMatmul(NDArray, NDArray)). A null x1 fails at the dispatch with a NullReferenceException, as it did through np.matmul.

Exceptions

ValueError

A 0-d operand, or core dimensions that do not match, or loop axes that do not broadcast (NumPy's gufunc texts).

TypeError

Text operands (matmul has no string loop).

NullReferenceException

An operand is null.

MatrixNorm(NDArray, bool, object)

NumPy's np.linalg.matrix_norm(x, keepdims=False, ord='fro'), the Array-API matrix norm: always over the LAST TWO axes.

public override NDArray MatrixNorm(NDArray x, bool keepdims = false, object ord = null)

Parameters

x NDArray

The matrix or stack.

keepdims bool

Leave the two reduced axes in the result with length 1.

ord object

The matrix order; null stands for NumPy's default "fro" (C# cannot spell a non-null default for an object parameter).

Returns

NDArray

The matrix norm over the last two axes.

Remarks

NumPy's one statement return norm(x, axis=(-2, -1), keepdims=keepdims, ord=ord), through this engine's Norm(NDArray, object, int[], bool) (so a subclass that overrides it computes matrix_norm too), the null order standing for NumPy's default "fro". It opens no scope: the call is the whole body and its result is returned as it is.

Exceptions

ValueError

An invalid matrix order, or a min order of an empty matrix.

AxisError

An operand of fewer than two axes.

TypeError

An order that is neither null, a number nor a string.

OpenBlasMissingBackendException

An order 2, -2 or "nuc" over a non-empty matrix with no matrix backend installed.

MatrixPower(NDArray, int)

NumPy's np.linalg.matrix_power(a, n): a square matrix (or each of a stack) raised to an integer power by binary exponentiation; a negative power inverts first.

public override NDArray MatrixPower(NDArray a, int n)

Parameters

a NDArray

The square matrix or stack (the last two axes).

n int

Any integer: 0 gives the identity in a's dtype and memory order.

Returns

NDArray

The power. Footgun (NumPy's own): n == 1 returns a ITSELF, so writing to the result writes to a; n == -1 returns the fresh inverse.

Remarks

NumPy's statements: _assert_stacked_square, the inverse for a negative power (through this engine's Inv(NDArray), NumPy's inv(a), so a subclass that overrides it computes this inverse too), the identity for 0, the operand itself for 1, and binary exponentiation with the core matmul above (CoreMatmul(NDArray, NDArray), the member matmul(NDArray, NDArray, NDArray, int[][], int?, bool?, DType, string, char) dispatches to).

Exceptions

LinAlgError

Fewer than two axes, a non-square operand, or a negative power of a singular matrix.

TypeError

A text matrix with n of 2 or more (matmul has no string loop), or with a negative n (inv's input cast).

MatrixRank(NDArray, double?, bool, double?)

NumPy's np.linalg.matrix_rank(A, tol=None, hermitian=False, rtol=None): the number of singular values above the tolerance, per matrix.

public override NDArray MatrixRank(NDArray A, double? tol = null, bool hermitian = false, double? rtol = null)

Parameters

A NDArray

The matrix or stack. Below two axes NumPy's answer is a PREDICATE, int(not all(A == 0)): matrix_rank([1, 2, 3]) is 1, an empty operand 0.

tol double?

The absolute threshold; null for S.max() * max(M, N) * eps (eps of the singular values' dtype).

hermitian bool

Take the singular values from the Hermitian (real symmetric) matrix whose lower triangle A holds (eigvalsh's square check applies).

rtol double?

The relative threshold (the Array-API spelling).

Returns

NDArray

The rank: an int64 0-d array for one matrix (or below two axes), one per matrix of a stack.

Remarks

NumPy's statements: the tolerance arguments, NumPy's predicate below two axes (int(not all(A == 0))), and otherwise the count of singular values (this engine's Svd(NDArray, bool, bool, bool)) above the tolerance, through the members np.amax, np.multiply, np.greater and np.count_nonzero dispatch to. An empty matrix (and a stack of them) is rank 0: the largest singular value starts from NumPy 2.5's initial=0, where NumPy 2.4 raised the no-identity ValueError.

Exceptions

ValueError

Both tol and rtol are set.

LinAlgError

A non-square operand with hermitian.

TypeError

A float16, decimal or char operand.

TypeError

A text operand of two or more axes (NumPy's gufunc input-cast refusal).

OpenBlasMissingBackendException

A non-empty operand of two or more axes that no matrix backend serves.

MultiDot(NDArray[], NDArray)

NumPy's np.linalg.multi_dot(arrays, out=None): a chained matrix product in the cheapest association order (the matrix-chain dynamic program; a direct comparison for three).

public override NDArray MultiDot(NDArray[] arrays, NDArray @out = null)

Parameters

arrays NDArray[]

Two or more arrays. With three or more, every one but the ends must be 2-D; a 1-D first operand is a row and a 1-D last one a column, the added axis removed again afterwards. Two arrays are a plain np.dot.

out NDArray

The final product's out array (np.dot's strict out: the product's exact dtype and rank, C-contiguous, the TWO-dimensional product's shape), or null.

Returns

NDArray

The product: out itself when given (a two-array chain, or no vector end); a view of it raveled when one end was a vector; NumPy's scalar stand-in when both were; otherwise a fresh array.

Remarks

NumPy's statements: two arrays are dot(a, b, out=out); three or more are promoted at their vector ends (atleast_2d, and its transpose for the last), checked by _assert_2d, multiplied in the cheapest association order (_multi_dot_three for three, the matrix-chain dynamic program above) with the out array handed to the FINAL dot, and the result reshaped back: result[0, 0] when both ends were vectors, ravel() when one was.

out= is np.dot's. NumPy passes out to the final dot, whose check is new_array_for_sum: no cast, no broadcast. So multi_dot([v, B, C], out=o) wants o shaped (1, k) and of the product's dtype, and a float64 o for an integer chain is refused where a copy into it would have cast. The inner products are computed first, so their errors come before the out check.

The vector ends. NumPy's result[0, 0] of the (1, 1) product is a scalar: here a fresh 0-d copy of that element, marked like NumPy's scalars (NumSharp.NDArray.PyArray_Return()), never a view of the product or of the out array. result.ravel() of the C-ordered (1, k) or (k, 1) product is a view of it.

Members, not facades. Every dot is np.dot's member (CoreDot(NDArray, NDArray, NDArray)), the promotions and the ravel the array object's (atleast_2d(NDArray), ravel(char)). The np.linalg.multi_dot facade has a matrix rule only, so a numpy.char.chararray vector end used to stay a chararray through np.atleast_2d; it is a plain view now, which changes no result: every chain of three or more ends in a dot, whose result is plain either way, and a text chain is refused by the dot.

Exceptions

ValueError

Fewer than two arrays (Expecting at least two arrays.), or an out array np.dot refuses.

IncorrectShapeException

Misaligned operands (np.dot's shapes (…) and (…) not aligned).

LinAlgError

With three or more arrays, an operand other than a vector end that is not two-dimensional.

Norm(NDArray, object, int[], bool)

NumPy's np.linalg.norm(x, ord=None, axis=None, keepdims=False): a matrix or vector norm. The number of reduced axes decides the vocabulary of orders: one axis is a vector norm, two a matrix norm.

public override NDArray Norm(NDArray x, object ord = null, int[] axis = null, bool keepdims = false)

Parameters

x NDArray

The operand: integer, bool and text (parsed by astype(float)) operands compute in float64.

ord object

The order: null (Frobenius for a matrix, 2 for a vector), a number (an infinity included), or "fro" / "f" / "nuc".

axis int[]

The reduced axes (one or two), or null for every axis (NumPy's int axis is a one-element array here).

keepdims bool

Leave the reduced axes in the result with length 1.

Returns

NDArray

The norm: a 0-d array for a whole-array norm, else the reduced array. An empty operand's inf-, 1- and 2-norms are 0.0 (NumPy 2.x reduces those with initial=0).

Remarks

NumPy's statements: x.astype(float) of a text operand, the float conversion of an integer / bool one, the fast path of the default order over the whole array (raveled in memory order, sqrt(x.dot(x)), and for a complex operand sqrt(x_real.dot(x_real) + x_imag.dot(x_imag))), then the one-axis (NormVectorBranch(NDArray, object, int, bool)) or two-axis (NormMatrixBranch(NDArray, object, int[], int, bool)) branch. Every main-namespace call of those statements (ravel, real, imag, dot, sqrt, sum, abs, amax, amin, not_equal, power, reciprocal, evaluate, transpose, moveaxis, reshape, ascontiguousarray, add, the allocations) is the member its facade dispatches to, on the plain operands np.linalg.norm's woven subclass path hands in (a numpy.matrix and a numpy.char.chararray operand arrive as their plain views), and each nested norm or svdvals is this engine's own member.

Exceptions

ValueError

An order that is invalid for the number of reduced axes, duplicate axes, more than two reduced axes (Improper number of dimensions to norm.), a min order of an empty operand, or a text element that does not parse as a float.

AxisError

An axis out of range.

TypeError

An order that is neither null, a number nor a string.

OpenBlasMissingBackendException

A matrix order 2, -2 or "nuc" over a non-empty matrix with no matrix backend installed; every other order is a reduction and needs none.

Outer(NDArray, NDArray)

NumPy's np.linalg.outer(x1, x2): the outer product of two VECTORS. Not outer(NDArray, NDArray, NDArray), which flattens whatever it is given; this one refuses anything but 1-D.

public override NDArray Outer(NDArray x1, NDArray x2)

Parameters

x1 NDArray

The first vector.

x2 NDArray

The second vector.

Returns

NDArray

The (len(x1), len(x2)) outer product, a fresh array.

Remarks

NumPy's two statements: the rank check (Input arrays must be one-dimensional, but they are x1.ndim={n} and x2.ndim={m}.), then _core_outer(x1, x2, out=None), which is outer(NDArray, NDArray, NDArray) (on its own it would flatten anything): the member that facade dispatches to, Outer(NDArray, NDArray, NDArray) of x1's engine, without an out.

Exceptions

ValueError

Either operand is not one-dimensional (Input arrays must be one-dimensional, but they are x1.ndim={n} and x2.ndim={m}.).

Pinv(NDArray, double?, bool, double?)

NumPy's np.linalg.pinv(a, rcond=None, hermitian=False, rtol=None): the Moore-Penrose pseudo-inverse, from the singular value decomposition.

public override NDArray Pinv(NDArray a, double? rcond = null, bool hermitian = false, double? rtol = null)

Parameters

a NDArray

The matrix or stack.

rcond double?

Singular values at or below rcond times the largest are treated as zero; with rtol null too, NumPy's 1e-15.

hermitian bool

Decompose the Hermitian (real symmetric) matrix whose lower triangle the conjugated operand holds, through the symmetric eigensolver.

rtol double?

The Array-API spelling of rcond; setting both is an error.

Returns

NDArray

The pseudo-inverse, shape (..., N, M): float64 / float32 / complex128 by the loop dtype, the operand's own dtype for an empty operand.

Remarks

C# cannot tell NumPy's rtol=_NoValue (1e-15) from rtol=None (the Array-API default max(M, N) * eps): with neither tolerance set, NumPy's 1e-15 applies.

Exceptions

ValueError

Both rcond and rtol are set, or an empty operand of fewer than two axes.

TypeError

A text operand (cannot conjugate non-numeric dtype), or a float16, decimal or char operand.

LinAlgError

Fewer than two axes, or a non-square operand with hermitian.

OpenBlasMissingBackendException

A non-empty operand that no matrix backend serves.

Qr(NDArray, string)

NumPy's np.linalg.qr(a, mode='reduced'): a = Q R with Q orthonormal and R upper triangular, per matrix of a stack.

public override (NDArray Q, NDArray R) Qr(NDArray a, string mode = "reduced")

Parameters

a NDArray

The matrix or stack.

mode string

"reduced" (Q (..., M, K), R (..., K, N), K = min(M, N)), "complete" (a square Q), "r" (R alone), "raw" (LAPACK's packed (h, tau)), or the legacy aliases NumPy still honours ("f" / "full" for reduced, "e" / "economic").

Returns

(NDArray Lhs, NDArray Rhs)

(Q, R): for "r" the Q slot is null, for "raw" the pair is (h, tau), for "economic" the packed matrix and null.

Remarks

NumPy's statements: the mode check (ResolveQrMode(string), before the operand is read), _assert_stacked_2d, _commonType, then QrKernel(NDArray, string) at the loop dtype; the raw and economic modes' factored matrix comes back as NumPy's object (RawFactor(NDArray, NDArray), FactoredCopy(NDArray, NDArray)).

Exceptions

ValueError

An unknown or null mode (Unrecognized mode '...', checked before the operand).

LinAlgError

Fewer than two axes.

TypeError

A float16, decimal or char operand.

OpenBlasMissingBackendException

A non-empty operand that no matrix backend serves.

QrKernel(NDArray, string)

The qr gufuncs (qr_r_raw plus qr_reduced / qr_complete): OpenBLAS geqrf plus orgqr / ungqr through the operand engine's Blas; an empty operand is Qr(NDArray, string), with or without a backend.

protected virtual (NDArray Q, NDArray R) QrKernel(NDArray a, string mode)

Parameters

a NDArray

The matrix or stack, validated and cast to the loop dtype.

mode string

The resolved mode: reduced, complete, r, raw or economic.

Returns

(NDArray Lhs, NDArray Rhs)

The mode's pair: (Q, R), (null, R), (h, tau) or (packed, null), C-ordered; Qr(NDArray, string) turns the raw and economic factors into NumPy's objects.

Exceptions

OpenBlasMissingBackendException

A non-empty operand that no backend serves.

Slogdet(NDArray)

NumPy's np.linalg.slogdet(a): the sign and the natural log of the absolute determinant, the overflow-safe Det(NDArray).

public override (NDArray sign, NDArray logabsdet) Slogdet(NDArray a)

Parameters

a NDArray

The square matrix or stack.

Returns

(NDArray Lhs, NDArray Rhs)

(sign, logabsdet), such that sign * exp(logabsdet) is the determinant: NumPy's scalars for one matrix, arrays for a stack. A singular matrix gives (0, -inf); a complex operand a unit-modulus complex sign.

Remarks

Needs no backend: without one the managed LU computes it.

Exceptions

LinAlgError

Fewer than two axes, or a non-square operand.

TypeError

A float16, decimal or char operand.

TypeError

A text operand (NumPy's gufunc input-cast refusal).

SlogdetKernel(NDArray)

The slogdet gufunc: OpenBLAS getrf through the operand engine's Blas, or NumSharp's managed LU (NumSharp.Backends.ManagedLu) when no backend serves the operand.

protected virtual (NDArray sign, NDArray logabsdet) SlogdetKernel(NDArray a)

Parameters

a NDArray

The square matrix or stack, validated and cast to the loop dtype by Slogdet(NDArray).

Returns

(NDArray Lhs, NDArray Rhs)

The sign and the log of the absolute determinant: NumPy's scalars for one matrix (read-only 0-d arrays, the gufunc's return step), writeable arrays for a stack. A singular matrix gives (0, -inf).

Remarks

NumPy's slogdet is the gufunc _umath_linalg.slogdet: both 0-d outputs come back as numpy scalars (NumSharp.NDArray.PyArray_Return(), a no-op for a stack's outputs).

Solve(NDArray, NDArray)

NumPy's np.linalg.solve(a, b): the solution of a x = b. b is a stack of vectors only when it is exactly 1-D (NumPy 2.0's rule); any other rank is a stack of matrices, so the two gufuncs are chosen by rank alone and report their own core-dimension errors.

public override NDArray Solve(NDArray a, NDArray b)

Parameters

a NDArray

The coefficient matrix or stack (..., M, M).

b NDArray

The ordinate values, (..., M) or (..., M, K); the stacked axes broadcast.

Returns

NDArray

The solution, a fresh array of the loop dtype (float64 for bool / integer operands).

Remarks

Needs no backend: without one the managed LU computes it.

Exceptions

LinAlgError

Fewer than two axes, a non-square a, or a singular matrix.

TypeError

A float16, decimal or char operand.

TypeError

A text operand (NumPy's gufunc input-cast refusal).

ValueError

A core dimension of b that does not match, a b of too few axes for the matrix gufunc, or stacked axes that do not broadcast (NumPy's gufunc texts).

SolveKernel(NDArray, NDArray, bool)

The solve / solve1 gufunc: OpenBLAS gesv through the operand engine's Blas, or NumSharp's managed LU (NumSharp.Backends.ManagedLu) when no backend serves the operands.

protected virtual NDArray SolveKernel(NDArray a, NDArray b, bool oneDimensionalRhs)

Parameters

a NDArray

The coefficient matrix or stack (..., M, M), validated and cast to the loop dtype.

b NDArray

The right-hand side, cast to the loop dtype: (..., M) when oneDimensionalRhs is set, else (..., M, K); its loop axes broadcast against a's (checked by Solve(NDArray, NDArray)).

oneDimensionalRhs bool

NumPy's choice of the (m,m),(m)->(m) gufunc: b was exactly one-dimensional.

Returns

NDArray

The solution, a fresh array of the loop dtype.

Exceptions

LinAlgError

A singular matrix (Singular matrix).

Svd(NDArray, bool, bool, bool)

NumPy's np.linalg.svd(a, full_matrices=True, compute_uv=True, hermitian=False): the singular value decomposition a = U diag(S) Vh, per matrix of a stack; the routine behind pinv, matrix_rank, cond and the spectral / nuclear norms.

public override (NDArray U, NDArray S, NDArray Vh) Svd(NDArray a, bool full_matrices = true, bool compute_uv = true, bool hermitian = false)

Parameters

a NDArray

The matrix or stack.

full_matrices bool

True (NumPy's default) for square U and Vh, false for K = min(M, N) columns / rows; ignored with hermitian.

compute_uv bool

False for the singular values alone (U and Vh null).

hermitian bool

Decompose the Hermitian (real symmetric) matrix whose lower triangle a holds, through eigh / eigvalsh as NumPy does: the upper triangle is not read, so a non-Hermitian operand gives another matrix's factors without an error.

Returns

(NDArray, NDArray, NDArray)

(U, S, Vh), the singular values descending and real.

Remarks

NumPy's statements: with hermitian the eigh-based branch (SvdHermitian(NDArray), SvdvalsHermitian(NDArray), through this engine's Eigh(NDArray, char) / Eigvalsh(NDArray, char)); otherwise the rank check, _commonType, the text refusal of the svd_f / svd_s / svd gufunc's input cast, then SvdKernel(NDArray, bool, bool) at the loop dtype.

Exceptions

LinAlgError

Fewer than two axes, a non-square operand with hermitian, or no convergence.

TypeError

A float16, decimal or char operand.

TypeError

A text operand (NumPy's gufunc input-cast refusal).

OpenBlasMissingBackendException

A non-empty operand that no matrix backend serves.

SvdKernel(NDArray, bool, bool)

The svd gufuncs (svd_f, svd_s, svd): OpenBLAS gesdd through the operand engine's Blas. Also behind pinv, matrix_rank, cond and the spectral / nuclear norms. An empty operand is Svd(NDArray, bool, bool), with or without a backend.

protected virtual (NDArray U, NDArray S, NDArray Vh) SvdKernel(NDArray a, bool fullMatrices, bool computeUv)

Parameters

a NDArray

The matrix or stack, validated and cast to the loop dtype.

fullMatrices bool

NumPy's full_matrices: square U and Vh, else min(M, N) columns / rows.

computeUv bool

NumPy's compute_uv; the U and Vh slots are null otherwise.

Returns

(NDArray, NDArray, NDArray)

U, the real singular values (descending) and Vh.

Remarks

Since NumPy 2.5 the svd gufuncs check each matrix before gesdd (all_finite, gh-32591 / gh-32719): LAPACK's SVD drivers loop forever on some inputs holding inf and return garbage for the rest, so a non-finite matrix is a failed factorisation — NumPy 2.4 returned NaN singular values for an inf and raised for a NaN. The gufunc marks the matrix failed and raises once its loop ends, so one non-finite matrix in a stack fails the whole call. The check is NumPy's code, not LAPACK's, so it runs with or without a backend (np.linalg cond's NaN-instead-of-error reading is CondSvdvals, which checks matrix by matrix itself).

Exceptions

LinAlgError

The SVD did not converge, or a matrix of the operand holds an inf or a NaN (SVD did not converge).

OpenBlasMissingBackendException

A non-empty, finite operand that no backend serves: Core carries no managed SVD.

Svdvals(NDArray)

NumPy's np.linalg.svdvals(x), the Array-API spelling of svd(x, compute_uv=False): the singular values alone.

public override NDArray Svdvals(NDArray x)

Parameters

x NDArray

The matrix or stack.

Returns

NDArray

The singular values, descending and real.

Remarks

svd(x, compute_uv=False)'s statements: the rank check, _commonType, the text refusal of the svd gufunc's input cast, then SvdKernel(NDArray, bool, bool) without U and Vh.

Exceptions

LinAlgError

Fewer than two axes, or no convergence.

TypeError

A float16, decimal or char operand.

TypeError

A text operand (NumPy's gufunc input-cast refusal).

OpenBlasMissingBackendException

A non-empty operand that no matrix backend serves.

Tensordot(NDArray, NDArray, int)

NumPy's np.linalg.tensordot(x1, x2, axes=2) with an integer axes, the Array-API spelling of tensordot(NDArray, NDArray, int): a sum product over the last axes axes of x1 and the first ones of x2.

public override NDArray Tensordot(NDArray x1, NDArray x2, int axes = 2)

Parameters

x1 NDArray

The first tensor.

x2 NDArray

The second tensor.

axes int

How many axes to contract: 0 is the outer product, 1 np.dot; a negative count contracts nothing.

Returns

NDArray

The contraction, shape x1.shape[:-axes] + x2.shape[axes:].

Remarks

NumPy's one statement return _core_tensordot(x1, x2, axes=axes) with an integer axes: the member tensordot(NDArray, NDArray, int) dispatches to, Tensordot(NDArray, NDArray, int) of x1's engine. A null x1 fails at the dispatch with a NullReferenceException, as it did inside np.tensordot's statements.

Exceptions

ValueError

The contracted extents differ (shape-mismatch for sum).

IndexError

The count exceeds an operand's rank (tuple index out of range).

Tensordot(NDArray, NDArray, int[], int[])

NumPy's np.linalg.tensordot(x1, x2, axes=(axesA, axesB)), the Array-API spelling of tensordot(NDArray, NDArray, (int[] AxesA, int[] AxesB)): axesA of x1 contracted element by element with axesB of x2.

public override NDArray Tensordot(NDArray x1, NDArray x2, int[] axesA, int[] axesB)

Parameters

x1 NDArray

The first tensor.

x2 NDArray

The second tensor.

axesA int[]

The contracted axes of x1.

axesB int[]

The contracted axes of x2, paired in order.

Returns

NDArray

The contraction: x1's free axes, then x2's.

Remarks

NumPy's one statement return _core_tensordot(x1, x2, axes=axes) with the pair of axis lists: the member tensordot(NDArray, NDArray, (int[] AxesA, int[] AxesB)) dispatches to, Tensordot(NDArray, NDArray, int[], int[]) of x1's engine.

Exceptions

ValueError

A repeated axis (duplicate axes are not allowed in tensordot, checked first), or lists of unequal length or mismatched extents (shape-mismatch for sum).

IndexError

A contraction axis out of range (tuple index out of range).

Tensorinv(NDArray, int)

NumPy's np.linalg.tensorinv(a, ind=2): the inverse of an N-dimensional array with respect to a tensordot contraction over its last a.ndim - ind axes.

public override NDArray Tensorinv(NDArray a, int ind = 2)

Parameters

a NDArray

The tensor to invert.

ind int

How many LEADING axes form the "row" side; must be positive.

Returns

NDArray

The inverse, shape a.shape[ind:] + a.shape[:ind]: a view of the inverse of the square matrix (NumPy's ia.reshape(*invshape)).

Remarks

NumPy's statements: the shape arithmetic, the reshape to a square matrix (the array object's reshape, np.reshape's member), its inverse through this engine's Inv(NDArray) (NumPy's inv(a), so a subclass that overrides it computes tensorinv's inverse too) and the reshape to the inverted shape.

Exceptions

ValueError

ind is not positive (Invalid ind argument.), or the reshape to a square matrix is impossible.

LinAlgError

The reshaped matrix is not square, or is singular.

TypeError

A float16, decimal or char operand, or a 0-d operand whose 1x1 inverse succeeded (NumPy's reshape() takes exactly 1 argument (0 given)).

TypeError

A text operand (inv's gufunc input-cast refusal).

Tensorsolve(NDArray, NDArray, int[])

NumPy's np.linalg.tensorsolve(a, b, axes=None): the solution x of the tensor equation tensordot(a, x, x.ndim) = b, a reshape of Solve(NDArray, NDArray).

public override NDArray Tensorsolve(NDArray a, NDArray b, int[] axes = null)

Parameters

a NDArray

The coefficient tensor; its leading b.ndim axes (after axes moved some to the end) index the equations.

b NDArray

The right-hand side.

axes int[]

Axes of a to move to the right first, as LIST VALUES (NumPy never normalizes them: only 0 .. a.ndim - 1 are found), or null.

Returns

NDArray

The solution, of NumPy's oldshape = a.shape[-(a.ndim - b.ndim):] (after the axis move); it owns its data (NumPy's res.shape = oldshape).

Remarks

NumPy's statements: the axis move, oldshape = a.shape[-(an - b.ndim):], the size check, the square system a.reshape(prod, prod) against b.ravel() (through this engine's Solve(NDArray, NDArray), NumPy's solve(a, b), so a subclass that overrides it computes the tensor system too) and return res.reshape(oldshape) — since NumPy 2.5 a view of the solution (owndata False, its base the 1-D solution), where NumPy 2.4's in-place res.shape = oldshape returned an owning array.

The axis move, the reshape and the ravel are the members np.transpose, np.reshape and np.ravel dispatch to. None of their class rules could fire here: np.linalg.tensorsolve wraps a numpy.matrix a and makes a numpy.char.chararray operand plain before it calls in, and a matrix b beside a plain a meets np.ravel, which has no matrix rule (its member's view is a plain array, so the system was always solved plain).

NumPy takes oldshape with a Python slice whose edges are part of the answer: when a.ndim == b.ndim the slice starts at -0, which is 0, so the whole shape is the unknowns' shape and only an operand of 0 or 1 elements passes the size check (tensorsolve(zeros((0, 0)), zeros((0, 0))) is an empty (0, 0) solution, tensorsolve([[2.]], [[4.]]) is [[2.]], a 0-d pair a 0-d solution); when b has more axes than a the slice starts past them, and the system is (1, 1) against every element of b.

Exceptions

ValueError

An axis that is not one of 0 .. a.ndim - 1 (list.remove(x): x not in list), or a right-hand side that does not match the square system (solve's gufunc text).

LinAlgError

a.size is not prod(oldshape) ** 2, or the system is singular.

TypeError

A float16, decimal or char operand.

TypeError

A text operand (solve's gufunc input-cast refusal).

Trace(NDArray, int, DType)

NumPy's np.linalg.trace(x, offset=0, dtype=None), the Array-API trace: the sum along the diagonals of the LAST two axes, where trace(NDArray, int, int, int, DType, NDArray) defaults to the first two (a (2, 3, 3) stack gives (2,) here and (3,) there).

public override NDArray Trace(NDArray x, int offset = 0, DType dtype = null)

Parameters

x NDArray

The operand, at least two-dimensional.

offset int

The diagonal's offset from the main one (positive above).

dtype DType

The accumulator and result dtype, or null for np.trace's rule (NumPy's sum rule).

Returns

NDArray

The traces, one per matrix (a 0-d array for one matrix).

Remarks

NumPy's one statement return _core_trace(x, offset, axis1=-2, axis2=-1, dtype=dtype): the member trace(NDArray, int, int, int, DType, NDArray) dispatches to, Trace(NDArray, int, int, int, DType, NDArray), over the last two axes, on x's engine.

Exceptions

AxisError

An operand of fewer than two axes.

ArgumentNullException

x is null.

TypeError

A text operand with a non-text dtype, or a string dtype.

ArgumentNullException

x is null (np.trace's refusal, checked here before the dispatch reads its engine).

Vecdot(NDArray, NDArray, int)

NumPy's np.linalg.vecdot(x1, x2, axis=-1), the Array-API spelling of vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType, string, char): the dot product of vectors along axis, conjugating x1.

public override NDArray Vecdot(NDArray x1, NDArray x2, int axis = -1)

Parameters

x1 NDArray

The first operand (conjugated when complex).

x2 NDArray

The second operand.

axis int

The axis of the vectors in both operands (negative counts from the end).

Returns

NDArray

The dot products: the operands' other axes broadcast, in the loop dtype (an int32 pair stays int32).

Remarks

NumPy's one statement return _core_vecdot(x1, x2, axis=axis): the member vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType, string, char) dispatches to, Vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType, string, char) of x1's engine, with axis and every other keyword at np.vecdot's default (no out, axes or dtype; keepdims false).

Exceptions

ValueError

A 0-d operand, vectors of different lengths, or other axes that do not broadcast (NumPy's gufunc texts).

AxisError

axis is out of range.

TypeError

Text operands (no vecdot loop).

NullReferenceException

An operand is null.

VectorNorm(NDArray, int, bool, object)

NumPy's np.linalg.vector_norm(x, axis=axis, keepdims=False, ord=2) with an integer axis: NumPy's norm(x, axis=axis, ord=ord), then for keepdims a reshape that puts the axis back with length 1.

public override NDArray VectorNorm(NDArray x, int axis, bool keepdims = false, object ord = null)

Parameters

x NDArray

The operand: integer and bool operands compute in float64.

axis int

The reduced axis (negative counts from the end).

keepdims bool

Leave the reduced axis in the result with length 1.

ord object

The vector order; null stands for NumPy's default of 2.

Returns

NDArray

The norm along axis; with keepdims a view of it (NumPy's reshape, which does not own its data).

Remarks

NumPy's res = norm(x, axis=_axis, ord=ord) (through this engine's Norm(NDArray, object, int[], bool), without keepdims) and, for keepdims, res.reshape(tuple(shape)) with the reduced axis of the input's shape set to 1.

NumPy's vector_norm never hands keepdims to norm ("We can't reuse np.linalg.norm(keepdims) because of the reshape hacks above"), so its keepdims result is a reshape of the reduced array, not the reduction's own keepdims array: a view that does not own its data.

Exceptions

AxisError

axis is out of range (a 0-d operand has no axis).

ValueError

A text order, or -inf of an empty axis.

TypeError

An order that is neither null, a number nor a string.

VectorNorm(NDArray, int[], bool, object)

NumPy's np.linalg.vector_norm(x, axis=None, keepdims=False, ord=2) with a tuple of axes (or none): the reduced axes moved to the front and merged into one, then a VECTOR norm over it, whatever their number.

public override NDArray VectorNorm(NDArray x, int[] axis = null, bool keepdims = false, object ord = null)

Parameters

x NDArray

The operand: integer and bool operands compute in float64.

axis int[]

The reduced axes, any number of them (negative counts from the end), or null for the flattened array. An empty array reduces nothing (the elementwise magnitude).

keepdims bool

Leave the reduced axes in the result with length 1.

ord object

The vector order; null stands for NumPy's default of 2.

Returns

NDArray

The vector norm over the axes.

Remarks

NumPy's int axis and its one-element tuple take different statements (the tuple is moved and merged first), which reduce in different layouts: the int is VectorNorm(NDArray, int, bool, object).

Exceptions

AxisError

An axis is out of range.

ValueError

An axis appears twice (repeated axis), a text order, or -inf of an empty operand.

TypeError

An order that is neither null, a number nor a string.