Butterfly module#

Preamble#

This module gathers utilities to manipulate and create a particular family of LazyLinOp associated to matrices with the so-called butterfly structure, i.e., which are expressed as a product of a few compatible Kronecker-Sparse factors. Classical examples of such operators are the Hadamard transform and the Discrete-Fourier-Transform.

Construction of a butterfly LazyLinOp from a given array.

The main function of the module is ksd() (Kronecker-sparse decomposition), which computes a near best approximation of a given array or of a LazyLinOp by an operator with a prescribed butterfly structure [1].

Example: Consider an \(N\times N\) Hadamard matrix (with \(N\) a power of two):

>>> import scipy as sp
>>> H = sp.linalg.hadamard(N)

Turning this NumPy array into an efficient butterfly implementation requires a simple call L = ksd(H, chain) where chain is a Chain object specifying the nature of the Kronecker-sparse factors involved in the decomposition. The classical chain associated to the Hadamard matrix is square-dyadic, and can be retrieved as follows:

>>> chain = Chain.square_dyadic(H.shape)
>>> L = ksd(H, chain)

It is also possible to use other chains (see below), leading to implementations with different tradeoffs between memory consumption, energy consumption and computational speed.

>>> chain2 = Chain.monarch(H.shape, ...)
>>> L2 = ksd(H, chain2)

Construction of individual or multiple Kronecker-sparse factors.

Under the hood, the operator L resulting from a call to ksd() is a (lazy) product of Kronecker-sparse factors, each of them benefitting from an optimized implementation on various backends via the function ksm() (Kronecker-sparse multiplication operator). A single Kronecker-sparse factor is a structure determined by a 4D array \(T\) of shape (a, b, c, d), and is fully determined as L = ksm(T) given a 4-dimensional array of values \(T_{i,j,k,l}\) of size \(a\times b\times c\times d\). The shape of L is then \(abd\times acd\), and converting it to an array would yield a structured sparse matrix with support (the set of possible nonzero entries) \(I_a\otimes 1_{b\times c}\otimes I_d\). See [1] and the documentation of ksm() for further details and illustrations.

Implementation parameters.

Options of ksm() (and of ksd()) notably allow to use either the CPU or the GPU with various implementation parameters, or to directly build a lazy product of Kronecker-sparse factors L = ksm([T1, ..., Tn], ...) to minimize memory movements between CPU and GPU when computing L @ x.

Saving and loading butterfly operators.

The LazyLinOp resulting from a call to ksm() or ksd() can be saved to disk (as a .json file) and load using:

>>> lazylinop.butterfly.save(L, 'filename')
>>> L = lazylinop.butterfly.load('filename')

Plot butterfly operators.

The LazyLinOp resulting from a call to ksm() or ksd() can be plotted or saved to disk (as a .png file and a .svg file) using:

>>> N = 16
>>> L = lazylinop.butterfly.dft(N)
>>> lazylinop.butterfly.plot(L)
>>> lazylinop.butterfly.plot(L, "dft_16x16")

It is also possible to save to disk as a MATLAB-style file and load using:

>>> lazylinop.butterfly.savemat(L, 'filename')
>>> L = lazylinop.butterfly.loadmat('filename')

Pre-built Discrete-Fourier-Transform.

We provide dft() a pre-built LazyLinOp L = B @ P with the Butterfly structure B multiplied by a bit-reversal permutation P corresponding to the Discrete-Fourier-Transform [2]. The L corresponding to a DFT of a signal of size \(256\) with \(8\) factors (square-dyadic decomposition) is given by:

>>> L = lazylinop.butterfly.dft(256)

Pre-built Fast-Walsh-Hadamard-Transform.

We provide fwht() a pre-built LazyLinOp L with the Butterfly structure corresponding to the Fast-Walsh-Hadamard-Transform (FWHT). The L corresponding to a FWHT of a signal of size \(256\) with \(8\) factors (square-dyadic decomposition) is given by:

>>> L = lazylinop.butterfly.fwht(256)

Chains and their manipulation.

A chain encodes the structure of the Butterfly operator L and corresponds to a sequence of tuples

\[\begin{equation} \left(\left(a_l,~b_l,~c_l,~d_l\right)\right)_{l=1}^n \end{equation}\]

such that Kronecker-sparse operators \(L_l\) with the corresponding structure have compatible sizes, i.e. such that the product \(L = L_1\cdots L_n\) is well-defined. The shape of \(L\) is given by the attribute chain.shape. The concatenation of compatible chains is implemented via chain = chain1 @ chain2. Specifying it explicitly is simple:

>>> chain = Chain([(a1, b1, c1, d1), ..., (an, bn, cn, dn)])

The most standard chain is probably the so-called square-dyadic chain, which is behind usual fast implementations of the Hadamard transform and of DFTs. It is only defined when \(\mathtt{shape}=\left(N,~N\right)\) with \(N\) a power of two as:

>>> sd_chain = Chain.square_dyadic(shape)

Another common chain with arbitrary non-prime shape is Monarch chain with two factors.

>>> chain = Chain.monarch(shape, ...)

You can visualize the structure of all Kronecker-sparse factors in these chains as follows:

>>> sd_chain.plot()
Output file of ``sd_chain.plot("square_dyadic")``.
>>> chain.plot()
Output file of ``chain.plot("monarch")``.

and anticipate the memory footprint of the corresponding operators:

>>> sd_chain = Chain.square_dyadic((32, 32))
>>> sd_chain.mem(np.float32)
1280
>>> chain = Chain.monarch((32, 32))
>>> chain.mem(np.float32)
1536

As you can see, the memory footprint of a monarch chain is higher than that of a square-dyadic one, but when it fits in the memory of a GPUs it can lead to a faster implementation.

Chainability.

This above chains satisfy a “chainability” property, which is crucial to ensure that ksd() can be run, with approximation guarantees [1]. Chainability can be checked using the attribute chain.chainability, and ksd() will generate an error if the provided chain is not chainable.

References#

[1] Butterfly Factorization with Error Guarantees. Leon Zheng, Quoc-Tung Le, Elisa Riccietti, and Remi Gribonval https://hal.science/hal-04763712v1/document

[2] Learning Fast Algorithms for Linear Transforms Using Butterfly Factorizations. Dao T, Gu A, Eichhorn M, Rudra A, Re C. Proc Mach Learn Res. 2019 Jun;97:1517-1527. PMID: 31777847; PMCID: PMC6879380.

Butterfly construction#

lazylinop.butterfly.ksm(ks_values, ksm_args=None)[source]#

Returns a specialization L of LazyLinOp for Kronecker Sparse Matrix Multiplication (KSMM see [1]). The sparsity pattern (or support) of a Kronecker-Sparse factor is defined as \(I_a\otimes 1_{b,c}\otimes I_d\) while its values are given by either a 4D NumPy, CuPy array or torch tensor of shape (a, b, c, d).

The shape of L is \(\left(abd,~acd\right)\).

To fill a ks_values and its Kronecker-Sparse factor M:

M = np.zeros((a * b * d, a * c * d), dtype=np.float32)
ks_values = np.empty((a, b, c, d), dtype=M.dtype)
for i in range(a):
    for j in range(b):
        for k in range(c):
            for l in range(d):
                tmp = np.random.randn()
                ks_values[i, j, k, l] = tmp
                M[i * b * d + j * d + l,
                  i * c * d + k * d + l] = tmp

For a = 3, b = 3, c = 5, d = 5 we have the following pattern.

_images/abcd.svg

Note

You can access a copy of the ks_values of L = ksm(...) using L.ks_values.

With OpenCL and CUDA backend, L @ X will implicitly cast X to:

  • match the dtype of L.ks_values

  • be of contiguous type

This can incur a loss of performance, as-well-as a loss of precision if the dtype of X was initially of higher precision than that of L.ks_values.

Args:
ks_values: CuPy/NumPy arrays, torch tensors or list of arrays

It could be:

  • A 4D array of values of the Kronecker-Sparse factor.

  • List of values of the Kronecker-Sparse factors. The length of the list corresponds to the number of Kronecker-Sparse factors.

The dtype of each ks_values is either torch.float8_e5m2, torch.float8_e4m3fn, torch.bfloat16 (torch only), 'float16', 'float32', 'float64', 'complex64' or 'complex128'. All the ks_values must have the same device. See code above for details on the expected indexing of ks_values.

The chain infered by the shape of ks_values must be valid and chainable.

ksm_args: dict, optional

A dict with two keys: 'backend' and 'params'.

The available backends depend on the namespace (see array-api-compat for more details) of the ks_values. By default, use a namespace-based implementation.

  • For torch namespace:

    • {'backend': 'ksmm'} to run the algorithm of [1]. It uses a CUDA device determined by ks_values and relies on torch.utils.cpp_extension.load_inline.

    • {'backend': 'torch_sparse'} uses torch.sparse_csr_tensor.

  • For cupy namespace:

    • {'backend': 'ksmm'} to run the algorithm of [1]. It uses a CUDA device determined by ks_values (must be on GPU) and relies on cp.RawModule.

    • {'backend': 'cupyx'} uses the cupyx.scipy.sparse.csr_matrix function.

  • For numpy namespace:

    • {'backend': 'scipy'} uses the SciPy sparse functions scipy.sparse.block_diag and scipy.sparse.csr_matrix.

    • {'backend': (platform, device)} to use OpenCL to run the algorithm of [1].

      • (None, None) uses the first platform and device.

      • (None, 'cpu') use the first platform and CPU device.

      • (None, 'gpu') use the first platform and GPU device.

      Please consider the following piece of code for advanced choices:

      import pyopencl as cl
      # Get your favorite platform.
      platform = cl.get_platforms()[pl_id]
      # To get your favorite CPU device.
      device = platform.get_devices(device_type=cl.device_type.CPU)[dev_id]
      # To get your favorite GPU device.
      device = platform.get_devices(device_type=cl.device_type.GPU)[dev_id]
      

      To check platforms and devices of your system you can also run the command line clinfo -a. See PyOpenCL documentation for more details.

    • {'backend': pycuda.driver.Device(id)} uses a CUDA device to run the algorithm of [1]. See PyCUDA documentation for more details.

