# -*- coding: utf-8 -*-

"""
Created on Tue Jul 12 12:29:29 2022

@author: bertelsl
"""


# bhattacharyya test
import numpy as np
import math
import pandas as pd

data = {'orange' : [37, 27, 45, 30, 57, 48, 34, 50, 20, 53, 33, 25, 51],
'lemon':  [12, 17, 20, 32, 16, 30, 30, 37, 25, 42, 13, 56, 13],
'pear':  [41, 19, 15, 12, 15, 55, 33, 37, 40, 40, 43, 46, 54],
'apple':  [38, 39, 12, 60, 34, 47, 13, 24, 30, 19, 57, 54, 55]}

columns = ['orange', 'lemon', 'pear','apple']

df = pd.DataFrame(data,columns=columns)


CropA = {'orange' : [37, 27, 45, 30, 57, 48, 34, 50, 20, 53, 33, 25, 51]}
CropB = {'lemon' : [737, 727, 745, 830, 857, 848, 834, 950, 920, 953, 933, 925, 952]}
#CropB = {'lemon':  [12, 17, 20, 32, 16, 30, 30, 37, 25, 42, 13, 56, 13]}


dfA = pd.DataFrame(CropA,columns=['orange'])
dfB = pd.DataFrame(CropB,columns=['lemon'])

meanA = np.mean(dfA)
meanB = np.mean(dfB)
meanDif = meanA.values - meanB.values

covA = np.cov(dfA.values.T)
covB = np.cov(dfB.values.T)

p = (covA + covB) / 2
# det_p = np.abs(np.linalg.det(p))
# det_A = np.abs(np.linalg.det(covA))
# det_B = np.abs(np.linalg.det(covB))

  # calculate the Bhattacharryya index
  # 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.values.T * np.power(p, -1) * meanDif.values + 0.5 * np.log(det_p / np.sqrt(det_A * det_B))
BHdist = 0.125 * meanDif * np.power(p, -1) * meanDif + 0.5 * np.log(p / np.sqrt(covA * covB))

#jm.distance <- 2 * ( 1 - exp ( -bh.distance ) )
JMdist = 2 * (1 - np.exp(-1 * BHdist))

print(JMdist)
