package np

  1. Overview
  2. Docs
Legend:
Library
Module
Module type
Parameter
Class
Class type
val get_py : string -> Py.Object.t

Get an attribute of this module as a Py.Object.t. This is useful to pass a Python function to another function.

val cholesky : ?lower:bool -> ?overwrite_a:bool -> ?check_finite:bool -> [> `Ndarray ] Obj.t -> [ `ArrayLike | `Ndarray | `Object ] Obj.t

Compute the Cholesky decomposition of a matrix.

Returns the Cholesky decomposition, :math:`A = L L^*` or :math:`A = U^* U` of a Hermitian positive-definite matrix A.

Parameters ---------- a : (M, M) array_like Matrix to be decomposed lower : bool, optional Whether to compute the upper or lower triangular Cholesky factorization. Default is upper-triangular. overwrite_a : bool, optional Whether to overwrite data in `a` (may improve performance). check_finite : bool, optional Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns ------- c : (M, M) ndarray Upper- or lower-triangular Cholesky factor of `a`.

Raises ------ LinAlgError : if decomposition fails.

Examples -------- >>> from scipy.linalg import cholesky >>> a = np.array([1,-2j],[2j,5]) >>> L = cholesky(a, lower=True) >>> L array([ 1.+0.j, 0.+0.j], [ 0.+2.j, 1.+0.j]) >>> L @ L.T.conj() array([ 1.+0.j, 0.-2.j], [ 0.+2.j, 5.+0.j])

val det : ?overwrite_a:bool -> ?check_finite:bool -> [> `Ndarray ] Obj.t -> Py.Object.t

Compute the determinant of a matrix

The determinant of a square matrix is a value derived arithmetically from the coefficients of the matrix.

The determinant for a 3x3 matrix, for example, is computed as follows::

a b c d e f = A g h i

det(A) = a*e*i + b*f*g + c*d*h - c*e*g - b*d*i - a*f*h

Parameters ---------- a : (M, M) array_like A square matrix. overwrite_a : bool, optional Allow overwriting data in a (may enhance performance). check_finite : bool, optional Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns ------- det : float or complex Determinant of `a`.

Notes ----- The determinant is computed via LU factorization, LAPACK routine z/dgetrf.

Examples -------- >>> from scipy import linalg >>> a = np.array([1,2,3], [4,5,6], [7,8,9]) >>> linalg.det(a) 0.0 >>> a = np.array([0,2,3], [4,5,6], [7,8,9]) >>> linalg.det(a) 3.0

val eig : ?b:[> `Ndarray ] Obj.t -> ?left:bool -> ?right:bool -> ?overwrite_a:bool -> ?overwrite_b:bool -> ?check_finite:bool -> ?homogeneous_eigvals:bool -> [> `Ndarray ] Obj.t -> Py.Object.t * Py.Object.t * Py.Object.t

Solve an ordinary or generalized eigenvalue problem of a square matrix.

Find eigenvalues w and right or left eigenvectors of a general matrix::

a vr:,i = wi b vr:,i a.H vl:,i = wi.conj() b.H vl:,i

where ``.H`` is the Hermitian conjugation.

Parameters ---------- a : (M, M) array_like A complex or real matrix whose eigenvalues and eigenvectors will be computed. b : (M, M) array_like, optional Right-hand side matrix in a generalized eigenvalue problem. Default is None, identity matrix is assumed. left : bool, optional Whether to calculate and return left eigenvectors. Default is False. right : bool, optional Whether to calculate and return right eigenvectors. Default is True. overwrite_a : bool, optional Whether to overwrite `a`; may improve performance. Default is False. overwrite_b : bool, optional Whether to overwrite `b`; may improve performance. Default is False. check_finite : bool, optional Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. homogeneous_eigvals : bool, optional If True, return the eigenvalues in homogeneous coordinates. In this case ``w`` is a (2, M) array so that::

w1,i a vr:,i = w0,i b vr:,i

Default is False.

Returns ------- w : (M,) or (2, M) double or complex ndarray The eigenvalues, each repeated according to its multiplicity. The shape is (M,) unless ``homogeneous_eigvals=True``. vl : (M, M) double or complex ndarray The normalized left eigenvector corresponding to the eigenvalue ``wi`` is the column vl:,i. Only returned if ``left=True``. vr : (M, M) double or complex ndarray The normalized right eigenvector corresponding to the eigenvalue ``wi`` is the column ``vr:,i``. Only returned if ``right=True``.

Raises ------ LinAlgError If eigenvalue computation does not converge.

See Also -------- eigvals : eigenvalues of general arrays eigh : Eigenvalues and right eigenvectors for symmetric/Hermitian arrays. eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian band matrices eigh_tridiagonal : eigenvalues and right eiegenvectors for symmetric/Hermitian tridiagonal matrices

Examples -------- >>> from scipy import linalg >>> a = np.array([0., -1.], [1., 0.]) >>> linalg.eigvals(a) array(0.+1.j, 0.-1.j)

>>> b = np.array([0., 1.], [1., 1.]) >>> linalg.eigvals(a, b) array( 1.+0.j, -1.+0.j)

>>> a = np.array([3., 0., 0.], [0., 8., 0.], [0., 0., 7.]) >>> linalg.eigvals(a, homogeneous_eigvals=True) array([3.+0.j, 8.+0.j, 7.+0.j], [1.+0.j, 1.+0.j, 1.+0.j])

>>> a = np.array([0., -1.], [1., 0.]) >>> linalg.eigvals(a) == linalg.eig(a)0 array( True, True) >>> linalg.eig(a, left=True, right=False)1 # normalized left eigenvector array([-0.70710678+0.j , -0.70710678-0.j ], [-0. +0.70710678j, -0. -0.70710678j]) >>> linalg.eig(a, left=False, right=True)1 # normalized right eigenvector array([0.70710678+0.j , 0.70710678-0.j ], [0. -0.70710678j, 0. +0.70710678j])

val eigh : ?b:[> `Ndarray ] Obj.t -> ?lower:bool -> ?eigvals_only:bool -> ?overwrite_a:bool -> ?overwrite_b:bool -> ?turbo:bool -> ?eigvals:Py.Object.t -> ?type_:int -> ?check_finite:bool -> [> `Ndarray ] Obj.t -> [ `ArrayLike | `Ndarray | `Object ] Obj.t * Py.Object.t

