#!/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,whereland from misc.ar6regions import flagar6 # if __name__ == '__main__': tt.check('end import') # #start from here #ifile = 'data_precip_FLOR_histRCP45_5ens_1860-2100_SouthAfrica.nc' #ifile = 't_ref_max_FLOR_HistRCP45_tigercpu_intelmpi_18_576PE_5ens_1860-2100_SouthAsia.nc' #ifile = 't_ref_max_FLOR_HistRCP45_tigercpu_intelmpi_18_576PE_5ens_1860-2100_SouthAsia_masked.nc' #ifile = 'precip_FLOR_HistRCP45_tigercpu_intelmpi_18_576PE_5ens_1860-2100_Pernambuco_masked.nc' #ifile = 'precip_AM2.5C360_amipHadISSTlong_chancorr_tigercpu_intelmpi_18_1080PE_10ens_1871-2021_Pernambuco_masked.nc' region = 'WCE' dsname = 'precip' #dsname = 't_ref_max' #dsname = 't_ref' if 't_ref' in sys.argv else 't_ref_max' model = 'AM2.5C360' if 'AM2.5C360' in sys.argv else 'FLOR' expname = 'HistRCP45_tigercpu_intelmpi_18_576PE' if model=='FLOR' else 'AM2.5C360_amipHadISSTlong_chancorr_tigercpu_intelmpi_18_1080PE' #nens = 5 if model=='FLOR' else 10 nens = 10 #ifile = f'{dsname}_FLOR_HistRCP45_tigercpu_intelmpi_18_576PE_5ens_1860-2100_UK.nc' if model=='FLOR' else f'{dsname}_AM2.5C360_amipHadISSTlong_chancorr_tigercpu_intelmpi_18_1080PE_10ens_1871-2021_UK.nc' #ifiles = 'precip_FLOR_HistRCP45_tigercpu_intelmpi_18_576PE_ens??_1860-2100_NHE.nc' ifiles = [ sorted(glob.glob('precip_AM2.5C360_amipHadISSTlong_chancorr_tigercpu_intelmpi_18_1080PE_ens??_1871-2019_NHE.nc')), sorted(glob.glob('precip_AM2.5C360_amipHadISSTlong_chancorr_tigercpu_intelmpi_18_1080PE_extend2020_ens??_2020-2020_NHE.nc')), sorted(glob.glob('precip_AM2.5C360_amipHadISSTlong_chancorr_tigercpu_intelmpi_18_1080PE_extend2021_ens??_2021-2021_NHE.nc')), ] daname = dsname units = 'mm/day' #units = '$^\circ$C' #func_units = lambda x: (x-273.15).assign_attrs(units=units) func_units = lambda x: x #years = slice('1981', '2010') years = slice('1950', '2021') #title = f'FLOR histRCP45 5ens {ifile.split(".")[-2].split("_")[-1]} {years.start}-{years.stop}' title = f'{model} {region} {dsname} {nens}ens {years.start}-{years.stop}' tag = '_' + title.replace(' ', '_') ofile_nc = __file__.replace('.py', f'.nc') #selregion = lambda x: x.sel(lat=slice(20, 37), lon=slice(65, 85)) if os.path.exists(ofile_nc): ds = xr.open_dataset(ofile_nc) print('[loaded]:', ofile_nc) else: print('loading...') #da = xr.open_dataarray(ifile).sel(time=years).load() da = xr.open_mfdataset(ifiles, combine='nested', concat_dim=['time', 'ens'])[daname].sel(time=years).load() print('calculating...') #da = da.where(landflag(da)>0.5).geo.fldmean() da = da.pipe(whereland).pipe(lambda x: x.where(flagar6(x)==17)).geo.fldmean() #da = da.pipe(selregion).pipe(lambda x: x.where(flagland(x)>0.5)).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']) damean = da.groupby('time.month').mean(['time', 'ens']) da_quantile = da.groupby('time.month').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 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)) """ #ds.m.pipe(func_units).plot(color='k', lw=2, label='mean') ds.m.pipe(func_units).plot(color='k', lw=2, label='mean') for ii,qi in enumerate(ds['quantile'].values): ds.q.sel(quantile=qi).pipe(func_units).plot(ax=ax, lw=1, color=f'C{ii}', label=f'{qi*100:.1f}%') #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'] """ 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') """ xticklabels = xr.DataArray(xticklabels, dims='dayofyear', coords=[xticks,]) xticklabels = xticklabels.roll(dayofyear=6, roll_coords=True) xticklabels = xticklabels.assign_coords(dayofyear=xticklabels.dayofyear.where(xticklabels.dayofyear>ndays, other=xticklabels.dayofyear+366)) ax.set_xticks(xticklabels.dayofyear.values) ax.set_xticklabels(xticklabels.values, ha='left') """ #ax.set_xlim(1+ndays, 366+ndays) #ax.set_xlim(1, 366) #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 right') ax.set_title(title, loc='left') #savefig if 'savefig' in sys.argv or 's' in sys.argv: #figname = __file__.replace('.py', f'.png') figname = ofile_nc.replace('.nc', '.png') if 'overwritefig' in sys.argv or 'o' in sys.argv: wysavefig(figname, overwritefig=True) else: wysavefig(figname) tt.check(f'**Done**') print() if 'notshowfig' in sys.argv: pass else: plt.show()