out_units = "m year-1" var_unit_str = "m a$^{-1}$" ylabel = ("speed (%s)" % var_unit_str) elif var in ("RU"): out_units = "km3" var_unit_str = "km$^3$" ylabel = ("runoff (%s)" % var_unit_str) else: print("unit %s not recognized" % var_units) ylabel = ("%s (%s)" % (var, var_units)) var_ylabels.append(ylabel) if (nc.variables[var].ndim == 3): if var_units is not None: var_vals = unit_converter( np.squeeze(nc.variables[var][:, index_j, index_i]), var_units, out_units) else: var_vals = np.squeeze(nc.variables[var][:, index_j, index_i]) else: if var_units is not None: var_vals = unit_converter(np.squeeze(nc.variables[var][:]), var_units, out_units) else: var_vals = np.squeeze(nc.variables[var][:]) if normalize: var_vals -= var_vals[0] values.append(var_vals) nc.close() var_dates.append(dates) var_values.append(values)
fig = plt.figure() ax = fig.add_subplot(111) for ifile in ifiles: nc = NC(ifile) exp = re.search("EXP-(.+?)_", ifile).group(1).upper() time = nc.variables["time"] time_units = time.units time_calendar = time.calendar date = num2date(time[:], units=time_units, calendar=time_calendar) var_vals = nc.variables[plot_var][:] if normalize: var_vals -= nc.variables[plot_var][0] iunits = nc.variables[plot_var].units var_vals = sign * unit_converter(var_vals, iunits, m_var["ounits"]) * mass2sle ax.plot_date(date, var_vals, "-", linestyle="-", linewidth=0.4, label=exp) nc.close() legend = ax.legend() legend.get_frame().set_linewidth(0.0) legend.get_frame().set_alpha(0.0) ax.set_xlim(datetime(2015, 1, 1), datetime(2100, 1, 1)) ax.set_xlabel("Year") ax.set_ylabel(ylabel) set_size(6, 3)
var_ylabels = [] var_longnames = [] print("opening file %s" % args[0]) nc = NC(args[0], 'r') t = nc.variables["time"][:] calendar = nc.variables["time"].calendar units = nc.variables["time"].units cdftime = utime(units, calendar) date = cdftime.num2date(t[:]) profile = nc.variables["z"] profile_units = profile.units profile_outunits = 'm' profile_axis = np.squeeze( unit_converter(profile[:], profile_units, profile_outunits)) var_units = nc.variables[var].units var_longname = nc.variables[var].long_name var_longnames.append(var_longname) if var in ("enthalpy"): out_units = "J kg-1" var_unit_str = ("J kg$^{\mathregular{-1}}$") ylabel = "enthalpy ({})".format(var_unit_str) else: print("unit %s not recognized" % var_units) var_vals = unit_converter(np.squeeze(nc.variables[var]), var_units, out_units) if normalize: var_vals -= var_vals[0]
# FIXME: # If a list of variables is given, only do first in list. var = variables[0] for k in range(no_args): file_name = args[k] print("opening file %s" % file_name) nc = NC(file_name, 'r') profile = nc.variables["profile"] profile_units = profile.units profile_outunits = 'km' profile_axis = np.squeeze( unit_converter(profile[:], profile_units, profile_outunits)) var_units = nc.variables[var].units var_longname = nc.variables[var].long_name var_longnames.append(var_longname) if var in ("ivol"): scale_exponent = 6 scale = 10 ** scale_exponent out_units = "km3" var_units_str = ("10$^{%i}$ km$^{3}$" % scale_exponent) ylabel = ("volume change [%s]" % var_units_str) elif var in ("imass", "mass", "ocean_kill_flux_cumulative", "surface_ice_flux_cumulative", "nonneg_flux_cumulative", "climatic_mass_balance_cumulative", "effective_climatic_mass_balance_cumulative", "effective_ice_discharge_cumulative"):
varname = name else: varname = in_varname for profile_id, profile_name in enumerate(profile_names): fig = plt.figure() ax = fig.add_subplot(111) profile_axis = nc.variables['profile'][profile_id] profile_axis_units = nc.variables['profile'].units profile_axis_name = nc.variables['profile'].long_name profile_axis_out_units = 'km' profile_axis = np.squeeze( unit_converter(profile_axis[:], profile_axis_units, profile_axis_out_units)) my_var = nc.variables[varname] my_var_units = my_var.units my_var_p = permute(my_var, output_order=output_order) data = np.squeeze(my_var_p[profile_id, 0, Ellipsis]) data = unit_converter(data, my_var_units, o_units) # stuff needed for masking z = np.squeeze(nc.variables['z'][:]) b = np.squeeze(nc.variables['topg'][:]) s = np.squeeze(nc.variables['usurf'][:]) ss = np.tile(s, [len(z), 1]) x = profile_axis xx = np.squeeze(np.tile(x, [len(z), 1])).transpose()
elif var in ("csurf", "cbase", "cbar", "ubar", "vbar"): out_units = "m year-1" var_unit_str = "m a$^{-1}$" ylabel = ("speed (%s)" % var_unit_str) elif var in ("RU"): out_units = "km3" var_unit_str = "km$^3$" ylabel = ("runoff (%s)" % var_unit_str) else: print("unit %s not recognized" % var_units) ylabel = ("%s (%s)" % (var, var_units)) var_ylabels.append(ylabel) if (nc.variables[var].ndim == 3): if var_units is not None: var_vals = unit_converter(np.squeeze(nc.variables[var][:, index_j, index_i]), var_units, out_units) else: var_vals = np.squeeze(nc.variables[var][:, index_j, index_i]) else: if var_units is not None: var_vals = unit_converter( np.squeeze(nc.variables[var][:]), var_units, out_units) else: var_vals = np.squeeze(nc.variables[var][:]) if normalize: var_vals -= var_vals[0] values.append(var_vals) nc.close() var_dates.append(dates) var_values.append(values)
def plot_rcp_traj_mass(plot_var=mass_plot_vars): jet = cm = plt.get_cmap('jet') for k, rcp in enumerate(rcp_list): rcp_files = [f for f in ifiles if 'rcp_{}'.format(rcp) in f] if len(rcp_files) < 3: print('Less than 3 files found for {}, skipping'.format( rcp_dict[rcp])) else: print('Reading files for {}'.format(rcp_dict[rcp])) cdf_mass_enspctl16 = cdo.enspctl('16', input=rcp_files, returnCdf=True, options=pthreads) cdf_mass_enspctl84 = cdo.enspctl('84', input=rcp_files, returnCdf=True, options=pthreads) cdf_mass_ensmedian = cdo.enspctl('50', input=rcp_files, returnCdf=True, options=pthreads) t = cdf_mass_ensmedian.variables['time'][:] mass_enspctl16_vals = cdf_mass_enspctl16.variables[ plot_var][:] - cdf_mass_enspctl16.variables[plot_var][0] iunits = cdf_mass_enspctl16[plot_var].units mass_enspctl16_vals = -unit_converter(mass_enspctl16_vals, iunits, mass_ounits) * gt2mSLE mass_enspctl84_vals = cdf_mass_enspctl84.variables[ plot_var][:] - cdf_mass_enspctl84.variables[plot_var][0] iunits = cdf_mass_enspctl84[plot_var].units mass_enspctl84_vals = -unit_converter(mass_enspctl84_vals, iunits, mass_ounits) * gt2mSLE mass_ensmedian_vals = cdf_mass_ensmedian.variables[ plot_var][:] - cdf_mass_ensmedian.variables[plot_var][0] iunits = cdf_mass_ensmedian[plot_var].units mass_ensmedian_vals = -unit_converter(mass_ensmedian_vals, iunits, mass_ounits) * gt2mSLE date = np.arange(start_year + step, start_year + (len(t[:]) + 1) * step, step) for lhs_param in lhs_params_dict: param = lhs_params_dict[lhs_param] param_name = param['param_name'] param_scale_factor = param['scale_factor'] norm = mpl.colors.Normalize(vmin=param['vmin'], vmax=param['vmax']) scalarMap = cmx.ScalarMappable(norm=norm, cmap=jet) fig = plt.figure() offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans) ax = fig.add_subplot(111) for rcp_file in rcp_files: nc = NC(rcp_file, 'r') pism_config = nc.variables['pism_config'] param_value = getattr(pism_config, param_name) * param_scale_factor colorVal = scalarMap.to_rgba(param_value) cdf_rcp_mass_file = nc.variables[plot_var] mass_vals = nc.variables[plot_var][:] - nc.variables[ plot_var][0] iunits = cdf_rcp_mass_file.units mass_vals = -unit_converter(mass_vals, iunits, mass_ounits) * gt2mSLE ax.plot(date[:], mass_vals, alpha=0.3, linewidth=0.2, color=colorVal) nc.close() ax.plot(date[:], mass_ensmedian_vals, color='k', linewidth=0.5) ax.plot(date[:], mass_enspctl16_vals, color='k', linestyle='dashed', linewidth=0.25) ax.plot(date[:], mass_enspctl84_vals, color='k', linestyle='dashed', linewidth=0.25) idx = np.where(np.array(date) == time_bounds[-1])[0][0] m_median = mass_ensmedian_vals[idx] m_pctl16 = mass_enspctl16_vals[idx] m_pctl84 = mass_enspctl84_vals[idx] # x_sle, y_sle = time_bounds[-1], m_median # plt.text( x_sle, y_sle, '{: 1.2f}$\pm${:1.2f}'.format(m_median, m_diff), # color='k') # if do_legend: # legend = ax.legend(loc="upper right", # edgecolor='0', # bbox_to_anchor=(0, 0, .35, 0.88), # bbox_transform=plt.gcf().transFigure) # legend.get_frame().set_linewidth(0.0) ax.set_xlabel('Year (CE)') ax.set_ylabel('$\Delta$(GMSL) (m)') if time_bounds: ax.set_xlim(time_bounds[0], time_bounds[1]) if bounds: ax.set_ylim(bounds[0], bounds[1]) ymin, ymax = ax.get_ylim() ax.yaxis.set_major_formatter(FormatStrFormatter('%1.2f')) if rotate_xticks: ticklabels = ax.get_xticklabels() for tick in ticklabels: tick.set_rotation(30) else: ticklabels = ax.get_xticklabels() for tick in ticklabels: tick.set_rotation(0) title = '{} {}'.format(rcp_dict[rcp], lhs_params_dict[lhs_param]['symb']) if title is not None: plt.title(title) for out_format in out_formats: out_file = outfile + '_rcp' + '_' + rcp + '_' + lhs_param.lower( ) + '_' + plot_var + '.' + out_format print " - writing image %s ..." % out_file fig.savefig(out_file, bbox_inches='tight', dpi=out_res)
def plot_rcp_flux_gt(plot_var=flux_plot_vars, anomaly=False): fig = plt.figure() offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans) ax = fig.add_subplot(111) for k, rcp in enumerate(rcp_list[::-1]): rcp_files = [f for f in ifiles if 'rcp_{}'.format(rcp) in f] if len(rcp_files) < 3: print('Less than 3 files found for {}, skipping'.format( rcp_dict[rcp])) else: print('Reading {} for {}'.format(plot_var, rcp_dict[rcp])) cdf_enspctl16 = cdo.enspctl('16', input=rcp_files, options=pthreads) cdf_enspctl84 = cdo.enspctl('84', input=rcp_files, options=pthreads) cdf_ensmedian = cdo.enspctl('50', input=rcp_files, options=pthreads) t = cdf_ensmedian.variables['time'][:] if anomaly == True: cdf_enspctl16 = cdo.runmean( '11', input='-sub {} -timmean -selyear,2008/2018 {}'.format( cdf_enspctl16, cdf_enspctl16), returnCdf=True, options=pthreads) cdf_enspctl84 = cdo.runmean( '11', input='-sub {} -timmean -selyear,2008/2018 {}'.format( cdf_enspctl84, cdf_enspctl84), returnCdf=True, options=pthreads) cdf_ensmedian = cdo.runmean( '11', input='-sub {} -timmean -selyear,2008/2018 {}'.format( cdf_ensmeadian, cdf_ensmedian), returnCdf=True, options=pthreads) else: cdf_enspctl16 = cdo.runmean('11', input=cdf_enspctl16, returnCdf=True, options=pthreads) cdf_enspctl84 = cdo.runmean('11', input=cdf_enspctl84, returnCdf=True, options=pthreads) cdf_ensmedian = cdo.runmean('11', input=cdf_ensmeadian, returnCdf=True, options=pthreads) enspctl16_vals = cdf_enspctl16.variables[plot_var][:] iunits = cdf_enspctl16[plot_var].units enspctl16_vals = unit_converter(enspctl16_vals, iunits, flux_ounits) enspctl84_vals = cdf_enspctl84.variables[plot_var][:] iunits = cdf_enspctl84[plot_var].units enspctl84_vals = unit_converter(enspctl84_vals, iunits, flux_ounits) ensmedian_vals = cdf_ensmedian.variables[plot_var][:] iunits = cdf_ensmedian[plot_var].units ensmedian_vals = unit_converter(ensmedian_vals, iunits, flux_ounits) date = np.arange(start_year + step, start_year + (len(t[:]) + 1) * step, step) # ensemble between 16th and 84th quantile ax.fill_between(date[:], enspctl16_vals, enspctl84_vals, color=rcp_col_dict[rcp], alpha=0.4, linewidth=0) ax.plot(date[:], ensmedian_vals, color=rcp_col_dict[rcp], linewidth=0.5, label=rcp_dict[rcp]) ax.plot(date[:], enspctl16_vals, color=rcp_col_dict[rcp], linestyle='solid', linewidth=0.25) ax.plot(date[:], enspctl84_vals, color=rcp_col_dict[rcp], linestyle='solid', linewidth=0.25) if ctrl_file is not None: rcp_ctrl_file = [ f for f in ctrl_file if 'rcp_{}'.format(rcp) in f ][0] cdf_ctrl = cdo.readCdf(rcp_ctrl_file) ctrl_t = cdf_ctrl.variables['time'][:] cdf_date = np.arange(start_year + step, start_year + (len(ctrl_t[:]) + 1) * step, step) ctrl_vals = cdf_ctrl.variables[ plot_var][:] - cdf_ctrl.variables[plot_var][0] iunits = cdf_ctrl[plot_var].units ctrl_vals = unit_converter(ctrl_vals, iunits, ounits) ax.plot(cdf_date[:], ctrl_vals, color=rcp_col_dict[rcp], linestyle='dashed', linewidth=0.5) for m_year in [2100, 2200, 2500]: idx = np.where(np.array(date) == m_year)[0][0] m_median = ensmedian_vals[idx] m_pctl16 = enspctl16_vals[idx] m_pctl84 = enspctl84_vals[idx] print('Year {}: {:1.2f} - {:1.2f} - {:1.2f} Gt year-1'.format( m_year, m_pctl84, m_median, m_pctl16)) if ctrl_file: m_ctrl = ctrl_vals[idx] print(' CTRL {:1.2f} Gt year-1'.format(m_ctrl)) if do_legend: legend = ax.legend(loc="upper right", edgecolor='0', bbox_to_anchor=(0, 0, .35, 0.88), bbox_transform=plt.gcf().transFigure) legend.get_frame().set_linewidth(0.0) ax.set_xlabel('Year (CE)') ax.set_ylabel('flux (Gt/yr)') if time_bounds: ax.set_xlim(time_bounds[0], time_bounds[1]) if bounds: ax.set_ylim(bounds[0], bounds[1]) ymin, ymax = ax.get_ylim() ax.yaxis.set_major_formatter(FormatStrFormatter('%1.0f')) if rotate_xticks: ticklabels = ax.get_xticklabels() for tick in ticklabels: tick.set_rotation(30) else: ticklabels = ax.get_xticklabels() for tick in ticklabels: tick.set_rotation(0) if title is not None: plt.title(title) for out_format in out_formats: out_file = outfile + '_rcp' + '_' + plot_var + '.' + out_format print " - writing image %s ..." % out_file fig.savefig(out_file, bbox_inches='tight', dpi=out_res)
def plot_per_basin_flux(plot_var=None): ''' Make a plot per basin with all flux_plot_vars ''' for basin in basin_list: fig = plt.figure() offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans) ax = fig.add_subplot(111) basin_file = [f for f in ifiles if 'b_{}'.format(basin) in f] for k, rcp in enumerate(rcp_list[::-1]): rcp_file = [f for f in basin_file if 'rcp_{}'.format(rcp) in f] print('reading {}'.format(rcp_file[0])) cdf_run = cdo.runmean('11', input=rcp_file[0], returnCdf=True, options=pthreads) t = cdf_run.variables["time"][:] date = np.arange(start_year + step, start_year + (len(t[:]) + 1) * step, step) if plot_var is None: m_vars = [ 'tendency_of_ice_mass_due_to_surface_mass_flux', 'tendency_of_ice_mass_due_to_discharge' ] label_var = 'fluxes' else: m_vars = [plot_var] label_var = plot_var for m_var in m_vars: iunits = cdf_run.variables[m_var].units var_vals = cdf_run.variables[m_var][:] var_vals = unit_converter(np.squeeze(var_vals), iunits, flux_ounits) plt.plot(date[:], var_vals[:], color=rcp_col_dict[rcp], ls=flux_style_dict[m_var], lw=0.5) if do_legend: legend = ax.legend(loc="upper right", edgecolor='0', bbox_to_anchor=(0, 0, 1.15, 1), bbox_transform=plt.gcf().transFigure) legend.get_frame().set_linewidth(0.2) ax.set_xlabel('Year (CE)') ax.set_ylabel('mass flux (Gt yr$^{\mathregular{-1}}$)') if time_bounds: ax.set_xlim(time_bounds[0], time_bounds[1]) if bounds: ax.set_ylim(bounds[0], bounds[1]) if rotate_xticks: ticklabels = ax.get_xticklabels() for tick in ticklabels: tick.set_rotation(30) else: ticklabels = ax.get_xticklabels() for tick in ticklabels: tick.set_rotation(0) if title is not None: plt.title(title) for out_format in out_formats: out_file = outfile + '_' + basin + '_' + label_var + '.' + out_format print " - writing image %s ..." % out_file fig.savefig(out_file, bbox_inches='tight', dpi=out_res)
def plot_basin_flux(plot_var='discharge'): ''' Make a plot per basin with all flux_plot_vars ''' fig = plt.figure() offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans) ax = fig.add_subplot(111) for basin in basin_list: basin_file = [f for f in ifiles if 'b_{}'.format(basin) in f] print basin_file print('reading {}'.format(basin_file[0])) if plot_var == 'discharge': cdf = cdo.expr( 'discharge=tendency_of_ice_mass_due_to_discharge+tendency_of_ice_mass_due_to_basal_mass_flux', input=basin_file[0]) cdf_run = cdo.runmean('11', input=cdf, returnCdf=True, options=pthreads) iunits = 'Gt year-1' var_vals = cdf_run.variables[plot_var][:] t = cdf_run.variables["time"][:] date = np.arange(start_year + step, start_year + (len(t[:]) + 1) * step, step) var_vals = unit_converter(np.squeeze(var_vals), iunits, flux_ounits) plt.plot(date[:], var_vals[:], color=basin_col_dict[basin], lw=0.5) if do_legend: legend = ax.legend(loc="upper right", edgecolor='0', bbox_to_anchor=(0, 0, 1.15, 1), bbox_transform=plt.gcf().transFigure) legend.get_frame().set_linewidth(0.2) ax.set_xlabel('Year (CE)') ax.set_ylabel('mass flux (Gt yr$^{\mathregular{-1}}$)') if time_bounds: ax.set_xlim(time_bounds[0], time_bounds[1]) if bounds: ax.set_ylim(bounds[0], bounds[1]) if rotate_xticks: ticklabels = ax.get_xticklabels() for tick in ticklabels: tick.set_rotation(30) else: ticklabels = ax.get_xticklabels() for tick in ticklabels: tick.set_rotation(0) if title is not None: plt.title(title) for out_format in out_formats: out_file = outfile + '_fluxes.' + out_format print " - writing image %s ..." % out_file fig.savefig(out_file, bbox_inches='tight', dpi=out_res)
def plot_basin_mass(): fig = plt.figure() offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans) ax = fig.add_subplot(111) mass_var_vals_positive_cum = 0 mass_var_vals_negative_cum = 0 for k, ifile in enumerate(ifiles): basin = basin_list[k] print('reading {}'.format(ifile)) nc = NC(ifile, 'r') t = nc.variables["time"][:] date = np.arange(start_year + step, start_year + (len(t[:]) + 1) * step, step) idx = np.where(np.array(date) == time_bounds[-1])[0][0] mvar = 'ice_mass' mass_var_vals = -np.squeeze(nc.variables[mvar][:] - nc.variables[mvar][0]) * gt2mSLE iunits = nc.variables[mvar].units mass_var_vals = unit_converter(mass_var_vals, iunits, mass_ounits) if mass_var_vals[idx] > 0: ax.fill_between(date[:], mass_var_vals_positive_cum, mass_var_vals_positive_cum + mass_var_vals[:], color=basin_col_dict[basin], linewidth=0, label=basin) else: print mass_var_vals[idx] ax.fill_between(date[:], mass_var_vals_negative_cum, mass_var_vals_negative_cum + mass_var_vals[:], color=basin_col_dict[basin], linewidth=0, label=basin) plt.rcParams['hatch.color'] = basin_col_dict[basin] plt.rcParams['hatch.linewidth'] = 0.1 ax.fill_between(date[:], mass_var_vals_negative_cum, mass_var_vals_negative_cum + mass_var_vals[:], facecolor="none", hatch="XXXXX", edgecolor="k", linewidth=0.0) if mass_var_vals[idx] > 0: ax.plot(date[:], mass_var_vals_positive_cum + mass_var_vals[:], color='k', linewidth=0.1) else: ax.plot(date[:], mass_var_vals_negative_cum + mass_var_vals[:], color='k', linewidth=0.1) offset = 0 if mass_var_vals[idx] > 0: try: x_sle, y_sle = date[idx] + offset, mass_var_vals_positive_cum[ idx] except: # first iteratio x_sle, y_sle = date[idx] + offset, mass_var_vals_positive_cum else: try: x_sle, y_sle = date[idx] + offset, mass_var_vals_negative_cum[ idx] + mass_var_vals[idx] except: # first iteration x_sle, y_sle = date[ idx] + offset, mass_var_vals_negative_cum + mass_var_vals[ idx] nc.close() if mass_var_vals[idx] > 0: mass_var_vals_positive_cum += mass_var_vals else: mass_var_vals_negative_cum += mass_var_vals ax.hlines(0, time_bounds[0], time_bounds[-1], lw=0.25) legend = ax.legend(loc="upper right", edgecolor='0', bbox_to_anchor=(0, 0, 1.15, 1), bbox_transform=plt.gcf().transFigure) legend.get_frame().set_linewidth(0.2) ax.set_xlabel('Year (CE)') ax.set_ylabel('$\Delta$(GMSL) (m)') if time_bounds: ax.set_xlim(time_bounds[0], time_bounds[1]) if bounds: ax.set_ylim(bounds[0], bounds[-1]) if rotate_xticks: ticklabels = ax.get_xticklabels() for tick in ticklabels: tick.set_rotation(30) else: ticklabels = ax.get_xticklabels() for tick in ticklabels: tick.set_rotation(0) if title is not None: plt.title(title) for out_format in out_formats: out_file = outfile + '_' + mvar + '.' + out_format print " - writing image %s ..." % out_file fig.savefig(out_file, bbox_inches='tight', dpi=out_res)