def mom_preproc_files(data_path, output_dir, analysis_period, payu_style): # Get Mom data if payu_style: all_mom_files = glob.glob(data_path + '/output*' + '/ocean/ocean.nc') all_mom_scalar_files = glob.glob(data_path + '/output*' + '/ocean/ocean_scalar.nc') else: all_mom_files = glob.glob(data_path + '/ocn/ocean_month.nc-*') all_mom_scalar_files = glob.glob(data_path + '/ocn/ocean_scalar.nc-*') # Weed out any files which we don't have permission to read. mom_data_files = [f for f in all_mom_files if os.access(f, os.R_OK)] mom_scalar_data_files = [f for f in all_mom_scalar_files if os.access(f, os.R_OK)] assert(mom_data_files != []) assert(mom_scalar_data_files != []) # Get outputfiles for the last x years. x_years_files, date_str, _ = get_last_x_years(mom_data_files, analysis_period) total_mean_file = os.path.join(output_dir, 'ocean_mean_{}.nc'.format(date_str)) monthly_mean_file = os.path.join(output_dir, 'ocean_monthly_mean_{}.nc'.format(date_str)) return (mom_data_files, mom_scalar_data_files, x_years_files, total_mean_file, monthly_mean_file)
def main(): parser = argparse.ArgumentParser() parser.add_argument('input_files', nargs='+', help="The input data file in NetCDF format.") parser.add_argument('--preproc_dir', default='./', help='Directory where preprocessed files are placed.') parser.add_argument('--output_file', default='amoc.png', help="""The name of the AMOC output file.""") parser.add_argument('--global_output_file', default=None, help=""" The name of the output file for the global moc. The global MOC is only calculated if this is set. """) parser.add_argument('--output_atlantic_mask', action='store_true', default=False, help=""" Output the mask file used to define the Atlantic basin. """) args = parser.parse_args() with nc.Dataset(args.input_files[0]) as f: lons = f.variables['geolon_t'][:] lats = f.variables['geolat_t'][:] times = f.variables['time'][:] if len(args.input_files) == 1 and len(times) == 1: mean_file = args.input_files[0] else: # Calculate a mean if one doesn't already exist. # Figure out output filename based on input files files, date_str, runtime = get_last_x_years(args.input_files, -1) mean_file = os.path.join(args.preproc_dir, 'ocean_mean_{}.nc'.format(date_str)) if not os.path.exists(mean_file): vars = ['ty_trans', 'dzt', 'geolon_t', 'geolat_t'] create_output_file(args.input_files[0], vars, mean_file + '.tmp') calc_overall_mean(args.input_files, ['ty_trans', 'dzt'], mean_file + '.tmp') shutil.move(mean_file + '.tmp', mean_file) with nc.Dataset(mean_file) as f: ty_trans = f.variables['ty_trans'][0, :, :, :] dzt = f.variables['dzt'][0, :, :, :] plot_atlantic_moc(ty_trans, dzt, lons, lats, args.output_file, args.output_atlantic_mask, date_str) if args.global_output_file is not None: plot_global_moc(ty_trans, dzt, lons, lats, args.global_output_file, date_str) return 0
def cice_preproc_files(data_path, output_dir, analysis_period, payu_style): # Get CICE data if payu_style: data_files = glob.glob(data_path + '/output*' + '/ice/HISTORY/iceh.*.nc') else: data_files = glob.glob(data_path + '/ice/iceh.*.nc') # Filter out any files which we don't have permission to read. data_files = [f for f in data_files if os.access(f, os.R_OK)] assert(data_files != []) x_years_files, date_str, runtime = get_last_x_years(data_files, analysis_period, model='ice') monthly_mean_file = os.path.join(output_dir, 'ice_monthly_mean_{}.nc'.format(date_str)) total_mean_file = os.path.join(output_dir, 'ice_mean_{}.nc'.format(date_str)) return (data_files, x_years_files, monthly_mean_file, total_mean_file, runtime)
def main(): parser = argparse.ArgumentParser() parser.add_argument("input_files", nargs="+", help="The MOM ocean.nc input data files.") parser.add_argument("--preproc_dir", default="./", help="Directory where preprocessed files are placed.") parser.add_argument("--output_file", default="nino34.png", help="Name of plot to output.") args = parser.parse_args() # Figure out output filename based on input files files, date_str, runtime = get_last_x_years(args.input_files, 30) monthly_mean_file = os.path.join(args.preproc_dir, "ocean_monthly_mean_{}.nc".format(date_str)) # Calculate the monthly means over the last 30 years of the time series mom_monthly_mean(files, monthly_mean_file, ["temp"]) lat_start_idx, lat_end_idx, lon_start_idx, lon_end_idx = get_indices_for_nino34_region(monthly_mean_file) # Grab surface temp spatial mean in the nino34 region with nc.Dataset(monthly_mean_file) as f: temp_var = f.variables["temp"] mean_ssts = [] for t in range(temp_var.shape[0]): sst = np.mean(temp_var[t, 0, lat_start_idx:lat_end_idx, lon_start_idx:lon_end_idx]) mean_ssts.append(sst) assert len(mean_ssts) == 12 # Split up the job and make the timeseries. args_len = len(args.input_files) results = futures.map( make_nino34_timeseries, args.input_files, [mean_ssts] * args_len, [lat_start_idx] * args_len, [lat_end_idx] * args_len, [lon_start_idx] * args_len, [lon_end_idx] * args_len, ) ts = pd.Series() for t in results: ts = ts.append(t) # Plot timeseries' with a 5 month running mean ts = ts.sort_index() ts_rm = pd.rolling_mean(ts, window=5) # Convert periods to datetime dates = [datetime.date(pi.year, pi.month, pi.day) for pi in ts.index] fig, axarr = plt.subplots(2, sharex=True) # FIXME: this assumes the data is monthly, an assumption should be checked # above but is not. smooth_years = 10.0 smooth_fraction = smooth_years * 12 / len(ts.values) lowess = sm.nonparametric.lowess(ts.values, range(len(ts.index)), frac=smooth_fraction) x_lowess = lowess[:, 0] y_lowess = lowess[:, 1] axarr[0].plot(dates, ts.values, "red", lw=1.0) axarr[0].plot(dates, y_lowess, "red", lw=3.0, label="Lowess 10 yr") axarr[0].set_ylabel("Temperature Anomaly (C)") axarr[0].set_title("Decadal Temperature Anomaly Trend in Nino3.4 Region") axarr[0].legend() # Include information about monotonically decreasing segments. text = "Mostly decreasing segments:\n" mdss = monotonically_decreasing_segments(x_lowess, y_lowess, tolerance=24) for i in range(5): temp_change = max(y_lowess[mdss[i]]) - min(y_lowess[mdss[i]]) text += "{0:.2f} deg C around {1} to {2}\n".format(temp_change, dates[mdss[i][0]], dates[mdss[i][-1]]) print(text) props = dict(boxstyle="round", facecolor="wheat", alpha=0.5) axarr[0].text(0.05, 0.95, text, transform=axarr[0].transAxes, verticalalignment="top", bbox=props) axarr[1].fill_between(dates, 0, ts_rm.values, where=ts_rm.values >= 0, facecolor="blue", interpolate=True) axarr[1].fill_between(dates, 0, ts_rm.values, where=ts_rm.values <= 0, facecolor="red", interpolate=True) axarr[1].set_ylabel("Temperature Anomaly (C)") axarr[1].set_xlabel("Time (years)") axarr[1].set_title("Temperature Anomalies in Nino3.4 Region") fig.set_size_inches(16, 10) plt.tight_layout() plt.savefig(args.output_file) plt.close()