"""Verify SVD shapes, approximation errors, and a truncated inverse.

Requires Python 3 and NumPy. Run python3 06-svd-low-rank.py.
Predict the rank-one residual before running the checks.
"""

import numpy as np


def reconstruct(left, values, right_t, rank):
    """Keep rank singular terms and preserve any leading batch axes."""
    return (left[..., :rank] * values[..., None, :rank]) @ right_t[..., :rank, :]


def main():
    matrix = np.array([[2., 2.], [1., -1.], [2., 2.]])
    left, values, right_t = np.linalg.svd(matrix, full_matrices=False)
    expected_right = np.array([[1., 1.], [1., -1.]]) / np.sqrt(2)
    expected_left = np.array([[1., 0.], [0., np.sqrt(2)], [1., 0.]]) / np.sqrt(2)
    np.testing.assert_allclose(values, [4, np.sqrt(2)])
    np.testing.assert_allclose(matrix @ expected_right.T, expected_left * values)
    np.testing.assert_allclose(reconstruct(left, values, right_t, 2), matrix)
    np.testing.assert_allclose(reconstruct(left, values, right_t, 0), np.zeros_like(matrix))

    rank_one = reconstruct(left, values, right_t, 1)
    np.testing.assert_allclose(rank_one, [[2, 2], [0, 0], [2, 2]], atol=1e-12)
    error = matrix - rank_one
    np.testing.assert_allclose(np.linalg.norm(error, "fro") ** 2, 2)
    np.testing.assert_allclose(np.linalg.norm(error, 2), np.sqrt(2))
    np.testing.assert_allclose(np.linalg.norm(error @ expected_right[1]), np.sqrt(2))

    batch = np.stack([matrix, 2 * matrix])
    batch_left, batch_values, batch_right_t = np.linalg.svd(batch, full_matrices=False)
    assert batch_left.shape == (2, 3, 2)
    assert batch_values.shape == (2, 2)
    assert batch_right_t.shape == (2, 2, 2)
    np.testing.assert_allclose(reconstruct(batch_left, batch_values, batch_right_t, 2), batch)

    # The second response has a tiny perturbation in a weak direction.
    ill_conditioned = np.diag([1., 1e-8])
    observed = np.array([1., 1e-5])
    left, values, right_t = np.linalg.svd(ill_conditioned, full_matrices=False)
    keep = values > 1e-6 * values[0]
    truncated = right_t[keep].T @ ((left[:, keep].T @ observed) / values[keep])
    np.testing.assert_allclose(np.linalg.solve(ill_conditioned, observed), [1, 1000])
    np.testing.assert_allclose(truncated, [1, 0])

    print("Reconstruction, residual bounds, batched shapes and truncation passed.")

    # Try it yourself:
    # 1. Transpose the input and compare full and reduced output shapes.
    # 2. Lower the inverse cutoff and predict which response component grows.
    # 3. Change the rank boundary and compare both error norms.


if __name__ == "__main__":
    main()
