_interface.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. """Abstract linear algebra library.
  2. This module defines a class hierarchy that implements a kind of "lazy"
  3. matrix representation, called the ``LinearOperator``. It can be used to do
  4. linear algebra with extremely large sparse or structured matrices, without
  5. representing those explicitly in memory. Such matrices can be added,
  6. multiplied, transposed, etc.
  7. As a motivating example, suppose you want have a matrix where almost all of
  8. the elements have the value one. The standard sparse matrix representation
  9. skips the storage of zeros, but not ones. By contrast, a LinearOperator is
  10. able to represent such matrices efficiently. First, we need a compact way to
  11. represent an all-ones matrix::
  12. >>> import numpy as np
  13. >>> from scipy.sparse.linalg._interface import LinearOperator
  14. >>> class Ones(LinearOperator):
  15. ... def __init__(self, shape):
  16. ... super().__init__(dtype=None, shape=shape)
  17. ... def _matvec(self, x):
  18. ... return np.repeat(x.sum(), self.shape[0])
  19. Instances of this class emulate ``np.ones(shape)``, but using a constant
  20. amount of storage, independent of ``shape``. The ``_matvec`` method specifies
  21. how this linear operator multiplies with (operates on) a vector. We can now
  22. add this operator to a sparse matrix that stores only offsets from one::
  23. >>> from scipy.sparse.linalg._interface import aslinearoperator
  24. >>> from scipy.sparse import csr_array
  25. >>> offsets = csr_array([[1, 0, 2], [0, -1, 0], [0, 0, 3]])
  26. >>> A = aslinearoperator(offsets) + Ones(offsets.shape)
  27. >>> A.dot([1, 2, 3])
  28. array([13, 4, 15])
  29. The result is the same as that given by its dense, explicitly-stored
  30. counterpart::
  31. >>> (np.ones(A.shape, A.dtype) + offsets.toarray()).dot([1, 2, 3])
  32. array([13, 4, 15])
  33. Several algorithms in the ``scipy.sparse`` library are able to operate on
  34. ``LinearOperator`` instances.
  35. """
  36. import types
  37. import warnings
  38. import numpy as np
  39. from scipy.sparse import issparse
  40. from scipy.sparse._sputils import isshape, isintlike, asmatrix, is_pydata_spmatrix
  41. __all__ = ['LinearOperator', 'aslinearoperator']
  42. class LinearOperator:
  43. """Common interface for performing matrix vector products
  44. Many iterative methods (e.g. `cg`, `gmres`) do not need to know the
  45. individual entries of a matrix to solve a linear system ``A@x = b``.
  46. Such solvers only require the computation of matrix vector
  47. products, ``A@v`` where ``v`` is a dense vector. This class serves as
  48. an abstract interface between iterative solvers and matrix-like
  49. objects.
  50. To construct a concrete `LinearOperator`, either pass appropriate
  51. callables to the constructor of this class, or subclass it.
  52. A subclass must implement either one of the methods ``_matvec``
  53. and ``_matmat``, and the attributes/properties ``shape`` (pair of
  54. integers) and ``dtype`` (may be None). It may call the ``__init__``
  55. on this class to have these attributes validated. Implementing
  56. ``_matvec`` automatically implements ``_matmat`` (using a naive
  57. algorithm) and vice-versa.
  58. Optionally, a subclass may implement ``_rmatvec`` or ``_adjoint``
  59. to implement the Hermitian adjoint (conjugate transpose). As with
  60. ``_matvec`` and ``_matmat``, implementing either ``_rmatvec`` or
  61. ``_adjoint`` implements the other automatically. Implementing
  62. ``_adjoint`` is preferable; ``_rmatvec`` is mostly there for
  63. backwards compatibility.
  64. Parameters
  65. ----------
  66. shape : tuple
  67. Matrix dimensions ``(M, N)``.
  68. matvec : callable f(v)
  69. Returns returns ``A @ v``.
  70. rmatvec : callable f(v)
  71. Returns ``A^H @ v``, where ``A^H`` is the conjugate transpose of ``A``.
  72. matmat : callable f(V)
  73. Returns ``A @ V``, where ``V`` is a dense matrix with dimensions ``(N, K)``.
  74. dtype : dtype
  75. Data type of the matrix.
  76. rmatmat : callable f(V)
  77. Returns ``A^H @ V``, where ``V`` is a dense matrix with dimensions ``(M, K)``.
  78. Attributes
  79. ----------
  80. args : tuple
  81. For linear operators describing products etc. of other linear
  82. operators, the operands of the binary operation.
  83. ndim : int
  84. Number of dimensions (this is always 2)
  85. See Also
  86. --------
  87. aslinearoperator : Construct LinearOperators
  88. Notes
  89. -----
  90. The user-defined `matvec` function must properly handle the case
  91. where ``v`` has shape ``(N,)`` as well as the ``(N,1)`` case. The shape of
  92. the return type is handled internally by `LinearOperator`.
  93. It is highly recommended to explicitly specify the `dtype`, otherwise
  94. it is determined automatically at the cost of a single matvec application
  95. on ``int8`` zero vector using the promoted `dtype` of the output.
  96. Python ``int`` could be difficult to automatically cast to numpy integers
  97. in the definition of the `matvec` so the determination may be inaccurate.
  98. It is assumed that `matmat`, `rmatvec`, and `rmatmat` would result in
  99. the same dtype of the output given an ``int8`` input as `matvec`.
  100. LinearOperator instances can also be multiplied, added with each
  101. other and exponentiated, all lazily: the result of these operations
  102. is always a new, composite LinearOperator, that defers linear
  103. operations to the original operators and combines the results.
  104. More details regarding how to subclass a LinearOperator and several
  105. examples of concrete LinearOperator instances can be found in the
  106. external project `PyLops <https://pylops.readthedocs.io>`_.
  107. Examples
  108. --------
  109. >>> import numpy as np
  110. >>> from scipy.sparse.linalg import LinearOperator
  111. >>> def mv(v):
  112. ... return np.array([2*v[0], 3*v[1]])
  113. ...
  114. >>> A = LinearOperator((2,2), matvec=mv)
  115. >>> A
  116. <2x2 _CustomLinearOperator with dtype=int8>
  117. >>> A.matvec(np.ones(2))
  118. array([ 2., 3.])
  119. >>> A @ np.ones(2)
  120. array([ 2., 3.])
  121. """
  122. ndim = 2
  123. # Necessary for right matmul with numpy arrays.
  124. __array_ufunc__ = None
  125. # generic type compatibility with scipy-stubs
  126. __class_getitem__ = classmethod(types.GenericAlias)
  127. def __new__(cls, *args, **kwargs):
  128. if cls is LinearOperator:
  129. # Operate as _CustomLinearOperator factory.
  130. return super().__new__(_CustomLinearOperator)
  131. else:
  132. obj = super().__new__(cls)
  133. if (type(obj)._matvec == LinearOperator._matvec
  134. and type(obj)._matmat == LinearOperator._matmat):
  135. warnings.warn("LinearOperator subclass should implement"
  136. " at least one of _matvec and _matmat.",
  137. category=RuntimeWarning, stacklevel=2)
  138. return obj
  139. def __init__(self, dtype, shape):
  140. """Initialize this LinearOperator.
  141. To be called by subclasses. ``dtype`` may be None; ``shape`` should
  142. be convertible to a length-2 tuple.
  143. """
  144. if dtype is not None:
  145. dtype = np.dtype(dtype)
  146. shape = tuple(shape)
  147. if not isshape(shape):
  148. raise ValueError(f"invalid shape {shape!r} (must be 2-d)")
  149. self.dtype = dtype
  150. self.shape = shape
  151. def _init_dtype(self):
  152. """Determine the dtype by executing `matvec` on an `int8` test vector.
  153. In `np.promote_types` hierarchy, the type `int8` is the smallest,
  154. so we call `matvec` on `int8` and use the promoted dtype of the output
  155. to set the default `dtype` of the `LinearOperator`.
  156. We assume that `matmat`, `rmatvec`, and `rmatmat` would result in
  157. the same dtype of the output given an `int8` input as `matvec`.
  158. Called from subclasses at the end of the __init__ routine.
  159. """
  160. if self.dtype is None:
  161. v = np.zeros(self.shape[-1], dtype=np.int8)
  162. try:
  163. matvec_v = np.asarray(self.matvec(v))
  164. except OverflowError:
  165. # Python large `int` promoted to `np.int64`or `np.int32`
  166. self.dtype = np.dtype(int)
  167. else:
  168. self.dtype = matvec_v.dtype
  169. def _matmat(self, X):
  170. """Default matrix-matrix multiplication handler.
  171. Falls back on the user-defined _matvec method, so defining that will
  172. define matrix multiplication (though in a very suboptimal way).
  173. """
  174. return np.hstack([self.matvec(col.reshape(-1,1)) for col in X.T])
  175. def _matvec(self, x):
  176. """Default matrix-vector multiplication handler.
  177. If self is a linear operator of shape (M, N), then this method will
  178. be called on a shape (N,) or (N, 1) ndarray, and should return a
  179. shape (M,) or (M, 1) ndarray.
  180. This default implementation falls back on _matmat, so defining that
  181. will define matrix-vector multiplication as well.
  182. """
  183. return self.matmat(x.reshape(-1, 1))
  184. def matvec(self, x):
  185. """Matrix-vector multiplication.
  186. Performs the operation y=A@x where A is an MxN linear
  187. operator and x is a column vector or 1-d array.
  188. Parameters
  189. ----------
  190. x : {matrix, ndarray}
  191. An array with shape (N,) or (N,1).
  192. Returns
  193. -------
  194. y : {matrix, ndarray}
  195. A matrix or ndarray with shape (M,) or (M,1) depending
  196. on the type and shape of the x argument.
  197. Notes
  198. -----
  199. This matvec wraps the user-specified matvec routine or overridden
  200. _matvec method to ensure that y has the correct shape and type.
  201. """
  202. x = np.asanyarray(x)
  203. M,N = self.shape
  204. if x.shape != (N,) and x.shape != (N,1):
  205. raise ValueError('dimension mismatch')
  206. y = self._matvec(x)
  207. if isinstance(x, np.matrix):
  208. y = asmatrix(y)
  209. else:
  210. y = np.asarray(y)
  211. if x.ndim == 1:
  212. y = y.reshape(M)
  213. elif x.ndim == 2:
  214. y = y.reshape(M,1)
  215. else:
  216. raise ValueError('invalid shape returned by user-defined matvec()')
  217. return y
  218. def rmatvec(self, x):
  219. """Adjoint matrix-vector multiplication.
  220. Performs the operation y = A^H @ x where A is an MxN linear
  221. operator and x is a column vector or 1-d array.
  222. Parameters
  223. ----------
  224. x : {matrix, ndarray}
  225. An array with shape (M,) or (M,1).
  226. Returns
  227. -------
  228. y : {matrix, ndarray}
  229. A matrix or ndarray with shape (N,) or (N,1) depending
  230. on the type and shape of the x argument.
  231. Notes
  232. -----
  233. This rmatvec wraps the user-specified rmatvec routine or overridden
  234. _rmatvec method to ensure that y has the correct shape and type.
  235. """
  236. x = np.asanyarray(x)
  237. M,N = self.shape
  238. if x.shape != (M,) and x.shape != (M,1):
  239. raise ValueError('dimension mismatch')
  240. y = self._rmatvec(x)
  241. if isinstance(x, np.matrix):
  242. y = asmatrix(y)
  243. else:
  244. y = np.asarray(y)
  245. if x.ndim == 1:
  246. y = y.reshape(N)
  247. elif x.ndim == 2:
  248. y = y.reshape(N,1)
  249. else:
  250. raise ValueError('invalid shape returned by user-defined rmatvec()')
  251. return y
  252. def _rmatvec(self, x):
  253. """Default implementation of _rmatvec; defers to adjoint."""
  254. if type(self)._adjoint == LinearOperator._adjoint:
  255. # _adjoint not overridden, prevent infinite recursion
  256. if (hasattr(self, "_rmatmat")
  257. and type(self)._rmatmat != LinearOperator._rmatmat):
  258. # Try to use _rmatmat as a fallback
  259. return self._rmatmat(x.reshape(-1, 1)).reshape(-1)
  260. raise NotImplementedError
  261. else:
  262. return self.H.matvec(x)
  263. def matmat(self, X):
  264. """Matrix-matrix multiplication.
  265. Performs the operation y=A@X where A is an MxN linear
  266. operator and X dense N*K matrix or ndarray.
  267. Parameters
  268. ----------
  269. X : {matrix, ndarray}
  270. An array with shape (N,K).
  271. Returns
  272. -------
  273. Y : {matrix, ndarray}
  274. A matrix or ndarray with shape (M,K) depending on
  275. the type of the X argument.
  276. Notes
  277. -----
  278. This matmat wraps any user-specified matmat routine or overridden
  279. _matmat method to ensure that y has the correct type.
  280. """
  281. if not (issparse(X) or is_pydata_spmatrix(X)):
  282. X = np.asanyarray(X)
  283. if X.ndim != 2:
  284. raise ValueError(f'expected 2-d ndarray or matrix, not {X.ndim}-d')
  285. if X.shape[0] != self.shape[1]:
  286. raise ValueError(f'dimension mismatch: {self.shape}, {X.shape}')
  287. try:
  288. Y = self._matmat(X)
  289. except Exception as e:
  290. if issparse(X) or is_pydata_spmatrix(X):
  291. raise TypeError(
  292. "Unable to multiply a LinearOperator with a sparse matrix."
  293. " Wrap the matrix in aslinearoperator first."
  294. ) from e
  295. raise
  296. if isinstance(Y, np.matrix):
  297. Y = asmatrix(Y)
  298. return Y
  299. def rmatmat(self, X):
  300. """Adjoint matrix-matrix multiplication.
  301. Performs the operation y = A^H @ x where A is an MxN linear
  302. operator and x is a column vector or 1-d array, or 2-d array.
  303. The default implementation defers to the adjoint.
  304. Parameters
  305. ----------
  306. X : {matrix, ndarray}
  307. A matrix or 2D array.
  308. Returns
  309. -------
  310. Y : {matrix, ndarray}
  311. A matrix or 2D array depending on the type of the input.
  312. Notes
  313. -----
  314. This rmatmat wraps the user-specified rmatmat routine.
  315. """
  316. if not (issparse(X) or is_pydata_spmatrix(X)):
  317. X = np.asanyarray(X)
  318. if X.ndim != 2:
  319. raise ValueError(f'expected 2-d ndarray or matrix, not {X.ndim}-d')
  320. if X.shape[0] != self.shape[0]:
  321. raise ValueError(f'dimension mismatch: {self.shape}, {X.shape}')
  322. try:
  323. Y = self._rmatmat(X)
  324. except Exception as e:
  325. if issparse(X) or is_pydata_spmatrix(X):
  326. raise TypeError(
  327. "Unable to multiply a LinearOperator with a sparse matrix."
  328. " Wrap the matrix in aslinearoperator() first."
  329. ) from e
  330. raise
  331. if isinstance(Y, np.matrix):
  332. Y = asmatrix(Y)
  333. return Y
  334. def _rmatmat(self, X):
  335. """Default implementation of _rmatmat defers to rmatvec or adjoint."""
  336. if type(self)._adjoint == LinearOperator._adjoint:
  337. return np.hstack([self.rmatvec(col.reshape(-1, 1)) for col in X.T])
  338. else:
  339. return self.H.matmat(X)
  340. def __call__(self, x):
  341. return self@x
  342. def __mul__(self, x):
  343. return self.dot(x)
  344. def __truediv__(self, other):
  345. if not np.isscalar(other):
  346. raise ValueError("Can only divide a linear operator by a scalar.")
  347. return _ScaledLinearOperator(self, 1.0/other)
  348. def dot(self, x):
  349. """Matrix-matrix or matrix-vector multiplication.
  350. Parameters
  351. ----------
  352. x : array_like
  353. 1-d or 2-d array, representing a vector or matrix.
  354. Returns
  355. -------
  356. Ax : array
  357. 1-d or 2-d array (depending on the shape of x) that represents
  358. the result of applying this linear operator on x.
  359. """
  360. if isinstance(x, LinearOperator):
  361. return _ProductLinearOperator(self, x)
  362. elif np.isscalar(x):
  363. return _ScaledLinearOperator(self, x)
  364. else:
  365. if not issparse(x) and not is_pydata_spmatrix(x):
  366. # Sparse matrices shouldn't be converted to numpy arrays.
  367. x = np.asarray(x)
  368. if x.ndim == 1 or x.ndim == 2 and x.shape[1] == 1:
  369. return self.matvec(x)
  370. elif x.ndim == 2:
  371. return self.matmat(x)
  372. else:
  373. raise ValueError(f'expected 1-d or 2-d array or matrix, got {x!r}')
  374. def __matmul__(self, other):
  375. if np.isscalar(other):
  376. raise ValueError("Scalar operands are not allowed, "
  377. "use '*' instead")
  378. return self.__mul__(other)
  379. def __rmatmul__(self, other):
  380. if np.isscalar(other):
  381. raise ValueError("Scalar operands are not allowed, "
  382. "use '*' instead")
  383. return self.__rmul__(other)
  384. def __rmul__(self, x):
  385. if np.isscalar(x):
  386. return _ScaledLinearOperator(self, x)
  387. else:
  388. return self._rdot(x)
  389. def _rdot(self, x):
  390. """Matrix-matrix or matrix-vector multiplication from the right.
  391. Parameters
  392. ----------
  393. x : array_like
  394. 1-d or 2-d array, representing a vector or matrix.
  395. Returns
  396. -------
  397. xA : array
  398. 1-d or 2-d array (depending on the shape of x) that represents
  399. the result of applying this linear operator on x from the right.
  400. Notes
  401. -----
  402. This is copied from dot to implement right multiplication.
  403. """
  404. if isinstance(x, LinearOperator):
  405. return _ProductLinearOperator(x, self)
  406. elif np.isscalar(x):
  407. return _ScaledLinearOperator(self, x)
  408. else:
  409. if not issparse(x) and not is_pydata_spmatrix(x):
  410. # Sparse matrices shouldn't be converted to numpy arrays.
  411. x = np.asarray(x)
  412. # We use transpose instead of rmatvec/rmatmat to avoid
  413. # unnecessary complex conjugation if possible.
  414. if x.ndim == 1 or x.ndim == 2 and x.shape[0] == 1:
  415. return self.T.matvec(x.T).T
  416. elif x.ndim == 2:
  417. return self.T.matmat(x.T).T
  418. else:
  419. raise ValueError(f'expected 1-d or 2-d array or matrix, got {x!r}')
  420. def __pow__(self, p):
  421. if np.isscalar(p):
  422. return _PowerLinearOperator(self, p)
  423. else:
  424. return NotImplemented
  425. def __add__(self, x):
  426. if isinstance(x, LinearOperator):
  427. return _SumLinearOperator(self, x)
  428. else:
  429. return NotImplemented
  430. def __neg__(self):
  431. return _ScaledLinearOperator(self, -1)
  432. def __sub__(self, x):
  433. return self.__add__(-x)
  434. def __repr__(self):
  435. M,N = self.shape
  436. if self.dtype is None:
  437. dt = 'unspecified dtype'
  438. else:
  439. dt = 'dtype=' + str(self.dtype)
  440. return f'<{M}x{N} {self.__class__.__name__} with {dt}>'
  441. def adjoint(self):
  442. """Hermitian adjoint.
  443. Returns the Hermitian adjoint of self, aka the Hermitian
  444. conjugate or Hermitian transpose. For a complex matrix, the
  445. Hermitian adjoint is equal to the conjugate transpose.
  446. Can be abbreviated self.H instead of self.adjoint().
  447. Returns
  448. -------
  449. A_H : LinearOperator
  450. Hermitian adjoint of self.
  451. """
  452. return self._adjoint()
  453. H = property(adjoint)
  454. def transpose(self):
  455. """Transpose this linear operator.
  456. Returns a LinearOperator that represents the transpose of this one.
  457. Can be abbreviated self.T instead of self.transpose().
  458. """
  459. return self._transpose()
  460. T = property(transpose)
  461. def _adjoint(self):
  462. """Default implementation of _adjoint; defers to rmatvec."""
  463. return _AdjointLinearOperator(self)
  464. def _transpose(self):
  465. """ Default implementation of _transpose; defers to rmatvec + conj"""
  466. return _TransposedLinearOperator(self)
  467. class _CustomLinearOperator(LinearOperator):
  468. """Linear operator defined in terms of user-specified operations."""
  469. def __init__(self, shape, matvec, rmatvec=None, matmat=None,
  470. dtype=None, rmatmat=None):
  471. super().__init__(dtype, shape)
  472. self.args = ()
  473. self.__matvec_impl = matvec
  474. self.__rmatvec_impl = rmatvec
  475. self.__rmatmat_impl = rmatmat
  476. self.__matmat_impl = matmat
  477. self._init_dtype()
  478. def _matmat(self, X):
  479. if self.__matmat_impl is not None:
  480. return self.__matmat_impl(X)
  481. else:
  482. return super()._matmat(X)
  483. def _matvec(self, x):
  484. return self.__matvec_impl(x)
  485. def _rmatvec(self, x):
  486. func = self.__rmatvec_impl
  487. if func is None:
  488. raise NotImplementedError("rmatvec is not defined")
  489. return self.__rmatvec_impl(x)
  490. def _rmatmat(self, X):
  491. if self.__rmatmat_impl is not None:
  492. return self.__rmatmat_impl(X)
  493. else:
  494. return super()._rmatmat(X)
  495. def _adjoint(self):
  496. return _CustomLinearOperator(shape=(self.shape[1], self.shape[0]),
  497. matvec=self.__rmatvec_impl,
  498. rmatvec=self.__matvec_impl,
  499. matmat=self.__rmatmat_impl,
  500. rmatmat=self.__matmat_impl,
  501. dtype=self.dtype)
  502. class _AdjointLinearOperator(LinearOperator):
  503. """Adjoint of arbitrary Linear Operator"""
  504. def __init__(self, A):
  505. shape = (A.shape[1], A.shape[0])
  506. super().__init__(dtype=A.dtype, shape=shape)
  507. self.A = A
  508. self.args = (A,)
  509. def _matvec(self, x):
  510. return self.A._rmatvec(x)
  511. def _rmatvec(self, x):
  512. return self.A._matvec(x)
  513. def _matmat(self, x):
  514. return self.A._rmatmat(x)
  515. def _rmatmat(self, x):
  516. return self.A._matmat(x)
  517. class _TransposedLinearOperator(LinearOperator):
  518. """Transposition of arbitrary Linear Operator"""
  519. def __init__(self, A):
  520. shape = (A.shape[1], A.shape[0])
  521. super().__init__(dtype=A.dtype, shape=shape)
  522. self.A = A
  523. self.args = (A,)
  524. def _matvec(self, x):
  525. # NB. np.conj works also on sparse matrices
  526. return np.conj(self.A._rmatvec(np.conj(x)))
  527. def _rmatvec(self, x):
  528. return np.conj(self.A._matvec(np.conj(x)))
  529. def _matmat(self, x):
  530. # NB. np.conj works also on sparse matrices
  531. return np.conj(self.A._rmatmat(np.conj(x)))
  532. def _rmatmat(self, x):
  533. return np.conj(self.A._matmat(np.conj(x)))
  534. def _get_dtype(operators, dtypes=None):
  535. if dtypes is None:
  536. dtypes = []
  537. for obj in operators:
  538. if obj is not None and hasattr(obj, 'dtype'):
  539. dtypes.append(obj.dtype)
  540. return np.result_type(*dtypes)
  541. class _SumLinearOperator(LinearOperator):
  542. def __init__(self, A, B):
  543. if not isinstance(A, LinearOperator) or \
  544. not isinstance(B, LinearOperator):
  545. raise ValueError('both operands have to be a LinearOperator')
  546. if A.shape != B.shape:
  547. raise ValueError(f'cannot add {A} and {B}: shape mismatch')
  548. self.args = (A, B)
  549. super().__init__(_get_dtype([A, B]), A.shape)
  550. def _matvec(self, x):
  551. return self.args[0].matvec(x) + self.args[1].matvec(x)
  552. def _rmatvec(self, x):
  553. return self.args[0].rmatvec(x) + self.args[1].rmatvec(x)
  554. def _rmatmat(self, x):
  555. return self.args[0].rmatmat(x) + self.args[1].rmatmat(x)
  556. def _matmat(self, x):
  557. return self.args[0].matmat(x) + self.args[1].matmat(x)
  558. def _adjoint(self):
  559. A, B = self.args
  560. return A.H + B.H
  561. class _ProductLinearOperator(LinearOperator):
  562. def __init__(self, A, B):
  563. if not isinstance(A, LinearOperator) or \
  564. not isinstance(B, LinearOperator):
  565. raise ValueError('both operands have to be a LinearOperator')
  566. if A.shape[1] != B.shape[0]:
  567. raise ValueError(f'cannot multiply {A} and {B}: shape mismatch')
  568. super().__init__(_get_dtype([A, B]),
  569. (A.shape[0], B.shape[1]))
  570. self.args = (A, B)
  571. def _matvec(self, x):
  572. return self.args[0].matvec(self.args[1].matvec(x))
  573. def _rmatvec(self, x):
  574. return self.args[1].rmatvec(self.args[0].rmatvec(x))
  575. def _rmatmat(self, x):
  576. return self.args[1].rmatmat(self.args[0].rmatmat(x))
  577. def _matmat(self, x):
  578. return self.args[0].matmat(self.args[1].matmat(x))
  579. def _adjoint(self):
  580. A, B = self.args
  581. return B.H @ A.H
  582. class _ScaledLinearOperator(LinearOperator):
  583. def __init__(self, A, alpha):
  584. if not isinstance(A, LinearOperator):
  585. raise ValueError('LinearOperator expected as A')
  586. if not np.isscalar(alpha):
  587. raise ValueError('scalar expected as alpha')
  588. if isinstance(A, _ScaledLinearOperator):
  589. A, alpha_original = A.args
  590. # Avoid in-place multiplication so that we don't accidentally mutate
  591. # the original prefactor.
  592. alpha = alpha * alpha_original
  593. dtype = _get_dtype([A], [type(alpha)])
  594. super().__init__(dtype, A.shape)
  595. self.args = (A, alpha)
  596. # Note: args[1] is alpha (a scalar), so use `*` below, not `@`
  597. def _matvec(self, x):
  598. return self.args[1] * self.args[0].matvec(x)
  599. def _rmatvec(self, x):
  600. return np.conj(self.args[1]) * self.args[0].rmatvec(x)
  601. def _rmatmat(self, x):
  602. return np.conj(self.args[1]) * self.args[0].rmatmat(x)
  603. def _matmat(self, x):
  604. return self.args[1] * self.args[0].matmat(x)
  605. def _adjoint(self):
  606. A, alpha = self.args
  607. return A.H * np.conj(alpha)
  608. class _PowerLinearOperator(LinearOperator):
  609. def __init__(self, A, p):
  610. if not isinstance(A, LinearOperator):
  611. raise ValueError('LinearOperator expected as A')
  612. if A.shape[0] != A.shape[1]:
  613. raise ValueError(f'square LinearOperator expected, got {A!r}')
  614. if not isintlike(p) or p < 0:
  615. raise ValueError('non-negative integer expected as p')
  616. super().__init__(_get_dtype([A]), A.shape)
  617. self.args = (A, p)
  618. def _power(self, fun, x):
  619. res = np.array(x, copy=True)
  620. for i in range(self.args[1]):
  621. res = fun(res)
  622. return res
  623. def _matvec(self, x):
  624. return self._power(self.args[0].matvec, x)
  625. def _rmatvec(self, x):
  626. return self._power(self.args[0].rmatvec, x)
  627. def _rmatmat(self, x):
  628. return self._power(self.args[0].rmatmat, x)
  629. def _matmat(self, x):
  630. return self._power(self.args[0].matmat, x)
  631. def _adjoint(self):
  632. A, p = self.args
  633. return A.H ** p
  634. class MatrixLinearOperator(LinearOperator):
  635. def __init__(self, A):
  636. super().__init__(A.dtype, A.shape)
  637. self.A = A
  638. self.__adj = None
  639. self.args = (A,)
  640. def _matmat(self, X):
  641. return self.A.dot(X)
  642. def _adjoint(self):
  643. if self.__adj is None:
  644. self.__adj = _AdjointMatrixOperator(self.A)
  645. return self.__adj
  646. class _AdjointMatrixOperator(MatrixLinearOperator):
  647. def __init__(self, adjoint_array):
  648. self.A = adjoint_array.T.conj()
  649. self.args = (adjoint_array,)
  650. self.shape = adjoint_array.shape[1], adjoint_array.shape[0]
  651. @property
  652. def dtype(self):
  653. return self.args[0].dtype
  654. def _adjoint(self):
  655. return MatrixLinearOperator(self.args[0])
  656. class IdentityOperator(LinearOperator):
  657. def __init__(self, shape, dtype=None):
  658. super().__init__(dtype, shape)
  659. def _matvec(self, x):
  660. return x
  661. def _rmatvec(self, x):
  662. return x
  663. def _rmatmat(self, x):
  664. return x
  665. def _matmat(self, x):
  666. return x
  667. def _adjoint(self):
  668. return self
  669. def aslinearoperator(A):
  670. """Return A as a LinearOperator.
  671. 'A' may be any of the following types:
  672. - ndarray
  673. - matrix
  674. - sparse array (e.g. csr_array, lil_array, etc.)
  675. - LinearOperator
  676. - An object with .shape and .matvec attributes
  677. See the LinearOperator documentation for additional information.
  678. Notes
  679. -----
  680. If 'A' has no .dtype attribute, the data type is determined by calling
  681. :func:`LinearOperator.matvec()` - set the .dtype attribute to prevent this
  682. call upon the linear operator creation.
  683. Examples
  684. --------
  685. >>> import numpy as np
  686. >>> from scipy.sparse.linalg import aslinearoperator
  687. >>> M = np.array([[1,2,3],[4,5,6]], dtype=np.int32)
  688. >>> aslinearoperator(M)
  689. <2x3 MatrixLinearOperator with dtype=int32>
  690. """
  691. if isinstance(A, LinearOperator):
  692. return A
  693. elif isinstance(A, np.ndarray) or isinstance(A, np.matrix):
  694. if A.ndim > 2:
  695. raise ValueError('array must have ndim <= 2')
  696. A = np.atleast_2d(np.asarray(A))
  697. return MatrixLinearOperator(A)
  698. elif issparse(A) or is_pydata_spmatrix(A):
  699. return MatrixLinearOperator(A)
  700. else:
  701. if hasattr(A, 'shape') and hasattr(A, 'matvec'):
  702. rmatvec = None
  703. rmatmat = None
  704. dtype = None
  705. if hasattr(A, 'rmatvec'):
  706. rmatvec = A.rmatvec
  707. if hasattr(A, 'rmatmat'):
  708. rmatmat = A.rmatmat
  709. if hasattr(A, 'dtype'):
  710. dtype = A.dtype
  711. return LinearOperator(A.shape, A.matvec, rmatvec=rmatvec,
  712. rmatmat=rmatmat, dtype=dtype)
  713. else:
  714. raise TypeError('type not understood')