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

import math 

x1 = 1
x2 = 1

w11 = 1
w21 = 0
w12 = 0
w22 = 2

v1 = 1
v2 = 1

h1_bias = 0
h2_bias = 0
o_bias = 0

def relu(x):
    return max(x, 0)

def sigmoid(x):
    return 1/(1+math.exp(-x))

z1 = x1*w11 + x2*w21 + h1_bias
h1 = relu(z1)

z2 = x1*w12 + x2*w22 + h2_bias
h2 = relu(z2)

s = h1*v1 + h2*v2 + o_bias
prob = sigmoid(s)

print("Hidden Activations:")
print("h1 =", h1)
print("h2 =", h2)

print("\nOutput Logit:", s)
print("Prediction Probability:", round(prob, 4))

Ro = s

Rh1 = ((h1*v1) / (h1*v1 + h2*v2)) * Ro
Rh2 = ((h2*v2) / (h1*v1 + h2*v2)) * Ro

Rx1 = (((x1*w11)/(x1*w11 + x2*w21)) * Rh1) + (((x1*w12)/(x1*w12 + x2*w22)) * Rh2)
Rx2 = (((x2*w21)/(x1*w11 + x2*w21)) * Rh1) + (((x2*w22)/(x1*w12 + x2*w22)) * Rh2)

print("\nHidden Layer Relevance:")
print("R_h1 =", Rh1)
print("R_h2 =", Rh2)

print("\nInput Feature Relevance:")
print("R_x1 =", Rx1)
print("R_x2 =", Rx2)
