#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 19 15:03:03 2022

@author: bertelsl
"""
import os
import glob
import netCDF4
import json
import xarray as xr
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
from scipy.stats import norm
import matplotlib.mlab as mlab

def hist_intersect(hist1, hist2):
    area = 0.
    
    for iX in range(len(hist1)):
        area += min(hist1[iX], hist2[iX])
        
    return area


fIn1 = r'/data/EEA_HRL_VLCC/user/luc/data/LUCAS2018/4_HANTS_matrices/Barley.nc'
fIn2 = '/data/EEA_HRL_VLCC/user/luc/data/LUCAS2018/4_HANTS_matrices/Common_wheat.nc'

xMX1 = xr.load_dataset(fIn1)  
aMX1 = xMX1['MX'].values
aMX1 = aMX1[~np.isnan(aMX1)]

xMX2 = xr.load_dataset(fIn2)  
aMX2 = xMX2['MX'].values
aMX2 = aMX2[~np.isnan(aMX2)]

hist1, bin_edges1 = np.histogram(aMX1, bins=100)
hist2, bin_edges2 = np.histogram(aMX2, bins=100)

hist1_norm = hist1 / len(aMX1)
hist2_norm = hist2 / len(aMX2)

mu, sigma = norm.fit(hist1)
# best_fit_line = scipy.stats.norm.pdf(bin_edges1, mu, sigma)
y = mlab.normpdf( bin_edges1, mu, sigma)
plt.plot(bin_edges1, y)

fig, ax = plt.subplots()
ax.bar(bin_edges1[:-1], hist1, width=np.diff(bin_edges1), edgecolor="black", align="edge")
plt.show()

# fig, ax = plt.subplots()
# ax.bar(bin_edges2[:-1], hist2, width=np.diff(bin_edges2), edgecolor="black", align="edge")
# plt.show()

# diff = hist_intersect(hist1_norm, hist2_norm)
# print(diff)

