"""Check PCA by hand and optionally compare three embedding methods.

Required: Python 3.10 or newer and NumPy. Run python3 07-pca-tsne-umap.py.
Install scikit-learn and umap-learn for --compare. Add --csv layouts.csv
to export the three two-dimensional layouts for plotting.
"""

import argparse
import csv

import numpy as np


def squared_distances(points):
    differences = points[:, None, :] - points[None, :, :]
    return np.sum(differences**2, axis=-1)


def nearest_indices(points, count):
    """Find exact Euclidean neighbors for a small, row-ordered fixture."""
    distances = squared_distances(points)
    np.fill_diagonal(distances, np.inf)
    return np.argsort(distances, axis=-1, kind="stable")[:, :count]


def neighbor_overlap(original, embedded, count):
    original_neighbors = nearest_indices(original, count)
    embedded_neighbors = nearest_indices(embedded, count)
    shared = (original_neighbors[:, :, None] == embedded_neighbors[:, None, :]).any(axis=2)
    return shared.mean()


def check_pca():
    train = np.array([[6., 2.], [4., 2.], [5., 4.], [5., 0.]])
    mean = train.mean(axis=0)
    centered = train - mean
    _, values, components_t = np.linalg.svd(centered, full_matrices=False)
    basis = components_t[:1].T
    scores = centered @ basis
    restored = scores @ basis.T + mean
    held_out_scores = (np.array([[7., 3.]]) - mean) @ basis

    np.testing.assert_allclose(mean, [5, 2])
    np.testing.assert_allclose(values**2 / (len(train) - 1), [8 / 3, 2 / 3])
    np.testing.assert_allclose(np.square(train - restored).sum(), 2)
    np.testing.assert_allclose(held_out_scores @ basis.T + mean, [[5, 3]])
    np.testing.assert_allclose(values[0] ** 2 / (values @ values), 0.8)
    np.testing.assert_allclose(neighbor_overlap(train, train, 2), 1)
    print("PCA sample variance, held-out transform and reconstruction checks passed.")


def check_affinities():
    """Reproduce the t-SNE layout weights and UMAP edge union from the lesson."""
    layout_points = np.array([[0., 0.], [1., 0.], [3., 0.]])
    weights = 1 / (1 + squared_distances(layout_points))
    np.fill_diagonal(weights, 0)
    probabilities = weights / weights.sum()
    np.testing.assert_allclose(probabilities.sum(), 1)
    np.testing.assert_allclose(probabilities[0, 1] / probabilities[0, 2], 5)

    directed = np.array([[0., 0.8], [0.25, 0.]])
    memberships = directed + directed.T - directed * directed.T
    np.testing.assert_allclose(memberships, [[0., 0.85], [0.85, 0.]])
    print("t-SNE layout affinities and UMAP fuzzy-union checks passed.")


def compare_embeddings(output_path):
    from sklearn.decomposition import PCA
    from sklearn.manifold import TSNE
    from umap import UMAP

    rng = np.random.default_rng(23)
    angle = rng.uniform(1.5 * np.pi, 4.5 * np.pi, 240)
    height = rng.uniform(0, 12, len(angle))
    points = np.column_stack([angle * np.cos(angle), height, angle * np.sin(angle)])
    layouts = {
        "PCA": PCA(n_components=2).fit_transform(points),
        "t-SNE": TSNE(n_components=2, perplexity=20, random_state=23).fit_transform(points),
        "UMAP": UMAP(n_neighbors=15, min_dist=0.1, random_state=23, n_jobs=1).fit_transform(points),
    }

    for name, layout in layouts.items():
        assert layout.shape == (len(points), 2)
        assert np.all(np.isfinite(layout))
        scores = [neighbor_overlap(points, layout, k) for k in (5, 15)]
        assert all(0 <= score <= 1 for score in scores)
        print(f"{name:5s} overlap at k=5: {scores[0]:.3f}, k=15: {scores[1]:.3f}")

    if output_path:
        with open(output_path, "w", newline="", encoding="utf-8") as output:
            writer = csv.writer(output)
            writer.writerow(("method", "point_id", "x", "y", "angle"))
            for name, layout in layouts.items():
                for point_id, ((x, y), color) in enumerate(zip(layout, angle, strict=True)):
                    writer.writerow((name, point_id, x, y, color))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--compare", action="store_true", help="Compare PCA, t-SNE and UMAP.")
    parser.add_argument("--csv", help="Write the comparison layouts to this path.")
    args = parser.parse_args()
    check_pca()
    check_affinities()
    if args.compare or args.csv:
        compare_embeddings(args.csv)

    # Try it yourself:
    # 1. Double the first feature and predict how PCA's variance ratio changes.
    # 2. Compare the overlap scores across seeds and neighborhood parameters.
    # 3. Inspect points with low overlap and compare their original neighbors.


if __name__ == "__main__":
    main()