Argument params only works for OpenCL and CUDA backends. By default, it automatically chooses the values of params. It could be:

  • A tuple params of tuples where params[0] and params[1] expect a tuple of ten elements (TILEX, TILEK, TILEY, TX, TY, VSIZE, WARP_TILEX, WARP_TILEY, WARP_TX, WARP_TY) (see [1] for more details). Do not use warp-tiling if WARP_TILEX = WARP_TX = WARP_TILEY = WARP_TY = None. If (None, None) (default), the choice of hyper-parameters for multiplication L @ X and the multiplication L.H @ X is automatic. Because we did not run a fine-tuning for all the possible \(\left(a,~b,~c,~d\right)\) and \(\left(a,~c,~b,~d\right)\) tuples, automatic does not always correspond to the best choice.

  • List of tuple of length the number of factors. params[i][0] and params[i][1] expect a tuple of ten elements (TILEX, TILEK, TILEY, TX, TY, VSIZE, WARP_TILEX, WARP_TILEY, WARP_TX, WARP_TY) (see [1] for more details). Do not use warp-tiling if WARP_TILEX = WARP_TX = WARP_TILEY = WARP_TY = None. See How to Optimize a CUDA Matmul Kernel for cuBLAS-like Performance: a Worklog for more details about warp-tiling. If None (default), the choice of hyper-parameters for multiplication L @ X and the multiplication L.H @ X is automatic. Because we did not run a fine-tuning for all the possible \(\left(a,~b,~c,~d\right)\) and \(\left(a,~c,~b,~d\right)\) tuples, automatic does not always correspond to the best choice.

List of assertions the tuple (TILEX, TILEK, TILEY, TX, TY, VSIZE) must satisfy:

  • TILEX = X * TX

  • TILEY = Y * TY

  • batch size % TILEX == 0 for performance reason. Consider zero-padding of the batch.

  • TILEX < batch size

  • TILEK <= c and c % TILEK == 0 for performance reason.

  • TILEX > TILEK and TILEY > TILEK

  • (VSIZE * X * Y) % TILEX == 0

  • TILEK % strideInput == 0

  • (VSIZE * X * Y) % TILEK == 0

  • TILEY % strideValues == 0

  • TILEY <= b

  • (b * d) % (d * TILEY) == 0

  • ks_values.dtype.itemsize * 2 * (TILEY * TILEK + TILEK * TILEX) < smem

where smem is the shared memory of the hardware used to compute, VSIZE ranges from \(1\) to \(4\), strideValues = VSIZE * X * Y / TILEK and strideInput = VSIZE * X * Y / TILEX.

Returns:

An instance L of lazylinop.butterfly.KsmLazyLinOp class that is a specialization of LazyLinOp for Kronecker Sparse Matrix Multiplication (KSMM). You can access a copy of the ks-values (resp. the chain) of L using L.ks_values (resp. L.chain).

