Skip to content

brahmap.core.NoiseCovLO_Toeplitz01

Bases: NoiseCovLinearOperator

A linear operator representing a Toeplitz noise covariance matrix \(N\).

This Toeplitz operator is based on embedding the Toeplitz matrix of size \(n\) into a circulant matrix of size \(2n\).

The input covariance array must be at least of the size \(n\). The input power spectrum array must be of the size \(2n-2\) or \(2n-1\).

Parameters:

Name Type Description Default
size int

The size (dimension) of the linear operator

required
input ArrayLike

The input array or data defining the operator

required
input_type Literal['covariance', 'power_spectrum']

Specifies whether the input is a covariance array or a power spectrum array, by default "power_spectrum"

'power_spectrum'
dtype DTypeFloat

The data type of the operator, by default np.float64

float64

Methods:

Name Description
reset_counters

Resets matrix-vector product counter to zero.

dot

Numpy-like dot() method.

matvec

Matrix-vector multiplication method.

to_array

Returns the dense form of the linear operator as a 2D NumPy array.

get_inverse

Returns the inverse of this Toeplitz noise covariance operator.

Attributes:

Name Type Description
dtype DTypeLike

The data type of the operator.

nargin int

Size of the input vector \(x\), i.e. the number of columns of the operator

nargout int

Size of the output vector \(A(x)\), i.e. the number of rows of the operator

symmetric bool

Indicates whether the operator is symmetric or not

shape tuple[int, int]

A tuple (nargout, nargin) representing the shape of the operator

nMatvec int

The number of matrix-vector multiplications computed so far

T LinearOperator

The transpose operator

H LinearOperator

The adjoint operator

size int

The dimension i.e. the number of rows/columns of the operator

diag NDArray[number]

The diagonal elements of the noise covariance operator.

Source code in brahmap/core/noise_ops_toeplitz.py
class NoiseCovLO_Toeplitz01(NoiseCovLinearOperator):
    """A linear operator representing a Toeplitz noise covariance matrix $N$.

    This Toeplitz operator is based on embedding the Toeplitz matrix
    of size $n$ into a circulant matrix of size $2n$.

    The input covariance array must be at least of the size $n$. The
    input power spectrum array must be of the size $2n-2$ or $2n-1$.

    Parameters
    ----------
    size : int
        The size (dimension) of the linear operator
    input : npt.ArrayLike
        The input array or data defining the operator
    input_type : Literal["covariance", "power_spectrum"], optional
        Specifies whether the `input` is a covariance array or a power
        spectrum array, by default `"power_spectrum"`
    dtype : DTypeFloat, optional
        The data type of the operator, by default `np.float64`
    """

    def __init__(
        self,
        size: int,
        input: npt.ArrayLike,
        input_type: Literal["covariance", "power_spectrum"] = "power_spectrum",
        dtype: DTypeFloat = np.float64,
    ) -> None:
        input = np.asarray(a=input, dtype=dtype)

        if input.ndim != 1:
            raise ValueError("The `input` array must be a 1-d vector")

        if input_type == "covariance":
            if size > input.shape[0]:
                raise ValueError(
                    "The input noise covariance array must be at least of the size of "
                    "the linear operator"
                )
            covariance = input[:size]
        elif input_type == "power_spectrum":
            if (2 * size - 1 != input.shape[0]) and (2 * size - 2 != input.shape[0]):
                raise ValueError(
                    "The input power spectrum array must be of the size 2n-2 or 2n-1, "
                    "where n is the size of the linear operator"
                )
            covariance = scipy.fft.ifft(
                input,
                workers=MPI_UTILS.nthreads_per_process,
            )[:size]
            covariance = covariance.real.astype(  # type: ignore
                dtype=dtype,
                copy=False,
            )

        self.__diag_factor = covariance[0]
        self.__input = np.concatenate([covariance, np.roll(covariance[::-1], 1)])
        self.__input = scipy.fft.rfft(  # type: ignore
            self.__input,
            workers=MPI_UTILS.nthreads_per_process,
        )

        del covariance

        super().__init__(
            nargin=size,
            matvec=self._mult,
            input_type=input_type,
            dtype=dtype,
        )

    @property
    def diag(self) -> npt.NDArray[np.number]:
        """The diagonal elements of the noise covariance operator.

        Returns
        -------
        npt.NDArray[np.number]
            A 1-d array containing the diagonal elements
        """
        return self.__diag_factor * np.ones(self.size, dtype=self.dtype)

    def get_inverse(self) -> "InvNoiseCovLO_Toeplitz01":
        """Returns the inverse of this Toeplitz noise covariance operator.

        The inverse operator is based on PCG based Toeplitz system solver.

        Returns
        -------
        InvNoiseCovLO_Toeplitz01
            The inverse operator $N^{-1}$
        """
        covariance = scipy.fft.irfft(
            self.__input,
            n=2 * self.size,
            workers=MPI_UTILS.nthreads_per_process,
        )[: self.size]
        covariance = covariance.astype(dtype=self.dtype)  # type: ignore
        inv_noise_cov = InvNoiseCovLO_Toeplitz01(
            size=self.size,
            input=covariance,
            input_type="covariance",
            dtype=cast(DTypeFloat, self.dtype),
        )
        return inv_noise_cov

    def _mult(self, vec: npt.NDArray[np.number]) -> npt.NDArray[np.number]:
        r"""Performs the matrix-vector product $N v$.

        Parameters
        ----------
        vec : npt.NDArray[np.number]
            The input vector $v$

        Returns
        -------
        npt.NDArray[np.number]
            The resulting vector
        """
        prod = np.pad(vec, pad_width=((0, self.size)), mode="constant")

        prod = scipy.fft.rfft(
            prod,
            workers=MPI_UTILS.nthreads_per_process,
        )
        prod = prod * self.__input
        prod = scipy.fft.irfft(
            prod,
            n=2 * self.size,
            workers=MPI_UTILS.nthreads_per_process,
        )[: self.size]

        return prod.astype(dtype=self.dtype, copy=False)  # type: ignore

