# XAI Experiment 3: Approximate Shapley Value (permutation sampling)  [lab notebook version]
# Requires: exam: none (random) | lab: numpy, pandas, matplotlib
# ===========================================================================

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random

def model(x):
    return 2*x[0] + 3*x[1]+ 5*x[2]

x = [4, 2, 3]

data = [
    [1, 6, 2],
    [5, 1, 4],
    [2, 5, 1]
]

p = len(x)

shapely = [0]*p
for j in range(p):
    for _ in range(1000):
        z = random.choice(data)
        order = [0, 1, 2]
        random.shuffle(order)
        index = order.index(j)
        
        xplus = [0]*p
        
        for i in range(index+1):
            xplus[order[i]]=x[order[i]]
        for i in range(index+1, len(order)):
            xplus[order[i]] = z[order[i]]
        
        
        xminus = [0]*p
            
        for i in range(index):
            xminus[order[i]]=x[order[i]]
        for i in range(index, len(order)):
            xminus[order[i]] = z[order[i]]
            
        
        shapely[j] += model(xplus) - model(xminus)

for j in range(p):
    shapely[j] /= 1000
print(shapely)