Examples:
>>> from lazylinop.butterfly.ksm import ksm
>>> import numpy as np
>>> a, b, c, d = 2, 4, 3, 2
>>> ks_values = np.full((a, b, c, d), 1.0, dtype=np.float32)
>>> L = ksm(ks_values)
>>> L.toarray(dtype='float')
array([[1., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
       [0., 1., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0.],
       [1., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
       [0., 1., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0.],
       [1., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
       [0., 1., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0.],
       [1., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
       [0., 1., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 1., 0.],
       [0., 0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 1.],
       [0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 1., 0.],
       [0., 0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 1.],
       [0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 1., 0.],
       [0., 0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 1.],
       [0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 1., 0.],
       [0., 0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 1.]])
>>> # List of Kronecker-Sparse factors.
>>> a1, b1, c1, d1 = 2, 4, 3, 3
>>> ks_values1 = np.full((a1, b1, c1, d1), 1.0, dtype=np.float32)
>>> a2, b2, c2, d2 = 3, 3, 5, 2
>>> ks_values2 = np.full((a2, b2, c2, d2), 1.0, dtype=np.float32)
>>> L = ksm(ks_values1) @ ksm(ks_values2)
>>> M = ksm([ks_values1, ks_values2])
>>> np.allclose(L.toarray(dtype='float'), M.toarray(dtype='float'))
True

References:

[1] Fast inference with Kronecker-sparse matrices. Antoine Gonon and Léon Zheng and Pascal Carrivain and Quoc-Tung Le https://arxiv.org/abs/2405.15013

Decomposition#

  1. lazylinop.butterfly.ksd()

  2. lazylinop.butterfly.suksd()

lazylinop.butterfly.ksd(A, chain, ortho=True, order='l2r', svd_backend=None, ksm_args=None)[source]#

Returns a lazylinop.butterfly.KsmLazyLinOp corresponding to the (often called “butterfly”) factorization of A into Kronecker-sparse factors with sparsity patterns determined by a chainable instance chain of Chain.

L = ksd(...) returns a lazylinop.butterfly.KsmLazyLinOp corresponding to the factorization of A where L = ksm(...) @ ksm(...) @ ... @ ksm(...).

Note

L.ks_values contains the ks_values of the factorization (see ksm() for more details).

As an example, the DFT matrix is factorized as follows:

M = 16
# Build DFT matrix using lazylinop.signal.fft function.
from lazylinop.signal import fft
V = fft(M).toarray()
# Use square-dyadic decomposition.
sd_chain = Chain.square dyadic(V.shape)
# Multiply the DFT matrix with the bit-reversal permutation matrix.
from lazylinop.basicops import bitrev
P = bitrev(M)
L = ksd(V @ P.T, chain=sd_chain)
Args:
A: np.ndarray, cp.array, torch.Tensor or LazyLinOp

Matrix or LazyLinOp to factorize. when A is a small LazyLinOp it is often faster to perform ksd(A.toarray(), ...) than ksd(A, ...) if the dense array A.toarray() fits in memory.

chain: Chain

Chainable instance of the Chain class. See Chain documentation for more details.

ortho: bool, optional

Whether to use orthonormalisation or not during the algorithm, see [1] for more details. Default is True.

order: str, optional

Determines in which order partial factorizations are performed, see [1] for more details.

  • 'l2r' Left-to-right decomposition (default).

  • 'balanced'

svd_backend: str, optional

See documentation of linalg.svds() for more details.

ksm_args: optional

See lazylinop.butterfly.ksm() for more details.

Returns:

L is a lazylinop.butterfly.KsmLazyLinOp that corresponds to the product of chain.n_patterns lazylinop.butterfly.KsmLazyLinOp Kronecker-sparse factors.

The namespace and device of the ks_values of all factors are determined as follows:

  • If A is an array (or aslazylinop(array)) then its namespace and device are used

  • otherwize, svd_backend determines the namespace and device

See also

References:

[1] Butterfly Factorization with Error Guarantees. Léon Zheng, Quoc-Tung Le, Elisa Riccietti, and Rémi Gribonval https://hal.science/hal-04763712v1/document

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import Chain, ksd
>>> from lazylinop.basicops import bitrev
>>> from lazylinop.signal import fft
>>> N = 256
>>> M = N
>>> V = fft(M).toarray()
>>> chain = Chain.square_dyadic(V.shape)
>>> # Use bit reversal permutations matrix.
>>> P = bitrev(N)
>>> approx = (ksd(V @ P.T, chain) @ P).toarray()
>>> error = np.linalg.norm(V - approx) / np.linalg.norm(V)
>>> np.allclose(error, 0.0)
True
lazylinop.butterfly.suksd(A, chain, rtol=1e-06, max_iter=100, svd_backend=None, ksm_args=None, verbose=True)[source]#

Return a LazyLinOp approximating A by a sum of Kronecker-Sparse decompositions.

Args:
A: CuPy/NumPy array, torch tensor or LazyLinOp

Matrix or LazyLinOp to factorize. when A is a small LazyLinOp it is often faster to perform suksd(A.toarray(), ...) than suksd(A, ...) if the dense array A.toarray() fits in memory.

chain: Chain

Chainable instance of the Chain class. See lazylinop.butterfly.Chain documentation for more details.

rtol: float, optional

Stop if the residual Frobenius norm of A - approx divided by the Frobenius norm of A is smaller than rtol.

max_iter: int, optional

Stop if the number of iterations is greater than max_iter.

svd_backend: optional

See lazylinop.butterfly.ksd() for more details.

ksm_args: optional

See lazylinop.butterfly.ksm() for more details.

verbose: bool, optional

Print number of iterations and relative error.

Returns:

A tuple (L, residual, rerr) where L is a LazyLinOp resulting from the approximation of A, residual is an array given by A - L.toarray(...) and rerr is the list of relative errors. The array namespace of residual is equal to:

  • the array namespace of A if A is an array.

  • NumPy if L is a LazyLinOp.

The length of rerr is the number of iterations of the algorithm.

Examples:
>>> from lazylinop.butterfly.suksd import suksd
>>> from lazylinop.butterfly import Chain
>>> import numpy as np
>>> N = 16
>>> A = np.random.randn(N, N)
>>> chain = Chain.monarch((N, N))
>>> L, res, rerr = suksd(A, chain, 1e-6, 100, verbose=False)
>>> bool(rerr[-1] < 1e-6 or len(rerr) == 100)
True

Signal processing#

  1. lazylinop.butterfly.dft()

  2. lazylinop.butterfly.fwht()

  3. lazylinop.butterfly.hadamard()

  4. lazylinop.butterfly.fnt()

  5. lazylinop.butterfly.dct()

  6. lazylinop.butterfly.dst()

  7. lazylinop.butterfly.nudft()

  8. lazylinop.butterfly.fkt()

  9. lazylinop.butterfly.fot()

lazylinop.butterfly.dft(N, dtype='complex128', device='cpu', ksm_args=None, output='F')[source]#

Return a LazyLinOp F = B @ P with the Butterfly structure \(\mathbf{B}\) corresponding to the Discrete-Fourier-Transform (DFT) multiplied by a bit-reversal permutation operator \(\mathbf{P}\).

Shape of F is \(\left(N,~N\right)\) where \(N=2^n\) must be a power of two.

Args:
N: int

Size of the DFT. \(N\) must be a power of two.

dtype, device: optional

dtype and device of the ks-values F.ks_values. Default values are 'complex128' and 'cpu'. Infer the namespace (see array-api-compat for more details) of F.ks_values from dtype and device arguments. By default, namespace of F.ks_values is numpy.

ksm_args: optional

See lazylinop.butterfly.ksm() for more details.

output: str, optional
  • output = 'F' (default value) returns a KsmLazyLinOp F = B @ P corresponding to the Discrete-Fourier-Transform.

  • output = 'BP' returns a tuple (B, P) corresponding to \(\mathbf{B}\) and \(\mathbf{P}\). User can reconstruct an optimized DFT using optimize(B, ...) @ P.

Returns:

Depending on the value of argument output return either a KsmLazyLinOp or a tuple (B, P) where B is a KsmLazyLinOp and P a LazyLinOp.

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import dft as bdft
>>> from lazylinop.signal import dft as sdft
>>> N = 2 ** 5
>>> x = np.random.randn(N).astype('float64')
>>> y = bdft(N) @ x
>>> z = sdft(N) @ x
>>> np.allclose(y, z)
True
>>> # Example of ksm_args usage.
>>> ksm_args = {'backend': 'xp'}
>>> B, P = bdft(N, dtype='complex128', ksm_args=ksm_args, output='BP')
>>> 'complex128' in str(B.ks_values[0].dtype)
True
>>> F = B @ P
>>> np.allclose(F @ x, z)
True
>>> # Optimize the DFT.
>>> from lazylinop.butterfly import optimize
>>> opt_args = {'dtype': 'float64', "batch_size": 8, 'verbose': False}
>>> B_opt = optimize(B, opt_args=opt_args)
>>> F_opt = B_opt @ P
>>> np.allclose(F_opt @ x, z)
True
References:
  • Learning Fast Algorithms for Linear Transforms Using Butterfly Factorizations.

    Dao T, Gu A, Eichhorn M, Rudra A, Re C. Proc Mach Learn Res. 2019 Jun;97:1517-1527. PMID: 31777847; PMCID: PMC6879380.

lazylinop.butterfly.fwht(N, dtype='float64', device='cpu', ksm_args=None)[source]#

Return a LazyLinOp L with the Butterfly structure corresponding to the Fast-Walsh-Hadamard-Transform (FWHT).

Shape of L is \(\left(N,~N\right)\) where \(N=2^n\) must be a power of two.

L is orthogonal and symmetric and the inverse WHT operator is L.T = L.

Args:
N: int

Size of the FWHT. \(N\) must be a power of two.

dtype, device: optional

dtype (expects floating-point precision) and device of the ks-values L.ks_values. Default values are 'float64' and 'cpu'. Infer the namespace (see array-api-compat for more details) of L.ks_values from dtype and device arguments. By default, namespace of L.ks_values is numpy.

ksm_args: optional

See lazylinop.butterfly.ksm() for more details.

Returns:

LazyLinOp L corresponding to the FWHT. L is equivalent to hadamard(N, ksm_args, dtype) / sqrt(N).

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import fwht as bfwht
>>> from lazylinop.signal import fwht as sfwht
>>> N = 2 ** 5
>>> x = np.random.randn(N).astype('float64')
>>> y = bfwht(N) @ x
>>> z = sfwht(N) @ x
>>> np.allclose(y, z)
True
>>> # Example of ksm_args usage.
>>> ksm_args = {'backend': 'xp'}
>>> L = bfwht(N, dtype='float64', ksm_args=ksm_args)
>>> y = L @ x
>>> np.allclose(y, z)
True
>>> # Optimize FWHT.
>>> from lazylinop.butterfly import optimize
>>> opt_args = {'dtype': 'float64', "batch_size": 8, 'verbose': False}
>>> L_opt = optimize(L, opt_args=opt_args)
>>> np.allclose(L @ x, L_opt @ x)
True
lazylinop.butterfly.hadamard(N, dtype='float64', device='cpu', ksm_args=None)[source]#

Return a LazyLinOp L with the Butterfly structure corresponding to the Hadamard matrix.

Shape of L is \(\left(N,~N\right)\) where \(N=2^n\) must be a power of two.

L is not orthogonal and its inverse is L.T / N. L is symmetric.

The number of factors \(n\) of the square-dyadic decomposition is given by \(n=\log_2\left(N\right)\).

Infer the namespace (see array-api-compat for more details) of L.ks_values from dtype and device arguments. By default, namespace of L.ks_values is numpy and dtype is 'float64'.

Args:
N: int

Size of the Hadamard matrix. \(N\) must be a power of two.

dtype, device: optional

dtype and device of the ks-values L.ks_values. Default values are 'float64' and 'cpu'. Infer the namespace (see array-api-compat for more details) of L.ks_values from dtype and device arguments. By default, namespace of L.ks_values is numpy.

ksm_args: optional

See lazylinop.butterfly.ksm() for more details.

Returns:

LazyLinOp L corresponding to the Hadamard matrix.

Examples:
>>> import numpy as np
>>> import scipy as sp
>>> from lazylinop.butterfly import hadamard
>>> N = 2 ** 5
>>> x = np.random.randn(N).astype('float64')
>>> y = hadamard(N, dtype='int64') @ x
>>> z = sp.linalg.hadamard(N, dtype='int64') @ x
>>> np.allclose(y, z)
True
>>> # Example of ksm_args usage.
>>> ksm_args = {'backend': 'xp'}
>>> L = hadamard(N, dtype='int64', ksm_args=ksm_args)
>>> y = L @ x
>>> np.allclose(y, z)
True
>>> # Optimize hadamard.
>>> from lazylinop.butterfly import optimize
>>> opt_args = {'dtype': 'float64', "batch_size": 8, 'verbose': False}
>>> L_opt = optimize(L, opt_args=opt_args)
>>> np.allclose(L @ x, L_opt @ x)
True
lazylinop.butterfly.fnt(N, dtype='complex128', device='cpu', ksm_args=None, output='F')[source]#

Return a LazyLinOp F = B @ P with the Butterfly structure \(\mathbf{B}\) corresponding to the Fast-Noiselet-Transform (FNT) multiplied by a bit-reversal permutation operator \(\mathbf{P}\) (see [1] for more details).

Shape of F is \(\left(N,~N\right)\) where \(N=2^n\) must be a power of two.

F is orthonormal, and the LazyLinOp for the inverse FNT is F.H.

Args:
N: int

Size of the FNT. \(N\) must be a power of two.

dtype, device: optional

dtype and device of the ks-values F.ks_values. Default values are 'complex128' and 'cpu'. Infer the namespace (see array-api-compat for more details) of F.ks_values from dtype and device arguments. By default, namespace of F.ks_values is numpy.

ksm_args: optional

See lazylinop.butterfly.ksm() for more details.

output: str, optional
  • output = 'F' (default value) returns a KsmLazyLinOp F = B @ P corresponding to the Fast-Noiselet-Transform.

  • output = 'BP' returns a tuple (B, P) corresponding to \(\mathbf{B}\) and \(\mathbf{P}\). User can reconstruct an optimized FNT using optimize(B, ...) @ P.

Returns:

LazyLinOp F corresponding to the FNT.

Examples:
>>> import numpy as np
>>> rng = np.random.default_rng()
>>> from lazylinop.butterfly import fnt as bfnt
>>> from lazylinop.signal import fnt as sfnt
>>> N = 2 ** 5
>>> x = rng.standard_normal((N, 4)).astype('float64')
>>> ksm_args = {'backend': 'xp'}
>>> F = bfnt(N, dtype='complex128', ksm_args=ksm_args)
>>> y = F @ x
>>> z = sfnt(N) @ x
>>> np.allclose(y, z)
True
>>> # F is orthonormal.
>>> np.allclose(F.H @ y, x)
True
>>> # Optimize FNT.
>>> from lazylinop.butterfly import optimize
>>> B, P = bfnt(N, dtype='complex128', ksm_args=ksm_args, output='BP')
>>> 'complex128' in str(B.ks_values[0].dtype)
True
>>> opt_args = {'dtype': 'float64', "batch_size": 4, 'verbose': False}
>>> B_opt = optimize(B, opt_args=opt_args)
>>> F_opt = B_opt @ P
>>> np.allclose(y, F_opt @ x)
True

References:

[1] Noiselets. R. Coifman, F. Geshwind, Y. Meyer https://www.sciencedirect.com/science/article/pii/S1063520300903130

lazylinop.butterfly.dct(N, type=2, dtype='float64', device='cpu', ksm_args=None, output='C')[source]#

Returns a LazyLinOp L for the Direct Cosine Transform (DCT).

Shape of L is \(\left(N,~N\right)\) where \(N=2^n\) must be a power of two except for DCT I (see below).

L is orthonormal, and the LazyLinOp for the inverse DCT is L.T.

According to a seminal paper of Makhoul [1] the DCT matrix of size \(N\) and type 2, \(\mathbf{C}_N\), can be expressed in terms of the DFT matrix of size \(N\), \(\mathbf{B}_N\mathbf{P}_N\). The most well-known expression is as \(\mathbf{C}_N=\mathtt{Re}(\mathbf{L}\mathbf{D}_N\mathbf{B}_N\mathbf{P}_N\mathbf{R})\) where the left and right matrices \(\mathbf{L}\), \(\mathbf{R}\) and bit-reversal permutation \(\mathbf{P}_N\) (of size \(N\times N\)) are real-valued, but the diagonal matrix \(\mathbf{D}_N\) and Butterfly matrix \(\mathbf{B}_N\) are complex-valued.

General expression of DCT of type 1, 3 and 4 is as \(\mathbf{C}_N=\mathtt{Re}(\mathbf{L}\mathbf{B}_M\mathbf{P}_M\mathbf{R})\) where \(\mathbf{L}\), \(\mathbf{R}\) and \(M\) depend on the DCT-type.

Return type:

Union[LazyLinOp, tuple]

Args:
N: int

Size of the input \(N\) must be:

  • a power of two for DCT II, III and IV.

  • a power of two plus one for DCT I.

type: int, optional

1, 2, 3, 4 (I, II, III, IV). Defaut is 2. See SciPy DCT and CuPy DCT for more details.

dtype, device: optional

dtype and device of the ks-values L.ks_values. Default values are 'float64' and 'cpu'. Infer the namespace (see array-api-compat for more details) of L.ks_values from dtype and device arguments. By default, namespace of L.ks_values is numpy.

ksm_args: optional

See lazylinop.butterfly.ksm() for more details.

output: str, optional
  • output = 'C' (default value) returns a LazyLinOp corresponding to \(\mathbf{C}_N\).

  • output = 'LBPR' returns a tuple (L, B, PR) corresponding to \(\mathbf{L}\), \(\mathbf{B}_M\) and \(\mathbf{P}_M\mathbf{R}\). User can reconstruct an optimized DCT using L @ optimize(B, ...) @ PR.

Returns:

Depending on the value of argument output return either a LazyLinOp or a tuple (L, B, PR) where L and PR are LazyLinOp and B is a lazylinop.butterfly.KsmLazyLinOp.

Examples:
>>> from lazylinop.butterfly import dct
>>> from scipy.fft import dct as sp_dct
>>> import numpy as np
>>> rng = np.random.default_rng()
>>> N = 32
>>> x = rng.standard_normal(N)
>>> F = dct(N, 2)
>>> y = F @ x
>>> yref = sp_dct(x, norm='ortho')
>>> np.allclose(y, yref)
True
>>> # compute the inverse DCT
>>> z = F.T @ y
>>> np.allclose(z, x)
True
>>> # To mimick SciPy DCT II norm='ortho' and orthogonalize=False
>>> from lazylinop.basicops import diag
>>> v = np.full(N, 1.0)
>>> v[0] = np.sqrt(2.0)
>>> y = diag(v) @ F @ x
>>> z = sp_dct(x, 2, N, 0, 'ortho', False, 1, orthogonalize=False)
>>> np.allclose(y, z)
True
>>> # Optimize B of the DCT (see the documentation)
>>> from lazylinop.butterfly import optimize
>>> L, B, PR = dct(N, 2, output='LBPR')
>>> opt_args = {"batch_size": 1, 'verbose': False}
>>> B_opt = optimize(B, opt_args=opt_args)
>>> y = (L @ B_opt @ PR) @ x
>>> np.allclose(y, yref)
True

References:

[1] A Fast Cosine Transform in One and Two Dimensions,

by J. Makhoul, IEEE Transactions on acoustics, speech and signal processing vol. 28(1), pp. 27-34, doi:10.1109/TASSP.1980.1163351 (1980).

lazylinop.butterfly.dst(N, type=2, dtype='float64', device='cpu', ksm_args=None, output='S')[source]#

Returns a LazyLinOp L for the Direct Sine Transform (DST).

Shape of L is \(\left(N,~N\right)\) where \(N=2^n\) must be a power of two except for DST I (see below).

L is orthonormal, and the LazyLinOp for the inverse DST is L.T.

DST of type 2 is equivalent to DCT of type 2 with reversed output and each element \(x_i\) of the input \(x\) multiplied by \((-1)^i\).

General expression of DST, \(\mathbf{S}_N\), of size \(N\) and of type 1, 3 and 4 can be expressed in terms of the DFT matrix of size \(M\), \(\mathbf{B}_{M}\mathbf{P}_M\) where \(M\) depends on the DST-type and where \(\mathbf{P}_M\) is the bit-reversal permutation matrix. The most well-known expression is as \(\mathbf{S}_N=-\mathtt{Im}(\mathbf{L}\mathbf{B}_M\mathbf{P}_M\mathbf{R})\) where the left and right matrices \(\mathbf{L}\) (of size \(N\times M\)) and \(\mathbf{R}\) (of size \(M\times N\)) are real-valued, but the Butterfly matrix \(\mathbf{B}_M\) is complex-valued.

Return type:

Union[LazyLinOp, tuple]

Args:
N: int

Size of the input \(N\) must be:

  • a power of two for DCT II, III and IV.

  • a power of two minus one for DCT I.

type: int, optional

1, 2, 3, 4 (I, II, III, IV). Defaut is 2. See SciPy DST and CuPy DST for more details.

dtype, device: optional

dtype and device of the ks-values L.ks_values. Default values are 'float64' and 'cpu'. Infer the namespace (see array-api-compat for more details) of L.ks_values from dtype and device arguments. By default, namespace of L.ks_values is numpy.

ksm_args: optional

See lazylinop.butterfly.ksm() for more details.

output: str, optional
  • output = 'S' (default value) returns a LazyLinOp corresponding to \(\mathbf{S}_N\).

  • output = 'LBPR' returns a triplet (L, B, PR) corresponding to \(\mathbf{L}\), \(\mathbf{B}_M\) and \(\mathbf{P}_M\mathbf{R}\). User can reconstruct an optimized DST using L @ optimize(B, ...) @ PR.

Returns:

Depending on the value of argument output return either a LazyLinOp or a triplet (L, B, PR) where L and PR are LazyLinOp and B is a lazylinop.butterfly.KsmLazyLinOp.

Examples:
>>> from lazylinop.butterfly import dst
>>> from scipy.fft import dst as sp_dst
>>> import numpy as np
>>> rng = np.random.default_rng()
>>> N = 32
>>> x = rng.standard_normal(N)
>>> F = dst(N, 2)
>>> y = F @ x
>>> yref = sp_dst(x, norm='ortho')
>>> np.allclose(y, yref)
True
>>> # compute the inverse DST
>>> z = F.T @ y
>>> np.allclose(z, x)
True
>>> # Optimize B of the DST (see the documentation)
>>> from lazylinop.butterfly import optimize
>>> L, B, PR = dst(N, 2, output='LBPR')
>>> opt_args = {"batch_size": 1, 'verbose': False}
>>> B_opt = optimize(B, opt_args=opt_args)
>>> y = (L @ B_opt @ PR) @ x
>>> np.allclose(y, yref)
True
lazylinop.butterfly.nudft(N, samples=None, frequencies=None, eps=1e-06, dtype='complex128', device='cpu', ksm_args=None, output='F')[source]#

Returns a LazyLinOp F = L @ Q @ B @ P @ R for the Non-Uniform Discrete Fourier Transform (NUDFT) using algorithm from [1] where the underlying Discrete Fourier Transform uses Butterfly structure \(\mathbf{B}\) and bit-reversal permutation \(\mathbf{P}\). The matrices \(\mathbf{L}\), \(\mathbf{Q}\) and \(\mathbf{R}\) depend on sample locations and frequencies.

Shape of F is \((N,~N)\).

In general, F.H is not the inverse NUDFT (as the generic NUDFT is not orthonormal).

F = nudft(N, None, None) (default) is functionally equivalent to the Discrete-Fourier-Transform operator and returns F = dft(N).

The nonuniform Discrete Fourier Transform y = F @ x of a signal \(x=\left(x_n\right)_n\) is defined (for possibly nonuniform sample locations \(s_n\) and possibly nonuniform frequencies \(\omega_k\)) as \(y=\left(y_k\right)_k\):

\[\begin{equation} y_k\equiv y\left(\omega_k\right)~\text{where}~y\left(\omega\right)=\frac{1}{\sqrt{N}}\sum_{n=0}^{N-1}x_ne^{-2\pi is_n\omega}\text{,}~\forall\omega\in\left[0,~N\right] \end{equation}\]
Args:
N: int

Size of the input (\(N > 0\)).

samples: 1d array

Sample locations \(s_n\in\left[0,~1\right[\) must be real. The size of samples must be \(N\). Default value is None (uniform sample locations \(s_n=\frac{n}{N}\) with \(0\le n\lt N\)).

frequencies: 1d array

Frequencies \(\omega_k\in\left[0,~N\right[\) must be real. The size of frequencies must be \(N\). Default value is None (uniform frequencies \(\omega_k=k\) with \(0\le k\lt N\)). Order of the frequencies does not change the precision of the output y = F @ x.

eps: float, optional

Precision to achieve (see [1] for more details). Default value is 1e-6.

dtype, device: optional

dtype and device of the ks-values of the underlying DFT when samples and frequencies are None. Default values are 'complex128' and 'cpu'. Infer the namespace (see array-api-compat for more details) of F.ks_values from dtype and device arguments. By default, namespace of F.ks_values is numpy.

ksm_args: optional

See lazylinop.butterfly.ksm() for more details.

output: str, optional
  • output = 'F' (default value) returns a LazyLinOp F = L @ Q @ B @ P @ R corresponding to the NUDFT.

  • output = 'LQBPR' returns a tuple (L, Q, B, P, R) corresponding to \(\mathbf{L}\), \(\mathbf{Q}\), \(\mathbf{B}\), \(\mathbf{P}\) and \(\mathbf{R}\). User can reconstruct an optimized NUDFT-I using hadapro(Q @ optimize(B, ...) @ P, L, R).

Returns:

Depending on the value of argument output return either a LazyLinOp L or a tuple (L, Q, B, P, R) where B is a KsmLazyLinOp, Q and P are LazyLinOp and L and R are 2d arrays.

Note

F.samples (resp. F.frequencies) returns the sample locations (resp. the frequencies).

Examples:
>>> from lazylinop.butterfly import nudft
>>> from lazylinop.basicops import hadapro
>>> import numpy as np
>>> rng = np.random.default_rng()
>>> N = 32
>>> x = rng.standard_normal((N, 4))
>>> samples = rng.random(N)
>>> k = 4
>>> F = nudft(N, samples, None)
>>> y = F @ x
>>> # Naive implementation of NUDFT-II.
>>> z = np.sum(x[:, 0] * np.exp(-2j * np.pi * k * samples)) / np.sqrt(N)
>>> np.allclose(y[k, 0], z)
True
>>> # Optimize the underlying DFT.
>>> from lazylinop.butterfly import optimize
>>> L, Q, B, P, R = nudft(N, samples, None, output='LQBPR')
>>> opt_args = {'dtype': 'float64', "batch_size": 4, 'verbose': False}
>>> B_opt = optimize(B, opt_args=opt_args)
>>> F_opt = hadapro(Q @ B_opt @ P, L, R)
>>> np.allclose(y, F_opt @ x)
True

See also

References:

[1] A Nonuniform Fast Fourier Transform Based on Low Rank Approximation. Diego Ruiz-Antolin and Alex Townsend SIAM Journal on Scientific Computing 2018 40:1, A529-A547

lazylinop.butterfly.fkt(K, v=None, ksm_args=None)[source]#

Return a LazyLinOp L corresponding to the Fast-Kronecker-Transform (FKT):

\[\mathbf{L}=\mathbf{K}_{n-1}\otimes\cdots\otimes\mathbf{K}_1\otimes\mathbf{K}_0\]

when v = None, with \(\mathbf{K}_j\) (\(0\le j\le 1\)) is K[j]. Indeed, it can be shown that this equation also write as:

\[\mathbf{L}=\mathbf{F}_{n-1}\cdots\mathbf{F}_1\mathbf{F}_0\]

where \(\mathbf{F}_{n-1-j}:=\mathbf{I}_{s^j}\otimes\mathbf{K}_{n-1-j}\otimes\mathbf{I}_{r^{n-1-j}}\) is a Kronecker-sparse factor (see lazylinop.butterfly.ksm() for more details.

For example, the Hadamard transform satisfies this expression with \(\mathbf{K}_j=\begin{pmatrix}1 & 1\\ 1 & -1 \end{pmatrix}\) for every \(j\), while the Pseudo-Hadamard transform corresponds to \(\mathbf{K}_j=\begin{pmatrix}2 & 1\\ 1 & 1 \end{pmatrix}\).

When all factors \(\mathbf{K}_j\) are orthogonal and v = None, L is also orthogonal and its inverse is L.H

For convenience, we also provide (when v is not None) a related construction (allowing to build for example the DFT lazylinop.butterfly.dft()), where \(\mathbf{L}=\mathbf{L}_n\) with \(\mathbf{L}_n\) defined recursively as:

\[\begin{split}\mathbf{L}&:=&\mathbf{L}_n\\ \mathbf{L}_n&=&\left(\mathbf{K}_{n-1}\otimes\mathbf{I}_{r^{n-1}}\right)\mathtt{diag}\left(v_{n-1-j}\right)\left(\mathbf{I}_s\otimes\mathbf{L}_{n-1}\right)\end{split}\]

It can indeed also be shown that such \(\mathbf{L}\) writes as \(\mathbf{F}_{n-1}'\cdots\mathbf{F}_1'\mathbf{F}_0'\) where \(\mathbf{F}_{n-1-j}'=\mathbf{F}_{n-1-j}\mathbf{D}_{n-1-j}\) (with \(\mathbf{F}_{n-1-j}\) as above and \(\mathbf{D}_{n-1-j}=\mathbf{I}_{s^j}\otimes\mathtt{diag}\left(v_{n-1-j}\right)\)) is also a Kronecker-sparse factor.

L is of shape \(\left(M,~N\right)\) where \(M=r^n\) and \(N=s^n\).

Args:
K: list of 2d arrays

K[j] dtype and device determine the dtype and device of the ks-values of the output L. All 2d arrays must be of the same dtype and device. Shape of K[j] is (r, s).

v: list of 1d arrays, optional

v[j] and K[j] must have the same dtype and device. All 1d arrays must be of the same dtype and device. Default value is None corresponding to 1d array of ones. Shape of v[j] is (s * r ** j, ).

ksm_args: optional

See lazylinop.butterfly.ksm() for more details.

Returns:

A LazyLinOp L corresponding to the FKT.

Examples:
>>> import numpy as np
>>> rng = np.random.default_rng()
>>> from lazylinop.butterfly import fkt
>>> from lazylinop.signal import dft
>>> from lazylinop.basicops import bitrev
>>> # Fast-Fourier-Transform.
>>> n = 3
>>> N = 2 ** n
>>> w = np.exp(2.0j * np.pi / N)
>>> # All factors K are orthogonal.
>>> K = [np.asarray([[1, 1], [1, -1]], dtype=w.dtype) / np.sqrt(2)] * n
>>> v = [None] * n
>>> v[2] = np.empty(8, dtype=w.dtype)
>>> w = np.exp(2.0j * np.pi / 8)
>>> v[2][:4] = 1
>>> v[2][4:] = np.pow(w, -np.arange(4))
>>> v[1] = np.empty(4, dtype=w.dtype)
>>> v[1][:2] = 1
>>> w = np.exp(2.0j * np.pi / 4)
>>> v[1][2:] = np.pow(w, -np.arange(2))
>>> v[0] = np.asarray([1, 1], dtype=w.dtype)
>>> B = fkt(K, v)
>>> L = B @ bitrev(N)
>>> np.allclose(L.toarray(), dft(N).toarray())
True
>>> K[0].dtype == B.ks_values[0].dtype
True
>>> K[0].device == B.ks_values[0].device
True
>>> # Hadamard transform.
>>> n = 2
>>> N = 2 ** n
>>> K = [np.asarray([[1.0, 1.0], [1.0, -1.0]])] * n
>>> L = fkt(K)
>>> L.toarray()
array([[ 1.,  1.,  1.,  1.],
       [ 1., -1.,  1., -1.],
       [ 1.,  1., -1., -1.],
       [ 1., -1., -1.,  1.]])
>>> # Fast-Walsh-Hadamard transform (orthonormal).
>>> n = 3
>>> N = 2 ** n
>>> K = [np.asarray([[1.0, 1.0], [1.0, -1.0]]) / np.sqrt(2.0)] * n
>>> L = fkt(K)
>>> x = rng.standard_normal(N)
>>> y = L @ x
>>> z = L.T @ y
>>> np.allclose(x, z)
True
>>> # Optimize FWHT.
>>> from lazylinop.butterfly import optimize
>>> opt_args = {'dtype': 'float64', "batch_size": 8, 'verbose': False}
>>> L_opt = optimize(L, opt_args=opt_args)
>>> x = rng.standard_normal((N, 8))
>>> np.allclose(L @ x, L_opt @ x)
True
>>> # Pseudo-Hadamard transform.
>>> n = 2
>>> N = 2 ** n
>>> K = [np.asarray([[2.0, 1.0], [1.0, 1.0]])] * n
>>> L = fkt(K)
>>> L.toarray()
array([[4., 2., 2., 1.],
       [2., 2., 1., 1.],
       [2., 1., 2., 1.],
       [1., 1., 1., 1.]])
>>> # Fast-Noiselet-Transform (orthonormal).
>>> n = 4
>>> N = 2 ** n
>>> K = [0.5 * np.asarray([[1 - 1j, 1 + 1j], [1 + 1j, 1 - 1j]])] * n
>>> L = fkt(K) @ bitrev(N)
>>> x = rng.standard_normal(N)
>>> y = L @ x
>>> z = L.H @ y
>>> np.allclose(x, z)
True
lazylinop.butterfly.fot(theta, ksm_args=None)[source]#

Return a LazyLinOp L with the Butterfly structure corresponding to the Fast-Orthogonal-Transform (FOT):

\[\begin{split}\mathbf{L}=\begin{pmatrix} \cos{2\pi\theta_{n-1}} & -\sin{2\pi\theta_{n-1}}\\ \sin{2\pi\theta_{n-1}} & \cos{2\pi\theta_{n-1}} \end{pmatrix}\otimes\cdots\otimes\begin{pmatrix} \cos{2\pi\theta_0} & -\sin{2\pi\theta_0}\\ \sin{2\pi\theta_0} & \cos{2\pi\theta_0} \end{pmatrix}\end{split}\]

Shape of L is \(\left(N,~N\right)\) where \(N=2^n\) must be a power of two.

L is orthonormal, and the lazylinop.butterfly.KsmLazyLinOp for the inverse FOT is L.T.

Args:
theta: NumPy, CuPy or torch 1d array

A 1d array of \(\theta_i\in[0,1]\) of size \(n\).

ksm_args: optional

See lazylinop.butterfly.ksm() for more details.

Returns:

An instance of KsmLazyLinOp. dtype and device of ks-values are determined by the dtype and device of theta.

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import fot
>>> n = 4
>>> theta = np.random.rand(n)
>>> L = fot(theta)
>>> len(L.ks_values)
4
>>> N = 2 ** n
>>> x = np.random.randn(N)
>>> y = L @ x
>>> z = L.T @ y
>>> # L is orthonormal.
>>> np.allclose(x, z)
True
>>> # Optimize FOT.
>>> from lazylinop.butterfly import optimize
>>> opt_args = {'dtype': 'float64', "batch_size": 8, 'verbose': False}
>>> L_opt = optimize(L, opt_args=opt_args)
>>> x = np.random.randn(N, 8)
>>> np.allclose(L @ x, L_opt @ x)
True

Chain class#

class lazylinop.butterfly.Chain(ks_patterns)[source]#

A Chain instance is built by calling the constructor Chain(ks_patterns).

Args:
ks_patterns: list

List of tuples \(((a_l,~b_l,~c_l,~d_l))_{l=1}^n\) each being called a pattern. The tuples \(((a_l,~b_l,~c_l,~d_l))_{l=1}^n\) must satisfy \(a_lc_ld_l=a_{l+1}b_{l+1}d_{l+1}\).

Attributes:
ks_patterns: list of tuple

List of patterns \((a_i,~b_i,~c_i,~d_i)\).

n_patterns: int

Equal to len(ks_patterns).

shape: tuple

shape is equal to \((a_1b_1d_1,~a_nc_nd_n)\) with n = n_patterns.

chainability: bool

True if for each \(l\):

  • \(a_l\) divides \(a_{l+1}\)

  • and \(d_{l+1}\) divides \(d_l\)

See [1] for more details.

Return:

chain with ks_patterns, n_patterns, shape and chainable attributes.

Examples:
>>> from lazylinop.butterfly import Chain
>>> chain = Chain([(2, 1, 1, 2), (2, 1, 1, 2)])
>>> chain.ks_patterns
((2, 1, 1, 2), (2, 1, 1, 2))
>>> # Concatenation of two chains.
>>> chain1 = Chain([(1, 4, 4, 2)])
>>> chain2 = Chain([(4, 2, 2, 1)])
>>> chain = chain1 @ chain2
>>> chain.shape
(8, 8)
>>> chain.n_patterns
2
>>> chain.ks_patterns
((1, 4, 4, 2), (4, 2, 2, 1))

References:

[1] Butterfly Factorization with Error Guarantees. Lu00E9on Zheng, Quoc-Tung Le, Elisa Riccietti, and Ru00E9mi Gribonval https://hal.science/hal-04763712v1/document

lazylinop.butterfly.Chain.square_dyadic(shape)#

Build a square-dyadic chain from shape.

shape must satisfy shape[0] = shape[1] = N with \(N=2^n\) a power of two. Number of ks_patterns is equal to \(n\). The l-th pattern is given by (2 ** (l - 1), 2, 2, shape[0] // 2 ** l) where 1 <= l <= n.

We can draw the square-dyadic decomposition for \(N=16\):

_images/square_dyadic.svg

using:

sq_chain = Chain.square_dyadic((16, 16))
sq_chain.plot()
Args:
shape: tuple

Shape of the input matrix must be \((N,~N)\) with \(N=2^n\).

lazylinop.butterfly.Chain.monarch(shape, p=None, q=None)#

Build a Monarch chain \(((1,~p,~q,~\frac{M}{p}),~(q,~\frac{M}{p},~\frac{N}{q},~1))\) from shape. \(p\) must divide \(M\) and \(q\) must divide \(N\). See [1] for more details.

Args:
shape: tuple

Shape of the input matrix \((M,~N)\). \(M\) and \(N\) must not be prime numbers.

p, q: int, optional

\(p\) must divide \(M\) and \(q\) must divide \(N\). If p (resp. q) is None, p (resp. q) is chosen such \(p\simeq\sqrt{m}\) (resp. \(q\simeq\sqrt{n}\)).

Examples:
>>> from lazylinop.butterfly.chain import Chain
>>> M, N = 21, 16
>>> chain = Chain.monarch((M, N))
>>> chain.ks_patterns
((1, 3, 4, 7), (4, 7, 4, 1))
>>> M, N = 12, 25
>>> chain = Chain.monarch((M, N))
>>> chain.ks_patterns
((1, 4, 5, 3), (5, 3, 5, 1))
>>> M, N = 12, 16
>>> chain = Chain.monarch((M, N))
>>> chain.ks_patterns
((1, 4, 4, 3), (4, 3, 4, 1))
>>> chain = Chain.monarch((M, N), p=2, q=4)
>>> chain.ks_patterns
((1, 2, 4, 6), (4, 6, 4, 1))

References:

[1] Monarch: Expressive structured matrices for efficient and accurate training. In International Conference on Machine Learning, pages 4690-4721. PMLR, 2022. T. Dao, B. Chen, N. S. Sohomi, A. D. Desai, M. Poli, J. Grogan, A. Liu, A. Rao, A. Rudra, and C. Ru00E9.

lazylinop.butterfly.Chain.chainable(shape)#

Build a non redundant and chainable architecture from shape using Lemma 4.25 from [1]. The function uses a prime factorization \((q_l)_{l=1}^L\) of M = shape[0] and a prime factorization \((p_l)_{l=1}^L\) of N = shape[0] where \(L\) is the length of the prime factorization. If the two factorization do not have the same length, merge the smallest elements of the larger factorization. Raise an Exception if shape[0] > 2 and shape[1] > 2 are prime numbers.

Args:
shape: tuple

Shape of the input matrix, expect a tuple \((M,~N)\). M is equal to the number of rows \(a_1b_1d_1\) of the first factor while N is equal to the number of columns \(a_nc_nd_n\) of the last factor.

Examples:
>>> from lazylinop.butterfly import Chain
>>> sq_chain = Chain.square_dyadic((8, 8))
>>> sq_chain.ks_patterns
((1, 2, 2, 4), (2, 2, 2, 2), (4, 2, 2, 1))
>>> nr_chain = Chain.chainable((8, 8))
>>> nr_chain.ks_patterns
((1, 2, 2, 4), (2, 2, 2, 2), (4, 2, 2, 1))

Chain methods#

lazylinop.butterfly.Chain.mem(self, dtype)#

Return the memory in bytes of the ks_values of dtype dtype to be created corresponding to self.

Args:
dtype: str

dtype of the ks_values.

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import Chain
>>> sd_chain = Chain.square_dyadic((32, 32))
>>> sd_chain.ks_patterns
((1, 2, 2, 16), (2, 2, 2, 8), (4, 2, 2, 4), (8, 2, 2, 2), (16, 2, 2, 1))
>>> sd_chain.mem(np.float32)
1280
>>> chain = Chain.monarch((32, 32))
>>> chain.ks_patterns
((1, 4, 4, 8), (4, 8, 8, 1))
>>> chain.mem(np.float32)
1536
lazylinop.butterfly.Chain.plot(self, name=None)#

Plot self.ks_patterns. The colors are randomly chosen. Matplotlib package must be installed.

Args:
name: str

Save the plot in both PNG file name + '.png' and SVG file name + '.svg'. Default value is None (it only draws the self.ks_patterns).

Examples:
>>> from lazylinop.butterfly import Chain
>>> sq_chain = Chain.square_dyadic((32, 32))
>>> sq_chain.plot("square_dyadic")
>>> chain = Chain.monarch((32, 32))
>>> chain.plot("monarch")

Chain attributes#

Chain.T#

The lazylinop.butterfly.Chain transpose such that L.chain.T == L.T.chain where L is either a lazylinop.butterfly.KsmLazyLinOp.

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import Chain, KsmLazyLinOp
>>> chain = Chain.monarch((64, 16))
>>> chain.ks_patterns
((1, 8, 4, 8), (4, 8, 4, 1))
>>> chain.T.ks_patterns
((4, 4, 8, 1), (1, 4, 8, 8))
>>> ks_patterns = [np.random.randn(*p) for p in chain.ks_patterns]
>>> L = KsmLazyLinOp(ks_patterns)
>>> L.chain.T == L.T.chain
True

KsmLazyLinOp class#

class lazylinop.butterfly.KsmLazyLinOp(ks_values, ksm_args=None, shape=None, matmat=None, rmatmat=None, **kwargs)[source]#

KsmLazyLinOp class is a specialization of LazyLinOp class when the underlying linear operator results from a call to lazylinop.butterfly.ksm() function.

Morevoer, the operations s * L, L.T, L.H, L.conj(), L1 @ L2 and L ** n return an instance of the KsmLazyLinOp class when L1, L2 and L are instances of KsmLazyLinOp class.

The main ways to build an instance from this class are via the ksm(), ksd() and suksd() functions.

KsmLazyLinOp attributes#

KsmLazyLinOp.ks_values#

Return the ks-values of self.

KsmLazyLinOp.chain#

Return the chain of self.

Utilities#

  1. lazylinop.butterfly.fuse()

  2. lazylinop.butterfly.optimize()

  3. lazylinop.butterfly.wisdom()

lazylinop.butterfly.fuse(ks_values, partition=None)[source]#

Fuse a list ks_values of chainable 4D arrays (see Chain for more details) and return a list res of 4D arrays. The resulting list res satisfies ksm(ks_values).toarray() == ksm(res).toarray(). By default, the function fuses all the ks-values and return a single 4D.

This function is a utility to optimize the implementation of butterfly matrices: while being frugal in memory, butterfly matrices implemented via many (chainable) Kronecker sparse factors are sometimes less computationally efficient than their (exact) fused implementation using fewer factors.

Args:
ks_values: a list of 4D arrays

Their dimensions must correspond to a chainable chain. See lazylinop.butterfly.Chain for more details.

partition: list[list[int]] or list[tuple[int]], optional

Fuse all the sub-lists of ks-values determined by the element of the partition argument partition. If partition is None (default), fuse all the elements of the ks-values list ks_values.

Returns:

The result is either:

  • a single 4D array res of shape \(\left(a_1,~\frac{b_1d_1}{d_n},~\frac{a_nc_n}{a_1},~d_n\right)\) if partition is None where the shape of the i-th ks_values[i] is \(\left(a_i,~b_i,~c_i,~d_i\right)\).

  • or a list res of 4D arrays if partition is not None. The i-th element res[i] is equal to fuse(ks_values[partition[i][0]:partition[i][-1]]) and its shape depends on partition[i]. The length of res is equal to the length of partition.

See also

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import ksm, fuse, Chain
>>> a1, b1, c1, d1 = 2, 2, 2, 4
>>> a2, b2, c2, d2 = 4, 2, 2, 2
>>> a3, b3, c3, d3 = 2, 4, 4, 2
>>> v1 = np.random.randn(a1, b1, c1, d1)
>>> v2 = np.random.randn(a2, b2, c2, d2)
>>> v3 = np.random.randn(a3, b3, c3, d3)
>>> v = fuse([v1, v2, v3])
>>> v.shape
(2, 4, 4, 2)
>>> L = ksm(v)
>>> L1 = ksm(v1)
>>> L2 = ksm(v2)
>>> L3 = ksm(v3)
>>> x = np.random.randn(L.shape[1])
>>> np.allclose(L @ x, L1 @ L2 @ L3 @ x)
True
>>> # Use a partition.
>>> N = 8
>>> chain = Chain.square_dyadic((N, N))
>>> ksv = [np.random.randn(*p) for p in chain.ks_patterns]
>>> v = fuse(ksv, partition=[[0], (1, 2)])
>>> len(v)
2
>>> v = fuse(ksv, partition=[(0, 1), [2]])
>>> len(v)
2
>>> v = fuse(ksv, partition=[(0, 1, 2)])
>>> len(v)
1
>>> w = fuse(ksv)
>>> np.allclose(v, w)
True
lazylinop.butterfly.optimize(input, opt_args={'backend': 'xp', 'batch_size': 16, 'strategy': 'benchmark'}, verbose=True)[source]#

This function is a utility to optimize the implementation of butterfly matrices: while being frugal in memory, butterfly matrices implemented via many (chainable) Kronecker sparse factors are sometimes less computationally efficient than their (exact) fused implementation using fewer factors.

With this purpose, the function therefore adaptively fuses either:

and return an object output of the same nature than the input:

  • an instance output of lazylinop.butterfly.Chain

  • a list output of chainable 4D arrays resulting from the needed hierarchical fusions such that ksm(input).toarray() == ksm(output).toarray()

  • an instance output of lazylinop.butterfly.KsmLazyLinOp such that input.toarray() == output.toarray()

Note

By default, the function optimize reads the file wisdom.csv (see wisdom() for more details) from previous runs to avoid benchmarking twice the same object. optimization usually results in the most optimized implementation with respect to wallclock time, but the optimization process may be time consuming, depending notably on the selected size of the factors, on the backend (see ksm() for more details), on the dtype and on the device of the ks-values.

Args:
input: Chain, list of 4D arrays, KsmLazyLinOp

Input to optimize.

opt_args: dict

  • When opt_args['strategy'] = 'benchmark' (default value) optimization process recursively fuses two consecutive elements if the resulting fused factor gives better matrix-vector multiplication performance than the succession of the two, non-fuses ones. Wallclock is either retrieved from wisdom.csv file (see wisdom() for more details) if available, or measured via a benchmark and saved to wisdom.csv.

    The keys and values of opt_args depends on the type of input:

    • If input is a LazyLinOp returned by ksm() function, the key "batch_size" is mandatory while array_namespace, dtype, device are determined using the ks-values input.ks_values and backend is determined by input.ksm_args['backend'].

    • If input is a list of ks_values, the keys "backend" and "batch_size" are mandatory while "array_namespace", 'dtype' and 'device' are determined using the ks-values.

    • If input is a chain, the keys "backend", "array_namespace", "dtype", "device" and "batch_size" are mandatory. Set opt_args["array_namespace"] to my_favorite_package where import package as my_favorite_package. Possible values of dtype and device depend on the array namespace (CuPy, NumPy and PyTorch).

  • Otherwize, opt_args["n_factors"] must be set to the target number of factors and opt_args['strategy'] can have the following values:

    • 'memory' iteratively fuse the two consecutive Kronecker-sparse factors that minimize the memory of the resulting fused one, until a target number of factors has been reached.

    • 'sparsity': iteratively fuse the two consecutive Kronecker-sparse factors that minimize the ratio \(\frac{1}{ad}\) of the resulting fused one, until a target number of factors has been reached.

    • 'speed': iteratively fuse the two consecutive Kronecker-sparse factors that minimize the ratio \(\frac{bc}{b+c}\) of the resulting fused one, until a target number of factors has been reached.

    • l2r: iteratively fuse factors from left to right until a target number of factors has been reached.

    • r2l: iteratively fuse factors from right to left until a target number of factors has been reached.

    • balanced: iteratively and alternatively fuse the two leftmost factors / the two rightmost ones, until a target number of factors has been reached.

verbose: bool, optional

Print fuse steps. Default value is True.

Returns:
  • an instance output of Chain

  • a list output of chainable 4D arrays resulting from the needed hierarchical fusions such that ksm(input).toarray() == ksm(output).toarray()

  • an instance output of KsmLazyLinOp such that input.toarray() == output.toarray()

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import ksm, optimize
>>> a1, b1, c1, d1 = 2, 2, 2, 4
>>> a2, b2, c2, d2 = 4, 2, 2, 2
>>> v1 = np.random.randn(a1, b1, c1, d1)
>>> v2 = np.random.randn(a2, b2, c2, d2)
>>> v = optimize([v1, v2], opt_args={'strategy': 'memory', "n_factors": 1})
       ['0', '1']
step=0 ['01']
>>> v[0].shape
(2, 4, 4, 2)
>>> L = ksm(v)
>>> L1 = ksm(v1)
>>> L2 = ksm(v2)
>>> x = np.random.randn(L.shape[1])
>>> np.allclose(L @ x, L1 @ L2 @ x)
True
>>> # Left-to-right strategy.
>>> n = 5
>>> ksv = [np.random.randn(2, 2, 2, 2)] * n
>>> v = optimize(ksv, opt_args={'strategy': 'l2r', "n_factors": 2})
       ['0', '1', '2', '3', '4']
step=0 ['01', '2', '3', '4']
step=1 ['01', '23', '4']
step=2 ['0123', '4']
>>> # Balanced strategy.
>>> n = 3
>>> ksv = [np.random.randn(2, 2, 2, 2)] * n
>>> v = optimize(ksv, opt_args={'strategy': 'balanced', "n_factors": 2})
       ['0', '1', '2']
step=0 ['01', '2']
>>> n = 5
>>> ksv = [np.random.randn(2, 2, 2, 2)] * n
>>> v = optimize(ksv, opt_args={'strategy': 'balanced', "n_factors": 2})
       ['0', '1', '2', '3', '4']
step=0 ['01', '2', '3', '4']
step=1 ['01', '2', '34']
step=2 ['012', '34']
>>> # Benchmark strategy (dft).
>>> from lazylinop.butterfly import dft
>>> N = 256
>>> B, _ = dft(N, output='BP')
>>> opt_args = {'dtype': 'float64', 'batch_size': 128, 'verbose': False}
>>> L_opt = optimize(L, opt_args=opt_args)
>>> len(L_opt.ks_values) <= len(L.ks_values)
True
>>> # Benchmark strategy (hadamard).
>>> from lazylinop.butterfly import hadamard
>>> N = 256
>>> L = hadamard(N, dtype='int64')
>>> opt_args = {'dtype': 'float64', 'batch_size': 128, 'verbose': False}
>>> L_opt = optimize(L, opt_args=opt_args)
>>> len(L_opt.ks_values) <= len(L.ks_values)
True
lazylinop.butterfly.wisdom(verbose=True, restart=False, enum={}, only={})[source]#

The function is currently in work-in-progress status.

Benchmark duration time of K @ x where K is an instance of lazylinop.butterfly.KsmLazyLinOp with a single ks-values and x. By default, the function will benchmark all the possible combination of array-namespace (NumPy, CuPy and torch 2d array), dtype, device, ksm backend (see lazylinop.butterfly.ksm() for more details), shape \((a,b,c,d)\) of ks-values (default values are the powers of two 2 ** np.arange(8)) and batch size (default values are [1,16,128,1024]) that fit in memory. By default, the number of threads used for parallelism on CPU is os.environ["OMP_NUM_THREADS"].

The function writes the results in the file "wisdom.csv". The header is array namespace,device,dtype,backend,cpu,cpu mem in bytes,gpu,gpu mem in bytes,ks pattern,dim out,dim in,batch size,hyper-parameters,OMP_NUM_THREADS,median,iqr,hash. See lazylinop.butterfly.ksm() for more details about hyper-parameters. median is the median duration time of K @ x and iqr the interquartile range.

Future call to optimize(L) will read the file "wisdom.csv" and select the option corresponding to the best performance.

The time execution of the wisdom function is quite long, at least one day for the following call on a Quadro RTX 6000 with 23G of RAM:

wisdom(
    verbose=True,
    restart=False,
    only['dtype']=['float16', 'float32', 'float64'],
    only[backend']='xp',
    only['device']=0,
)

Please refer to enum and only arguments to skip some of the benchmark.

Args:
verbose: bool, optional

Print the current status of the benchmark. Default value is True.

restart: bool, optional

Restart the benchmark even if previous run has been found in the wisdom.csv file, and overwrite the corresponding entry in the wisdom.csv file. Default value is False.

enum: dict, optional

The possible keys are:

  • 'a', 'b', 'c', 'd' and 'batch_size' to loop over itertools.product(enum['a'], enum['b'], enum['c'], enum['d']).

  • 'shape' to loop over all ks-patterns (a, b, c, d) such that a * b * d = enum['shape'][0] and a * c * d = enum['shape'][1].

  • "batch_size" to loop over enum["batch_size"].

Keys 'a', 'b', 'c', 'd' on the one hand and 'shape' on the other hand are mutually exclusive.

only: dict, optional

The possible keys are:

  • 'namespace' to benchmark only against array-namespace that are in the list only['namespace']. Default values are ['cupy', 'numpy', 'torch'].

  • 'dtype' to benchmark only against dtype that are in the list only['dtype'].

  • 'backend' to benchmark only backend that are in the list only['backend'].

  • 'device' to benchmark only device that are in the list only['device'].

Examples:
>>> from lazylinop.butterfly import wisdom
>>> enum = {}
>>> enum['a'] = 1
>>> enum['b'] = 2
>>> enum['c'] = 2
>>> enum['d'] = 2
>>> enum["batch_size"] = 128
>>> only = {}
>>> only['namespace'] = 'numpy'
>>> only['dtype'] = "float64"
>>> only['backend'] = 'xp'
>>> wisdom(verbose=False, restart=True, enum=enum, only=only)
>>> ref = pd.read_csv("wisdom.csv", sep=",")
>>> # Restart argument.
>>> wisdom(verbose=False, restart=False, enum=enum, only=only)
>>> data = pd.read_csv("wisdom.csv", sep=",")
>>> ref.compare(data).empty
True
>>> # Use enum['shape']
>>> enum = {}
>>> enum['a'] = 42
>>> enum['b'] = 42
>>> enum['c'] = 42
>>> enum['d'] = 42
>>> enum['shape'] = (4, 4)
>>> enum["batch_size"] = 128
>>> wisdom(verbose=False, restart=True, enum=enum, only=only)
>>> ref = pd.read_csv("wisdom.csv", sep=",")
>>> # Keys ``'a'``, ``'b'``, ``'c'``, ``'d'`` on the one hand
>>> # and ``'shape'`` on the other hand are mutually exclusive.
>>> df = ref.loc[ref["ks pattern"] == "(42, 42, 42, 42)"]
>>> df.empty
True
>>> df = ref.loc[ref["ks pattern"] == "(2, 1, 1, 2)"]
>>> df.empty
False
>>> # Restart argument.
>>> wisdom(verbose=False, restart=False, enum=enum, only=only)
>>> data = pd.read_csv("wisdom.csv", sep=",")
>>> ref.compare(data).empty
True

Basicops#

  1. lazylinop.butterfly.ksm_block_diag()

  2. lazylinop.butterfly.ksm_hstack()

  3. lazylinop.butterfly.ksm_vstack()

  4. lazylinop.butterfly.ksm_add()

  5. lazylinop.butterfly.ksm_real()

  6. lazylinop.butterfly.ksm_imag()

  7. lazylinop.butterfly.inv()

lazylinop.butterfly.ksm_block_diag(ops)[source]#

Return an instance B of lazylinop.butterfly.KsmLazyLinOp corresponding to a block-diagonal concatenation of compatible lazylinop.butterfly.KsmLazyLinOp linear operators ops such that B.toarray() == lazylinop.basicops.block_diag(ops).toarray().

As an example, the block-diagonal concatenation of two operators \(K_1K_2\cdots K_n\) and \(K_1'K_2'\cdots K_n'\) (with the same number \(n\) of factors, this is the first compatibility condition) is:

\[\begin{split}B=\begin{pmatrix} L & 0\\ 0 & L' \end{pmatrix}=\begin{pmatrix} K_1K_2\cdots K_n & 0\\ 0 & K_1'K_2'\cdots K_n' \end{pmatrix}=\begin{pmatrix} K_1 & 0\\ 0 & K_1' \end{pmatrix}\begin{pmatrix} K_2 & 0\\ 0 & K_2' \end{pmatrix}\cdots\begin{pmatrix} K_n & 0\\ 0 & K_n' \end{pmatrix}\end{split}\]

If the shape of \(K_i\) (resp. \(K_i'\)) is \((a_i,b_i,c_i,d_i)\) (resp. \((a_i',b_i',c_i',d_i')\) where \(b_i'=b_i\), \(c_i'=c_i\) and \(d_i'=d_i\)) (this is the second compatibility condition) each factor \(K_i''\) is a basic lazylinop.butterfly.KsmLazyLinOp of shape \((a_i+a_i',b_i,c_i,d_i)\), hence \(B=K_1''K_2''\cdots K_n''\).

Args:
ops: list or tuple

Operators \(L_1,\cdots,L_n\) to concatenate block-diagonally where each \(L_i\) is a lazylinop.butterfly.KsmLazyLinOp.

Returns:

An instance B of lazylinop.butterfly.KsmLazyLinOp.

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import ksm_block_diag, ksm
>>> b, c, d = 4, 3, 2
>>> A = ksm(np.random.randn(2, b, c, d))
>>> B = ksm(np.random.randn(3, b, c, d))
>>> C = ksm(np.random.randn(1, b, c, d))
>>> L = ksm_block_diag([A, B, C])
>>> len(L.ks_values)
1
>>> L.ks_values[0].shape
(6, 4, 3, 2)
>>> # Check against lazylinop.basicops.block_diag.
>>> from lazylinop.basicops import block_diag
>>> x = np.random.randn(L.shape[1])
>>> V = block_diag(*[A, B, C])
>>> np.allclose(L @ x, V @ x)
True

See also

  • lazylinop.butterfly.wip_ksm_hstack(),

  • lazylinop.butterfly.wip_ksm_vstack().

lazylinop.butterfly.ksm_hstack(ops)[source]#

Return an instance H of lazylinop.butterfly.KsmLazyLinOp corresponding to an horizontal concatenation of compatible lazylinop.butterfly.KsmLazyLinOp linear operators ops such that H.toarray() == lazylinop.basicops.hstack(ops).toarray().

ksm_hstack(ops) is a shorthand for:

\[H=\begin{bmatrix} \mathtt{Id} & \cdots & \mathtt{Id} \end{bmatrix}@\mathtt{ksm\_block\_diag}(ops)\]

where \(\begin{bmatrix}\mathtt{Id} & \cdots & \mathtt{Id}\end{bmatrix}\) can be written as a lazylinop.butterfly.KsmLazyLinOp.

Args:
ops: list or tuple

Operators to concatenate vertically where ops[i] is a lazylinop.butterfly.KsmLazyLinOp.

Returns:

An instance H of lazylinop.butterfly.KsmLazyLinOp.

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import ksm_hstack, ksm
>>> a, b, c, d = 3, 4, 2, 2
>>> L1 = ksm(np.random.randn(a, b, c, d))
>>> L2 = ksm(np.random.randn(a, b, c, d))
>>> L3 = ksm(np.random.randn(a, b, c, d))
>>> L = ksm_hstack([L1, L2, L3])
>>> len(L.ks_values)
2
>>> # Check against lazylinop.basicops.hstack.
>>> from lazylinop.basicops import hstack
>>> x = np.random.randn(L.shape[1])
>>> H = hstack((L1, L2, L3))
>>> np.allclose(L @ x, H @ x)
True
lazylinop.butterfly.ksm_vstack(ops)[source]#

Return an instance V of lazylinop.butterfly.KsmLazyLinOp corresponding to an horizontal concatenation of compatible lazylinop.butterfly.KsmLazyLinOp() linear operators ops such that V.toarray() == lazylinop.basicops.vstack(ops).toarray().

ksm_vstack(ops) is a shorthand for:

\[\begin{split}V=\mathtt{ksm\_block\_diag}(ops)@\begin{bmatrix} \mathtt{Id}\\ \vdots\\ \mathtt{Id} \end{bmatrix}\end{split}\]

where \(\begin{bmatrix}\mathtt{Id}\\\vdots\\\mathtt{Id}\end{bmatrix}\) can be written as a lazylinop.butterfly.KsmLazyLinOp.

Args:
ops: list or tuple

Operators to concatenate vertically where ops[i] is a lazylinop.butterfly.KsmLazyLinOp.

Returns:

An instance V of lazylinop.butterfly.KsmLazyLinOp.

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import ksm_vstack, ksm
>>> a, b, c, d = 2, 5, 3, 2
>>> L1 = ksm(np.random.randn(a, b, c, d))
>>> L2 = ksm(np.random.randn(a, b, c, d))
>>> L3 = ksm(np.random.randn(a, b, c, d))
>>> L = ksm_vstack([L1, L2, L3])
>>> len(L.ks_values)
2
>>> # Check against lazylinop.basicops.vstack.
>>> from lazylinop.basicops import vstack
>>> x = np.random.randn(L.shape[1])
>>> V = vstack((L1, L2, L3))
>>> np.allclose(L @ x, V @ x)
True
lazylinop.butterfly.ksm_add(ops)[source]#

Return an instance A of lazylinop.butterfly.KsmLazyLinOp corresponding to the addition of compatible lazylinop.butterfly.KsmLazyLinOp linear operators ops such that A.toarray() == lazylinop.basicops.add(ops).toarray().

ksm_add(ops) is a shorthand for:

\[\begin{split}A=\begin{bmatrix} \mathtt{Id} & \cdots & \mathtt{Id} \end{bmatrix}@ \mathtt{ksm\_block\_diag}(ops)@ \begin{bmatrix} \mathtt{Id}\\ \vdots\\ \mathtt{Id} \end{bmatrix}\end{split}\]

Currently, ksm_add(ops) @ x is slower than add(ops) @ x.

  • If you care about speed use add(ops).

  • If you need to access to the ks-values use ksm_add(ops).

Args:
ops: list or tuple

Addition of ops[0] + ... + ops[n - 1] where ops[i] is an instance of lazylinop.butterfly.KsmLazyLinOp class.

Returns:

An instance A of lazylinop.butterfly.KsmLazyLinOp.

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import ksm_add, ksm
>>> a, b, c, d = 2, 4, 3, 5
>>> L1 = ksm(np.random.randn(a, b, c, d))
>>> L2 = ksm(np.random.randn(a, b, c, d))
>>> L3 = ksm(np.random.randn(a, b, c, d))
>>> L = ksm_add([L1, L2, L3])
>>> len(L.ks_values)
1
>>> L.ks_values[0].shape == (a, b, c, d)
True
>>> # Check against lazylinop.basicops.add.
>>> from lazylinop.basicops import add
>>> x = np.random.randn(L.shape[1])
>>> V = add(*[L1, L2, L3])
>>> np.allclose(L @ x, V @ x)
True
lazylinop.butterfly.ksm_real(L)[source]#

Return the real part of a lazylinop.butterfly.KsmLazyLinOp L as an instance R of the same class such that ksm_real(L).toarray() == real(L.toarray()).

L.chain or L.chain.T must be chainable.

Args:

L: lazylinop.butterfly.KsmLazyLinOp

Returns:

An instance R of lazylinop.butterfly.KsmLazyLinOp.

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import ksm, ksm_real
>>> a, b, c, d = 3, 4, 4, 2
>>> randn = np.random.randn
>>> L1 = randn(a, b, c, d) + 1j * randn(a, b, c, d)
>>> L2 = randn(a, b, c, d) + 1j * randn(a, b, c, d)
>>> L3 = randn(a, b, c, d) + 1j * randn(a, b, c, d)
>>> L = ksm([L1, L2, L3])
>>> R = ksm_real(L)
>>> np.allclose(np.real(L.toarray()), R.toarray())
True
lazylinop.butterfly.ksm_imag(L)[source]#

Return the real part of a lazylinop.butterfly.KsmLazyLinOp L as an instance I of the same class such that ksm_imag(L).toarray() == imag(L.toarray()).

L.chain or L.chain.T must be chainable.

Args:

L: lazylinop.butterfly.KsmLazyLinOp

Returns:

An instance I of lazylinop.butterfly.KsmLazyLinOp depending on L.

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import ksm, ksm_imag
>>> a, b, c, d = 3, 4, 4, 2
>>> randn = np.random.randn
>>> L1 = randn(a, b, c, d) + 1j * randn(a, b, c, d)
>>> L2 = randn(a, b, c, d) + 1j * randn(a, b, c, d)
>>> L3 = randn(a, b, c, d) + 1j * randn(a, b, c, d)
>>> L = ksm([L1, L2, L3])
>>> I = ksm_imag(L)
>>> np.allclose(np.imag(L.toarray()), I.toarray())
True
lazylinop.butterfly.inv(L)[source]#

Return the inverse of a square lazylinop.butterfly.KsmLazyLinOp class as an operator of the same class of L.

Args:
L: lazylinop.butterfly.KsmLazyLinOp

L to be inverted.

Returns:

The inverse of L as an operator of the same class as L.

I/O (load/save)#

  1. lazylinop.butterfly.load()

  2. lazylinop.butterfly.save()

  3. lazylinop.butterfly.loadmat()

  4. lazylinop.butterfly.savemat()

lazylinop.butterfly.load(name)[source]#

Load L from file name.json. The file name.json has been created by lazylinop.butterfly.save().

Args:
name: str

Name of the .json file where to load L.

Returns:

L a lazy linear operator resulting from a call to ksm(...) or ksd(...) function. If file does not exist, return None.

Examples:
>>> import scipy as sp
>>> import numpy as np
>>> from lazylinop.butterfly import Chain, ksd, load, save
>>> H = sp.linalg.hadamard(8)
>>> x = np.random.randn(8)
>>> chain = Chain.square_dyadic(H.shape)
>>> A = ksd(H, chain)
>>> save(A, "hadamard_8x8")
>>> A_ = load("hadamard_8x8")
>>> y = A @ x
>>> y_ = A_ @ x
>>> np.allclose(y, y_)
True
lazylinop.butterfly.save(L, name)[source]#

Save L = ksm(...) or L = ksd(...) in a json file name + '.json'.

Args:
L:

A lazy linear operator returned by L = ksm(...) or L = ksd(...).

name: str

Name of the file.

Examples:
>>> import scipy as sp
>>> import numpy as np
>>> from lazylinop.butterfly import Chain, ksd, load, save
>>> H = sp.linalg.hadamard(8)
>>> x = np.random.randn(8)
>>> chain = Chain.square_dyadic(H.shape)
>>> L = ksd(H, chain)
>>> save(L, "hadamard_8x8")
>>> L_ = load("hadamard_8x8")
>>> y = L @ x
>>> y_ = L_ @ x
>>> np.allclose(y, y_)
True
lazylinop.butterfly.loadmat(name)[source]#

Load an instance L of lazylinop.butterfly.KsmLazyLinOp from file name.mat. The file name.mat has been created by savemat().

Args:
name: str

Name of the .mat file where to load L.

Returns:

An instance L of lazylinop.butterfly.KsmLazyLinOp. If file does not exist, return None.

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import KsmLazyLinOp
>>> from lazylinop.butterfly import loadmat, savemat
>>> ksv = [np.random.randn(2, 2, 2, 2) for _ in range(3)]
>>> L = KsmLazyLinOp(ksv)
>>> x = np.random.randn(8)
>>> savemat(L, "savemat_L")
>>> L_load = loadmat("savemat_L")
>>> y = L @ x
>>> y_load = L_load @ x
>>> np.allclose(y, y_load)
True
lazylinop.butterfly.savemat(L, name)[source]#

Save an instance L of lazylinop.butterfly.KsmLazyLinOp into a MATLAB file name + '.mat'.

Args:
L: lazylinop.butterfly.KsmLazyLinOp

An instance L of lazylinop.butterfly.KsmLazyLinOp to save.

name: str

Name of the file.

Examples:
>>> import numpy as np
>>> from lazylinop.butterfly import KsmLazyLinOp
>>> from lazylinop.butterfly import loadmat, savemat
>>> ksv = [np.random.randn(2, 2, 2, 2) for _ in range(3)]
>>> L = KsmLazyLinOp(ksv)
>>> x = np.random.randn(8)
>>> savemat(L, "savemat_L")
>>> L_load = loadmat("savemat_L")
>>> y = L @ x
>>> y_load = L_load @ x
>>> np.allclose(y, y_load)
True

Plot#

  1. lazylinop.butterfly.plot()

lazylinop.butterfly.plot(L, name=None, colormap='rainbow', log_scale=True)[source]#

Plot L.ks_values on a logarithmic or linear scale. If ks_values is complex plot xp.sqrt(ks_values * xp.conj(ks_values)). Matplotlib package must be installed.

Args:
L: lazylinop.butterfly.KsmLazyLinOp

Plot L.ks_values on a logarithmic scale.

name: str

Save the plot in both PNG file name + '.png' and SVG file name + '.svg' and show the figure. Default value (None) only returns a tuple (fig, ax) for further manipulations of the plot.

colormap: str, optional

Use Matplotlib colormap. See colormaps documentation for more details.

log_scale: bool, optional
  • True: plot ks_values on a logarithmic scale (default value).

  • False: plot ks_values on a linear scale.

Returns:

If name is a str, save, show and return (None, None), otherwize return (fig, ax) corresponding to the plot of L.ks_values where fig is the matplotlib.figure.Figure instance and ax is the matplotlib.axes.Axes instance corresponding to the plot of the ks-values.

Examples:
>>> from lazylinop.butterfly import dft
>>> from lazylinop.butterfly import plot
>>> import matplotlib.image as mpl_img
>>> import matplotlib.pyplot as plt
>>> B, _ = dft(16, output='BP')
>>> # Get fig and ax of the plot.
>>> fig, ax = plot(B)
>>> axs = fig.get_axes()
>>> axs[0].set_ylim(4, 12)
(4.0, 12.0)
>>> fig.savefig("my_dft.png")
>>> fig.clf()
>>> plt.close("my_dft")
>>> # Save the plot option.
>>> fig, ax = plot(B, name="my_dft")
>>> fig is None and ax is None
True
>>> img = mpl_img.imread("my_dft.png", format='png')
>>> _ = plt.imshow(img)
>>> plt.show(block=True)
>>> plt.close()