#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 13 08:34:50 2022

@author: bertelsl
"""

# from: https://stackoverflow.com/questions/24762383/spectral-separability-using-jeffries-matusita-distance-method-in-r

import numpy as np
import math
import pandas as pd

cropA = [[37, 27, 45, 30, 57, 48, 34, 50, 20, 53, 33, 25, 51],
[12, 17, 20, 32, 16, 30, 30, 37, 25, 42, 13, 56, 13], 
[41, 19, 15, 12, 15, 55, 33, 37, 40, 40, 43, 46, 54], 
[38, 39, 12, 60, 34, 47, 13, 24, 30, 19, 57, 54, 55]]

df = pd.DataFrame(cropA)
# df = pd.DataFrame()

iX = 0

# for name, values in dftmp.iteritems():    
#     tmp = values / np.max(values)     
#     df[iX] = tmp
#     iX += 1

def calcJM(v1, v2):
    meanA = np.mean(v1)
    meanB = np.mean(v2)
    meanDif = meanA - meanB
    
    covA = np.cov(v1)
    covB = np.cov(v2)
    
    p = (covA + covB) / 2

  # calculate the Bhattacharryya distance:
  # bh.distance <- 0.125 *t ( mean.difference ) * p^ ( -1 ) * mean.difference +
  #   0.5 * log (det ( p ) / sqrt (det ( cv.Matrix.1 ) * det ( cv.Matrix.2 )))

    BHdist = 0.125 * meanDif * np.power(p, -1) * meanDif + 0.5 * np.log(p / np.sqrt(covA * covB))
    
    # calculate the jeffries-matsushita distance:
    # jm.distance <- 2 * ( 1 - exp ( -bh.distance ) )
    
    JMdist = 2 * (1 - np.exp(-1 * BHdist))

    return JMdist

nEntries = len(cropA)

aMX = np.zeros(shape=(nEntries, nEntries))

for iX in range(0, nEntries-1):
    for iY in range (iX+1, nEntries):
        
        JMdist = calcJM(df.iloc[iX], df.iloc[iY])

        aMX[iY, iX] = JMdist
        
print(aMX)


