# -*- coding: utf-8 -*-
"""
Created on Tue Nov 23 20:40:34 2021

@author: jcrav
"""


import xarray as xr
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
#______________________________________________________________________________
#ds = xarray.open_dataset('C:/Users/drago/Desktop/EJERCICIO ONI/DATA SST/NOAA_NCDC_ERSST_v3b_SST-1960.nc')
ds = xr.open_mfdataset('C:/ACTUAL/PYTHON SENAMHI/CURSO PYTHON SENAMHI/MODULO II/EJERCICIO ONI/data.nc',
                       decode_times=False)

#units, reference_date = ds.T.attrs['units'].split('since')
ds['T'] = pd.date_range(start="1854-01-01", periods=ds.sizes['T'], freq='MS')

#______________________________________________________________________________
sst = ds.sst.sel(T=slice('1980',None))
#sst.isel(T=0).plot(size=8)
sst_nino34 = sst.sel(Y=slice(-5,5),X=slice(190,240))

sst_nino34_p = sst.sel(Y=slice(-5,5),X=slice(190,240)).mean(dim=['X','Y'])
#______________________________________________________________________________
#.data para visualizar arrays
#.values para visualizar la variable principal

p = sst.isel(T=0).plot(size=10, alpha=0.1)
sst.where((sst.Y<5) & (sst.Y>-5) & (sst.X>190) & (sst.X<240)).isel(T=0).plot(ax=p.axes)
#______________________________________________________________________________
print('Verificamos si se tiene las dimensiones correctas')
print('Rango de latitud: {:.1f} - {:.1f}'.format(sst_nino34.Y.min().values, sst_nino34.Y.max().values))
print('Rango de longitud: {:.1f} - {:.1f}'.format(sst_nino34.X.min().values, sst_nino34.X.max().values))
#______________________________________________________________________________

sst_nino34_climatology = sst_nino34.sel(T=slice('1991','2020')).groupby('T.month').mean(dim=['X','Y','T'])
index_nino34 = sst_nino34_p.groupby('T.month')-sst_nino34_climatology

#______________________________________________________________________________
index_nino34.plot(size=8)

oni=index_nino34.rolling(T=3,center=True).mean().round(1)

valores=oni.values.flatten()
tiempos=oni['T'].data

df = pd.DataFrame({'t':tiempos.astype('datetime64[ns]'), 'd':valores})

#______________________________________________________________________________
fig = plt.figure(figsize=(14, 8))

plt.fill_between(df['t'], df['d'].where(df['d']>=0.5), 0.5, color='red', alpha=0.8)
plt.fill_between(df['t'], df['d'].where(df['d']<=-0.5), -0.5, color='blue', alpha=0.3)
#plt.fill_between(tmp.T.values, tmp.where(tmp<0.4,0.4).where(tmp>-0.4,-0.4).values, color='white')
plt.plot(df['t'],df['d'],color='black')

plt.axhline(0,color='black',lw=0.5)
plt.axhline(0.5,color='black',linewidth=0.5,linestyle='dotted')
plt.axhline(-0.5,color='black',linewidth=0.5,linestyle='dotted')
plt.title('Indice ONI Region 3.4 (Rango = +-0.5 Grados Celsius °C)')