pylops.LinearOperator¶
- class pylops.LinearOperator(Op=None, dtype=None, shape=None, dims=None, dimsd=None, clinear=None, explicit=None, forceflat=None, name=None)[source]¶
Common interface for performing matrix-vector products.
This class acts as an abstract interface between matrix-like objects and iterative solvers, providing methods to perform matrix-vector and adjoint matrix-vector products as as well as convenience methods such as
eigs,cond, andconj.Note
End users of PyLops should not use this class directly but simply use operators that are already implemented. This class is meant for developers and it has to be used as the parent class of any new operator developed within PyLops. Find more details regarding implementation of new operators at 🖌️ Implementing new operators.
- Parameters:
- Op
scipy.sparse.linalg.LinearOperatororpylops.linearoperator.LinearOperator Operator. If other arguments are provided, they will overwrite those obtained from
Op.- dtype
strornumpy.dtype, optional Type of elements in input array. Any
numpy.dtype-like input (e.g.,"float64"ornp.float64) is always cast to anumpy.dtypevianp.dtype(dtype), both at initialization and whendtypeis set afterwards. IfNone,dtypeis taken fromOpor, ifOpis not provided, defaults tonumpy.float64(followingnp.dtype(None)); the same applies when settingdtypetoNoneafterwards.- shape
tuple(int, int), optional Shape of operator. If not provided, obtained from
dimsanddimsd.- dims
tuple(int, ..., int), optional Added in version 2.0.0.
Dimensions of model. If not provided,
(self.shape[1],)is used.- dimsd
tuple(int, ..., int), optional Added in version 2.0.0.
Dimensions of data. If not provided,
(self.shape[0],)is used.- clinear
bool, optional Added in version 1.17.0.
Operator is complex-linear. Defaults to
True.- explicit
bool, optional Operator contains a matrix that can be solved explicitly (
True) or not (False). Defaults toFalse.- forceflat
bool, optional Added in version 2.2.0.
Force an array to be flattened after matvec/rmatvec if the input is ambiguous (i.e., is a 1D array both when operating with ND arrays and with 1D arrays). Defaults to
Nonefor operators that have no ambiguity or toTruefor those with ambiguity.- name
str, optional Added in version 2.0.0.
Name of operator (to be used by
pylops.utils.describe.describe)
- Op
- Attributes:
- matvec_count
int Counter tracking the number of
matvecoperations performed since the operator was instantiated.- rmatvec_count
int Counter tracking the number of
rmatvecoperations performed since the operator was instantiated.- matmat_count
int Counter tracking the number of
matmatoperations performed since the operator was instantiated.- rmatmat_count
int Counter tracking the number of
rmatmatoperations performed since the operator was instantiated.
- matvec_count
Methods
__init__([Op, dtype, shape, dims, dimsd, ...])adjoint()apply_columns(cols)Apply subset of columns of operator
cond([uselobpcg, backend])Condition number of linear operator.
conj()Complex conjugate operator
div(y[, niter, densesolver])Solve the linear problem or divide by a scalar
dot(x)Dot-product
eigs([neigs, symmetric, niter, uselobpcg, ...])N-most significant eigenvalues of a linear operator.
matmat(X[, pool])Matrix-matrix multiplication.
matvec(x)Matrix-vector multiplication.
Reset counters
rmatmat(X[, pool])Matrix-matrix multiplication.
rmatvec(x)Adjoint matrix-vector multiplication.
todense([backend])Return dense matrix.
toimag([forw, adj])Imag operator
toreal([forw, adj])Real operator
tosparse()Return sparse matrix.
trace([neval, method, backend])Trace of linear operator.
- LinearOperator.apply_columns(cols)[source]¶
Apply subset of columns of operator
This method can be used to wrap a LinearOperator and mimic the action of a subset of columns of the operator on a reduced model in forward mode, and retrieve only the result of a subset of rows in adjoint mode.
Note that unless the operator has
explicit=True, this is not optimal as the entire forward and adjoint passes of the original operator will have to be perfomed. It can however be useful for the implementation of solvers such as Orthogonal Matching Pursuit (OMP) that iteratively build a solution by evaluate only a subset of the columns of the operator.- Parameters:
- cols
list Columns to be selected
- cols
- Returns:
- colop
pylops.LinearOperator Apply column operator
- colop
- LinearOperator.cond(uselobpcg=False, backend='numpy', **kwargs_eig)[source]¶
Condition number of linear operator.
Return an estimate of the condition number of the linear operator as the ratio of the largest and lowest estimated eigenvalues.
Note
If
backend="cupy", the condition number can only be computed with theuselobpcg=Trueoption (and therefore for square, symmetric operators only).- Parameters:
- uselobpcg
bool, optional Use
scipy.sparse.linalg.lobpcgto compute eigenvalues- backend
str, optional Added in version 2.9.0.
Backend to use (numpy or cupy).
- **kwargs_eig
Arbitrary keyword arguments for
scipy.sparse.linalg.eigs,scipy.sparse.linalg.eigsh, orscipy.sparse.linalg.lobpcg
- uselobpcg
- Returns:
- eigenvalues
numpy.ndarray Operator eigenvalues.
- eigenvalues
Notes
The condition number of a matrix (or linear operator) can be estimated as the ratio of the largest and lowest estimated eigenvalues:
\[k= \frac{\lambda_{max}}{\lambda_{min}}\]The condition number provides an indication of the rate at which the solution of the inversion of the linear operator \(A\) will change with respect to a change in the data \(y\).
Thus, if the condition number is large, even a small error in \(y\) may cause a large error in \(x\). On the other hand, if the condition number is small then the error in \(x\) is not much bigger than the error in \(y\). A problem with a low condition number is said to be well-conditioned, while a problem with a high condition number is said to be ill-conditioned.
- LinearOperator.conj()[source]¶
Complex conjugate operator
- Returns:
- conjop
pylops.LinearOperator Complex conjugate operator
- conjop
- LinearOperator.div(y, niter=100, densesolver='scipy')[source]¶
Solve the linear problem or divide by a scalar
Overloading of operator
/to improve expressivity of Pylops when solving inverse problems.Division of a PyLops operator by a:
scalar: returns a scaled operator, so
Op / ais the same asOp * (1 / a).1d-array: solves the linear problem \(\mathbf{y}=\mathbf{A}\mathbf{x}\) and returns the estimated model. Explicit operators are solved with a sparse or dense direct solver, whilst any other operator is solved iteratively;
- Parameters:
- y
floatornumpy.ndarray Scalar or data of size
shape[0].- niter
int, optional Number of iterations (to be used only when
explicit=False)- densesolver
str, optional Use scipy (
scipy) or numpy (numpy) dense solver (to be used only for square explicit operators with dense matrix)
- y
- Returns:
- xest
pylops.LinearOperatorornumpy.ndarray Scaled operator or estimated model.
- xest
- LinearOperator.dot(x)[source]¶
Dot-product
Dot-product between a PyLops operator and a:
scalar: returns a scaled operator, i.e.,
alpha * Op;1d- or nd-array: applies the operator to the input and returns an array. A 1d-array of size
shape[1](or an nd-array of shapedimswhendimsis defined andforceflatis not set) is treated as a vector and passed topylops.LinearOperator.matvec; a 2d-array of shape(shape[1], P)(or an nd-array of shape(*dims, P)) is treated as a matrix ofPvectors and passed topylops.LinearOperator.matmat. Arrays with more than 2 dimensions are accepted only if nd-array multiplication is enabled viapylops.set_ndarray_multiplication, in which case the output is reshaped todimsd(or(*dimsd, P));linear operator: returns the product of the two operators, i.e.,
Op1 @ Op2.
- Parameters:
- x
float,numpy.ndarrayorpylops.LinearOperator Input scalar, array (or matrix) or linear operator
- x
- Returns:
- y
numpy.ndarrayorpylops.LinearOperator Scaled operator (scalar input), array (or matrix) that represents the result of applying the linear operator on
x(array input), or product operator (operator input).
- y
- Raises:
- ValueError
If
xis an array with an unsupported shape, or if the two operators have conflictingforceflat.
- LinearOperator.eigs(neigs=None, symmetric=False, niter=None, uselobpcg=False, backend='numpy', **kwargs_eig)[source]¶
N-most significant eigenvalues of a linear operator.
Return an estimate of the
neigsmost significant eigenvalues of the linear operator. If the operator has rectangular shape (shape[0] != shape[1]), eigenvalues are first computed for the square operator \(\mathbf{A^H}\mathbf{A}\) and the square-root values are returned.Note
If
backend="cupy", the eigenvalues of a square operator can be computed only when in symmetric (symmetric=True), since CuPy does not provide an equivalent ofscipy.sparse.linalg.eigs. ANotImplementedErroris raised.- Parameters:
- neigs
int Number of eigenvalues to compute. Note that for
explicit=False, only \(N-1\) eigenvalues can be computed for real-valued symmetric or non-square operators, and \(N-2\) eigenvalues otherwise, where \(N\) is the size of the operator in the model space. IfNone, return \(N\) for explicit case and \(N-2\) for implicit operators.- symmetric
bool, optional Operator is real-symmetric or complex-hermitian (
True) or not (False). User should set this parameter toTrueonly when it is guaranteed that the operator is real-symmetric or complex-hermitian- niter
int, optional Number of iterations for eigenvalue estimation
- uselobpcg
bool, optional Use
scipy.sparse.linalg.lobpcg. Note that this method is only available for symmetric operators.- backend
str, optional Added in version 2.9.0.
Backend to use (numpy or cupy)
- **kwargs_eig
Arbitrary keyword arguments for
scipy.linalg.eigvals,scipy.sparse.linalg.eigs,scipy.sparse.linalg.eigsh, orscipy.sparse.linalg.lobpcgand CuPy equivalents.
- neigs
- Returns:
- eigenvalues
numpy.ndarray Operator eigenvalues.
- eigenvalues
- Raises:
- ValueError
If
uselobpcg=Truefor a non-symmetric square matrix with complex type, or ifuselobpcg=Trueand the size of the operator minus the number of constraintsYis smaller than 5 timesneigs(in which casescipy.sparse.linalg.lobpcgwould switch to a dense solver)- NotImplementedError
If
backend="cupy"andsymmetric=Falsefor a square operator for which only a limited number of eigenvalues is requested (neigssmaller than the size of the operator, orexplicit=False), as CuPy does not provide an equivalent ofscipy.sparse.linalg.eigs
Notes
Depending on the size of the operator, whether it is explicit or not and the number of eigenvalues requested, different algorithms are used by this routine.
More precisely, when only a limited number of eigenvalues is requested the
scipy.sparse.linalg.eigshmethod is used in case ofsymmetric=Trueand thescipy.sparse.linalg.eigsmethod is usedsymmetric=False. However, when the matrix is represented explicitly within the linear operator (explicit=True) and all the eigenvalues are requested (orneigsis equal to the number of columns of the operator minus one for a square, non-symmetric operator) thescipy.linalg.eigvalsis used instead. Note that for or a complex-valued operator, whenneigsis equal to the number of columns of the operator minus one, the eigenvalues are selected based onwhichandsigmais ignored.Finally, when only a limited number of eigenvalues is required, it is also possible to explicitly choose to use the
scipy.sparse.linalg.lobpcgmethod via theuselobpcginput parameter flag.Most of these algorithms are a port of ARPACK [1], a Fortran package which provides routines for quickly finding eigenvalues/eigenvectors of a matrix. As ARPACK requires only left-multiplication by the matrix in question, eigenvalues/eigenvectors can also be estimated for linear operators when the dense matrix is not available.
- LinearOperator.matmat(X, pool=None)[source]¶
Matrix-matrix multiplication.
Modified version of scipy matmat which does not consider the case where the input vector is
np.matrix(the usenp.matrixis now discouraged in numpy’s documentation).- Parameters:
- x
numpy.ndarray Input array of shape (N,K)
- pool
multiprocessing.Poolorconcurrent.futures.ThreadPoolExecutororNone Pool of workers used to evaluate the operator on different columns of
Xin parallel.
- x
- Returns:
- y
numpy.ndarray Output array of shape (M,K)
- y
- LinearOperator.matvec(x)[source]¶
Matrix-vector multiplication.
Modified version of scipy matvec which does not consider the case where the input vector is
np.matrix(the usenp.matrixis now discouraged in numpy’s documentation).- Parameters:
- x
numpy.ndarray Input array of shape (N,) or (N,1)
- x
- Returns:
- y
numpy.ndarray Output array of shape (M,) or (M,1)
- y
- LinearOperator.rmatmat(X, pool=None)[source]¶
Matrix-matrix multiplication.
Modified version of scipy rmatmat which does not consider the case where the input vector is
np.matrix(the usenp.matrixis now discouraged in numpy’s documentation).- Parameters:
- x
numpy.ndarray Input array of shape (M,K)
- pool
multiprocessing.Poolorconcurrent.futures.ThreadPoolExecutororNone Pool of workers used to evaluate the operator on different columns of
Xin parallel.
- x
- Returns:
- y
numpy.ndarray Output array of shape (N,K)
- y
- LinearOperator.rmatvec(x)[source]¶
Adjoint matrix-vector multiplication.
Modified version of scipy rmatvec which does not consider the case where the input vector is
np.matrix(the usenp.matrixis now discouraged in numpy’s documentation).- Parameters:
- y
numpy.ndarray Input array of shape (M,) or (M,1)
- y
- Returns:
- x
numpy.ndarray Output array of shape (N,) or (N,1)
- x
- LinearOperator.todense(backend='numpy')[source]¶
Return dense matrix.
The operator is converted into its dense matrix equivalent. In order to do so, square or tall operators are applied to an identity matrix whose number of rows and columns is equivalent to the number of columns of the operator. Conversely, for skinny operators, the transpose operator is applied to an identity matrix whose number of rows and columns is equivalent to the number of rows of the operator and the resulting matrix is transposed (and complex conjugated).
Note that this operation may be costly for operators with large number of rows and columns and it should be used mostly as a way to inspect the structure of the matricial equivalent of the operator.
- Parameters:
- backend
str, optional Backend used to densify matrix (
numpyorcupyorjax). Note that this must be consistent with how the operator has been created.
- backend
- Returns:
- matrix
numpy.ndarrayorcupy.ndarray Dense matrix.
- matrix
- LinearOperator.toimag(forw=True, adj=True)[source]¶
Imag operator
- Parameters:
- Returns:
- imagop
pylops.LinearOperator Imag operator
- imagop
- LinearOperator.toreal(forw=True, adj=True)[source]¶
Real operator
- Parameters:
- Returns:
- realop
pylops.LinearOperator Real operator
- realop
- LinearOperator.tosparse()[source]¶
Return sparse matrix.
The operator in converted into its sparse (CSR) matrix equivalent. In order to do so, the operator is applied to series of unit vectors with length equal to the number of coloumns in the original operator.
- Returns:
- matrix
scipy.sparse.csr_matrix Sparse matrix.
- matrix
- LinearOperator.trace(neval=None, method=None, backend='numpy', **kwargs_trace)[source]¶
Trace of linear operator.
Returns the trace (or its estimate) of the linear operator.
- Parameters:
- neval
int, optional Maximum number of matrix-vector products compute. Default depends
method.- method
str, optional Should be one of the following:
explicit: If the operator is not explicit, will convert to dense first.
hutchinson: see
pylops.utils.trace_hutchinsonhutch++: see
pylops.utils.trace_hutchppna-hutch++: see
pylops.utils.trace_nahutchpp
Defaults to ‘explicit’ for explicit operators, and ‘Hutch++’ for the rest.
- backend
str, optional Backend used to densify matrix (
numpyorcupy). Note that this must be consistent with how the operator has been created.- **kwargs_trace
Arbitrary keyword arguments passed to
pylops.utils.trace_hutchinson,pylops.utils.trace_hutchpp, orpylops.utils.trace_nahutchpp
- neval
- Returns:
- trace
float Operator trace.
- trace
- Raises:
- ValueError
If the operator has rectangular shape (
shape[0] != shape[1])- NotImplementedError
If the
methodis not one of the available methods.
Examples using pylops.LinearOperator¶
PWD-based slope estimation and structural smoothing