import numpy as np import pytest from spectra_moe.transforms import ( apply_2d, invert_2d, dct2d, idct2d, haar_2d, ihaar_2d, incoherence_process, inverse_incoherence, ) from spectra_moe.transforms.hadamard import fwht, gaussianity from spectra_moe.transforms.wavelet import band_energies, subband_slices SHAPES = [(16, 24), (32, 32), (7, 13), (64, 48)] @pytest.mark.parametrize("shape", SHAPES) @pytest.mark.parametrize("t", ["none", "dct", "haar", "wht"]) def test_transform_roundtrip(shape, t): X = np.random.default_rng(0).normal(size=shape) C = apply_2d(X, t, levels=2) R = invert_2d(C, t, shape=X.shape, levels=2) assert np.abs(R - X).max() < 1e-10 @pytest.mark.parametrize("shape", SHAPES) def test_parseval_dct(shape): X = np.random.default_rng(1).normal(size=shape) assert np.isclose(np.linalg.norm(dct2d(X)), np.linalg.norm(X)) def test_fwht_self_inverse(): x = np.random.default_rng(2).normal(size=(4, 16)) assert np.abs(fwht(fwht(x)) - x).max() < 1e-12 def test_fwht_rejects_non_power_of_two(): with pytest.raises(ValueError): fwht(np.zeros((3, 5))) @pytest.mark.parametrize("shape", SHAPES) def test_incoherence_roundtrip(shape): X = np.random.default_rng(3).normal(size=shape) A, d1, d2, sh = incoherence_process(X, seed=3) assert np.abs(inverse_incoherence(A, d1, d2, sh) - X).max() < 1e-10 def test_incoherence_gaussianises_heavy_tails(): """Scrambling is what makes a fixed lattice codebook near-optimal.""" H = np.random.default_rng(4).standard_t(2.5, size=(64, 64)) A, *_ = incoherence_process(H, seed=0) assert gaussianity(A) < 0.25 * gaussianity(H) def test_subband_slices_partition_coefficients(): C = haar_2d(np.random.default_rng(5).normal(size=(32, 32)), 2) energies = band_energies(C, 2) assert 0.99 < sum(energies.values()) <= 1.0 + 1e-9 def test_haar_energy_concentrates_for_smooth_signal(): x = np.add.outer(np.linspace(0, 1, 32), np.linspace(0, 1, 32)) C = haar_2d(x, 2) ll = band_energies(C, 2)["L2LL"] assert ll > 0.95