# XAI Experiment 2: Decision Trees (Gini, rules, permutation importance) and KNN  [exam version]
# Requires: exam: none (math, random) | lab: numpy, pandas, matplotlib, scikit-learn
# ===========================================================================

# ---- DT ----

import random

X = [[2, 3], [3, 4], [4, 5], [7, 8], [8, 9], [9, 10]]
y = ["A", "A", "A", "B", "B", "B"]

names = ["Feature1", "Feature2"]

def gini(y):
    return 1 - sum((y.count(c)/len(y))**2 for c in set(y))

def build(X, y, depth=0):
    if len(set(y)) == 1 or depth == 3:
        return y[0] if len(set(y)) == 1 else max(set(y), key=y.count)

    best = 0
    split = None

    for j in range(len(X[0])):
        for t in set(row[j] for row in X):
            left = [i for i in range(len(y)) if X[i][j] <= t]
            right = [i for i in range(len(y)) if X[i][j] > t]

            if not left or not right:
                continue

            gain = gini(y) - (
                len(left)*gini([y[i] for i in left]) +
                len(right)*gini([y[i] for i in right])
            ) / len(y)

            if gain > best:
                best = gain
                split = (j, t, left, right)

    if split is None:
        return max(set(y), key=y.count)

    j, t, l, r = split
    return (j, t,
            build([X[i] for i in l], [y[i] for i in l], depth+1),
            build([X[i] for i in r], [y[i] for i in r], depth+1))

def show(tree):
    if not isinstance(tree, tuple):
        print("Predict:", tree)
        return
    j, t, left, right = tree
    print("IF", names[j], "<=", t)
    show(left)
    print("ELSE")
    show(right)

def predict(tree, x):
    if not isinstance(tree, tuple):
        return tree
    j, t, left, right = tree
    return predict(left if x[j] <= t else right, x)

tree = build(X, y)

print("Decision Rules:")
show(tree)

print("Prediction:", predict(tree, [3, 4]))

# Permutation importance
base = sum(predict(tree, x) == y[i]
           for i, x in enumerate(X)) / len(y)

for j in range(len(names)):
    old = [x[j] for x in X]
    random.shuffle(old)

    for i in range(len(X)):
        X[i][j] = old[i]

    score = sum(predict(tree, x) == y[i]
                for i, x in enumerate(X)) / len(y)

    print(names[j], "Permutation Importance:", base-score)

    for i in range(len(X)):
        X[i][j] = old[i]


# ---- KNN ----
import math

n = int(input("Number of training samples: "))
X = []
y = []

for i in range(n):
    X.append(list(map(float, input("Enter features: ").split())))
    y.append(input("Enter target/class: "))

test = list(map(float, input("Enter test sample: ").split()))
k = int(input("Enter K: "))

distances = []

for i in range(n):
    d = math.sqrt(sum((X[i][j] - test[j]) ** 2
                      for j in range(len(test))))
    distances.append((d, y[i], i))

distances.sort()

neighbors = distances[:k]

print("\nNEAREST NEIGHBORS")

for d, label, i in neighbors:
    print("Sample:", X[i], "Distance:", round(d, 3),
          "Target:", label)

# Classification
votes = [label for d, label, i in neighbors]
prediction = max(set(votes), key=votes.count)

print("\nClassification Prediction:", prediction)

# Regression
values = [float(label) for d, label, i in neighbors]
prediction = sum(values) / k

print("Regression Prediction:", prediction)
