# XAI Experiment 10: Layer-wise Relevance Propagation (LRP)  [exam version]
# Requires: exam: none (math) | lab: none
# ===========================================================================

import math

def lrp(x1, x2):
    # Weights and biases
    w11, w21 = 1, 0
    w12, w22 = 0, 2
    v1, v2 = 1, 1

    # Forward propagation
    h1 = max(0, x1*w11 + x2*w21)
    h2 = max(0, x1*w12 + x2*w22)

    s = h1*v1 + h2*v2
    probability = 1 / (1 + math.exp(-s))

    # Initialize output relevance
    R_output = s

    # Output -> hidden layer
    denominator = h1*v1 + h2*v2

    if denominator == 0:
        Rh1 = Rh2 = Rx1 = Rx2 = 0
    else:
        Rh1 = (h1*v1 / denominator) * R_output
        Rh2 = (h2*v2 / denominator) * R_output

        # Hidden neuron 1 -> input
        d1 = x1*w11 + x2*w21
        Rx1_h1 = (x1*w11 / d1) * Rh1 if d1 != 0 else 0
        Rx2_h1 = (x2*w21 / d1) * Rh1 if d1 != 0 else 0

        # Hidden neuron 2 -> input
        d2 = x1*w12 + x2*w22
        Rx1_h2 = (x1*w12 / d2) * Rh2 if d2 != 0 else 0
        Rx2_h2 = (x2*w22 / d2) * Rh2 if d2 != 0 else 0

        # Total input relevance
        Rx1 = Rx1_h1 + Rx1_h2
        Rx2 = Rx2_h1 + Rx2_h2

    # Display results
    print("\nInput:", x1, x2)
    print("Hidden activations:", h1, h2)
    print("Output logit:", s)
    print("Probability:", round(probability, 4))
    print("Output relevance:", R_output)
    print("Hidden relevance:", Rh1, Rh2)
    print("Input relevance:", Rx1, Rx2)

    print("Hidden conservation:", Rh1 + Rh2 == R_output)
    print("Input conservation:", math.isclose(Rx1 + Rx2, R_output))


# All test cases from the PDF
lrp(1, 1)
lrp(2, 1)
lrp(0, 1)
lrp(1, 0)
lrp(0, 0)