Attributes

dtype: npt.DTypeLike property writable

The data type of the operator.

Returns:

Type Description
DTypeLike

The NumPy data type of the operator

nargin: int property

Size of the input vector \(x\), i.e. the number of columns of the operator

Returns:

Type Description
int

The number of input columns

nargout: int property

Size of the output vector \(A(x)\), i.e. the number of rows of the operator

Returns:

Type Description
int

The number of output rows

symmetric: bool property

Indicates whether the operator is symmetric or not

Returns:

Type Description
bool

True if symmetric, False otherwise

shape: Tuple[int, int] property

A tuple (nargout, nargin) representing the shape of the operator

Returns:

Type Description
tuple[int, int]

A tuple (nrows, ncols)

nMatvec: int property

The number of matrix-vector multiplications computed so far

Returns:

Type Description
int

The number of matrix-vector multiplications performed

T: LinearOperator property

The transpose operator

Returns:

Type Description
LinearOperator

The transpose of this linear operator

H: LinearOperator property

The adjoint operator

Returns:

Type Description
LinearOperator

The Hermitian adjoint of this linear operator

size: int property

The dimension i.e. the number of rows/columns of the operator

Returns:

Type Description
int

The size of the operator

diag: npt.NDArray[np.number] property

The diagonal elements of the noise covariance operator.

Returns:

Type Description
NDArray[number]

A 1-d array containing the diagonal elements

Functions

reset_counters() -> None

Resets matrix-vector product counter to zero.

Source code in brahmap/base/linop.py
def reset_counters(self) -> None:
    """Resets matrix-vector product counter to zero."""
    self._nMatvec = 0

dot(x) -> npt.NDArray[np.number]

Numpy-like dot() method.

Parameters:

Name Type Description Default
x Any

The input vector or object to multiply with.

required

Returns:

Type Description
NDArray[number]

The result of the dot product.

Source code in brahmap/base/linop.py
def dot(self, x) -> npt.NDArray[np.number]:
    """Numpy-like dot() method.

    Parameters
    ----------
    x : Any
        The input vector or object to multiply with.
    Returns
    -------
    npt.NDArray[np.number]
        The result of the dot product.
    """
    return self.__mul__(x)

matvec(x) -> npt.NDArray[np.number]

Matrix-vector multiplication method.

