#!/usr/bin/env python # Wenchang Yang (wenchang@princeton.edu) # Sun Sep 11 08:42:49 EDT 2022 if __name__ == '__main__': import sys from misc.timer import Timer tt = Timer('start ' + ' '.join(sys.argv)) import sys, os.path, os, glob, datetime import xarray as xr, numpy as np, pandas as pd, matplotlib.pyplot as plt #more imports # if __name__ == '__main__': tt.check('end import') # #start from here #LMR sst anomaly plus HadISST base climatology lmr_version = '2018' if '2018' in sys.argv else '2019' #years = slice('1200', '1400') #years = slice('1450', '1550') if '1500' in sys.argv else slice('1200', '1400') #years = slice('1350', '1450') years = slice('1250', '1350') baseyears = slice('1981', '2000') ofile = f'LMR{lmr_version}_HadISST_sst_{years.start}-{years.stop}_clim.nc' note = f'HadISST sst monthly climatology over {baseyears.start}-{baseyears.stop} plus LMR{lmr_version} sst anomaly over {years.start}-{years.stop} from the base climatology period.' print(note) if os.path.exists(ofile) and not 'o' in sys.argv: print('[exists]:', ofile) sys.exit() else: #hadisst print('HadISST') ifile = '/tigress/wenchang/HIRAM/input_wy/HadISST/HadISST_sst.187001-202202.wy.nc' print(ifile) da = xr.open_dataarray(ifile).sel(time=baseyears) #make new time coords for the monthly clim t = da.sel(time='1990').time.dt time_new = [datetime.datetime(year, month, day) for year,month,day in zip(t.year, t.month, t.day)] #monthly clim da = da.groupby('time.month').mean('time', keep_attrs=True) da = da.rename(month='time').assign_coords(time=time_new) da['time'].attrs['modulo'] = ' ' #so the GCM knows the monthly climatology is repeated sst_base = da #lmr print('LMR', lmr_version) ifile = f'/tigress/gvecchi/DATA/LMR_{lmr_version}/sst_MCruns_ensemble_mean.nc' print(ifile) da = xr.open_dataarray(ifile) daa = da.sel(time=years).mean(['time', 'MCrun']) - da.sel(time=baseyears).mean(['time', 'MCrun']) #lmr sst interp onto hadisst lon/lat grids #first copy lon=0 to lon=360 daa0 = daa.isel(lon=0) daa0 = daa0.assign_coords(lon=daa0.lon.values+360) daa = xr.concat([daa, daa0], dim='lon') #interp sst_anom = daa.interp(lon=sst_base.lon.values, lat=sst_base.lat.values) #merge with xr.set_options(keep_attrs=True): sst = sst_base + sst_anom.fillna(0) #save ds = sst.to_dataset(name='sst') ds.attrs['note'] = note nc_encoding = {'time':{'dtype': 'double', '_FillValue': None, 'calendar': 'gregorian'}, 'lon':{'_FillValue': None}, 'lat':{'_FillValue': None}, 'sst':{'dtype': 'float32', '_FillValue': None}, } ds.to_netcdf(ofile, encoding=nc_encoding, unlimited_dims='time') print('[saved]:', ofile) if __name__ == '__main__': #from wyconfig import * #my plot settings #savefig if 'savefig' in sys.argv or 's' in sys.argv: figname = __file__.replace('.py', f'.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()