"""DfAM Practitioner Program, Lab 2 - process selection by AHP and TOPSIS (starter code).

Run:  python T2_ahp_topsis.py
Reproduces the worked example of topic L6, then tests the sensitivity of the ranking to the weights.
"""
import numpy as np

RI = {1: 0.0, 2: 0.0, 3: 0.58, 4: 0.90, 5: 1.12, 6: 1.24, 7: 1.32, 8: 1.41, 9: 1.45}   # Saaty's random index


def ahp_weights(A):
    """Weights (row geometric mean), lambda_max and consistency ratio of a pairwise matrix."""
    A = np.asarray(A, dtype=float)
    n = A.shape[0]
    g = A.prod(axis=1) ** (1.0 / n)
    w = g / g.sum()
    lam = float(np.mean(A @ w / w))
    ci = (lam - n) / (n - 1) if n > 1 else 0.0
    cr = ci / RI[n] if RI[n] > 0 else 0.0
    return w, lam, cr


def topsis(X, w, benefit):
    """Closeness coefficient of each alternative. X: alternatives x criteria; benefit: list of bool."""
    X = np.asarray(X, dtype=float)
    R = X / np.sqrt((X ** 2).sum(axis=0))
    V = R * np.asarray(w)
    best = np.where(benefit, V.max(axis=0), V.min(axis=0))
    worst = np.where(benefit, V.min(axis=0), V.max(axis=0))
    s_plus = np.sqrt(((V - best) ** 2).sum(axis=1))
    s_minus = np.sqrt(((V - worst) ** 2).sum(axis=1))
    return s_minus / (s_plus + s_minus)


if __name__ == "__main__":
    # criteria: strength (benefit), dimensional error (cost), cost per part (cost)
    A = [[1, 2, 3], [1 / 2, 1, 2], [1 / 3, 1 / 2, 1]]
    names = ["Material extrusion", "Vat photopolymerisation", "Polymer powder bed fusion"]
    X = [[35, 0.30, 450], [50, 0.10, 900], [48, 0.20, 1200]]
    benefit = [True, False, False]

    w, lam, cr = ahp_weights(A)
    print("weights:", np.round(w, 3), " lambda_max: %.4f  CR: %.3f" % (lam, cr))
    C = topsis(X, w, benefit)
    for n_, c in sorted(zip(names, C), key=lambda t: -t[1]):
        print("  %-28s C = %.3f" % (n_, c))

    # sensitivity: change each weight by +/-20 % (renormalised) and report the winner
    print("\nSensitivity of the ranking to each weight (+/-20 %):")
    base_winner = names[int(np.argmax(C))]
    for k, crit in enumerate(["strength", "accuracy", "cost"]):
        for f in (0.8, 1.2):
            w2 = w.copy(); w2[k] *= f; w2 /= w2.sum()
            winner = names[int(np.argmax(topsis(X, w2, benefit)))]
            flag = "" if winner == base_winner else "   <-- ranking changes"
            print("  %-9s x %.1f  ->  %s%s" % (crit, f, winner, flag))