The matvec method encapsulates the matvec routine specified at construct time, to ensure the consistency of the input and output arrays with the operator's shape.

Parameters:

Name Type Description Default
x NDArray[number]

The input vector \(x\) to be multiplied by the operator

required

Returns:

Type Description
NDArray[number]

The result of the matrix-vector multiplication \(A(x)\)

Source code in brahmap/base/linop.py
def matvec(self, x) -> npt.NDArray[np.number]:
    """
    Matrix-vector multiplication method.

    The `matvec` method encapsulates the `matvec`
    routine specified at construct time, to ensure the
    consistency of the input and output arrays with the
    operator's shape.

    Parameters
    ----------
    x : npt.NDArray[np.number]
        The input vector $x$ to be multiplied by the operator

    Returns
    -------
    npt.NDArray[np.number]
        The result of the matrix-vector multiplication $A(x)$
    """
    x = np.asanyarray(x, dtype=self.dtype)
    M, N = self.shape

    # check input data consistency
    N = int(N)
    try:
        x = x.reshape(N)
    except ValueError:
        msg = (
            f"The size of the input array is incompatible with the "
            f"dimensions required by the operator\n"
            f"size of the input array: {x.size}\n"
            f"shape of the operator: {self.shape}"
        )
        msg = f"{self.__class__.__name__}: " + msg
        raise ValueError(msg)

    y = self.__matvec(x)

    # check output data consistency
    M = int(M)
    try:
        y = y.reshape(M)
    except ValueError:
        msg = (
            f"The size of the output array is incompatible with the "
            f"dimensions required by the operator\n"
            f"size of the output array: {y.size}\n"
            f"shape of the operator: {self.shape}"
        )
        msg = f"{self.__class__.__name__}: " + msg
        raise ValueError(msg)

    return y

to_array() -> npt.NDArray[np.number]

Returns the dense form of the linear operator as a 2D NumPy array.

Warning

This method first allocates a NumPy array of shape self.shape and data-type self.dtype, and then fills them with numbers. As such, for a large linear operator, it can occupy an enormous amount of memory and crash your system. Don't use it unless you understand the risk!

Returns:

Type Description
NDArray[number]

The dense 2D array representation of the linear operator

Source code in brahmap/base/linop.py
def to_array(self) -> npt.NDArray[np.number]:
    """Returns the dense form of the linear operator as a 2D NumPy array.

    !!! Warning

        This method first allocates a NumPy array of shape `self.shape`
        and data-type `self.dtype`, and then fills them with numbers. As
        such, for a large linear operator, it can occupy an enormous
        amount of memory and crash your system. Don't use it unless you
        understand the risk!

    Returns
    -------
    npt.NDArray[np.number]
        The dense 2D array representation of the linear operator
    """
    n, m = self.shape
    H = np.empty((n, m), dtype=self.dtype)
    ej = np.zeros(m, dtype=self.dtype)
    for j in range(m):
        ej[j] = 1.0
        H[:, j] = self * ej
        ej[j] = 0.0
    return H

get_inverse() -> InvNoiseCovLO_Toeplitz01

Returns the inverse of this Toeplitz noise covariance operator.

The inverse operator is based on PCG based Toeplitz system solver.

Returns:

Type Description
InvNoiseCovLO_Toeplitz01

The inverse operator \(N^{-1}\)

Source code in brahmap/core/noise_ops_toeplitz.py
def get_inverse(self) -> "InvNoiseCovLO_Toeplitz01":
    """Returns the inverse of this Toeplitz noise covariance operator.

    The inverse operator is based on PCG based Toeplitz system solver.

    Returns
    -------
    InvNoiseCovLO_Toeplitz01
        The inverse operator $N^{-1}$
    """
    covariance = scipy.fft.irfft(
        self.__input,
        n=2 * self.size,
        workers=MPI_UTILS.nthreads_per_process,
    )[: self.size]
    covariance = covariance.astype(dtype=self.dtype)  # type: ignore
    inv_noise_cov = InvNoiseCovLO_Toeplitz01(
        size=self.size,
        input=covariance,
        input_type="covariance",
        dtype=cast(DTypeFloat, self.dtype),
    )
    return inv_noise_cov