egttools.numerical.linear_operator.LinearOperator¶
- class LinearOperator(*args, **kwargs)[source]¶
Bases:
objectCommon interface for performing matrix vector products.
Many iterative methods (e.g. cg, gmres) do not need to know the individual entries of a matrix to solve a linear system
A@x = b. Such solvers only require the computation of matrix vector products,A@v, wherevis a dense vector. This class serves as an abstract interface between iterative solvers and matrix-like objects.To construct a concrete LinearOperator, either pass appropriate callables to the constructor of this class, or subclass it.
A subclass must implement either one of the methods
_matvecand_matmat, and the attributes/propertiesshape(pair of integers, optionally with additional batch dimensions at the front) anddtype(may be None). It may call the__init__on this class to have these attributes validated. Implementing_matvecautomatically implements_matmat(using a naive algorithm) and vice-versa.Optionally, a subclass may implement
_rmatvecor_adjointto implement the Hermitian adjoint (conjugate transpose). As with_matvecand_matmat, implementing either_rmatvecor_adjointimplements the other automatically. Implementing_adjointis preferable;_rmatvecis mostly there for backwards compatibility.The defined operator may have additional “batch” dimensions prepended to the core shape, to represent a batch of 2-D operators; see Batched Linear Operations for details.
- Parameters:
shape (tuple) – Matrix dimensions
(..., M, N), where...represents any additional batch dimensions.matvec (callable f(v)) – Applies
Atov, wherevis a dense vector with shape(..., N).rmatvec (callable f(v)) – Applies
A^Htov, whereA^His the conjugate transpose ofA, andvis a dense vector of shape(..., M).matmat (callable f(V)) – Returns
A @ V, whereVis a dense matrix with dimensions(..., N, K).rmatmat (callable f(V)) – Returns
A^H @ V, whereA^His the conjugate transpose ofA, and whereVis a dense matrix with dimensions(..., M, K).dtype (dtype) – Data type of the matrix or matrices.
xp (array_namespace, optional) – A namespace compatible with the array API standard for use in array operations. Default:
numpy.
- args¶
For linear operators describing products etc. of other linear operators, the operands of the binary operation.
- Type:
- T¶
Transpose.
- Type:
- H¶
Hermitian adjoint.
- Type:
See also
aslinearoperator()Construct a LinearOperator.
Notes
The user-defined matvec function must properly handle the case where
vhas shape(..., N).It is highly recommended to explicitly specify the dtype, otherwise it is determined automatically at the cost of a single matvec application on
int8zero vector using the promoted dtype of the output. It is assumed that matmat, rmatvec, and rmatmat would result in the same dtype of the output given anint8input as matvec.LinearOperator instances can also be multiplied, added with each other, and raised to integral powers, all lazily: the result of these operations is always a new, composite LinearOperator, that defers linear operations to the original operators and combines the results.
More details regarding how to subclass a LinearOperator and several examples of concrete LinearOperator instances can be found in the external project PyLops.
Array API Standard Support
LinearOperator has experimental support for Python Array API Standard compatible backends in addition to NumPy. Please consider testing these features by setting an environment variable
SCIPY_ARRAY_API=1and providing CuPy, PyTorch, JAX, or Dask arrays as array arguments. The following combinations of backend and device (or other capability) are supported.Library
CPU
GPU
NumPy
✅
n/a
CuPy
n/a
✅
PyTorch
✅
✅
JAX
✅
✅
Dask
✅
n/a
See Support for the array API standard for more information.
Examples
>>> import numpy as np >>> from scipy.sparse.linalg import LinearOperator >>> def mv(v): ... return np.array([2*v[0], 3*v[1]]) ... >>> A = LinearOperator((2,2), matvec=mv) >>> A <2x2 _CustomLinearOperator with dtype=int8> >>> A.matvec(np.ones(2)) array([ 2., 3.]) >>> A @ np.ones(2) array([ 2., 3.])
Initialize this LinearOperator.
To be called by subclasses.
dtypemay be None;shapeshould be convertible to a length >=2 tuple.Methods
Hermitian adjoint.
Multi-purpose multiplication method.
Matrix-matrix multiplication.
Matrix-vector multiplication.
Multi-purpose multiplication method from the right.
Adjoint matrix-matrix multiplication.
Adjoint matrix-vector multiplication.
Transpose.
Attributes
- classmethod __class_getitem__()¶
Represent a PEP 585 generic type
E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
- __add__(x)[source]¶
Linear operator addition.
The input must be a LinearOperator. A lazily summed linear operator is returned.
- __init__(dtype, shape, xp=None)[source]¶
Initialize this LinearOperator.
To be called by subclasses.
dtypemay be None;shapeshould be convertible to a length >=2 tuple.
- __matmul__(other)[source]¶
Matrix Multiplication.
Used by the
@operator. Rejects scalar input. Otherwise, equivalent to dot.
- __rmatmul__(other)[source]¶
Matrix Multiplication from the right.
Used by the
@operator from the right. Rejects scalar input. Otherwise, equivalent to rdot.
- __rmul__(x)[source]¶
Multiplication from the right.
Used by the
*operator from the right. Equivalent to rdot.
- adjoint()[source]¶
Hermitian adjoint.
Returns the Hermitian adjoint of this linear operator, also known as the Hermitian conjugate or Hermitian transpose. For a complex matrix, the Hermitian adjoint is equal to the conjugate transpose.
- Returns:
Hermitian adjoint of self.
- Return type:
LinearOperator
See also
HEquivalent attribute.
- dot(x)[source]¶
Multi-purpose multiplication method.
- Parameters:
x (array_like or LinearOperator or scalar) – Array-like input will be interpreted as a 1-D row vector or 2-D matrix (or batch of matrices) depending on its shape. See the Returns section for details.
- Returns:
Ax –
For LinearOperator input, operator composition is performed.
For scalar input, a lazily scaled operator is returned.
Otherwise, the input is expected to take the form of a dense 1-D vector or 2-D matrix (or batch of matrices), interpreted as follows (where
selfis anMbyNlinear operator):If x has shape
(N,)it is interpreted as a row vector and matvec is called.If x has shape
(..., N, K)for some integerK, it is interpreted as a matrix (or batch of matrices if there are batch dimensions) and matmat is called.
- Return type:
array or LinearOperator
See also
__mul__Equivalent method used by the
*operator.__matmul__Method used by the
@operator which rejects scalar input before calling this method.
Notes
To perform matrix-vector multiplication on batches of vectors, use matvec.
For clarity, it is recommended to use the matvec or matmat methods directly instead of this method when interacting with dense vectors and matrices.
- matmat(X)[source]¶
Matrix-matrix multiplication.
Performs the operation
A @ XwhereAis anMxNlinear operator (or batch of linear operators) and X is a denseNxKmatrix (or batch of dense matrices).- Parameters:
X ({matrix, ndarray}) – An array with shape
(..., N, K)representing the dense matrix (or batch of dense matrices).- Returns:
Y – An array with shape
(..., M, K).- Return type:
{matrix, ndarray}
Notes
This method wraps any user-specified
matmatroutine or overridden_matmatmethod to ensure that Y has the correct type.
- matvec(x)[source]¶
Matrix-vector multiplication.
Applies
Ato x, whereAis anMxNlinear operator (or batch of linear operators) and x is a row vector (or batch of such vectors).- Parameters:
x ({matrix, ndarray}) –
An array with shape
(..., N)representing a row vector (or batch of row vectors).Added in version 1.18.0: A
FutureWarningis emitted for column vector input of shape(N, 1), for which an array with shape(M, 1)is returned. matmat can be called instead for identical behaviour on such input.- Returns:
y – An array with shape
(..., M).- Return type:
{matrix, ndarray}
Notes
This method wraps the user-specified
matvecroutine or overridden_matvecmethod to ensure that y has the correct shape and type.
- rdot(x)[source]¶
Multi-purpose multiplication method from the right.
Note
This method returns
x A. To perform adjoint multiplication instead, use one of rmatvec or rmatmat, or take the adjoint first, likeself.H.rdot(x)orx * self.H.- Parameters:
x (array_like or LinearOperator or scalar) – Array-like input will be interpreted as a 1-D row vector or 2-D matrix (or batch of matrices) depending on its shape. See the Returns section for details.
- Returns:
xA –
For LinearOperator input, operator composition is performed.
For scalar input, a lazily scaled operator is returned.
Otherwise, the input is expected to take the form of a dense 1-D vector or 2-D matrix (or batch of matrices), interpreted as follows (where
selfis anMbyNlinear operator):If x has shape
(M,)it is interpreted as a row vector.If x has shape
(..., K, M)for some integerK, it is interpreted as a matrix (or batch of matrices if there are batch dimensions).
- Return type:
array or LinearOperator
See also
dotMulti-purpose multiplication method from the left.
__rmul__Equivalent method, used by the
*operator from the right.__rmatmul__Method used by the
@operator from the right which rejects scalar input before calling this method.
- rmatmat(X)[source]¶
Adjoint matrix-matrix multiplication.
Performs the operation
A^H @ XwhereAis anMxNlinear operator (or batch of linear operators) and X is a denseMxKmatrix (or batch of dense matrices). The default implementation defers to the adjoint.- Parameters:
X ({matrix, ndarray}) – An array with shape
(..., M, K)representing the dense matrix (or batch of dense matrices).- Returns:
Y – An array with shape
(..., N, K).- Return type:
{matrix, ndarray}
Notes
This method wraps any user-specified
rmatmatroutine or overridden_rmatmatmethod to ensure that Y has the correct type.
- rmatvec(x)[source]¶
Adjoint matrix-vector multiplication.
Applies
A^Hto x, whereAis anMxNlinear operator (or batch of linear operators) and x is a row vector (or batch of such vectors).- Parameters:
x ({matrix, ndarray}) –
An array with shape
(..., M)representing a row vector (or batch of row vectors), or an array with shape(M, 1)representing a column vector.Added in version 1.18.0: A
FutureWarningis now emitted for column vector input of shape(M, 1), for which an array with shape(N, 1)is returned. rmatmat can be called instead for identical behaviour on such input.- Returns:
y – An array with shape
(..., N).- Return type:
{matrix, ndarray}
Notes
This method wraps the user-specified
rmatvecroutine or overridden_rmatvecmethod to ensure that y has the correct shape and type.
- transpose()[source]¶
Transpose.
- Returns:
Transpose of the linear operator.
- Return type:
LinearOperator
See also
TEquivalent attribute.
- property H¶
Hermitian adjoint.
See also
scipy.sparse.linalg.LinearOperator.adjointEquivalent method.
- property T¶
Transpose.
See also
scipy.sparse.linalg.LinearOperator.transposeEquivalent method.
- __annotations__ = {'__class_getitem__': <class 'classmethod'>, 'ndim': <class 'int'>}¶
- __array_ufunc__ = None¶