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, and conj.

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
Opscipy.sparse.linalg.LinearOperator or pylops.linearoperator.LinearOperator

Operator. If other arguments are provided, they will overwrite those obtained from Op.

dtypestr, optional

Type of elements in input array.

shapetuple(int, int), optional

Shape of operator. If not provided, obtained from dims and dimsd.

dimstuple(int, ..., int), optional

New in version 2.0.0.

Dimensions of model. If not provided, (self.shape[1],) is used.

dimsdtuple(int, ..., int), optional

New in version 2.0.0.

Dimensions of data. If not provided, (self.shape[0],) is used.

clinearbool, optional

New in version 1.17.0.

Operator is complex-linear. Defaults to True.

explicitbool, optional

Operator contains a matrix that can be solved explicitly (True) or not (False). Defaults to False.

forceflatbool, optional

New 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 None for operators that have no ambiguity or to True for those with ambiguity.

namestr, optional

New in version 2.0.0.

Name of operator (to be used by pylops.utils.describe.describe)

Attributes
matvec_countint

Counter tracking the number of matvec operations performed since the operator was instantiated.

rmatvec_countint

Counter tracking the number of rmatvec operations performed since the operator was instantiated.

matmat_countint

Counter tracking the number of matmat operations performed since the operator was instantiated.

rmatmat_countint

Counter tracking the number of rmatmat operations performed since the operator was instantiated.

Methods

__init__([Op, dtype, shape, dims, dimsd, ...])

adjoint()

apply_columns(cols)

Apply subset of columns of operator

cond([uselobpcg])

Condition number of linear operator.

conj()

Complex conjugate operator

div(y[, niter, densesolver])

Solve the linear problem \(\mathbf{y}=\mathbf{A}\mathbf{x}\).

dot(x)

Matrix-matrix or matrix-vector multiplication.

eigs([neigs, symmetric, niter, uselobpcg])

Most significant eigenvalues of linear operator.

matmat(X)

Matrix-matrix multiplication.

matvec(x)

Matrix-vector multiplication.

reset_count()

Reset counters

rmatmat(X)

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.

transpose()

LinearOperator.adjoint()[source]#
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
colslist

Columns to be selected

Returns
coloppylops.LinearOperator

Apply column operator

LinearOperator.cond(uselobpcg=False, **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.

Parameters
uselobpcgbool, optional

Use scipy.sparse.linalg.lobpcg to compute eigenvalues

**kwargs_eig

Arbitrary keyword arguments for scipy.sparse.linalg.eigs, scipy.sparse.linalg.eigsh, or scipy.sparse.linalg.lobpcg

Returns
eigenvaluesnumpy.ndarray

Operator 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
conjoppylops.LinearOperator

Complex conjugate operator

LinearOperator.div(y, niter=100, densesolver='scipy')[source]#

Solve the linear problem \(\mathbf{y}=\mathbf{A}\mathbf{x}\).

Overloading of operator / to improve expressivity of Pylops when solving inverse problems.

Parameters
ynumpy.ndarray

Data

niterint, optional

Number of iterations (to be used only when explicit=False)

densesolverstr, optional

Use scipy (scipy) or numpy (numpy) dense solver

Returns
xestnumpy.ndarray

Estimated model

LinearOperator.dot(x)[source]#

Matrix-matrix or matrix-vector multiplication.

Parameters
xnumpy.ndarray

Input array (or matrix)

Returns
ynumpy.ndarray

Output array (or matrix) that represents the result of applying the linear operator on x.

LinearOperator.eigs(neigs=None, symmetric=False, niter=None, uselobpcg=False, **kwargs_eig)[source]#

Most significant eigenvalues of linear operator.

Return an estimate of the most 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.

Parameters
neigsint

Number of eigenvalues to compute (if None, return all). Note that for explicit=False, only \(N-1\) eigenvalues can be computed where \(N\) is the size of the operator in the model space

symmetricbool, optional

Operator is symmetric (True) or not (False). User should set this parameter to True only when it is guaranteed that the operator is real-symmetric or complex-hermitian matrices

niterint, optional

Number of iterations for eigenvalue estimation

uselobpcgbool, optional

Use scipy.sparse.linalg.lobpcg

**kwargs_eig

Arbitrary keyword arguments for scipy.sparse.linalg.eigs, scipy.sparse.linalg.eigsh, or scipy.sparse.linalg.lobpcg

Returns
eigenvaluesnumpy.ndarray

Operator eigenvalues.

Raises
ValueError

If uselobpcg=True for a non-symmetric square matrix with complex type

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.eigsh method is used in case of symmetric=True and the scipy.sparse.linalg.eigs method is used symmetric=False. However, when the matrix is represented explicitly within the linear operator (explicit=True) and all the eigenvalues are requested the scipy.linalg.eigvals is used instead.

Finally, when only a limited number of eigenvalues is required, it is also possible to explicitly choose to use the scipy.sparse.linalg.lobpcg method via the uselobpcg input 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.

1

http://www.caam.rice.edu/software/ARPACK/

LinearOperator.matmat(X)[source]#

Matrix-matrix multiplication.

Modified version of scipy matmat which does not consider the case where the input vector is np.matrix (the use np.matrix is now discouraged in numpy’s documentation).

Parameters
xnumpy.ndarray

Input array of shape (N,K)

Returns
ynumpy.ndarray

Output array of shape (M,K)

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 use np.matrix is now discouraged in numpy’s documentation).