Solve an ordinary or generalized eigenvalue problem for a complex Hermitian or real symmetric matrix.

Find eigenvalues w and optionally eigenvectors v of matrix `a`, where `b` is positive definite::

a v:,i = wi b v:,i vi,:.conj() a v:,i = wi vi,:.conj() b v:,i = 1

Parameters ---------- a : (M, M) array_like A complex Hermitian or real symmetric matrix whose eigenvalues and eigenvectors will be computed. b : (M, M) array_like, optional A complex Hermitian or real symmetric definite positive matrix in. If omitted, identity matrix is assumed. lower : bool, optional Whether the pertinent array data is taken from the lower or upper triangle of `a`. (Default: lower) eigvals_only : bool, optional Whether to calculate only eigenvalues and no eigenvectors. (Default: both are calculated) turbo : bool, optional Use divide and conquer algorithm (faster but expensive in memory, only for generalized eigenvalue problem and if eigvals=None) eigvals : tuple (lo, hi), optional Indexes of the smallest and largest (in ascending order) eigenvalues and corresponding eigenvectors to be returned: 0 <= lo <= hi <= M-1. If omitted, all eigenvalues and eigenvectors are returned. type : int, optional Specifies the problem type to be solved:

type = 1: a v:,i = wi b v:,i

type = 2: a b v:,i = wi v:,i

type = 3: b a v:,i = wi v:,i overwrite_a : bool, optional Whether to overwrite data in `a` (may improve performance) overwrite_b : bool, optional Whether to overwrite data in `b` (may improve performance) check_finite : bool, optional Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns ------- w : (N,) float ndarray The N (1<=N<=M) selected eigenvalues, in ascending order, each repeated according to its multiplicity. v : (M, N) complex ndarray (if eigvals_only == False)

The normalized selected eigenvector corresponding to the eigenvalue wi is the column v:,i.

Normalization:

type 1 and 3: v.conj() a v = w

type 2: inv(v).conj() a inv(v) = w

type = 1 or 2: v.conj() b v = I

type = 3: v.conj() inv(b) v = I

Raises ------ LinAlgError If eigenvalue computation does not converge, an error occurred, or b matrix is not definite positive. Note that if input matrices are not symmetric or hermitian, no error is reported but results will be wrong.

See Also -------- eigvalsh : eigenvalues of symmetric or Hermitian arrays eig : eigenvalues and right eigenvectors for non-symmetric arrays eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays eigh_tridiagonal : eigenvalues and right eiegenvectors for symmetric/Hermitian tridiagonal matrices

Notes ----- This function does not check the input array for being hermitian/symmetric in order to allow for representing arrays with only their upper/lower triangular parts.

Examples -------- >>> from scipy.linalg import eigh >>> A = np.array([6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]) >>> w, v = eigh(A) >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4))) True

val eigvals : ?b:[> `Ndarray ] Obj.t -> ?overwrite_a:bool -> ?check_finite:bool -> ?homogeneous_eigvals:bool -> [> `Ndarray ] Obj.t -> Py.Object.t

Compute eigenvalues from an ordinary or generalized eigenvalue problem.

Find eigenvalues of a general matrix::

a vr:,i = wi b vr:,i

Parameters ---------- a : (M, M) array_like A complex or real matrix whose eigenvalues and eigenvectors will be computed. b : (M, M) array_like, optional Right-hand side matrix in a generalized eigenvalue problem. If omitted, identity matrix is assumed. overwrite_a : bool, optional Whether to overwrite data in a (may improve performance) check_finite : bool, optional Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. homogeneous_eigvals : bool, optional If True, return the eigenvalues in homogeneous coordinates. In this case ``w`` is a (2, M) array so that::

w1,i a vr:,i = w0,i b vr:,i

Default is False.

Returns ------- w : (M,) or (2, M) double or complex ndarray The eigenvalues, each repeated according to its multiplicity but not in any specific order. The shape is (M,) unless ``homogeneous_eigvals=True``.

Raises ------ LinAlgError If eigenvalue computation does not converge

See Also -------- eig : eigenvalues and right eigenvectors of general arrays. eigvalsh : eigenvalues of symmetric or Hermitian arrays eigvals_banded : eigenvalues for symmetric/Hermitian band matrices eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal matrices

Examples -------- >>> from scipy import linalg >>> a = np.array([0., -1.], [1., 0.]) >>> linalg.eigvals(a) array(0.+1.j, 0.-1.j)

>>> b = np.array([0., 1.], [1., 1.]) >>> linalg.eigvals(a, b) array( 1.+0.j, -1.+0.j)

>>> a = np.array([3., 0., 0.], [0., 8., 0.], [0., 0., 7.]) >>> linalg.eigvals(a, homogeneous_eigvals=True) array([3.+0.j, 8.+0.j, 7.+0.j], [1.+0.j, 1.+0.j, 1.+0.j])

val eigvalsh : ?b:[> `Ndarray ] Obj.t -> ?lower:bool -> ?overwrite_a:bool -> ?overwrite_b:bool -> ?turbo:bool -> ?eigvals:Py.Object.t -> ?type_:int -> ?check_finite:bool -> [> `Ndarray ] Obj.t -> [ `ArrayLike | `Ndarray | `Object ] Obj.t

Solve an ordinary or generalized eigenvalue problem for a complex Hermitian or real symmetric matrix.

Find eigenvalues w of matrix a, where b is positive definite::

a v:,i = wi b v:,i vi,:.conj() a v:,i = wi vi,:.conj() b v:,i = 1

Parameters ---------- a : (M, M) array_like A complex Hermitian or real symmetric matrix whose eigenvalues and eigenvectors will be computed. b : (M, M) array_like, optional A complex Hermitian or real symmetric definite positive matrix in. If omitted, identity matrix is assumed. lower : bool, optional Whether the pertinent array data is taken from the lower or upper triangle of `a`. (Default: lower) turbo : bool, optional Use divide and conquer algorithm (faster but expensive in memory, only for generalized eigenvalue problem and if eigvals=None) eigvals : tuple (lo, hi), optional Indexes of the smallest and largest (in ascending order) eigenvalues and corresponding eigenvectors to be returned: 0 <= lo < hi <= M-1. If omitted, all eigenvalues and eigenvectors are returned. type : int, optional Specifies the problem type to be solved:

type = 1: a v:,i = wi b v:,i

type = 2: a b v:,i = wi v:,i

type = 3: b a v:,i = wi v:,i overwrite_a : bool, optional Whether to overwrite data in `a` (may improve performance) overwrite_b : bool, optional Whether to overwrite data in `b` (may improve performance) check_finite : bool, optional Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns ------- w : (N,) float ndarray The N (1<=N<=M) selected eigenvalues, in ascending order, each repeated according to its multiplicity.

Raises ------ LinAlgError If eigenvalue computation does not converge, an error occurred, or b matrix is not definite positive. Note that if input matrices are not symmetric or hermitian, no error is reported but results will be wrong.

See Also -------- eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays eigvals : eigenvalues of general arrays eigvals_banded : eigenvalues for symmetric/Hermitian band matrices eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal matrices

Notes ----- This function does not check the input array for being hermitian/symmetric in order to allow for representing arrays with only their upper/lower triangular parts.

Examples -------- >>> from scipy.linalg import eigvalsh >>> A = np.array([6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]) >>> w = eigvalsh(A) >>> w array(-3.74637491, -0.76263923, 6.08502336, 12.42399079)

val fft : ?n:int -> ?axis:int -> ?norm:string -> ?overwrite_x:bool -> ?workers:int -> [> `Ndarray ] Obj.t -> Py.Object.t

