mathmat.random

MathMat Random Matrix Toolbox

 1"""MathMat Random Matrix Toolbox"""
 2
 3from .mathmat import Matrix
 4import numpy as np
 5from scipy.fft import dct
 6
 7
 8class Gaussian(Matrix):
 9    """A Gaussian matrix has entries drawn from a standard normal."""
10
11    def __init__(self, nr, nc):
12        """Initialize a new Gaussian matrix with the given size."""
13        super().__init__(np.random.standard_normal(size=(nr, nc)))
14
15
16class FFTSketchedMatrix(Matrix):
17    """A sketching matrix based on the FFT / DCT."""
18
19    def __init__(self, M: Matrix):
20        """Sketch an existing Matrix."""
21        signs = np.sign(np.random.standard_normal(size=(1, M.nc)))
22        arr = signs * M.entries
23        if M.is_complex():
24            arr = np.fft.fft2(arr)
25        else:
26            arr = dct(arr, type=2)
27        super().__init__(arr)
28
29
30def approx_hmt(M: Matrix, r: int):
31    """Compute a rank `r` approximation using the HMT algorithm."""
32    S = Gaussian(M.nr, r)
33    MS = M @ S
34    Q, _ = MS.qr()
35    return Q @ Q.transpose() @ M
class Gaussian(mathmat.mathmat.Matrix):
 9class Gaussian(Matrix):
10    """A Gaussian matrix has entries drawn from a standard normal."""
11
12    def __init__(self, nr, nc):
13        """Initialize a new Gaussian matrix with the given size."""
14        super().__init__(np.random.standard_normal(size=(nr, nc)))

A Gaussian matrix has entries drawn from a standard normal.

Gaussian(nr, nc)
12    def __init__(self, nr, nc):
13        """Initialize a new Gaussian matrix with the given size."""
14        super().__init__(np.random.standard_normal(size=(nr, nc)))

Initialize a new Gaussian matrix with the given size.

class FFTSketchedMatrix(mathmat.mathmat.Matrix):
17class FFTSketchedMatrix(Matrix):
18    """A sketching matrix based on the FFT / DCT."""
19
20    def __init__(self, M: Matrix):
21        """Sketch an existing Matrix."""
22        signs = np.sign(np.random.standard_normal(size=(1, M.nc)))
23        arr = signs * M.entries
24        if M.is_complex():
25            arr = np.fft.fft2(arr)
26        else:
27            arr = dct(arr, type=2)
28        super().__init__(arr)

A sketching matrix based on the FFT / DCT.

FFTSketchedMatrix(M: mathmat.mathmat.Matrix)
20    def __init__(self, M: Matrix):
21        """Sketch an existing Matrix."""
22        signs = np.sign(np.random.standard_normal(size=(1, M.nc)))
23        arr = signs * M.entries
24        if M.is_complex():
25            arr = np.fft.fft2(arr)
26        else:
27            arr = dct(arr, type=2)
28        super().__init__(arr)

Sketch an existing Matrix.

def approx_hmt(M: mathmat.mathmat.Matrix, r: int):
31def approx_hmt(M: Matrix, r: int):
32    """Compute a rank `r` approximation using the HMT algorithm."""
33    S = Gaussian(M.nr, r)
34    MS = M @ S
35    Q, _ = MS.qr()
36    return Q @ Q.transpose() @ M

Compute a rank r approximation using the HMT algorithm.