'''metrics for compare two 2D saliency maps'''

import numpy as np
import math

def preprocess(smap):
    smap = smap.flatten()
    if np.sum(smap) != 0:
        smap = smap / np.sum(smap)
    return smap

def computeCC(saliency_map, gt_saliency_map):
    saliency_map = preprocess(saliency_map)
    gt_saliency_map = preprocess(gt_saliency_map)
    score = np.corrcoef([gt_saliency_map, saliency_map])[0][1]
    return score

def computeKL(saliency_map, gt_saliency_map):
    epsilon = 2.2204e-16 #MIT benchmark
    saliency_map = np.clip(saliency_map.flatten(), a_min=epsilon, a_max=None)
    saliency_map = preprocess(saliency_map)
    gt_saliency_map = np.clip(gt_saliency_map.flatten(), a_min=epsilon, a_max=None)
    gt_saliency_map = preprocess(gt_saliency_map)

    kl = 0
    for i in range(len(gt_saliency_map)):
        kl += gt_saliency_map[i] * math.log(gt_saliency_map[i] / (saliency_map[i] + epsilon) + epsilon) 
    return kl