Parameters
xnumpy.ndarray

Input array of shape (N,) or (N,1)

Returns
ynumpy.ndarray

Output array of shape (M,) or (M,1)

LinearOperator.reset_count()[source]#

Reset counters

When invoked all counters are set back to 0.

LinearOperator.rmatmat(X)[source]#

Matrix-matrix multiplication.

Modified version of scipy rmatmat which does not consider the case where the input vector is np.matrix (the use np.matrix is now discouraged in numpy’s documentation).

Parameters
xnumpy.ndarray

Input array of shape (M,K)

Returns
ynumpy.ndarray

Output array of shape (N,K)

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 use np.matrix is now discouraged in numpy’s documentation).

Parameters
ynumpy.ndarray

Input array of shape (M,) or (M,1)

Returns
xnumpy.ndarray

Output array of shape (N,) or (N,1)

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
backendstr, optional

Backend used to densify matrix (numpy or cupy or jax). Note that this must be consistent with how the operator has been created.

Returns
matrixnumpy.ndarray or cupy.ndarray

Dense matrix.

LinearOperator.toimag(forw=True, adj=True)[source]#

Imag operator

Parameters
forwbool, optional

Apply imag to output of forward pass

adjbool, optional

Apply imag to output of adjoint pass

Returns
imagoppylops.LinearOperator

Imag operator

LinearOperator.toreal(forw=True, adj=True)[source]#

Real operator

Parameters
forwbool, optional

Apply real to output of forward pass

adjbool, optional

Apply real to output of adjoint pass

Returns
realoppylops.LinearOperator

Real operator

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
matrixscipy.sparse.csr_matrix

Sparse 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
nevalint, optional

Maximum number of matrix-vector products compute. Default depends method.

methodstr, optional

Should be one of the following:

  • explicit: If the operator is not explicit, will convert to dense first.

  • hutchinson: see pylops.utils.trace_hutchinson

  • hutch++: see pylops.utils.trace_hutchpp

  • na-hutch++: see pylops.utils.trace_nahutchpp

Defaults to ‘explicit’ for explicit operators, and ‘Hutch++’ for the rest.

backendstr, optional

Backend used to densify matrix (numpy or cupy). 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, or pylops.utils.trace_nahutchpp

Returns
tracefloat

Operator trace.

Raises
ValueError

If the operator has rectangular shape (shape[0] != shape[1])

NotImplementedError

If the method is not one of the available methods.

LinearOperator.transpose()[source]#

Examples using pylops.LinearOperator#

1D Smoothing

1D Smoothing

1D, 2D and 3D Sliding

1D, 2D and 3D Sliding

2D Smoothing

2D Smoothing

AVO modelling

AVO modelling

Acoustic Wave Equation modelling

Acoustic Wave Equation modelling

Bayesian Linear Regression

Bayesian Linear Regression

Bilinear Interpolation

Bilinear Interpolation

Blending

Blending

CGLS and LSQR Solvers

CGLS and LSQR Solvers

Causal Integration

Causal Integration

Chirp Radon Transform

Chirp Radon Transform

Conj

Conj

Convolution

Convolution

Derivatives

Derivatives

Describe

Describe

Diagonal

Diagonal

Discrete Cosine Transform

Discrete Cosine Transform

Flip along an axis

Flip along an axis

Fourier Radon Transform

Fourier Radon Transform

Identity

Identity

Imag

Imag

L1-L1 IRLS

L1-L1 IRLS

Linear Regression

Linear Regression

MP, OMP, ISTA and FISTA

MP, OMP, ISTA and FISTA

Matrix Multiplication

Matrix Multiplication

Non-stationary Convolution

Non-stationary Convolution

Non-stationary Filter Estimation

Non-stationary Filter Estimation

Normal Moveout (NMO) Correction

Normal Moveout (NMO) Correction

Operators concatenation

Operators concatenation

Operators with Multithreading/Multiprocessing

Operators with Multithreading/Multiprocessing

PWD-based slope estimation and structural smoothing

PWD-based slope estimation and structural smoothing

Padding

Padding

Patching

Patching

Polynomial Regression

Polynomial Regression

Real

Real

Restriction and Interpolation

Restriction and Interpolation

Roll

Roll

Seislet transform

Seislet transform

Spread How-to

Spread How-to

Sum

Sum

Symmetrize

Symmetrize

Total Variation (TV) Regularization

Total Variation (TV) Regularization

Transpose

Transpose

Wavelet estimation

Wavelet estimation

Wavelet transform

Wavelet transform

Zero

Zero

01. The LinearOperator

01. The LinearOperator

02. The Dot-Test

02. The Dot-Test

03. Solvers

03. Solvers

03. Solvers (Advanced)

03. Solvers (Advanced)

04. Bayesian Inversion

04. Bayesian Inversion

05. Image deblurring

05. Image deblurring

06. 2D Interpolation

06. 2D Interpolation

08. Pre-stack (AVO) inversion

08. Pre-stack (AVO) inversion

12. Seismic regularization

12. Seismic regularization

16. CT Scan Imaging

16. CT Scan Imaging

17. Real/Complex Inversion

17. Real/Complex Inversion

18. Deblending

18. Deblending

19. Image Domain Least-squares migration

19. Image Domain Least-squares migration

20. Torch Operator

20. Torch Operator

21. JAX Operator

21. JAX Operator