# -*- 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
#______________________________________________________________________________
#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 SST/*nc', combine='by_coords')
ds
#______________________________________________________________________________
sst = ds.sst.sel(time=slice('1980',None))
#sst.isel(time=0).plot(size=8)
sst_nino34 = sst.sel(lat=slice(-5,5),lon=slice(190,240))

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

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

sst_nino34_climatology = sst_nino34.sel(time=slice('1986','2015')).groupby('time.month').mean(dim=['lon','lat','time'])
index_nino34 = sst_nino34_p.groupby('time.month')-sst_nino34_climatology

#______________________________________________________________________________
index_nino34.plot(size=8)

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

#______________________________________________________________________________
fig = plt.figure(figsize=(14, 8))
plt.fill_between(oni.time.values, oni.where(oni>=0.5).values, 0.5, color='red', alpha=0.8)
plt.fill_between(oni.time.values, oni.where(oni<=-0.5).values, -0.5, color='blue', alpha=0.3)
#plt.fill_between(tmp.time.values, tmp.where(tmp<0.4,0.4).where(tmp>-0.4,-0.4).values, color='white')
oni.plot(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)')