Compute the one-dimensional discrete Fourier Transform.

This function computes the one-dimensional *n*-point discrete Fourier Transform (DFT) with the efficient Fast Fourier Transform (FFT) algorithm 1_.

Parameters ---------- x : array_like Input array, can be complex. n : int, optional Length of the transformed axis of the output. If `n` is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If `n` is not given, the length of the input along the axis specified by `axis` is used. axis : int, optional Axis over which to compute the FFT. If not given, the last axis is used. norm : None, 'ortho', optional Normalization mode. Default is None, meaning no normalization on the forward transforms and scaling by ``1/n`` on the `ifft`. For ``norm='ortho'``, both directions are scaled by ``1/sqrt(n)``. overwrite_x : bool, optional If True, the contents of `x` can be destroyed; the default is False. See the notes below for more details. workers : int, optional Maximum number of workers to use for parallel computation. If negative, the value wraps around from ``os.cpu_count()``. See below for more details.

Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified.

Raises ------ IndexError if `axes` is larger than the last axis of `x`.

See Also -------- ifft : The inverse of `fft`. fft2 : The two-dimensional FFT. fftn : The *n*-dimensional FFT. rfftn : The *n*-dimensional FFT of real input. fftfreq : Frequency bins for given FFT parameters. next_fast_len : Size to pad input to for most efficient transforms

Notes -----

FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform (DFT) can be calculated efficiently, by using symmetries in the calculated terms. The symmetry is highest when `n` is a power of 2, and the transform is therefore most efficient for these sizes. For poorly factorizable sizes, `scipy.fft` uses Bluestein's algorithm 2_ and so is never worse than O(`n` log `n`). Further performance improvements may be seen by zero-padding the input using `next_fast_len`.

If ``x`` is a 1d array, then the `fft` is equivalent to ::

yk = np.sum(x * np.exp(-2j * np.pi * k * np.arange(n)/n))

The frequency term ``f=k/n`` is found at ``yk``. At ``yn/2`` we reach the Nyquist frequency and wrap around to the negative-frequency terms. So, for an 8-point transform, the frequencies of the result are 0, 1, 2, 3, -4, -3, -2, -1. To rearrange the fft output so that the zero-frequency component is centered, like -4, -3, -2, -1, 0, 1, 2, 3, use `fftshift`.

Transforms can be done in single, double or extended precision (long double) floating point. Half precision inputs will be converted to single precision and non floating-point inputs will be converted to double precision.

If the data type of ``x`` is real, a 'real FFT' algorithm is automatically used, which roughly halves the computation time. To increase efficiency a little further, use `rfft`, which does the same calculation, but only outputs half of the symmetrical spectrum. If the data is both real and symmetrical, the `dct` can again double the efficiency, by generating half of the spectrum from half of the signal.

When ``overwrite_x=True`` is specified, the memory referenced by ``x`` may be used by the implementation in any way. This may include reusing the memory for the result, but this is in no way guaranteed. You should not rely on the contents of ``x`` after the transform as this may change in future without warning.

The ``workers`` argument specifies the maximum number of parallel jobs to split the FFT computation into. This will execute independent 1-dimensional FFTs within ``x``. So, ``x`` must be at least 2-dimensional and the non-transformed axes must be large enough to split into chunks. If ``x`` is too small, fewer jobs may be used than requested.

References ---------- .. 1 Cooley, James W., and John W. Tukey, 1965, 'An algorithm for the machine calculation of complex Fourier series,' *Math. Comput.* 19: 297-301. .. 2 Bluestein, L., 1970, 'A linear filtering approach to the computation of discrete Fourier transform'. *IEEE Transactions on Audio and Electroacoustics.* 18 (4): 451-455.

Examples -------- >>> import scipy.fft >>> scipy.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8)) array(-2.33486982e-16+1.14423775e-17j, 8.00000000e+00-1.25557246e-15j, 2.33486982e-16+2.33486982e-16j, 0.00000000e+00+1.22464680e-16j, -1.14423775e-17+2.33486982e-16j, 0.00000000e+00+5.20784380e-16j, 1.14423775e-17+1.14423775e-17j, 0.00000000e+00+1.22464680e-16j)

In this example, real input has an FFT which is Hermitian, i.e., symmetric in the real part and anti-symmetric in the imaginary part:

>>> from scipy.fft import fft, fftfreq, fftshift >>> import matplotlib.pyplot as plt >>> t = np.arange(256) >>> sp = fftshift(fft(np.sin(t))) >>> freq = fftshift(fftfreq(t.shape-1)) >>> plt.plot(freq, sp.real, freq, sp.imag) <matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...> >>> plt.show()

