# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Small pure-Python NMFk reference for XRD phase mapping."""

import math
import random
from functools import lru_cache


def _matrix(a, name):
    if not a or not a[0]:
        raise ValueError(f"{name} must be nonempty")
    width = len(a[0])
    out = []
    for row in a:
        if len(row) != width:
            raise ValueError(f"{name} must be rectangular")
        vals = [float(x) for x in row]
        if any((not math.isfinite(x)) or x < 0 for x in vals):
            raise ValueError(f"{name} must be finite and nonnegative")
        out.append(vals)
    return out


def _transpose(a):
    return [list(col) for col in zip(*a, strict=True)]


def _matmul(a, b):
    if len(a[0]) != len(b):
        raise ValueError("matrix shapes do not align")
    bt = _transpose(b)
    return [[math.fsum(x * y for x, y in zip(row, col, strict=True)) for col in bt] for row in a]


def _frobenius(a):
    return math.sqrt(math.fsum(x * x for row in a for x in row))


def _normalize_columns(w, h):
    for j in range(len(w[0])):
        scale = math.fsum(w[i][j] for i in range(len(w)))
        if scale <= 0:
            continue
        for i in range(len(w)):
            w[i][j] /= scale
        for n in range(len(h[0])):
            h[j][n] *= scale


def multiplicative_step(V, W, H, epsilon=1e-15):
    """One Frobenius Lee-Seung H update followed by W update and column normalization."""
    V = _matrix(V, "V")
    W = _matrix(W, "W")
    H = _matrix(H, "H")
    if len(V) != len(W) or len(W[0]) != len(H) or len(V[0]) != len(H[0]):
        raise ValueError("V, W, H shapes must satisfy V ≈ WH")

    wt = _transpose(W)
    num_h = _matmul(wt, V)
    den_h = _matmul(_matmul(wt, W), H)
    for i in range(len(H)):
        for j in range(len(H[0])):
            H[i][j] *= num_h[i][j] / (den_h[i][j] + epsilon)

    ht = _transpose(H)
    num_w = _matmul(V, ht)
    den_w = _matmul(_matmul(W, H), ht)
    for i in range(len(W)):
        for j in range(len(W[0])):
            W[i][j] *= num_w[i][j] / (den_w[i][j] + epsilon)

    _normalize_columns(W, H)
    return W, H


def relative_reconstruction_error(V, W, H):
    V = _matrix(V, "V")
    W = _matrix(W, "W")
    H = _matrix(H, "H")
    approx = _matmul(W, H)
    if len(approx) != len(V) or len(approx[0]) != len(V[0]):
        raise ValueError("V, W, H shapes must satisfy V ≈ WH")
    denom = _frobenius(V)
    if denom == 0:
        raise ValueError("V must contain nonzero intensity")
    residual = [[V[i][j] - approx[i][j] for j in range(len(V[0]))] for i in range(len(V))]
    return _frobenius(residual) / denom


def factorize_nmf(patterns, k, *, steps=400, seed=0):
    """Factor patterns (samples × bins) into normalized bases and abundances."""
    X = _matrix(patterns, "patterns")
    n, m = len(X), len(X[0])
    if not 1 <= k <= min(n, m):
        raise ValueError("k must be between 1 and min(samples, bins)")
    V = _transpose(X)
    rng = random.Random(seed)
    W = [[0.1 + rng.random() for _ in range(k)] for _ in range(m)]
    H = [[0.1 + rng.random() for _ in range(n)] for _ in range(k)]
    _normalize_columns(W, H)
    for _ in range(int(steps)):
        W, H = multiplicative_step(V, W, H)
    bases = [[W[i][j] for i in range(m)] for j in range(k)]
    return bases, H, relative_reconstruction_error(V, W, H)


def _cosine_distance(a, b):
    dot = math.fsum(x * y for x, y in zip(a, b, strict=True))
    na = math.sqrt(math.fsum(x * x for x in a))
    nb = math.sqrt(math.fsum(y * y for y in b))
    if na == 0 or nb == 0:
        return 1.0
    return 1.0 - dot / (na * nb)


def _mean(vectors):
    return [math.fsum(col) / len(vectors) for col in zip(*vectors, strict=True)]


def _assignment(centroids, bases):
    """Minimum cosine-distance one-to-one assignment, cluster index → basis index."""
    k = len(centroids)
    costs = [[_cosine_distance(centroids[i], bases[j]) for j in range(k)] for i in range(k)]

    @lru_cache(maxsize=None)
    def solve(i, mask):
        if i == k:
            return 0.0, ()
        best = (float("inf"), ())
        for j in range(k):
            if mask & (1 << j):
                continue
            tail_cost, tail = solve(i + 1, mask | (1 << j))
            candidate = (costs[i][j] + tail_cost, (j,) + tail)
            if candidate[0] < best[0]:
                best = candidate
        return best

    return solve(0, 0)[1]


