"""Tutorial — measure how much a MoS2 flake tilts away from the sliding direction.

Friction 2025, Fig. 6 defines the flake angle: the angle between a flake's basal plane and the
shear plane. Flat flakes (small angle) slide easily; tilted flakes resist sliding. The paper found
small and oxidized flakes stay tilted during sliding.

The angle comes from principal component analysis (PCA) of one flake's atom positions:
the eigenvector with the smallest eigenvalue is the flake normal.

Run:   python flake_angle.py frames.extxyz --flake-ids flake_ids.txt   (your own simulation)
       python flake_angle.py --demo                                    (synthetic flakes, < 1 s)
Output: out/flake_angles.png (demo) or printed angles per frame.
"""
import argparse
from pathlib import Path

import numpy as np

OUT = Path(__file__).parent / "out"
OUT.mkdir(exist_ok=True)


def flake_angle(positions, shear_normal=(0, 0, 1)):
    """Angle in degrees between a flake's plane and the plane whose normal is `shear_normal`."""
    x = positions - positions.mean(axis=0)
    w, v = np.linalg.eigh(x.T @ x)
    normal = v[:, 0]  # smallest-variance direction
    c = abs(normal @ np.asarray(shear_normal, float)) / np.linalg.norm(shear_normal)
    return np.degrees(np.arccos(np.clip(c, 0, 1)))


def synthetic_flake(n_side, tilt_deg, rng):
    """Flat triangular-lattice patch tilted about the y axis, with thermal noise."""
    a = 3.18
    pts = np.array([[i * a + 0.5 * j * a, j * a * np.sqrt(3) / 2, 0.0] for i in range(n_side) for j in range(n_side)])
    pts += rng.normal(0, 0.15, pts.shape)
    t = np.radians(tilt_deg)
    R = np.array([[np.cos(t), 0, np.sin(t)], [0, 1, 0], [-np.sin(t), 0, np.cos(t)]])
    return pts @ R.T


def demo():
    rng = np.random.default_rng(0)
    sizes = {"small (16 atoms)": 4, "large (144 atoms)": 12}
    true = np.linspace(0, 40, 9)
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots(figsize=(5, 4))
    for label, n in sizes.items():
        meas = [np.mean([flake_angle(synthetic_flake(n, t, rng)) for _ in range(20)]) for t in true]
        ax.plot(true, meas, "o-", label=label)
    ax.plot(true, true, "k:", lw=1, label="exact")
    ax.set_xlabel("Imposed tilt (°)")
    ax.set_ylabel("Measured flake angle (°)")
    ax.legend(frameon=False)
    ax.set_title("PCA flake-angle check")
    fig.tight_layout()
    fig.savefig(OUT / "flake_angles.png", dpi=160)
    print("wrote", OUT / "flake_angles.png")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("traj", nargs="?")
    ap.add_argument("--flake-ids", help="text file: one integer flake id per atom (same order as the trajectory)")
    ap.add_argument("--demo", action="store_true")
    a = ap.parse_args()
    if a.demo or not a.traj:
        return demo()
    from ase.io import iread
    ids = np.loadtxt(a.flake_ids, dtype=int)
    for k, frame in enumerate(iread(a.traj)):
        pos = frame.get_positions()
        angles = [flake_angle(pos[ids == f]) for f in np.unique(ids) if (ids == f).sum() >= 6]
        print(f"frame {k}: mean flake angle {np.mean(angles):.1f}° over {len(angles)} flakes")


if __name__ == "__main__":
    main()
