Converts a standard matrix or duck-typed object into a BrahMap LinearOperator.
This function safely coerces various matrix-like objects -- such as
SciPy sparse matrices, dense NumPy arrays, or custom objects with
.shape and .matvec attributes -- into the framework's native
LinearOperator type, ensuring they can participate in algebraic
expressions (addition, composition) with core map-making operators.
Parameters:
| Name |
Type |
Description |
Default |
A
|
Any
|
An object that can be interpreted as a linear operator. 'A' may be any of the
following types:
linop.LinearOperator
scipy.LinearOperator
ndarray
matrix
- sparse matrix (e.g. csr_matrix, lil_matrix, etc.)
- any object with .shape and .matvec attributes
|
required
|
Returns:
| Type |
Description |
LinearOperator
|
The standard LinearOperator wrapping the input A
|
Source code in brahmap/base/linop.py
| def aslinearoperator(A) -> LinearOperator:
"""Converts a standard matrix or duck-typed object into a BrahMap `LinearOperator`.
This function safely coerces various matrix-like objects -- such as
SciPy sparse matrices, dense NumPy arrays, or custom objects with
`.shape` and `.matvec` attributes -- into the framework's native
`LinearOperator` type, ensuring they can participate in algebraic
expressions (addition, composition) with core map-making operators.
Parameters
----------
A : Any
An object that can be interpreted as a linear operator. 'A' may be any of the
following types:
- `linop.LinearOperator`
- `scipy.LinearOperator`
- `ndarray`
- `matrix`
- sparse matrix (e.g. csr_matrix, lil_matrix, etc.)
- any object with .shape and .matvec attributes
Returns
-------
LinearOperator
The standard `LinearOperator` wrapping the input `A`
"""
if isinstance(A, LinearOperator):
return A
try:
import numpy as np
if isinstance(A, np.ndarray) or isinstance(A, np.matrix):
return MatrixLinearOperator(A)
except ImportError:
pass
try:
import scipy.sparse as ssp
if ssp.isspmatrix(A):
return MatrixLinearOperator(A)
except ImportError:
pass
if hasattr(A, "shape"):
nargout, nargin = A.shape
matvec = None
rmatvec = None
dtype = None
symmetric = False
if hasattr(A, "matvec"):
matvec = A.matvec
if hasattr(A, "rmatvec"):
rmatvec = A.rmatvec
elif hasattr(A, "matvec_transp"):
rmatvec = A.matvec_transp
if hasattr(A, "dtype"):
dtype = A.dtype
if hasattr(A, "symmetric"):
symmetric = A.symmetric
elif hasattr(A, "__mul__"):
def matvec(x):
return A * x
if hasattr(A, "__rmul__"):
def rmatvec(x):
return x * A
if hasattr(A, "dtype"):
dtype = A.dtype
try:
symmetric = A.isSymmetric()
except Exception:
symmetric = False
if matvec is None:
raise TypeError("unsupported object type: missing matvec or __mul__")
return LinearOperator(
nargin,
nargout,
symmetric=symmetric,
matvec=matvec,
rmatvec=rmatvec,
dtype=dtype,
)
else:
raise TypeError("unsupported object type")
|