def equal_size_cluster(run_bases):
    """Cluster repeated NMF bases so every run contributes exactly one basis per cluster."""
    if len(run_bases) < 2:
        raise ValueError("need at least two runs")
    k = len(run_bases[0])
    if k < 1:
        raise ValueError("each run must contain at least one basis")
    width = len(run_bases[0][0])
    cleaned = []
    for run in run_bases:
        if len(run) != k:
            raise ValueError("every run must contain the same number of bases")
        current = []
        for basis in run:
            if len(basis) != width:
                raise ValueError("all bases must have the same length")
            vals = [float(x) for x in basis]
            if any(not math.isfinite(x) for x in vals):
                raise ValueError("basis values must be finite")
            current.append(vals)
        cleaned.append(current)

    clusters = [[basis] for basis in cleaned[0]]
    assignments = [list(range(k))]
    for bases in cleaned[1:]:
        centroids = [_mean(cluster) for cluster in clusters]
        order = list(_assignment(centroids, bases))
        assignments.append(order)
        for cluster_index, basis_index in enumerate(order):
            clusters[cluster_index].append(bases[basis_index])
    return [clusters, assignments]


def silhouette_score(clusters):
    """Average cosine-distance silhouette for explicit clusters."""
    if not clusters or any(not cluster for cluster in clusters):
        raise ValueError("clusters must be nonempty")
    if len(clusters) == 1:
        return 1.0
    values = []
    for ci, cluster in enumerate(clusters):
        for idx, point in enumerate(cluster):
            same = [q for j, q in enumerate(cluster) if j != idx]
            a = math.fsum(_cosine_distance(point, q) for q in same) / len(same) if same else 0.0
            b = min(
                math.fsum(_cosine_distance(point, q) for q in other) / len(other)
                for cj, other in enumerate(clusters)
                if cj != ci
            )
            denom = max(a, b)
            values.append(0.0 if denom == 0 else (b - a) / denom)
    return math.fsum(values) / len(values)


def nmfk_metrics(patterns, k, *, runs=8, steps=400):
    """Repeated NMF plus equal-size clustering; return stability and fit metrics."""
    if runs < 2:
        raise ValueError("runs must be at least 2")
    solutions = [factorize_nmf(patterns, k, steps=steps, seed=s) for s in range(runs)]
    clusters, _ = equal_size_cluster([solution[0] for solution in solutions])
    centroids = [_mean(cluster) for cluster in clusters]
    for centroid in centroids:
        total = math.fsum(centroid)
        if total > 0:
            for i in range(len(centroid)):
                centroid[i] /= total
    errors = sorted(solution[2] for solution in solutions)
    mid = len(errors) // 2
    median_error = errors[mid] if len(errors) % 2 else 0.5 * (errors[mid - 1] + errors[mid])
    return {
        "k": int(k),
        "reconstruction_error": median_error,
        "silhouette": silhouette_score(clusters),
        "basis": centroids,
    }


def _pearson(a, b):
    if len(a) < 2:
        return 0.0
    ma = math.fsum(a) / len(a)
    mb = math.fsum(b) / len(b)
    da = [x - ma for x in a]
    db = [x - mb for x in b]
    denom = math.sqrt(math.fsum(x * x for x in da) * math.fsum(y * y for y in db))
    if denom == 0:
        return 0.0
    return math.fsum(x * y for x, y in zip(da, db, strict=True)) / denom


def best_shift_correlation(a, b, max_shift):
    """Return [shift, Pearson correlation]; positive shift means b is at higher indices."""
    a = [float(x) for x in a]
    b = [float(x) for x in b]
    if len(a) != len(b) or len(a) < 3:
        raise ValueError("a and b must have the same length ≥ 3")
    if max_shift < 0 or max_shift >= len(a) - 1:
        raise ValueError("max_shift must be between 0 and len(a)-2")
    best = None
    for shift in range(-int(max_shift), int(max_shift) + 1):
        if shift >= 0:
            aa, bb = a[: len(a) - shift], b[shift:]
        else:
            aa, bb = a[-shift:], b[: len(b) + shift]
        corr = _pearson(aa, bb)
        candidate = (corr, -abs(shift), -shift)
        if best is None or candidate > best[0]:
            best = (candidate, shift, corr)
    return [best[1], best[2]]
