# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Verify NMFk behavior on a fixed two-component synthetic XRD-like dataset."""

import sys
from pathlib import Path

ROOT = Path(__file__).parents[1]
sys.path.insert(0, str(ROOT / "reference"))
import nmfk

basis_a = [1.0, 0.2, 0.0, 0.0, 0.0, 0.0]
basis_b = [0.0, 0.0, 0.0, 0.0, 0.2, 1.0]
weights = [
    (1.0, 0.0),
    (0.85, 0.15),
    (0.7, 0.3),
    (0.55, 0.45),
    (0.45, 0.55),
    (0.3, 0.7),
    (0.15, 0.85),
    (0.0, 1.0),
]
patterns = [
    [wa * a + wb * b for a, b in zip(basis_a, basis_b, strict=True)]
    for wa, wb in weights
]

rank1 = nmfk.nmfk_metrics(patterns, 1, runs=4, steps=250)
rank2 = nmfk.nmfk_metrics(patterns, 2, runs=6, steps=350)

assert rank1["reconstruction_error"] > 0.20
assert rank2["reconstruction_error"] < 0.03
assert rank2["silhouette"] > 0.90

clusters, assignments = nmfk.equal_size_cluster([
    [[1.0, 0.0], [0.0, 1.0]],
    [[0.0, 1.0], [1.0, 0.0]],
    [[0.99, 0.01], [0.01, 0.99]],
])
assert assignments == [[0, 1], [1, 0], [0, 1]]
assert all(len(cluster) == 3 for cluster in clusters)
assert nmfk.silhouette_score(clusters) > 0.99

shift, corr = nmfk.best_shift_correlation(
    [0.0, 1.0, 2.0, 1.0, 0.0],
    [0.0, 0.0, 1.0, 2.0, 1.0],
    2,
)
assert shift == 1 and corr > 0.999999
print(f"PASS rank 1 underfits: relative error {rank1['reconstruction_error']:.3f}")
print(f"PASS rank 2 is stable and accurate: error {rank2['reconstruction_error']:.3f}, silhouette {rank2['silhouette']:.3f}")
print("PASS equal-size clustering assigns one basis from every run to every cluster")
print("PASS one-bin shifted basis is detected with correlation 1")
