"""Explore linear transformations, eigenvectors, and projected variance.

Run with Python 3 and NumPy installed:
    python3 05-matrix-transformations-eigenvalues.py

Predict each transform and eigenpair before running the assertions.
All inputs are small, deterministic, and use double precision.
"""

import numpy as np


def main():
    transform = np.array([[3.0, 2.0], [0.0, 1.0]])
    points = np.array([[1.0, 1.0], [-1.0, 1.0]])
    np.testing.assert_allclose(points @ transform.T, [[5, 1], [-1, 1]])

    # Find the characteristic roots for a two-by-two matrix, then check
    # the independent null-space directions solved by hand in the lesson.
    a, b = transform[0]
    c, d = transform[1]
    trace = a + d
    determinant = a * d - b * c
    discriminant_root = np.lib.scimath.sqrt(trace**2 - 4 * determinant)
    manual_values = (trace + np.array([discriminant_root, -discriminant_root])) / 2
    manual_vectors = np.array([[1.0, -1.0], [0.0, 1.0]])
    np.testing.assert_allclose(transform @ manual_vectors, manual_vectors * manual_values)
    coordinates = np.linalg.solve(manual_vectors, points[0])
    np.testing.assert_allclose(coordinates, [2, 1])
    np.testing.assert_allclose(manual_vectors @ (manual_values**2 * coordinates), [17, 1])

    rotation = np.array([[0.0, -1.0], [1.0, 0.0]])
    shear = np.array([[1.0, 2.0], [0.0, 1.0]])
    matrices = np.stack([transform, rotation, shear])
    values, vectors = np.linalg.eig(matrices)
    assert values.shape == (3, 2)
    assert vectors.shape == (3, 2, 2)
    np.testing.assert_allclose(matrices @ vectors, vectors * values[..., None, :], atol=1e-12)
    np.testing.assert_allclose(np.sort(values[0]), [1, 3])
    np.testing.assert_allclose(np.sort(values[1].imag), [-1, 1])
    np.testing.assert_allclose(values[1].real, [0, 0], atol=1e-12)
    np.testing.assert_allclose(values[2], [1, 1])
    assert np.linalg.matrix_rank(shear - np.eye(2)) == 1
    np.testing.assert_allclose(np.linalg.matrix_power(shear, 5) @ [0, 1], [10, 1])

    samples = np.array([[2., 1.], [-2., -1.], [1., 2.], [-1., -2.]])
    centered = samples - samples.mean(axis=0)
    covariance = centered.T @ centered / (len(samples) - 1)
    variances, directions = np.linalg.eigh(covariance)
    projected = centered @ directions
    np.testing.assert_allclose(variances, [2 / 3, 6])
    np.testing.assert_allclose(projected.var(axis=0, ddof=1), variances)
    np.testing.assert_allclose(directions.T @ directions, np.eye(2), atol=1e-12)
    np.testing.assert_allclose((directions * variances) @ directions.T, covariance)
    np.testing.assert_allclose(variances[-1] / variances.sum(), 0.9)

    print("Hand-computed eigenvalues:", manual_values)
    print("Variance along covariance eigenvectors:", variances)
    print("All transformation and covariance checks passed.")

    # Try it yourself:
    # 1. Replace the rotation with a reflection and predict the real spectrum.
    # 2. Double the first feature and compare its leading covariance direction.
    # 3. Compare projectors for two orthonormal bases of the identity's eigenspace.


if __name__ == "__main__":
    main()