val fft2 : ?s:int list -> ?axes:int list -> ?norm:string -> ?overwrite_x:bool -> ?workers:int -> [> `Ndarray ] Obj.t -> Py.Object.t

Compute the 2-dimensional discrete Fourier Transform

This function computes the *n*-dimensional discrete Fourier Transform over any axes in an *M*-dimensional array by means of the Fast Fourier Transform (FFT). By default, the transform is computed over the last two axes of the input array, i.e., a 2-dimensional FFT.

Parameters ---------- x : array_like Input array, can be complex s : sequence of ints, optional Shape (length of each transformed axis) of the output (``s0`` refers to axis 0, ``s1`` to axis 1, etc.). This corresponds to ``n`` for ``fft(x, n)``. Along each axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if `s` is not given, the shape of the input along the axes specified by `axes` is used. axes : sequence of ints, optional Axes over which to compute the FFT. If not given, the last two axes are used. norm : None, 'ortho', optional Normalization mode (see `fft`). Default is None. overwrite_x : bool, optional If True, the contents of `x` can be destroyed; the default is False. See :func:`fft` for more details. workers : int, optional Maximum number of workers to use for parallel computation. If negative, the value wraps around from ``os.cpu_count()``. See :func:`~scipy.fft.fft` for more details.

Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axes indicated by `axes`, or the last two axes if `axes` is not given.

Raises ------ ValueError If `s` and `axes` have different length, or `axes` not given and ``len(s) != 2``. IndexError If an element of `axes` is larger than than the number of axes of `x`.

See Also -------- ifft2 : The inverse two-dimensional FFT. fft : The one-dimensional FFT. fftn : The *n*-dimensional FFT. fftshift : Shifts zero-frequency terms to the center of the array. For two-dimensional input, swaps first and third quadrants, and second and fourth quadrants.

Notes ----- `fft2` is just `fftn` with a different default for `axes`.

The output, analogously to `fft`, contains the term for zero frequency in the low-order corner of the transformed axes, the positive frequency terms in the first half of these axes, the term for the Nyquist frequency in the middle of the axes and the negative frequency terms in the second half of the axes, in order of decreasingly negative frequency.

See `fftn` for details and a plotting example, and `fft` for definitions and conventions used.

Examples -------- >>> import scipy.fft >>> x = np.mgrid:5, :50 >>> scipy.fft.fft2(x) array([ 50. +0.j , 0. +0.j , 0. +0.j , # may vary 0. +0.j , 0. +0.j ], [-12.5+17.20477401j, 0. +0.j , 0. +0.j , 0. +0.j , 0. +0.j ], [-12.5 +4.0614962j , 0. +0.j , 0. +0.j , 0. +0.j , 0. +0.j ], [-12.5 -4.0614962j , 0. +0.j , 0. +0.j , 0. +0.j , 0. +0.j ], [-12.5-17.20477401j, 0. +0.j , 0. +0.j , 0. +0.j , 0. +0.j ])

val fftn : ?s:int list -> ?axes:int list -> ?norm:string -> ?overwrite_x:bool -> ?workers:int -> [> `Ndarray ] Obj.t -> Py.Object.t

Compute the N-dimensional discrete Fourier Transform.

This function computes the *N*-dimensional discrete Fourier Transform over any number of axes in an *M*-dimensional array by means of the Fast Fourier Transform (FFT).

Parameters ---------- x : array_like Input array, can be complex. s : sequence of ints, optional Shape (length of each transformed axis) of the output (``s0`` refers to axis 0, ``s1`` to axis 1, etc.). This corresponds to ``n`` for ``fft(x, n)``. Along any axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if `s` is not given, the shape of the input along the axes specified by `axes` is used. axes : sequence of ints, optional Axes over which to compute the FFT. If not given, the last ``len(s)`` axes are used, or all axes if `s` is also not specified. norm : None, 'ortho', optional Normalization mode (see `fft`). Default is None. overwrite_x : bool, optional If True, the contents of `x` can be destroyed; the default is False. See :func:`fft` for more details. workers : int, optional Maximum number of workers to use for parallel computation. If negative, the value wraps around from ``os.cpu_count()``. See :func:`~scipy.fft.fft` for more details.

Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axes indicated by `axes`, or by a combination of `s` and `x`, as explained in the parameters section above.

Raises ------ ValueError If `s` and `axes` have different length. IndexError If an element of `axes` is larger than than the number of axes of `x`.

See Also -------- ifftn : The inverse of `fftn`, the inverse *n*-dimensional FFT. fft : The one-dimensional FFT, with definitions and conventions used. rfftn : The *n*-dimensional FFT of real input. fft2 : The two-dimensional FFT. fftshift : Shifts zero-frequency terms to centre of array

Notes ----- The output, analogously to `fft`, contains the term for zero frequency in the low-order corner of all axes, the positive frequency terms in the first half of all axes, the term for the Nyquist frequency in the middle of all axes and the negative frequency terms in the second half of all axes, in order of decreasingly negative frequency.

