enso_clim = enso.mean(dim='year').values # Tile the climatology to each year for plot_tseries_together vals = atm.biggify(tseries_clim[onset_nm], index['tseries'].values, tile=True) _, _, coords, dims = atm.meta(index['tseries']) ts_clim = xray.DataArray(vals, name=tseries_clim[onset_nm].name, coords=coords, dims=dims) tseries[onset_nm + '_clim'] = ts_clim # ---------------------------------------------------------------------- # Timeseries relative to onset, shifted to 0 at onset day npre, npost = 0, 200 tseries_rel = xray.Dataset() for key in tseries.data_vars: tseries_rel[key] = daily_rel2onset(tseries[key], onset, npre, npost, yearnm='year', daynm='day') if key.startswith('CHP') or key.endswith('ACC'): tseries_rel[key] = tseries_rel[key] - tseries_rel[key][:, 0] # ---------------------------------------------------------------------- # Composite timeseries def lowest_highest(ind, nyrs): ind_sorted = ind.to_series() ind_sorted.sort() lowest = ind_sorted[:nyrs].index.values highest = ind_sorted[-1:-nyrs-1:-1].index.values return lowest, highest # Composite definitions nyrs = 5
data = utils.wrapyear(ds, ds_pre, ds_post, daymin, daymax, year=year) data.attrs = ds.attrs return data for plev in plevs: for y, year in enumerate(years): datafile = datafiles[plev][y] d_onset, d_retreat = onset[y], retreat[y] d0 = int(index[ind_nm][y].values) ds_rel = xray.Dataset() ds = get_data(datafile, year, d0, npre, npost) ds_rel.attrs = ds.attrs for nm in ds.data_vars: var = atm.expand_dims(ds[nm], 'year', year) ds_rel[nm] = utils.daily_rel2onset(var, d_onset, npre, npost) ds_rel.attrs['d_onset'] = d_onset ds_rel.attrs['d_retreat'] = d_retreat savefile = savefiles[plev][y] print('Saving to ' + savefile) ds_rel.to_netcdf(savefile) # ---------------------------------------------------------------------- # Compute climatologies and save yearstr = '%d-%d' % (years.min(), years.max()) for plev in plevs: relfiles = savefiles[plev] savefile = savestr % plev + '_' + yearstr + '.nc' ds = atm.combine_daily_years(None, relfiles, years, yearname='year')
with xray.open_dataset(onsetfile) as ds: u = ds['U'].load() oci = indices.onset_OCI(u) d_onset = oci['onset'] # Daily data fields var = 'precip' yearnm, daynm = 'year', 'day' cmap = 'hot_r' axlims = (-10, 50, 40, 120) with xray.open_dataset(datafile) as ds: data = ds['PRECTOT'].load() # Align daily data relative to onset day ndays = 30 data = daily_rel2onset(data, d_onset, ndays, ndays, yearnm=yearnm, daynm=daynm) years = data[yearnm].values databar = data.mean(dim=yearnm) # Days for pre/onset/post composites compdays = comp_days_centered(5) #compdays = comp_days_centered(1, 9) # Calculate composites comp = composite(data, compdays, daynm=daynm + 'rel') compbar = collections.OrderedDict() for key in comp: compbar[key] = comp[key].mean(dim=yearnm) # Plot pre/onset/post composites - climatology cmin, cmax = 0, 20
saveclose('corr_tseries_', isave, exts) # ---------------------------------------------------------------------- # Composite indices relative to onset day keys = ['HOWI_100', 'OCI', 'SJKE', 'TT', 'WLH_MERRA_MFC_nroll7', 'WLH_MERRA_PRECIP_nroll7'] npre, npost = 30, 80 tseries_rel = xray.Dataset() for key in keys: print(key) ts = index[key]['tseries'] d_onset = index[key]['onset'].values tseries_rel[key] = utils.daily_rel2onset(ts, d_onset, npre, npost, yearnm='year', daynm='day') dayrel = tseries_rel['dayrel'].values def plot_tseries(dayrel, ind, std, clr, key, xlabel, ylabel): plt.plot(dayrel, ind, clr, label=key) plt.fill_between(dayrel, ind-std, ind+std, color=clr, alpha=0.2) plt.title(key, fontsize=12) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.grid(True) plt.autoscale(tight=True) plt.figure(figsize=(9, 12)) nrow, ncol = 3, 2 clr = 'k' for i, key in enumerate(keys):
# -- Interpolate to daily resolution days = np.arange(1, 367) pcp_i = np.nan * np.ones((len(years), len(days))) for y, year in enumerate(years): pcp_i[y] = np.interp(days, pcp_box['day'], pcp_box[y]) coords = {'day' : days, 'year' : years} pcp = xray.DataArray(pcp_i, dims=['year', 'day'], coords=coords) # Monsoon onset, retreat indices index = utils.get_onset_indices(onset_nm, indfiles, years) mfc = atm.rolling_mean(index['ts_daily'], nroll, center=True) onset = index['onset'] ssn_length=index['length'].mean(dim='year') data = {} data['MFC'] = utils.daily_rel2onset(mfc, onset, npre, npost) data[pcp_nm] = utils.daily_rel2onset(pcp, onset, npre, npost) data['MFC_ACC'] = utils.daily_rel2onset(index['tseries'], onset, npre, npost) for nm in varnms: print('Loading ' + relfiles[nm]) with xray.open_dataset(relfiles[nm]) as ds: if nm == 'PSI': data[nm] = atm.streamfunction(ds['V']) psimid = atm.subset(data[nm], {'plev' : (pmid, pmid)}, squeeze=True) psimid.name = 'PSI%d' % pmid data['PSI%d' % pmid] = psimid elif nm == 'VFLXLQV': var = atm.dim_mean(ds['VFLXQV'], 'lon', lon1, lon2) data[nm] = var * atm.constants.Lv.values
for key in enso_keys: if key not in enso.columns: months = atm.season_months(key) month_names = [(atm.month_str(m)).capitalize() for m in months] enso[key] = enso[month_names].mean(axis=1) enso = enso[enso_keys] col_names = [enso_nm + ' ' + nm for nm in enso.columns] enso.columns = col_names # ---------------------------------------------------------------------- # Daily timeseries ts = xray.Dataset() for nm in ['GPCP', 'PRECTOT']: ts[nm] = atm.mean_over_geobox(data[nm], lat1, lat2, lon1, lon2) ts['MFC'] = utils.daily_rel2onset(index_all['CHP_MFC']['daily_ts'], index[ind_nm], npre, npost) ts['CMFC'] = utils.daily_rel2onset(index_all['CHP_MFC']['tseries'], index[ind_nm], npre, npost) # Extract variables at specified latitudes for nm, lat0 in lat_extract.iteritems(): var = atm.dim_mean(data[nm], 'lon', lon1, lon2) lat = atm.get_coord(var, 'lat') lat0_str = atm.latlon_labels(lat0, 'lat', deg_symbol=False) # key = nm + '_' + lat0_str key = nm lat_closest, _ = atm.find_closest(lat, lat0) print '%s %.2f %.2f' % (nm, lat0, lat_closest) ts[key] = atm.subset(var, {'lat' : (lat_closest, None)}, squeeze=True)
index.load() index = index.sel(year=years) d0 = index[ind_nm].values # Precip data if pcp_nm == 'cmap': pcp = precipdat.read_cmap(pcpfiles, yearmin=min(years), yearmax=max(years)) # Interpolate to daily resolution name, attrs, coords, dimnames = atm.meta(pcp) days = np.arange(3, 364) interp_func = scipy.interpolate.interp1d(pcp['day'], pcp, axis=1) vals = interp_func(days) coords['day'] = xray.DataArray(days, coords={'day' : days}) pcp = xray.DataArray(vals, dims=dimnames, coords=coords, name=name, attrs=attrs) else: pcp = atm.combine_daily_years(None, pcpfiles, years, yearname='year', subset_dict=subset_dict) # Wrap from following year to get extended daily range daymin = min(d0) - npre daymax = max(d0) + npost pcp = utils.wrapyear_all(pcp, daymin=daymin, daymax=daymax) # Daily relative to onset/withdrawal pcp_rel = utils.daily_rel2onset(pcp, d0, npre, npost) print('Saving to ' + savefile) atm.save_nc(savefile, pcp_rel)