#!/usr/bin/env python # Wenchang Yang (wenchang@princeton.edu) # Tue Jun 29 16:14:32 EDT 2021 if __name__ == '__main__': from misc.timer import Timer tt = Timer(f'start {__file__}') import sys, os.path, os, glob, datetime import xarray as xr, numpy as np, pandas as pd, matplotlib.pyplot as plt #more imports import geoxarray #from misc.landmask import flagland #import salem from misc import get_kws_from_argv # if __name__ == '__main__': tt.check('end import') # #start from here model = os.path.basename(os.getcwd()) #shapefile = '../state_Rio_Grande_do_Sul/43UF2500G.shp' #shdf = salem.read_shapefile(shapefile) #region = 'Rio Grande' region = get_kws_from_argv('region', 'southern') #ifile = 'precip_FLOR_HistRCP45_tigercpu_intelmpi_18_576PE_10ens_1860-2100_atmos_daily.landfldmean.20_28.5_36_42.5.nc' #ifile = glob.glob(f'precip_*.landfldmean.20_28.5_36_42.5.nc')[0] if region == 'southern': ifile = glob.glob(f'precip_*_{region}_masked.nc')[0] elif region == 'northern': ifiles = glob.glob('precip_*_hurricaneHelene.nc') ifiles.sort() #if model == 'AM2.5C360': # ifile = 'precip_AM2.5C360_amipHadISSTrcp45_tigercpu_intelmpi_18_1080PE_3ens_1871-2100_atmos_daily.region.300_312_-35_-25.RioGrande.nc' #elif modle = 'FLOR': # ifile = 'precip_FLOR_HistRCP45_tigercpu_intelmpi_18_576PE_10ens_1860-2100_atmos_daily.region.300_312_-35_-25.RioGrande.nc' dsname = 'precip' daname = dsname units = 'mm/day' #years = slice('1981', '2010') #years = slice('1990', '2020') years = slice('1991', '2020') #title = f'AM2p5C360 AMIP 3ens East Africa {years.start}-{years.stop}' title = f'{daname} {model} {region} {years.start}-{years.stop}' tag = '__' + title.replace(' ', '_') ofile_nc = __file__.replace('.py', f'{tag}.nc') if os.path.exists(ofile_nc): ds = xr.open_dataset(ofile_nc) print('[loaded]:', ofile_nc) else: print('loading...') if region == 'southern': da = xr.open_dataarray(ifile).sel(time=years).load() elif region == 'northern': da = xr.open_mfdataset(ifiles)[daname].sel(time=years).load() print('calculating...') #da = da.where(landflag(da)>0.5).geo.fldmean() #da = da.geo.fldmean() #da = da.assign_coords(lon=da.lon.values-360).salem.roi(shape=shdf).geo.fldmean() da = da.geo.fldmean() damean = da.groupby('time.dayofyear').mean(['time', 'ens']) da_quantile = da.groupby('time.dayofyear').quantile([0.025, 0.17, 0.83, 0.975], dim=['time', 'ens']) ds = xr.Dataset(dict(m=damean, q=da_quantile)) print('saving...') ds.to_netcdf(ofile_nc) print('[saved]:', ofile_nc) if __name__ == '__main__': from wyconfig import * #my plot settings #ds = ds.pipe(lambda x: x-273.15) fig, ax = plt.subplots() #rotate dayofyear roll_time = False if roll_time: ndays = 31+29+31+30+31+30 #Jan-Jun days ds = ds.roll(dayofyear=-ndays, roll_coords=True) ds = ds.assign_coords(dayofyear=ds.dayofyear.where(ds.dayofyear>ndays, other=ds.dayofyear+366)) else: ndays = 0 ds.m.plot(color='k', lw=2, label='mean') for ii,qi in enumerate(ds['quantile'].values): ds.q.sel(quantile=qi).plot(ax=ax, color=f'C{ii}', label=f'{qi*100:.1f}%', lw=1) xticks = np.cumsum([1, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30]) xticklabels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] #roll xticks if roll_time: xticks = np.roll(xticks, -6) xticks = np.where(xticks>ndays, xticks, xticks+366) xticklabels = np.roll(xticklabels, -6) ax.set_xticks(xticks) ax.set_xticklabels(xticklabels, ha='left') ax.set_xlim(1+ndays, 366+ndays) ax.set_xlabel('') ax.set_ylabel(f'{daname} [{units}]') ax.set_title('') #ax.text(0,1, f' {360-lons.start}-{360-lons.stop}W, {lats.start}-{lats.stop}N, land', transform=ax.transAxes, # ha='left', va='top') #ax.legend(loc='upper left') ax.legend() ax.set_title(title, loc='left') #savefig if 'savefig' in sys.argv or 's' in sys.argv: figname = __file__.replace('.py', f'{tag}.png') wysavefig(figname) tt.check(f'**Done**') plt.show()