Examples -------- >>> import scipy.fft >>> x = np.mgrid:3, :3, :30 >>> scipy.fft.fftn(x, axes=(1, 2)) array([[ 0.+0.j, 0.+0.j, 0.+0.j], # may vary [ 0.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j]], [[ 9.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j]], [[18.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j]]) >>> scipy.fft.fftn(x, (2, 2), axes=(0, 1)) array([[ 2.+0.j, 2.+0.j, 2.+0.j], # may vary [ 0.+0.j, 0.+0.j, 0.+0.j]], [[-2.+0.j, -2.+0.j, -2.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j]])

>>> import matplotlib.pyplot as plt >>> X, Y = np.meshgrid(2 * np.pi * np.arange(200) / 12, ... 2 * np.pi * np.arange(200) / 34) >>> S = np.sin(X) + np.cos(Y) + np.random.uniform(0, 1, X.shape) >>> FS = scipy.fft.fftn(S) >>> plt.imshow(np.log(np.abs(scipy.fft.fftshift(FS))**2)) <matplotlib.image.AxesImage object at 0x...> >>> plt.show()

val i0 : [ `Ndarray of [> `Ndarray ] Obj.t | `PyObject of Py.Object.t ] -> Py.Object.t

Modified Bessel function of the first kind, order 0.

Usually denoted :math:`I_0`. This function does broadcast, but will *not* 'up-cast' int dtype arguments unless accompanied by at least one float or complex dtype argument (see Raises below).

Parameters ---------- x : array_like, dtype float or complex Argument of the Bessel function.

Returns ------- out : ndarray, shape = x.shape, dtype = x.dtype The modified Bessel function evaluated at each of the elements of `x`.

Raises ------ TypeError: array cannot be safely cast to required type If argument consists exclusively of int dtypes.

See Also -------- scipy.special.i0, scipy.special.iv, scipy.special.ive

Notes ----- The scipy implementation is recommended over this function: it is a proper ufunc written in C, and more than an order of magnitude faster.

We use the algorithm published by Clenshaw 1_ and referenced by Abramowitz and Stegun 2_, for which the function domain is partitioned into the two intervals 0,8 and (8,inf), and Chebyshev polynomial expansions are employed in each interval. Relative error on the domain 0,30 using IEEE arithmetic is documented 3_ as having a peak of 5.8e-16 with an rms of 1.4e-16 (n = 30000).

References ---------- .. 1 C. W. Clenshaw, 'Chebyshev series for mathematical functions', in *National Physical Laboratory Mathematical Tables*, vol. 5, London: Her Majesty's Stationery Office, 1962. .. 2 M. Abramowitz and I. A. Stegun, *Handbook of Mathematical Functions*, 10th printing, New York: Dover, 1964, pp. 379. http://www.math.sfu.ca/~cbm/aands/page_379.htm .. 3 http://kobesearch.cpan.org/htdocs/Math-Cephes/Math/Cephes.html

Examples -------- >>> np.i0(0.) array(1.0) # may vary >>> np.i0(0., 1. + 2j) array( 1.00000000+0.j , 0.18785373+0.64616944j) # may vary

val ifft : ?n:int -> ?axis:int -> ?norm:string -> ?overwrite_x:bool -> ?workers:int -> [> `Ndarray ] Obj.t -> Py.Object.t

Compute the one-dimensional inverse discrete Fourier Transform.

This function computes the inverse of the one-dimensional *n*-point discrete Fourier transform computed by `fft`. In other words, ``ifft(fft(x)) == x`` to within numerical accuracy.

The input should be ordered in the same way as is returned by `fft`, i.e.,

* ``x0`` should contain the zero frequency term, * ``x1:n//2`` should contain the positive-frequency terms, * ``xn//2 + 1:`` should contain the negative-frequency terms, in increasing order starting from the most negative frequency.

For an even number of input points, ``xn//2`` represents the sum of the values at the positive and negative Nyquist frequencies, as the two are aliased together. See `fft` for details.

Parameters ---------- x : array_like Input array, can be complex. n : int, optional Length of the transformed axis of the output. If `n` is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If `n` is not given, the length of the input along the axis specified by `axis` is used. See notes about padding issues. axis : int, optional Axis over which to compute the inverse DFT. If not given, the last axis is used. norm : None, 'ortho', optional Normalization mode (see `fft`). Default is None. overwrite_x : bool, optional If True, the contents of `x` can be destroyed; the default is False. See :func:`fft` for more details. workers : int, optional Maximum number of workers to use for parallel computation. If negative, the value wraps around from ``os.cpu_count()``. See :func:`~scipy.fft.fft` for more details.

Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified.

Raises ------ IndexError If `axes` is larger than the last axis of `x`.

See Also -------- fft : The one-dimensional (forward) FFT, of which `ifft` is the inverse ifft2 : The two-dimensional inverse FFT. ifftn : The n-dimensional inverse FFT.

Notes ----- If the input parameter `n` is larger than the size of the input, the input is padded by appending zeros at the end. Even though this is the common approach, it might lead to surprising results. If a different padding is desired, it must be performed before calling `ifft`.

If ``x`` is a 1d array, then the `ifft` is equivalent to ::

yk = np.sum(x * np.exp(2j * np.pi * k * np.arange(n)/n)) / len(x)

As with `fft`, `ifft` has support for all floating point types and is optimized for real input.

Examples -------- >>> import scipy.fft >>> scipy.fft.ifft(0, 4, 0, 0) array( 1.+0.j, 0.+1.j, -1.+0.j, 0.-1.j) # may vary

Create and plot a band-limited signal with random phases:

>>> import matplotlib.pyplot as plt >>> t = np.arange(400) >>> n = np.zeros((400,), dtype=complex) >>> n40:60 = np.exp(1j*np.random.uniform(0, 2*np.pi, (20,))) >>> s = scipy.fft.ifft(n) >>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--') <matplotlib.lines.Line2D object at ...>, <matplotlib.lines.Line2D object at ...> >>> plt.legend(('real', 'imaginary')) <matplotlib.legend.Legend object at ...> >>> plt.show()

val ifft2 : ?s:int list -> ?axes:int list -> ?norm:string -> ?overwrite_x:bool -> ?workers:int -> [> `Ndarray ] Obj.t -> Py.Object.t

Compute the 2-dimensional inverse discrete Fourier Transform.

This function computes the inverse of the 2-dimensional discrete Fourier Transform over any number of axes in an M-dimensional array by means of the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(x)) == x`` to within numerical accuracy. By default, the inverse transform is computed over the last two axes of the input array.

The input, analogously to `ifft`, should be ordered in the same way as is returned by `fft2`, i.e. it should have the term for zero frequency in the low-order corner of the two axes, the positive frequency terms in the first half of these axes, the term for the Nyquist frequency in the middle of the axes and the negative frequency terms in the second half of both axes, in order of decreasingly negative frequency.

Parameters ---------- x : array_like Input array, can be complex. s : sequence of ints, optional Shape (length of each axis) of the output (``s0`` refers to axis 0, ``s1`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``. Along each axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if `s` is not given, the shape of the input along the axes specified by `axes` is used. See notes for issue on `ifft` zero padding. axes : sequence of ints, optional Axes over which to compute the FFT. If not given, the last two axes are used. norm : None, 'ortho', optional Normalization mode (see `fft`). Default is None. overwrite_x : bool, optional If True, the contents of `x` can be destroyed; the default is False. See :func:`fft` for more details. workers : int, optional Maximum number of workers to use for parallel computation. If negative, the value wraps around from ``os.cpu_count()``. See :func:`~scipy.fft.fft` for more details.

Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axes indicated by `axes`, or the last two axes if `axes` is not given.

Raises ------ ValueError If `s` and `axes` have different length, or `axes` not given and ``len(s) != 2``. IndexError If an element of `axes` is larger than than the number of axes of `x`.

See Also -------- fft2 : The forward 2-dimensional FFT, of which `ifft2` is the inverse. ifftn : The inverse of the *n*-dimensional FFT. fft : The one-dimensional FFT. ifft : The one-dimensional inverse FFT.

Notes ----- `ifft2` is just `ifftn` with a different default for `axes`.

See `ifftn` for details and a plotting example, and `fft` for definition and conventions used.

Zero-padding, analogously with `ifft`, is performed by appending zeros to the input along the specified dimension. Although this is the common approach, it might lead to surprising results. If another form of zero padding is desired, it must be performed before `ifft2` is called.

Examples -------- >>> import scipy.fft >>> x = 4 * np.eye(4) >>> scipy.fft.ifft2(x) array([1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j], [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j], [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j])

val ifftn : ?s:int list -> ?axes:int list -> ?norm:string -> ?overwrite_x:bool -> ?workers:int -> [> `Ndarray ] Obj.t -> Py.Object.t

Compute the N-dimensional inverse discrete Fourier Transform.

This function computes the inverse of the N-dimensional discrete Fourier Transform over any number of axes in an M-dimensional array by means of the Fast Fourier Transform (FFT). In other words, ``ifftn(fftn(x)) == x`` to within numerical accuracy.

The input, analogously to `ifft`, should be ordered in the same way as is returned by `fftn`, i.e. it should have the term for zero frequency in all axes in the low-order corner, the positive frequency terms in the first half of all axes, the term for the Nyquist frequency in the middle of all axes and the negative frequency terms in the second half of all axes, in order of decreasingly negative frequency.

Parameters ---------- x : array_like Input array, can be complex. s : sequence of ints, optional Shape (length of each transformed axis) of the output (``s0`` refers to axis 0, ``s1`` to axis 1, etc.). This corresponds to ``n`` for ``ifft(x, n)``. Along any axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if `s` is not given, the shape of the input along the axes specified by `axes` is used. See notes for issue on `ifft` zero padding. axes : sequence of ints, optional Axes over which to compute the IFFT. If not given, the last ``len(s)`` axes are used, or all axes if `s` is also not specified. norm : None, 'ortho', optional Normalization mode (see `fft`). Default is None. overwrite_x : bool, optional If True, the contents of `x` can be destroyed; the default is False. See :func:`fft` for more details. workers : int, optional Maximum number of workers to use for parallel computation. If negative, the value wraps around from ``os.cpu_count()``. See :func:`~scipy.fft.fft` for more details.

Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axes indicated by `axes`, or by a combination of `s` or `x`, as explained in the parameters section above.

Raises ------ ValueError If `s` and `axes` have different length. IndexError If an element of `axes` is larger than than the number of axes of `x`.

See Also -------- fftn : The forward *n*-dimensional FFT, of which `ifftn` is the inverse. ifft : The one-dimensional inverse FFT. ifft2 : The two-dimensional inverse FFT. ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning of array.

Notes ----- Zero-padding, analogously with `ifft`, is performed by appending zeros to the input along the specified dimension. Although this is the common approach, it might lead to surprising results. If another form of zero padding is desired, it must be performed before `ifftn` is called.

Examples -------- >>> import scipy.fft >>> x = np.eye(4) >>> scipy.fft.ifftn(scipy.fft.fftn(x, axes=(0,)), axes=(1,)) array([1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j])

Create and plot an image with band-limited frequency content:

>>> import matplotlib.pyplot as plt >>> n = np.zeros((200,200), dtype=complex) >>> n60:80, 20:40 = np.exp(1j*np.random.uniform(0, 2*np.pi, (20, 20))) >>> im = scipy.fft.ifftn(n).real >>> plt.imshow(im) <matplotlib.image.AxesImage object at 0x...> >>> plt.show()

val inv : ?overwrite_a:bool -> ?check_finite:bool -> [> `Ndarray ] Obj.t -> [ `ArrayLike | `Ndarray | `Object ] Obj.t

Compute the inverse of a matrix.

Parameters ---------- a : array_like Square matrix to be inverted. overwrite_a : bool, optional Discard data in `a` (may improve performance). Default is False. check_finite : bool, optional Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns ------- ainv : ndarray Inverse of the matrix `a`.

Raises ------ LinAlgError If `a` is singular. ValueError If `a` is not square, or not 2-dimensional.

Examples -------- >>> from scipy import linalg >>> a = np.array([1., 2.], [3., 4.]) >>> linalg.inv(a) array([-2. , 1. ], [ 1.5, -0.5]) >>> np.dot(a, linalg.inv(a)) array([ 1., 0.], [ 0., 1.])

val lstsq : ?cond:float -> ?overwrite_a:bool -> ?overwrite_b:bool -> ?check_finite:bool -> ?lapack_driver:string -> b:Py.Object.t -> [> `Ndarray ] Obj.t -> Py.Object.t * Py.Object.t * int * Py.Object.t option

Compute least-squares solution to equation Ax = b.

Compute a vector x such that the 2-norm ``|b - A x|`` is minimized.

Parameters ---------- a : (M, N) array_like Left hand side array b : (M,) or (M, K) array_like Right hand side array cond : float, optional Cutoff for 'small' singular values; used to determine effective rank of a. Singular values smaller than ``rcond * largest_singular_value`` are considered zero. overwrite_a : bool, optional Discard data in `a` (may enhance performance). Default is False. overwrite_b : bool, optional Discard data in `b` (may enhance performance). Default is False. check_finite : bool, optional Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. lapack_driver : str, optional Which LAPACK driver is used to solve the least-squares problem. Options are ``'gelsd'``, ``'gelsy'``, ``'gelss'``. Default (``'gelsd'``) is a good choice. However, ``'gelsy'`` can be slightly faster on many problems. ``'gelss'`` was used historically. It is generally slow but uses less memory.

.. versionadded:: 0.17.0

Returns ------- x : (N,) or (N, K) ndarray Least-squares solution. Return shape matches shape of `b`. residues : (K,) ndarray or float Square of the 2-norm for each column in ``b - a x``, if ``M > N`` and ``ndim(A) == n`` (returns a scalar if b is 1-D). Otherwise a (0,)-shaped array is returned. rank : int Effective rank of `a`. s : (min(M, N),) ndarray or None Singular values of `a`. The condition number of a is ``abs(s0 / s-1)``.

Raises ------ LinAlgError If computation does not converge.

ValueError When parameters are not compatible.

See Also -------- scipy.optimize.nnls : linear least squares with non-negativity constraint

Notes ----- When ``'gelsy'`` is used as a driver, `residues` is set to a (0,)-shaped array and `s` is always ``None``.

Examples -------- >>> from scipy.linalg import lstsq >>> import matplotlib.pyplot as plt

Suppose we have the following data:

>>> x = np.array(1, 2.5, 3.5, 4, 5, 7, 8.5) >>> y = np.array(0.3, 1.1, 1.5, 2.0, 3.2, 6.6, 8.6)

We want to fit a quadratic polynomial of the form ``y = a + b*x**2`` to this data. We first form the 'design matrix' M, with a constant column of 1s and a column containing ``x**2``:

>>> M = x:, np.newaxis**0, 2 >>> M array([ 1. , 1. ], [ 1. , 6.25], [ 1. , 12.25], [ 1. , 16. ], [ 1. , 25. ], [ 1. , 49. ], [ 1. , 72.25])

We want to find the least-squares solution to ``M.dot(p) = y``, where ``p`` is a vector with length 2 that holds the parameters ``a`` and ``b``.

>>> p, res, rnk, s = lstsq(M, y) >>> p array( 0.20925829, 0.12013861)

Plot the data and the fitted curve.

>>> plt.plot(x, y, 'o', label='data') >>> xx = np.linspace(0, 9, 101) >>> yy = p0 + p1*xx**2 >>> plt.plot(xx, yy, label='least squares fit, $y = a + bx^2$') >>> plt.xlabel('x') >>> plt.ylabel('y') >>> plt.legend(framealpha=1, shadow=True) >>> plt.grid(alpha=0.25) >>> plt.show()

val norm : ?ord:[ `PyObject of Py.Object.t | `Fro ] -> ?axis:[ `I of int | `T2_tuple_of_ints of Py.Object.t ] -> ?keepdims:bool -> ?check_finite:bool -> Py.Object.t -> Py.Object.t

Matrix or vector norm.

This function is able to return one of seven different matrix norms, or one of an infinite number of vector norms (described below), depending on the value of the ``ord`` parameter.

Parameters ---------- a : (M,) or (M, N) array_like Input array. If `axis` is None, `a` must be 1-D or 2-D. ord : non-zero int, inf, -inf, 'fro', optional Order of the norm (see table under ``Notes``). inf means numpy's `inf` object axis : nt, 2-tuple of ints, None, optional If `axis` is an integer, it specifies the axis of `a` along which to compute the vector norms. If `axis` is a 2-tuple, it specifies the axes that hold 2-D matrices, and the matrix norms of these matrices are computed. If `axis` is None then either a vector norm (when `a` is 1-D) or a matrix norm (when `a` is 2-D) is returned. keepdims : bool, optional If this is set to True, the axes which are normed over are left in the result as dimensions with size one. With this option the result will broadcast correctly against the original `a`. check_finite : bool, optional Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns ------- n : float or ndarray Norm of the matrix or vector(s).

Notes ----- For values of ``ord <= 0``, the result is, strictly speaking, not a mathematical 'norm', but it may still be useful for various numerical purposes.

The following norms can be calculated:

===== ============================ ========================== ord norm for matrices norm for vectors ===== ============================ ========================== None Frobenius norm 2-norm 'fro' Frobenius norm -- inf max(sum(abs(x), axis=1)) max(abs(x)) -inf min(sum(abs(x), axis=1)) min(abs(x)) 0 -- sum(x != 0) 1 max(sum(abs(x), axis=0)) as below -1 min(sum(abs(x), axis=0)) as below 2 2-norm (largest sing. value) as below -2 smallest singular value as below other -- sum(abs(x)**ord)**(1./ord) ===== ============================ ==========================

The Frobenius norm is given by 1_:

:math:`||A||_F = \sum_{i,j} abs(a_{i,j})^2^

/2

`

The ``axis`` and ``keepdims`` arguments are passed directly to ``numpy.linalg.norm`` and are only usable if they are supported by the version of numpy in use.

References ---------- .. 1 G. H. Golub and C. F. Van Loan, *Matrix Computations*, Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15

Examples -------- >>> from scipy.linalg import norm >>> a = np.arange(9) - 4.0 >>> a array(-4., -3., -2., -1., 0., 1., 2., 3., 4.) >>> b = a.reshape((3, 3)) >>> b array([-4., -3., -2.], [-1., 0., 1.], [ 2., 3., 4.])

>>> norm(a) 7.745966692414834 >>> norm(b) 7.745966692414834 >>> norm(b, 'fro') 7.745966692414834 >>> norm(a, np.inf) 4 >>> norm(b, np.inf) 9 >>> norm(a, -np.inf) 0 >>> norm(b, -np.inf) 2

>>> norm(a, 1) 20 >>> norm(b, 1) 7 >>> norm(a, -1) -4.6566128774142013e-010 >>> norm(b, -1) 6 >>> norm(a, 2) 7.745966692414834 >>> norm(b, 2) 7.3484692283495345

>>> norm(a, -2) 0 >>> norm(b, -2) 1.8570331885190563e-016 >>> norm(a, 3) 5.8480354764257312 >>> norm(a, -3) 0

val pinv : ?cond:Py.Object.t -> ?rcond:Py.Object.t -> ?return_rank:bool -> ?check_finite:bool -> [> `Ndarray ] Obj.t -> [ `ArrayLike | `Ndarray | `Object ] Obj.t * int

Compute the (Moore-Penrose) pseudo-inverse of a matrix.

Calculate a generalized inverse of a matrix using its singular-value decomposition and including all 'large' singular values.

Parameters ---------- a : (M, N) array_like Matrix to be pseudo-inverted. cond, rcond : float or None Cutoff for 'small' singular values; singular values smaller than this value are considered as zero. If both are omitted, the default value ``max(M,N)*largest_singular_value*eps`` is used where ``eps`` is the machine precision value of the datatype of ``a``.

.. versionchanged:: 1.3.0 Previously the default cutoff value was just ``eps*f`` where ``f`` was ``1e3`` for single precision and ``1e6`` for double precision.

return_rank : bool, optional If True, return the effective rank of the matrix. check_finite : bool, optional Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs.

Returns ------- B : (N, M) ndarray The pseudo-inverse of matrix `a`. rank : int The effective rank of the matrix. Returned if `return_rank` is True.

Raises ------ LinAlgError If SVD computation does not converge.

Examples -------- >>> from scipy import linalg >>> a = np.random.randn(9, 6) >>> B = linalg.pinv2(a) >>> np.allclose(a, np.dot(a, np.dot(B, a))) True >>> np.allclose(B, np.dot(B, np.dot(a, B))) True

val register_func : name:Py.Object.t -> func:Py.Object.t -> unit -> Py.Object.t

None

val restore_all : unit -> Py.Object.t

None

val restore_func : Py.Object.t -> Py.Object.t

None

val solve : ?sym_pos:bool -> ?lower:bool -> ?overwrite_a:bool -> ?overwrite_b:bool -> ?debug:Py.Object.t -> ?check_finite:bool -> ?assume_a:string -> ?transposed:bool -> b:[> `Ndarray ] Obj.t -> [> `Ndarray ] Obj.t -> [ `ArrayLike | `Ndarray | `Object ] Obj.t

Solves the linear equation set ``a * x = b`` for the unknown ``x`` for square ``a`` matrix.

If the data matrix is known to be a particular type then supplying the corresponding string to ``assume_a`` key chooses the dedicated solver. The available options are

=================== ======== generic matrix 'gen' symmetric 'sym' hermitian 'her' positive definite 'pos' =================== ========

If omitted, ``'gen'`` is the default structure.

The datatype of the arrays define which solver is called regardless of the values. In other words, even when the complex array entries have precisely zero imaginary parts, the complex solver will be called based on the data type of the array.

Parameters ---------- a : (N, N) array_like Square input data b : (N, NRHS) array_like Input data for the right hand side. sym_pos : bool, optional Assume `a` is symmetric and positive definite. This key is deprecated and assume_a = 'pos' keyword is recommended instead. The functionality is the same. It will be removed in the future. lower : bool, optional If True, only the data contained in the lower triangle of `a`. Default is to use upper triangle. (ignored for ``'gen'``) overwrite_a : bool, optional Allow overwriting data in `a` (may enhance performance). Default is False. overwrite_b : bool, optional Allow overwriting data in `b` (may enhance performance). Default is False. check_finite : bool, optional Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. assume_a : str, optional Valid entries are explained above. transposed: bool, optional If True, ``a^T x = b`` for real matrices, raises `NotImplementedError` for complex matrices (only for True).

Returns ------- x : (N, NRHS) ndarray The solution array.

Raises ------ ValueError If size mismatches detected or input a is not square. LinAlgError If the matrix is singular. LinAlgWarning If an ill-conditioned input a is detected. NotImplementedError If transposed is True and input a is a complex matrix.

Examples -------- Given `a` and `b`, solve for `x`:

>>> a = np.array([3, 2, 0], [1, -1, 0], [0, 5, 1]) >>> b = np.array(2, 4, -1) >>> from scipy import linalg >>> x = linalg.solve(a, b) >>> x array( 2., -2., 9.) >>> np.dot(a, x) == b array( True, True, True, dtype=bool)

Notes ----- If the input b matrix is a 1D array with N elements, when supplied together with an NxN input a, it is assumed as a valid column vector despite the apparent size mismatch. This is compatible with the numpy.dot() behavior and the returned result is still 1D array.

The generic, symmetric, hermitian and positive definite solutions are obtained via calling ?GESV, ?SYSV, ?HESV, and ?POSV routines of LAPACK respectively.

val svd : ?full_matrices:bool -> ?compute_uv:bool -> ?overwrite_a:bool -> ?check_finite:bool -> ?lapack_driver:[ `Gesdd | `Gesvd ] -> [> `Ndarray ] Obj.t -> [ `ArrayLike | `Ndarray | `Object ] Obj.t * [ `ArrayLike | `Ndarray | `Object ] Obj.t * [ `ArrayLike | `Ndarray | `Object ] Obj.t

Singular Value Decomposition.

Factorizes the matrix `a` into two unitary matrices ``U`` and ``Vh``, and a 1-D array ``s`` of singular values (real, non-negative) such that ``a == U @ S @ Vh``, where ``S`` is a suitably shaped matrix of zeros with main diagonal ``s``.

Parameters ---------- a : (M, N) array_like Matrix to decompose. full_matrices : bool, optional If True (default), `U` and `Vh` are of shape ``(M, M)``, ``(N, N)``. If False, the shapes are ``(M, K)`` and ``(K, N)``, where ``K = min(M, N)``. compute_uv : bool, optional Whether to compute also ``U`` and ``Vh`` in addition to ``s``. Default is True. overwrite_a : bool, optional Whether to overwrite `a`; may improve performance. Default is False. check_finite : bool, optional Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. lapack_driver : 'gesdd', 'gesvd', optional Whether to use the more efficient divide-and-conquer approach (``'gesdd'``) or general rectangular approach (``'gesvd'``) to compute the SVD. MATLAB and Octave use the ``'gesvd'`` approach. Default is ``'gesdd'``.

.. versionadded:: 0.18

Returns ------- U : ndarray Unitary matrix having left singular vectors as columns. Of shape ``(M, M)`` or ``(M, K)``, depending on `full_matrices`. s : ndarray The singular values, sorted in non-increasing order. Of shape (K,), with ``K = min(M, N)``. Vh : ndarray Unitary matrix having right singular vectors as rows. Of shape ``(N, N)`` or ``(K, N)`` depending on `full_matrices`.

For ``compute_uv=False``, only ``s`` is returned.

Raises ------ LinAlgError If SVD computation does not converge.

See also -------- svdvals : Compute singular values of a matrix. diagsvd : Construct the Sigma matrix, given the vector s.

Examples -------- >>> from scipy import linalg >>> m, n = 9, 6 >>> a = np.random.randn(m, n) + 1.j*np.random.randn(m, n) >>> U, s, Vh = linalg.svd(a) >>> U.shape, s.shape, Vh.shape ((9, 9), (6,), (6, 6))

Reconstruct the original matrix from the decomposition:

>>> sigma = np.zeros((m, n)) >>> for i in range(min(m, n)): ... sigmai, i = si >>> a1 = np.dot(U, np.dot(sigma, Vh)) >>> np.allclose(a, a1) True

Alternatively, use ``full_matrices=False`` (notice that the shape of ``U`` is then ``(m, n)`` instead of ``(m, m)``):

>>> U, s, Vh = linalg.svd(a, full_matrices=False) >>> U.shape, s.shape, Vh.shape ((9, 6), (6,), (6, 6)) >>> S = np.diag(s) >>> np.allclose(a, np.dot(U, np.dot(S, Vh))) True

>>> s2 = linalg.svd(a, compute_uv=False) >>> np.allclose(s, s2) True

OCaml

Innovation. Community. Security.