def main(): import application_properties application_properties.set_current_directory() plot_utils.apply_plot_params(font_size=12, width_cm=25, height_cm=25) # Create folder for output images if not img_folder.is_dir(): img_folder.mkdir(parents=True) with_lakes_c_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/quebec_0.1_crcm5-hcd-rl-cc-canesm2-1980-2010.hdf5" with_lakes_label = "CRCM5-L" no_lakes_c_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/quebec_0.1_crcm5-r-cc-canesm2-1980-2010.hdf5" no_lakes_label = "CRCM5-NL" start_year_c = 1980 end_year_c = 2010 varname = "STFL" nyears_to_future = 75 with_lakes_config_c = RunConfig(data_path=with_lakes_c_path, start_year=start_year_c, end_year=end_year_c, label=with_lakes_label) with_lakes_config_f = with_lakes_config_c.get_shifted_config( nyears_to_future) no_lakes_config_c = RunConfig(data_path=no_lakes_c_path, start_year=start_year_c, end_year=end_year_c, label=no_lakes_label) no_lakes_config_f = no_lakes_config_c.get_shifted_config(nyears_to_future) bmp_info = analysis.get_basemap_info_from_hdf(file_path=with_lakes_c_path) # Calculate daily climatologic fields with_lakes_c_daily = analysis.get_daily_climatology_for_rconf( with_lakes_config_c, var_name=varname, level=0) with_lakes_f_daily = analysis.get_daily_climatology_for_rconf( with_lakes_config_f, var_name=varname, level=0) no_lakes_c_daily = analysis.get_daily_climatology_for_rconf( no_lakes_config_c, var_name=varname, level=0) no_lakes_f_daily = analysis.get_daily_climatology_for_rconf( no_lakes_config_f, var_name=varname, level=0) configs = DataConfig(bmp_info, no_lakes_config_c, no_lakes_config_f, with_lakes_config_c, with_lakes_config_f) args = (no_lakes_c_daily, no_lakes_f_daily, with_lakes_c_daily, with_lakes_f_daily) data = Data(*[arg[1] for arg in args]) plot_comparison_std(configs, data, varname=varname)
def main(): import application_properties application_properties.set_current_directory() plot_utils.apply_plot_params(font_size=12, width_cm=25, height_cm=25) # Create folder for output images if not img_folder.is_dir(): img_folder.mkdir(parents=True) with_lakes_c_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/quebec_0.1_crcm5-hcd-rl-cc-canesm2-1980-2010.hdf5" with_lakes_label = "CRCM5-L" no_lakes_c_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/quebec_0.1_crcm5-r-cc-canesm2-1980-2010.hdf5" no_lakes_label = "CRCM5-NL" start_year_c = 1980 end_year_c = 2010 varname = "STFL" nyears_to_future = 75 with_lakes_config_c = RunConfig(data_path=with_lakes_c_path, start_year=start_year_c, end_year=end_year_c, label=with_lakes_label) with_lakes_config_f = with_lakes_config_c.get_shifted_config(nyears_to_future) no_lakes_config_c = RunConfig(data_path=no_lakes_c_path, start_year=start_year_c, end_year=end_year_c, label=no_lakes_label) no_lakes_config_f = no_lakes_config_c.get_shifted_config(nyears_to_future) bmp_info = analysis.get_basemap_info_from_hdf(file_path=with_lakes_c_path) # Calculate daily climatologic fields with_lakes_c_daily = analysis.get_daily_climatology_for_rconf(with_lakes_config_c, var_name=varname, level=0) with_lakes_f_daily = analysis.get_daily_climatology_for_rconf(with_lakes_config_f, var_name=varname, level=0) no_lakes_c_daily = analysis.get_daily_climatology_for_rconf(no_lakes_config_c, var_name=varname, level=0) no_lakes_f_daily = analysis.get_daily_climatology_for_rconf(no_lakes_config_f, var_name=varname, level=0) configs = DataConfig(bmp_info, no_lakes_config_c, no_lakes_config_f, with_lakes_config_c, with_lakes_config_f) args = (no_lakes_c_daily, no_lakes_f_daily, with_lakes_c_daily, with_lakes_f_daily) data = Data(*[arg[1] for arg in args]) plot_comparison_std(configs, data, varname=varname)
def main(): import application_properties application_properties.set_current_directory() # Create folder for output images if not img_folder.is_dir(): img_folder.mkdir(parents=True) rea_driven_path = "/RESCUE/skynet3_rech1/huziy/hdf_store/quebec_0.1_crcm5-hcd-rl.hdf5" rea_driven_label = "CRCM5-L-ERAI" # gcm_driven_path_c = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/quebec_0.1_crcm5-r-cc-canesm2-1980-2010.hdf5" gcm_driven_path_c = "/home/huziy/skynet3_rech1/hdf_store/cc-canesm2-driven/quebec_0.1_crcm5-hcd-rl-cc-canesm2-1980-2010.hdf5" gcm_driven_label_c = "CRCM5-L" gcm_driven_path_f = "/home/huziy/skynet3_rech1/hdf_store/cc-canesm2-driven/quebec_0.1_crcm5-hcd-rl-cc-canesm2-2070-2100.hdf5" start_year_c = 1980 end_year_c = 2010 varname = "STFL" future_shift_years = 90 params = dict( data_path=rea_driven_path, start_year=start_year_c, end_year=end_year_c, label=rea_driven_label) geo_data_file = "/skynet3_rech1/huziy/hdf_store/pm1979010100_00000000p" rea_driven_config = RunConfig(**params) params.update(dict(data_path=gcm_driven_path_c, label=gcm_driven_label_c)) gcm_driven_config_c = RunConfig(**params) gcm_driven_config_f = gcm_driven_config_c.get_shifted_config(shift_years=future_shift_years, data_path=gcm_driven_path_f) r_obj = RPN(geo_data_file) facc = r_obj.get_first_record_for_name("FAA") fldr = r_obj.get_first_record_for_name("FLDR") lkfr = r_obj.get_first_record_for_name("ML") # get basemap information bmp_info = analysis.get_basemap_info_from_hdf(file_path=rea_driven_path) # get basin mask _, bname_to_mask = plot_basin_outlets(bmp_info=bmp_info, directions=fldr, accumulation_areas=facc, lake_fraction_field=lkfr) all_basins_mask = np.zeros(fldr.shape) for bname, the_mask in bname_to_mask.items(): all_basins_mask += the_mask rs_gcm_c = get_return_levels_and_unc_using_bootstrap(gcm_driven_config_c, varname=varname) rs_gcm_f = get_return_levels_and_unc_using_bootstrap(gcm_driven_config_f, varname=varname) plot_utils.apply_plot_params(font_size=10, width_cm=20, height_cm=18) # Plot return level changes fig = plt.figure() nplots = 0 for the_type, rp_to_rl in rs_gcm_c.return_lev_dict.items(): nplots += len(rp_to_rl) ncols = 2 nrows = nplots // ncols + int(nplots % ncols != 0) gs = GridSpec(nrows, ncols + 1, width_ratios=[1.0, ] * ncols + [0.05, ]) xx, yy = bmp_info.get_proj_xy() cmap = cm.get_cmap("bwr", 20) limits = { "high": (-50, 50), "low": (-150, 150) } for row, (the_type, rp_to_rl) in enumerate(sorted(rs_gcm_c.return_lev_dict.items(), key=lambda itm: itm[0])): for col, rp in enumerate(sorted(rp_to_rl)): ax = fig.add_subplot(gs[row, col]) rl = rp_to_rl[rp] # Ignore 0 return levels in the current climate for percentage calculations # rl = np.ma.masked_where(rl <= 0, rl) rl_future = rs_gcm_f.return_lev_dict[the_type][rp] # Calculate climate change signal diff = (rl_future - rl) / (np.abs(rl + rl_future) * 0.5) * 100 diff[(rl_future <= 0) & (rl <= 0)] = 0 # diff = rl diff = maskoceans(bmp_info.lons, bmp_info.lats, diff) print(diff.min(), diff.max()) std_c = rs_gcm_c.std_dict[the_type][rp] std_f = rs_gcm_f.std_dict[the_type][rp] significance = (np.ma.abs(diff) >= 1.96 * (std_c + std_f)) & (~diff.mask) significance = significance.astype(int) vmin, vmax = limits[the_type] diff = np.ma.masked_where(all_basins_mask < 0.5, diff) im = bmp_info.basemap.pcolormesh(xx, yy, diff, vmin=vmin, vmax=vmax, cmap=cmap) significance = np.ma.masked_where(all_basins_mask < 0.5, significance) cs = bmp_info.basemap.contourf(xx, yy, significance, levels=[0, 0.5, 1], hatches=["////", None, None], colors="none") if row == nrows - 1 and col == ncols - 1: # create a legend for the contour set artists, labels = cs.legend_elements() ax.legend([artists[0], ], ["not significant", ], handleheight=0.5, bbox_to_anchor=(1, -0.1), loc="upper right", borderaxespad=0.) ax.set_title("T = {}-year".format(rp)) if col == 0: ax.set_ylabel("{} flow".format(the_type)) bmp_info.basemap.drawcoastlines(ax=ax) bmp_info.basemap.drawmapboundary(fill_color="0.75") bmp_info.basemap.readshapefile(".".join(quebec_info.BASIN_BOUNDARIES_DERIVED_10km.split(".")[:-1]).replace("utm18", "latlon"), "basin", linewidth=1.2, ax=ax) if col == ncols - 1: cax = fig.add_subplot(gs[row, -1]) plt.colorbar(im, cax=cax, extend="both") cax.set_title("%") # Print basin average changes print("--- start ----------------{rp}-year {ext_type} flow ----------------".format(rp=rp, ext_type=the_type)) bname_to_diff = [(bname, diff[the_mask > 0.5].mean()) for bname, the_mask in bname_to_mask.items()] bname_to_diff = list(sorted(bname_to_diff, key=lambda item: item[1])) for bname, the_diff in bname_to_diff: print("{bname}: cc = {cc:.2f}%".format(bname=bname, cc=the_diff)) print("--- end ----------------{rp}-year {ext_type} flow ----------------".format(rp=rp, ext_type=the_type)) img_file = img_folder.joinpath("rl_cc_{}.png".format(gcm_driven_config_c.label)) with img_file.open("wb") as f: fig.savefig(f, bbox_inches="tight") plt.close(fig)
def main(): start_year_c = 1980 end_year_c = 2010 img_folder = "cc_paper" current_path = "/RESCUE/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/quebec_0.1_crcm5-hcd-rl-intfl-cc-canesm2-1980-2010.hdf5" base_label = "CRCM5-LI" # Need to read land fraction geo_file_path = "/RESCUE/skynet3_rech1/huziy/hdf_store/pm1979010100_00000000p" r_obj = RPN(geo_file_path) mg_field = r_obj.get_first_record_for_name("MG") lons, lats = r_obj.get_longitudes_and_latitudes_for_the_last_read_rec() r_obj.close() future_shift_years = 90 params = dict(data_path=current_path, start_year=start_year_c, end_year=end_year_c, label=base_label) base_config_c = RunConfig(**params) base_config_f = base_config_c.get_shifted_config(future_shift_years) varname = "INTF" level = 0 daily_dates, intf_c = analysis.get_daily_climatology( path_to_hdf_file=base_config_c.data_path, var_name=varname, level=level, start_year=base_config_c.start_year, end_year=base_config_c.end_year) _, intf_f = analysis.get_daily_climatology( path_to_hdf_file=base_config_f.data_path, var_name=varname, level=level, start_year=base_config_f.start_year, end_year=base_config_f.end_year) mg_fields = np.asarray([mg_field for d in daily_dates]) mg_crit = 0.0001 the_mask = mg_fields <= mg_crit # Convert to mm/day as well intf_c = _avg_along_lon(intf_c, the_mask) * 24 * 3600 intf_f = _avg_along_lon(intf_f, the_mask) * 24 * 3600 lats_agg = lats.mean(axis=0) num_dates = date2num(daily_dates) lats_agg_2d, num_dates_2d = np.meshgrid(lats_agg, num_dates) # Do the plotting fig = plt.figure() gs = GridSpec(2, 3, width_ratios=[1, 1, 0.05]) norm = SymLogNorm(5e-5) all_axes = [] # Current ax = fig.add_subplot(gs[0, 0]) cs = ax.contourf(num_dates_2d, lats_agg_2d, intf_c[:], 60, norm=norm) ax.set_title("Current ({}-{})".format(base_config_c.start_year, base_config_c.end_year)) all_axes.append(ax) # Future ax = fig.add_subplot(gs[0, 1]) ax.set_title("Future ({}-{})".format(base_config_f.start_year, base_config_f.end_year)) cs = ax.contourf(num_dates_2d, lats_agg_2d, intf_f[:], levels=cs.levels, norm=norm) all_axes.append(ax) # Colorbar for value plots cax = fig.add_subplot(gs[0, 2]) sfmt = ScalarFormatter(useMathText=True) sfmt.set_powerlimits((-1, 2)) plt.colorbar(cs, cax=cax, format=sfmt) cax.set_xlabel("mm/day") cax.yaxis.get_offset_text().set_position((-2, 10)) # CC diff_cmap = cm.get_cmap("RdBu_r", 20) diff = (intf_f - intf_c) / (0.5 * (intf_c + intf_f)) * 100 diff[(intf_f == 0) & (intf_c == 0)] = 0 print(np.min(diff), np.max(diff)) print(np.any(diff.mask)) print(np.any(intf_c.mask)) print(np.any(intf_f.mask)) delta = 200 vmin = -delta vmax = delta locator = MaxNLocator(nbins=20, symmetric=True) clevs = locator.tick_values(vmin=vmin, vmax=vmax) ax = fig.add_subplot(gs[1, 1]) cs = ax.contourf(num_dates_2d, lats_agg_2d, diff, cmap=diff_cmap, levels=clevs, extend="both") ax.set_title("Future - Current") # ax.set_aspect("auto") all_axes.append(ax) cb = plt.colorbar(cs, cax=fig.add_subplot(gs[1, -1])) cb.ax.set_xlabel(r"%") for i, the_ax in enumerate(all_axes): the_ax.xaxis.set_minor_formatter( FuncFormatter(lambda d, pos: num2date(d).strftime("%b")[0])) the_ax.xaxis.set_major_formatter(FuncFormatter(lambda d, pos: "")) the_ax.xaxis.set_minor_locator(MonthLocator(bymonthday=15)) the_ax.xaxis.set_major_locator(MonthLocator()) the_ax.grid() if i != 1: the_ax.set_ylabel(r"Latitude ${\rm \left(^\circ N \right)}$") # identify approximately the melting period and lower latitudes march1 = date2num(datetime(daily_dates[0].year, 3, 1)) june1 = date2num(datetime(daily_dates[0].year, 6, 1)) sel_mask = (num_dates_2d >= march1) & (num_dates_2d < june1) & (lats_agg_2d <= 50) print("Mean interflow decrease in the southern regions: {}%".format( diff[sel_mask].mean())) # identify the regions of max interflow rates in current and future climates lat_min = 55 lat_max = 57.5 may1 = date2num(datetime(daily_dates[0].year, 5, 1)) july1 = date2num(datetime(daily_dates[0].year, 7, 1)) mean_max_current = intf_c[(lats_agg_2d >= lat_min) & (lats_agg_2d <= lat_max) & (num_dates_2d <= july1) & (num_dates_2d >= june1)].mean() mean_max_future = intf_f[(lats_agg_2d >= lat_min) & (lats_agg_2d <= lat_max) & (num_dates_2d <= june1) & (num_dates_2d >= may1)].mean() print("Mean change in the maximum interflow rate: {} %".format( (mean_max_future - mean_max_current) * 100 / mean_max_current)) img_file = Path(img_folder).joinpath("INTF_rate_longit_avg.png") fig.tight_layout() from crcm5.analyse_hdf import common_plot_params fig.savefig(str(img_file), bbox_inches="tight", transparent=True, dpi=common_plot_params.FIG_SAVE_DPI)
def main(): start_year_c = 1980 end_year_c = 2010 img_folder = "cc_paper" current_path = "/RESCUE/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/quebec_0.1_crcm5-hcd-rl-cc-canesm2-1980-2010.hdf5" base_label = "CRCM5-L" # Need to read land fraction geo_file_path = "/RESCUE/skynet3_rech1/huziy/hdf_store/pm1979010100_00000000p" r_obj = RPN(geo_file_path) mg_field = r_obj.get_first_record_for_name("MG") lons, lats = r_obj.get_longitudes_and_latitudes_for_the_last_read_rec() r_obj.close() future_shift_years = 75 params = dict(data_path=current_path, start_year=start_year_c, end_year=end_year_c, label=base_label) base_config_c = RunConfig(**params) base_config_f = base_config_c.get_shifted_config(future_shift_years) data_path = "/RESCUE/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/quebec_0.1_crcm5-hcd-rl-intfl-cc-canesm2-1980-2010.hdf5" params.update(dict(data_path=data_path, label="CRCM5-LI")) modif_config_c = RunConfig(**params) modif_config_f = modif_config_c.get_shifted_config(future_shift_years) varnames = ["I1+I2", "I0", "PR", "TRAF", "AV", "I0_max", "I0_min"] levels = [0, 0, 0, 0, 0, 0, 0] var_labels = ["SM", "ST", "PR", "TRAF", "LHF", "STmin", "STmax"] # width of the first soil layer in mm multipliers = [100, 1, 1000 * 24 * 3600, 24 * 3600, 1, 1, 1] offsets = [ 0, ] * len(varnames) units = ["mm", "K", "mm/day", "mm/day", r"${\rm W/m^2}$", "K", "K"] SimData = collections.namedtuple("SimData", "base_c base_f modif_c modif_f") mg_fields = None fig = plt.figure() gs = GridSpec(len(varnames), 5, width_ratios=2 * [ 1, ] + [0.05, 1, 0.05]) lats_agg = lats.mean(axis=0) diff_cmap = cm.get_cmap("RdBu_r", 10) the_zip = zip(varnames, levels, var_labels, multipliers, offsets, units) row = 0 for vname, level, var_label, multiplier, offset, unit_label in the_zip: daily_dates, base_data_c = analysis.get_daily_climatology( path_to_hdf_file=base_config_c.data_path, var_name=vname, level=level, start_year=base_config_c.start_year, end_year=base_config_c.end_year) _, base_data_f = analysis.get_daily_climatology( path_to_hdf_file=base_config_f.data_path, var_name=vname, level=level, start_year=base_config_f.start_year, end_year=base_config_f.end_year) _, modif_data_c = analysis.get_daily_climatology( path_to_hdf_file=modif_config_c.data_path, var_name=vname, level=level, start_year=modif_config_c.start_year, end_year=modif_config_c.end_year) _, modif_data_f = analysis.get_daily_climatology( path_to_hdf_file=modif_config_f.data_path, var_name=vname, level=level, start_year=modif_config_f.start_year, end_year=modif_config_f.end_year) if mg_fields is None: mg_fields = np.asarray([mg_field for d in daily_dates]) num_dates = date2num(daily_dates) # create 2d dates and latitudes for the contour plots lats_agg_2d, num_dates_2d = np.meshgrid(lats_agg, num_dates) sim_data = SimData(_avg_along_lon(base_data_c, mg_fields), _avg_along_lon(base_data_f, mg_fields), _avg_along_lon(modif_data_c, mg_fields), _avg_along_lon(modif_data_f, mg_fields)) # Unit conversion sim_data = SimData(*[multiplier * si + offset for si in sim_data]) # Plot the row for the variable all_axes = [] # Calculate nice color levels delta = np.percentile( np.abs([ sim_data.modif_c - sim_data.base_c, sim_data.modif_f - sim_data.base_f ]), 99) vmin = -delta vmax = delta locator = MaxNLocator(nbins=10, symmetric=True) clevs = locator.tick_values(vmin=vmin, vmax=vmax) # Current ax = fig.add_subplot(gs[row, 0]) cs = ax.contourf(num_dates_2d, lats_agg_2d, sim_data.modif_c - sim_data.base_c, extend="both", levels=clevs, cmap=diff_cmap) if row == 0: ax.set_title("Current ({}-{})".format(base_config_c.start_year, base_config_c.end_year)) all_axes.append(ax) # Future ax = fig.add_subplot(gs[row, 1]) if row == 0: ax.set_title("Future ({}-{})".format(base_config_f.start_year, base_config_f.end_year)) cs = ax.contourf(num_dates_2d, lats_agg_2d, sim_data.modif_f - sim_data.base_f, levels=cs.levels, extend="both", cmap=diff_cmap) all_axes.append(ax) # Colorbar for value plots cax = fig.add_subplot(gs[row, 2]) plt.colorbar(cs, cax=cax) cax.set_title("{} ({})\n".format(var_label, unit_label)) diff = (sim_data.modif_f - sim_data.base_f) - (sim_data.modif_c - sim_data.base_c) delta = np.percentile(np.abs(diff), 99) vmin = -delta vmax = delta locator = MaxNLocator(nbins=10, symmetric=True) clevs = locator.tick_values(vmin=vmin, vmax=vmax) ax = fig.add_subplot(gs[row, 3]) cs = ax.contourf(num_dates_2d, lats_agg_2d, diff, cmap=diff_cmap, levels=clevs, extend="both") all_axes.append(ax) cb = plt.colorbar(cs, cax=fig.add_subplot(gs[row, 4])) if row == 0: ax.set_title("Future - Current") cb.ax.set_title("{}\n".format(unit_label)) for i, the_ax in enumerate(all_axes): the_ax.xaxis.set_major_formatter(DateFormatter("%b")) the_ax.xaxis.set_major_locator(MonthLocator(interval=2)) the_ax.grid() if i == 0: the_ax.set_ylabel("Latitude") row += 1 fig.tight_layout() img_path = Path(img_folder).joinpath( "{}_long_avg_intf_impact_{}-{}_vs_{}-{}.png".format( "_".join(varnames), base_config_f.start_year, base_config_f.end_year, base_config_c.start_year, base_config_c.end_year)) fig.savefig(str(img_path), bbox_inches="tight")
def main(): base_current_path = \ "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/quebec_0.1_crcm5-r-cc-canesm2-1980-2010.hdf5" base_label = "CanESM2-CRCM5-NL" modif_current_path = \ "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/quebec_0.1_crcm5-hcd-rl-cc-canesm2-1980-2010.hdf5" modif_label = "CanESM2-CRCM5-L" start_year_c = 1980 end_year_c = 2010 varname = "STFL" future_shift_years = 90 params = dict(data_path=base_current_path, start_year=start_year_c, end_year=end_year_c, label=base_label) geo_data_file = "/skynet3_rech1/huziy/hdf_store/pm1979010100_00000000p" base_config_c = RunConfig(**params) base_config_f = base_config_c.get_shifted_config(future_shift_years) base_configs = [base_config_c, base_config_f] params.update(dict(data_path=modif_current_path, label=modif_label)) modif_config_c = RunConfig(**params) modif_config_f = modif_config_c.get_shifted_config(future_shift_years) modif_configs = [modif_config_c, modif_config_f] r_obj = RPN(geo_data_file) facc = r_obj.get_first_record_for_name("FAA") fldr = r_obj.get_first_record_for_name("FLDR") lake_fraction = r_obj.get_first_record_for_name_and_level("ML") lake_fraction = np.ma.masked_where((fldr <= 0) | (fldr > 128), lake_fraction) bmp_info = analysis.get_basemap_info_from_hdf(file_path=base_current_path) # plots basin boundaries and names on the domain plot basin_name_to_out_indices_map, basin_name_to_basin_mask = plot_basin_outlets( bmp_info=bmp_info, accumulation_areas=facc, directions=fldr, lake_fraction_field=lake_fraction) # basin_name_to_out_indices_map, basin_name_to_basin_mask = get_basin_to_outlet_indices_map(bmp_info=bmp_info, # accumulation_areas=facc, # directions=fldr, # lake_fraction_field=lake_fraction) data_to_plot = read_cc_and_cc_diff( base_configs, modif_configs, name_to_indices=basin_name_to_out_indices_map, varname=varname) basin_name_to_basin_mask = basin_name_to_basin_mask if varname not in [ "STFA", "STFL" ] else None img_path = get_image_path(base_config_c, base_config_f, modif_config_c, modif_config_f, varname) # select lake rich basins sel_basins = ["ARN", "PYR", "LGR", "RDO", "SAG", "WAS"] basin_name_to_out_indices_map = { k: v for k, v in basin_name_to_out_indices_map.items() if k in sel_basins } calculate_and_plot_climate_change_hydrographs( data_to_plot, name_to_out_indices=basin_name_to_out_indices_map, months=list(range(1, 13)), varname=varname, img_path=img_path)
def main(): season_to_months = get_default_season_to_months_dict() # var_names = ["TT", "HU", "PR", "AV", "STFL"] # var_names = ["TRAF", "STFL", "TRAF+TDRA"] # var_names = ["TT", "PR", "STFL"] # var_names = ["TT", "PR", "I5", "STFL", "AV", "AH"] var_names = ["TT", ] levels = [0, ] * len(var_names) multipliers = { "PR": 1.0, "TRAF+TDRA": 24 * 60 * 60 } name_to_units = { "TRAF": "mm/day", "I1": "mm", "PR": "mm/day", "TRAF+TDRA": "mm/day", "I5": "mm", "AV": r"${\rm W/m^2}$" } base_current_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/" \ "quebec_0.1_crcm5-r-cc-canesm2-1980-2010.hdf5" base_label = "CanESM2-CRCM5-NL" modif_current_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/" \ "quebec_0.1_crcm5-hcd-rl-cc-canesm2-1980-2010.hdf5" modif_label = "CanESM2-CRCM5-L" plot_cc_only_for = modif_label # plot_cc_only_for = None start_year_c = 1980 end_year_c = 2010 future_shift_years = 90 params = dict( data_path=base_current_path, start_year=start_year_c, end_year=end_year_c, label=base_label ) base_config_c = RunConfig(**params) base_config_f = base_config_c.get_shifted_config(future_shift_years) params.update( dict(data_path=modif_current_path, label=modif_label) ) modif_config_c = RunConfig(**params) modif_config_f = modif_config_c.get_shifted_config(future_shift_years) config_dict = OrderedDict([ ("Current", OrderedDict([(base_label, base_config_c), (modif_label, modif_config_c)])), ("Future", OrderedDict([(base_label, base_config_f), (modif_label, modif_config_f)])) ]) # Changes global plot properties mainly figure size and font size plot_utils.apply_plot_params(font_size=12, width_cm=25, height_cm=10) # Plot the differences fig = plt.figure() gs = GridSpec(len(var_names), len(season_to_months) + 1, width_ratios=[1., ] * len(season_to_months) + [0.05, ]) config_dict.fig = fig config_dict.gs = gs config_dict.label_modif = modif_config_c.label config_dict.label_base = base_config_c.label config_dict.season_to_months = season_to_months config_dict.multipliers = multipliers lons, lats, bmp = analysis.get_basemap_from_hdf(base_current_path) config_dict.lons = lons config_dict.lats = lats config_dict.basemap = bmp config_dict.name_to_units = name_to_units # Calculate and plot seasonal means for vname, level, the_row in zip(var_names, levels, list(range(len(levels)))): config_dict.the_row = the_row _plot_row(vname=vname, level=level, config_dict=config_dict, plot_cc_only_for=plot_cc_only_for, mark_significance=False) # Save the image to the file if plot_cc_only_for is None: img_path = get_image_path(base_config_c, base_config_f, modif_config_c, season_to_months=season_to_months) else: config_c = base_config_c if base_config_c.label == plot_cc_only_for else modif_config_c config_f = base_config_f if base_config_f.label == plot_cc_only_for else modif_config_f img_path = get_image_path(config_c, config_f, config_c, season_to_months=season_to_months) fig.savefig(img_path, bbox_inches="tight", transparent=True, dpi=common_plot_params.FIG_SAVE_DPI) print("saving the plot to: {}".format(img_path)) plt.close(fig)
def main_interflow(): # Changes global plot properties mainly figure size and font size plot_utils.apply_plot_params(font_size=12, width_cm=20) # season_to_months = get_default_season_to_months_dict() season_to_months = OrderedDict([("January", [1, ]), ("February", [2, ]), ("March", [3, ]), ]) var_names = ["TT", "HU", "PR", "AV", "TRAF", "I1", "STFL"] levels = [0, ] * len(var_names) plot_utils.apply_plot_params(font_size=10, width_pt=None, width_cm=20 * len(season_to_months) / 4.0, height_cm=20 * len(var_names) / 5.0) multipliers = { "PR": 1., "TRAF": 1., "I1": infovar.soil_layer_widths_26_to_60[0] * 1000.0, "TRAF+TDRA": 24 * 60 * 60 } name_to_units = { "TRAF": "mm/day", "I1": "mm", "PR": "mm/day", "TRAF+TDRA": "mm/day" } base_current_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/" \ "quebec_0.1_crcm5-hcd-rl-cc-canesm2-1980-2010.hdf5" base_label = "CanESM2-CRCM5-L" modif_current_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/" \ "quebec_0.1_crcm5-hcd-rl-intfl-cc-canesm2-1980-2010.hdf5" modif_label = "CanESM2-CRCM5-LI" start_year_c = 1980 end_year_c = 2010 future_shift_years = 90 params = dict( data_path=base_current_path, start_year=start_year_c, end_year=end_year_c, label=base_label ) base_config_c = RunConfig(**params) base_config_f = base_config_c.get_shifted_config(future_shift_years) params.update( dict(data_path=modif_current_path, label=modif_label) ) modif_config_c = RunConfig(**params) modif_config_f = modif_config_c.get_shifted_config(future_shift_years) config_dict = OrderedDict([ ("Current", OrderedDict([(base_label, base_config_c), (modif_label, modif_config_c)])), ("Future", OrderedDict([(base_label, base_config_f), (modif_label, modif_config_f)])) ]) # Plot the differences fig = plt.figure() gs = GridSpec(len(var_names), len(season_to_months) + 1, width_ratios=[1., ] * len(season_to_months) + [0.05, ]) config_dict.fig = fig config_dict.gs = gs config_dict.label_modif = modif_config_c.label config_dict.label_base = base_config_c.label config_dict.season_to_months = season_to_months config_dict.multipliers = multipliers lons, lats, bmp = analysis.get_basemap_from_hdf(base_current_path) config_dict.lons = lons config_dict.lats = lats config_dict.basemap = bmp config_dict.name_to_units = name_to_units # Calculate and plot seasonal means for vname, level, the_row in zip(var_names, levels, list(range(len(levels)))): config_dict.the_row = the_row _plot_row(vname=vname, level=level, config_dict=config_dict) # Save the image to the file img_path = get_image_path(base_config_c, base_config_f, modif_config_c, season_to_months=season_to_months) fig.savefig(img_path, bbox_inches="tight")
def main(): """ """ season_to_months = get_default_season_to_months_dict() # season_to_months = OrderedDict([("April", [4, ]), ("May", [5, ]), ("June", [6, ]), ("July", [7, ])]) var_names = ["TT", "HU", "PR", "AV", "AH", "STFL", "TRAF", "I5", "I0"] # var_names = ["TT", "PR"] levels = [ 0, ] * len(var_names) multipliers = {"PR": 1.0e3 * 24.0 * 3600., "TRAF": 24 * 3600.0} base_current_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/" \ "quebec_0.1_crcm5-r-cc-canesm2-1980-2010.hdf5" base_label = "CanESM2-CRCM5-NL" modif_current_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/" \ "quebec_0.1_crcm5-hcd-rl-cc-canesm2-1980-2010.hdf5" modif_label = "CanESM2-CRCM5-L" # base_current_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/" \ # "quebec_0.1_crcm5-hcd-rl-cc-canesm2-1980-2010.hdf5" # base_label = "CRCM5-L" # # modif_current_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/" \ # "quebec_0.1_crcm5-hcd-rl-intfl-cc-canesm2-1980-2010.hdf5" # modif_label = "CRCM5-LI" start_year_c = 1980 end_year_c = 2010 future_shift_years = 90 params = dict(data_path=base_current_path, start_year=start_year_c, end_year=end_year_c, label=base_label) base_config_c = RunConfig(**params) base_config_f = base_config_c.get_shifted_config(future_shift_years) params.update(dict(data_path=modif_current_path, label=modif_label)) modif_config_c = RunConfig(**params) modif_config_f = modif_config_c.get_shifted_config(future_shift_years) config_dict = OrderedDict([("Current", OrderedDict([(base_label, base_config_c), (modif_label, modif_config_c)])), ("Future", OrderedDict([(base_label, base_config_f), (modif_label, modif_config_f)]))]) # Plot the differences config_dict.label_modif = modif_config_c.label config_dict.label_base = base_config_c.label config_dict.season_to_months = season_to_months config_dict.multipliers = multipliers lons, lats, bmp = analysis.get_basemap_from_hdf(base_current_path) config_dict.lons = lons config_dict.lats = lats config_dict.basemap = bmp # Calculate and plot seasonal means for vname, level in zip(var_names, levels): data = get_data(vname=vname, level=level, config_dict=config_dict) _plot_var(vname=vname, level=level, config_dict=config_dict, data_dict=data)
def main(): """ """ season_to_months = get_default_season_to_months_dict() # season_to_months = OrderedDict([("April", [4, ]), ("May", [5, ]), ("June", [6, ]), ("July", [7, ])]) var_names = ["TT", "HU", "PR", "AV", "AH", "STFL", "TRAF", "I5", "I0"] # var_names = ["TT", "PR"] levels = [0, ] * len(var_names) multipliers = { "PR": 1.0e3 * 24.0 * 3600., "TRAF": 24 * 3600.0 } base_current_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/" \ "quebec_0.1_crcm5-r-cc-canesm2-1980-2010.hdf5" base_label = "CanESM2-CRCM5-NL" modif_current_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/" \ "quebec_0.1_crcm5-hcd-rl-cc-canesm2-1980-2010.hdf5" modif_label = "CanESM2-CRCM5-L" # base_current_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/" \ # "quebec_0.1_crcm5-hcd-rl-cc-canesm2-1980-2010.hdf5" # base_label = "CRCM5-L" # # modif_current_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/" \ # "quebec_0.1_crcm5-hcd-rl-intfl-cc-canesm2-1980-2010.hdf5" # modif_label = "CRCM5-LI" start_year_c = 1980 end_year_c = 2010 future_shift_years = 90 params = dict( data_path=base_current_path, start_year=start_year_c, end_year=end_year_c, label=base_label ) base_config_c = RunConfig(**params) base_config_f = base_config_c.get_shifted_config(future_shift_years) params.update( dict(data_path=modif_current_path, label=modif_label) ) modif_config_c = RunConfig(**params) modif_config_f = modif_config_c.get_shifted_config(future_shift_years) config_dict = OrderedDict([ ("Current", OrderedDict([(base_label, base_config_c), (modif_label, modif_config_c)])), ("Future", OrderedDict([(base_label, base_config_f), (modif_label, modif_config_f)])) ]) # Plot the differences config_dict.label_modif = modif_config_c.label config_dict.label_base = base_config_c.label config_dict.season_to_months = season_to_months config_dict.multipliers = multipliers lons, lats, bmp = analysis.get_basemap_from_hdf(base_current_path) config_dict.lons = lons config_dict.lats = lats config_dict.basemap = bmp # Calculate and plot seasonal means for vname, level in zip(var_names, levels): data = get_data(vname=vname, level=level, config_dict=config_dict) _plot_var(vname=vname, level=level, config_dict=config_dict, data_dict=data)
def main(): lkfr_limit = 0.05 model_data_current_path = "/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/" \ "quebec_0.1_crcm5-hcd-rl-cc-canesm2-1980-2010.hdf5" modif_label = "CanESM2-CRCM5-L" start_year_c = 1980 end_year_c = 2010 future_shift_years = 90 params = dict( start_year=start_year_c, end_year=end_year_c ) params.update( dict(data_path=model_data_current_path, label=modif_label) ) model_config_c = RunConfig(**params) model_config_f = model_config_c.get_shifted_config(future_shift_years) bmp_info = analysis.get_basemap_info(r_config=model_config_c) specific_cond_heat = 0.250100e7 # J/kg water_density = 1000.0 # kg/m**3 season_to_months = OrderedDict([ ("Summer", [6, 7, 8]), ]) lkfr = analysis.get_array_from_file(path="/RESCUE/skynet3_rech1/huziy/hdf_store/quebec_0.1_crcm5-hcd-rl.hdf5", var_name=infovar.HDF_LAKE_FRACTION_NAME) assert lkfr is not None, "Could not find lake fraction in the file" # Current climate traf_c = analysis.get_seasonal_climatology_for_runconfig(run_config=model_config_c, varname="TRAF", level=5, season_to_months=season_to_months) pr_c = analysis.get_seasonal_climatology_for_runconfig(run_config=model_config_c, varname="PR", level=0, season_to_months=season_to_months) lktemp_c = analysis.get_seasonal_climatology_for_runconfig(run_config=model_config_c, varname="L1", level=0, season_to_months=season_to_months) airtemp_c = analysis.get_seasonal_climatology_for_runconfig(run_config=model_config_c, varname="TT", level=0, season_to_months=season_to_months) lhc = OrderedDict([ (s, specific_cond_heat * (pr_c[s] * water_density - traf_c[s])) for s, traf in traf_c.items() ]) avc = analysis.get_seasonal_climatology_for_runconfig(run_config=model_config_c, varname="AV", level=0, season_to_months=season_to_months) plt.figure() lhc["Summer"] = np.ma.masked_where(lkfr < lkfr_limit, lhc["Summer"]) print("min: {}, max: {}".format(lhc["Summer"].min(), lhc["Summer"].max())) cs = plt.contourf(lhc["Summer"].T) plt.title("lhc") plt.colorbar() plt.figure() cs = plt.contourf(avc["Summer"].T, levels=cs.levels, norm=cs.norm, cmap=cs.cmap) plt.title("avc") plt.colorbar() # Future climate traf_f = analysis.get_seasonal_climatology_for_runconfig(run_config=model_config_f, varname="TRAF", level=5, season_to_months=season_to_months) pr_f = analysis.get_seasonal_climatology_for_runconfig(run_config=model_config_f, varname="PR", level=0, season_to_months=season_to_months) lktemp_f = analysis.get_seasonal_climatology_for_runconfig(run_config=model_config_f, varname="L1", level=0, season_to_months=season_to_months) airtemp_f = analysis.get_seasonal_climatology_for_runconfig(run_config=model_config_f, varname="TT", level=0, season_to_months=season_to_months) lhf = OrderedDict([ (s, specific_cond_heat * (pr_f[s] * water_density - traf_f[s])) for s, traf in traf_f.items() ]) plt.figure() plt.pcolormesh(traf_c["Summer"].T) plt.title("TRAF over lakes current") plt.colorbar() avf = analysis.get_seasonal_climatology_for_runconfig(run_config=model_config_f, varname="AV", level=0, season_to_months=season_to_months) plt.figure() cs = plt.contourf(avf["Summer"].T) plt.title("avf") plt.colorbar() plt.figure() cs = plt.contourf(avf["Summer"].T - avc["Summer"].T, levels=np.arange(-40, 45, 5)) plt.title("d(av)") plt.colorbar() plt.figure() plt.contourf(lhf["Summer"].T - lhc["Summer"].T, levels=cs.levels, cmap=cs.cmap, norm=cs.norm) plt.title("d(lh)") plt.colorbar() # plotting plot_utils.apply_plot_params(width_cm=15, height_cm=15, font_size=10) gs = GridSpec(2, 2) # tair_c_ts = analysis.get_area_mean_timeseries(model_config_c.data_path, var_name="TT", level_index=0, # start_year=model_config_c.start_year, end_year=model_config_c.end_year, # the_mask=lkfr >= lkfr_limit) # # tair_f_ts = analysis.get_area_mean_timeseries(model_config_f.data_path, var_name="TT", level_index=0, # start_year=model_config_f.start_year, end_year=model_config_f.end_year, # the_mask=lkfr >= lkfr_limit) # # # tlake_c_ts = analysis.get_area_mean_timeseries(model_config_c.data_path, var_name="TT", level_index=0, # start_year=model_config_c.start_year, end_year=model_config_c.end_year, # the_mask=lkfr >= lkfr_limit) # # tlake_f_ts = analysis.get_area_mean_timeseries(model_config_f.data_path, var_name="TT", level_index=0, # start_year=model_config_f.start_year, end_year=model_config_f.end_year, # the_mask=lkfr >= lkfr_limit) for season in season_to_months: fig = plt.figure() lktemp_c[season] -= 273.15 dT_c = np.ma.masked_where(lkfr < lkfr_limit, lktemp_c[season] - airtemp_c[season]) lktemp_f[season] -= 273.15 dT_f = np.ma.masked_where(lkfr < lkfr_limit, lktemp_f[season] - airtemp_f[season]) d = np.round(max(np.ma.abs(dT_c).max(), np.ma.abs(dT_f).max())) vmin = -d vmax = d clevs = np.arange(-12, 13, 1) ncolors = len(clevs) - 1 bn = BoundaryNorm(clevs, ncolors=ncolors) cmap = cm.get_cmap("seismic", ncolors) ax_list = [] fig.suptitle(season) xx, yy = bmp_info.get_proj_xy() # Current gradient ax = fig.add_subplot(gs[0, 0]) ax.set_title(r"current: $T_{\rm lake} - T_{\rm atm}$") cs = bmp_info.basemap.pcolormesh(xx, yy, dT_c, ax=ax, norm=bn, cmap=cmap) bmp_info.basemap.colorbar(cs, ax=ax, extend="both") ax_list.append(ax) # Future Gradient ax = fig.add_subplot(gs[0, 1]) ax.set_title(r"future: $T_{\rm lake} - T_{\rm atm}$") cs = bmp_info.basemap.pcolormesh(xx, yy, dT_f, ax=ax, norm=cs.norm, cmap=cs.cmap, vmin=vmin, vmax=vmax) bmp_info.basemap.colorbar(cs, ax=ax, extend="both") ax_list.append(ax) # Change in the gradient ax = fig.add_subplot(gs[1, 0]) ax.set_title(r"$\Delta T_{\rm future} - \Delta T_{\rm current}$") ddT = dT_f - dT_c d = np.round(np.ma.abs(ddT).max()) clevs = np.arange(-3, 3.1, 0.1) ncolors = len(clevs) - 1 bn = BoundaryNorm(clevs, ncolors=ncolors) cmap = cm.get_cmap("seismic", ncolors) cs = bmp_info.basemap.pcolormesh(xx, yy, ddT, norm=bn, cmap=cmap) bmp_info.basemap.colorbar(cs, ax=ax, extend="both") ax_list.append(ax) # Change in the latent heat flux # ax = fig.add_subplot(gs[1, 1]) # ax.set_title(r"$LE_{\rm future} - LE_{\rm current}$") # dlh = np.ma.masked_where(lkfr < lkfr_limit, lhf[season] - lhc[season]) # # d = np.round(np.ma.abs(dlh).max() // 10) * 10 # clevs = np.arange(0, 105, 5) # bn = BoundaryNorm(clevs, ncolors=ncolors) # cmap = cm.get_cmap("jet", ncolors) # # cs = bmp_info.basemap.pcolormesh(xx, yy, dlh, norm=bn, cmap=cmap) # bmp_info.basemap.colorbar(cs, ax=ax, extend="max") # Change in the latent heat flux # ax_list.append(ax) for the_ax in ax_list: bmp_info.basemap.drawcoastlines(linewidth=0.3, ax=the_ax) fig.tight_layout() fig.savefig(os.path.join(img_folder, "lake_atm_gradients_and_fluxes_{}-{}_{}-{}.png".format(model_config_f.start_year, model_config_f.end_year, start_year_c, end_year_c)), dpi=800, bbox_inches="tight")
def main(): # import seaborn as sns # sns.set_context("paper", font_scale=2) # sns.set_style("whitegrid") level_widths_mm = MM_PER_METER * infovar.soil_layer_widths_26_to_60 avg_axis = "lon" start_year_c = 1980 end_year_c = 2010 img_folder = Path("cc_paper/lake_props") if not img_folder.exists(): img_folder.mkdir(parents=True) # Configuration without interflow, to be compared with the one with intf. base_config = RunConfig( start_year=start_year_c, end_year=end_year_c, data_path= "/home/huziy/skynet3_rech1/hdf_store/quebec_0.1_crcm5-hcd-rl.hdf5", label="CRCM5-L") current_path = "/RESCUE/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/quebec_0.1_crcm5-hcd-rl-cc-canesm2-1980-2010.hdf5" # Need to read land fraction geo_file_path = "/RESCUE/skynet3_rech1/huziy/hdf_store/pm1979010100_00000000p" r_obj = RPN(geo_file_path) mg_field = r_obj.get_first_record_for_name("MG") depth_to_bedrock_mm = r_obj.get_first_record_for_name("8L") * MM_PER_METER lake_fraction = r_obj.get_first_record_for_name("ML") # recompute layer widths to account for the depth to bedrock layer_widths_3d = np.ones(depth_to_bedrock_mm.shape + level_widths_mm.shape) layer_widths_3d *= level_widths_mm[np.newaxis, np.newaxis, :] layer_bottoms_3d = layer_widths_3d.cumsum(axis=2) corrections = depth_to_bedrock_mm[:, :, np.newaxis] - layer_bottoms_3d layer_widths_3d[corrections < 0] += corrections[corrections < 0] layer_widths_3d[layer_widths_3d < 0] = 0 lons, lats = r_obj.get_longitudes_and_latitudes_for_the_last_read_rec() r_obj.close() # Current and future configurations current_config = RunConfig(start_year=start_year_c, end_year=end_year_c, data_path=current_path, label="CRCM5-L") n_shift_years = 90 future_config = current_config.get_shifted_config(n_shift_years) print(future_config) varname = "L1" level = 0 daily_dates, lake_temp_c = analysis.get_daily_climatology_for_rconf( current_config, var_name=varname, level=level) _, lake_temp_f = analysis.get_daily_climatology_for_rconf(future_config, var_name=varname, level=level) # average along a dim lake_temp_c = _avg_along(lake_temp_c, axis=avg_axis, lake_fraction=lake_fraction) lake_temp_f = _avg_along(lake_temp_f, axis=avg_axis, lake_fraction=lake_fraction) zagg = None ztitle = "" if avg_axis == "lon": zagg = lats.mean(axis=0) ztitle = "Latitude" elif avg_axis == "lat": zagg = lons.mean(axis=1) ztitle = "Longitude" num_dates = date2num(daily_dates) z_agg_2d, num_dates_2d = np.meshgrid(zagg, num_dates) # Do the plotting plot_utils.apply_plot_params(font_size=14, width_pt=None, width_cm=20, height_cm=30) fig = plt.figure() gs = GridSpec(4, 2, width_ratios=[1, 0.02]) all_axes = [] # ----------------------------------Lake temperature---------------------------------- row = 0 ax = fig.add_subplot(gs[row, 0]) cmap = cm.get_cmap("bwr", 15) to_plot = lake_temp_f - lake_temp_c[:, :] vmax = max(to_plot.max(), 0) vmin = min(to_plot.min(), 0) vmax = max(abs(vmin), abs(vmax)) # norm = MidpointNormalize(vmin=vmin, vmax=vmax) clevs = MaxNLocator(cmap.N + 1).tick_values(-vmax, vmax) cs = ax.contourf(num_dates_2d, z_agg_2d, to_plot, cmap=cmap, levels=clevs, extend="both") ax.set_title("Lake surface water temperature") all_axes.append(ax) # Colorbar for value plots cax = fig.add_subplot(gs[row, -1]) sfmt = ScalarFormatter(useMathText=True) sfmt.set_powerlimits((-2, 3)) plt.colorbar(cs, cax=cax, format=sfmt) cax.set_xlabel(r"${\rm ^\circ C}$") cax.yaxis.get_offset_text().set_position((-2, 10)) # ----------------------------------Lake ice thickness---------------------------------- level = 0 varname = "LD" _, lake_ice_th_c = analysis.get_daily_climatology_for_rconf( current_config, var_name=varname, level=level) _, lake_ice_th_f = analysis.get_daily_climatology_for_rconf( future_config, var_name=varname, level=level) lake_ice_th = _avg_along(lake_ice_th_f - lake_ice_th_c, axis=avg_axis, lake_fraction=lake_fraction) # get the points for which the average should be calculated winter_points = np.asarray( [i for i, d in enumerate(daily_dates) if d.month in [1, 2, 12]]) row += 1 ax = fig.add_subplot(gs[row, 0]) vmax = max(lake_ice_th.max(), 0) vmin = min(lake_ice_th.min(), 0) vmax = max(abs(vmin), abs(vmax)) # norm = MidpointNormalize(vmin=vmin, vmax=vmax) clevs = MaxNLocator(cmap.N + 1).tick_values(-vmax, vmax) cs = ax.contourf(num_dates_2d, z_agg_2d, lake_ice_th, cmap=cmap, levels=clevs, extend="both") ax.set_title("Lake ice thickness") print("Mean change in ice thickness: {} m".format( lake_ice_th.mean(axis=1)[winter_points].mean())) all_axes.append(ax) # Colorbar for value plots cax = fig.add_subplot(gs[row, -1]) sfmt = ScalarFormatter(useMathText=True) sfmt.set_powerlimits((-2, 2)) plt.colorbar(cs, cax=cax, format=sfmt) cax.set_xlabel("m") cax.yaxis.get_offset_text().set_position((-2, 10)) # ----------------------------------Lake ice fraction---------------------------------- level = 0 varname = "LC" _, lake_ice_fraction_c = analysis.get_daily_climatology_for_rconf( current_config, var_name=varname, level=level) _, lake_ice_fraction_f = analysis.get_daily_climatology_for_rconf( future_config, var_name=varname, level=level) lake_ice_fraction = _avg_along(lake_ice_fraction_f - lake_ice_fraction_c, axis=avg_axis, lake_fraction=lake_fraction) row += 1 ax = fig.add_subplot(gs[row, 0]) vmax = max(lake_ice_fraction.max(), 0) vmin = min(lake_ice_fraction.min(), 0) vmax = max(abs(vmin), abs(vmax)) # norm = MidpointNormalize(vmin=vmin, vmax=vmax) clevs = MaxNLocator(cmap.N + 1).tick_values(-vmax, vmax) cs = ax.contourf(num_dates_2d, z_agg_2d, lake_ice_fraction, cmap=cmap, levels=clevs, extend="both") ax.set_title("Lake ice fraction") print("Mean change in ice fraction: {}".format( lake_ice_fraction.mean(axis=1)[winter_points].mean())) all_axes.append(ax) # Colorbar for value plots cax = fig.add_subplot(gs[row, -1]) sfmt = ScalarFormatter(useMathText=True) sfmt.set_powerlimits((-2, 2)) plt.colorbar(cs, cax=cax, format=sfmt) cax.set_xlabel("") cax.yaxis.get_offset_text().set_position((-2, 10)) # ----------------------------------Lake depth---------------------------------- level = 0 varname = "CLDP" _, lake_depth_c = analysis.get_daily_climatology_for_rconf( current_config, var_name=varname, level=level) _, lake_depth_f = analysis.get_daily_climatology_for_rconf( future_config, var_name=varname, level=level) lake_depth_cc = _avg_along(lake_depth_f - lake_depth_c, axis=avg_axis, lake_fraction=lake_fraction) row += 1 ax = fig.add_subplot(gs[row, 0]) clevs = [0.01, 0.1, 0.5, 0.75, 1, 2, 3] clevs = [-c for c in reversed(clevs)] + clevs cmap = cm.get_cmap("bwr", len(clevs) - 1) norm = BoundaryNorm(boundaries=clevs, ncolors=len(clevs) - 1) cs = ax.contourf(num_dates_2d, z_agg_2d, lake_depth_cc, cmap=cmap, levels=clevs, norm=norm, extend="both") ax.set_title("Lake level") all_axes.append(ax) # Colorbar for value plots cax = fig.add_subplot(gs[row, -1]) sfmt = ScalarFormatter(useMathText=True) sfmt.set_powerlimits((-2, 2)) plt.colorbar(cs, cax=cax, format=sfmt, ticks=clevs) cax.set_xlabel("m") cax.yaxis.get_offset_text().set_position((-2, 10)) for i, the_ax in enumerate(all_axes): the_ax.xaxis.set_major_formatter( FuncFormatter(lambda d, pos: num2date(d).strftime("%b")[0])) the_ax.xaxis.set_major_locator(MonthLocator(bymonthday=15)) the_ax.xaxis.set_minor_locator(MonthLocator(bymonthday=1)) the_ax.grid(which="minor") the_ax.set_ylabel(ztitle) img_file = Path(img_folder).joinpath( "cc_{}_Lake_props_current_{}_avg_{}-{}_vs_{fsy}-{fey}.png".format( base_config.label, avg_axis, start_year_c, end_year_c, fsy=future_config.start_year, fey=future_config.end_year)) fig.tight_layout() fig.savefig(str(img_file), bbox_inches="tight") plt.show()
def main(): # import seaborn as sns # sns.set_context("paper", font_scale=2) # sns.set_style("whitegrid") level_widths_mm = MM_PER_METER * infovar.soil_layer_widths_26_to_60 avg_axis = "lon" start_year_c = 1980 end_year_c = 2010 img_folder = Path("cc_paper/lake_props") if not img_folder.exists(): img_folder.mkdir(parents=True) # Configuration without interflow, to be compared with the one with intf. base_config = RunConfig(start_year=start_year_c, end_year=end_year_c, data_path="/home/huziy/skynet3_rech1/hdf_store/quebec_0.1_crcm5-hcd-rl.hdf5", label="CRCM5-L") current_path = "/RESCUE/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/quebec_0.1_crcm5-hcd-rl-cc-canesm2-1980-2010.hdf5" # Need to read land fraction geo_file_path = "/RESCUE/skynet3_rech1/huziy/hdf_store/pm1979010100_00000000p" r_obj = RPN(geo_file_path) mg_field = r_obj.get_first_record_for_name("MG") depth_to_bedrock_mm = r_obj.get_first_record_for_name("8L") * MM_PER_METER lake_fraction = r_obj.get_first_record_for_name("ML") # recompute layer widths to account for the depth to bedrock layer_widths_3d = np.ones(depth_to_bedrock_mm.shape + level_widths_mm.shape) layer_widths_3d *= level_widths_mm[np.newaxis, np.newaxis, :] layer_bottoms_3d = layer_widths_3d.cumsum(axis=2) corrections = depth_to_bedrock_mm[:, :, np.newaxis] - layer_bottoms_3d layer_widths_3d[corrections < 0] += corrections[corrections < 0] layer_widths_3d[layer_widths_3d < 0] = 0 lons, lats = r_obj.get_longitudes_and_latitudes_for_the_last_read_rec() r_obj.close() # Current and future configurations current_config = RunConfig(start_year=start_year_c, end_year=end_year_c, data_path=current_path, label="CRCM5-L") n_shift_years = 90 future_config = current_config.get_shifted_config(n_shift_years) print(future_config) varname = "L1" level = 0 daily_dates, lake_temp_c = analysis.get_daily_climatology_for_rconf(current_config, var_name=varname, level=level) _, lake_temp_f = analysis.get_daily_climatology_for_rconf(future_config, var_name=varname, level=level) # average along a dim lake_temp_c = _avg_along(lake_temp_c, axis=avg_axis, lake_fraction=lake_fraction) lake_temp_f = _avg_along(lake_temp_f, axis=avg_axis, lake_fraction=lake_fraction) zagg = None ztitle = "" if avg_axis == "lon": zagg = lats.mean(axis=0) ztitle = "Latitude" elif avg_axis == "lat": zagg = lons.mean(axis=1) ztitle = "Longitude" num_dates = date2num(daily_dates) z_agg_2d, num_dates_2d = np.meshgrid(zagg, num_dates) # Do the plotting plot_utils.apply_plot_params(font_size=14, width_pt=None, width_cm=20, height_cm=30) fig = plt.figure() gs = GridSpec(4, 2, width_ratios=[1, 0.02]) all_axes = [] # ----------------------------------Lake temperature---------------------------------- row = 0 ax = fig.add_subplot(gs[row, 0]) cmap = cm.get_cmap("bwr", 15) to_plot = lake_temp_f - lake_temp_c[:, :] vmax = max(to_plot.max(), 0) vmin = min(to_plot.min(), 0) vmax = max(abs(vmin), abs(vmax)) # norm = MidpointNormalize(vmin=vmin, vmax=vmax) clevs = MaxNLocator(cmap.N + 1).tick_values(-vmax, vmax) cs = ax.contourf(num_dates_2d, z_agg_2d, to_plot, cmap=cmap, levels=clevs, extend="both") ax.set_title("Lake surface water temperature") all_axes.append(ax) # Colorbar for value plots cax = fig.add_subplot(gs[row, -1]) sfmt = ScalarFormatter(useMathText=True) sfmt.set_powerlimits((-2, 3)) plt.colorbar(cs, cax=cax, format=sfmt) cax.set_xlabel(r"${\rm ^\circ C}$") cax.yaxis.get_offset_text().set_position((-2, 10)) # ----------------------------------Lake ice thickness---------------------------------- level = 0 varname = "LD" _, lake_ice_th_c = analysis.get_daily_climatology_for_rconf(current_config, var_name=varname, level=level) _, lake_ice_th_f = analysis.get_daily_climatology_for_rconf(future_config, var_name=varname, level=level) lake_ice_th = _avg_along(lake_ice_th_f - lake_ice_th_c, axis=avg_axis, lake_fraction=lake_fraction) # get the points for which the average should be calculated winter_points = np.asarray([i for i, d in enumerate(daily_dates) if d.month in [1, 2, 12]]) row += 1 ax = fig.add_subplot(gs[row, 0]) vmax = max(lake_ice_th.max(), 0) vmin = min(lake_ice_th.min(), 0) vmax = max(abs(vmin), abs(vmax)) # norm = MidpointNormalize(vmin=vmin, vmax=vmax) clevs = MaxNLocator(cmap.N + 1).tick_values(-vmax, vmax) cs = ax.contourf(num_dates_2d, z_agg_2d, lake_ice_th, cmap=cmap, levels=clevs, extend="both") ax.set_title("Lake ice thickness") print("Mean change in ice thickness: {} m".format(lake_ice_th.mean(axis=1)[winter_points].mean())) all_axes.append(ax) # Colorbar for value plots cax = fig.add_subplot(gs[row, -1]) sfmt = ScalarFormatter(useMathText=True) sfmt.set_powerlimits((-2, 2)) plt.colorbar(cs, cax=cax, format=sfmt) cax.set_xlabel("m") cax.yaxis.get_offset_text().set_position((-2, 10)) # ----------------------------------Lake ice fraction---------------------------------- level = 0 varname = "LC" _, lake_ice_fraction_c = analysis.get_daily_climatology_for_rconf(current_config, var_name=varname, level=level) _, lake_ice_fraction_f = analysis.get_daily_climatology_for_rconf(future_config, var_name=varname, level=level) lake_ice_fraction = _avg_along(lake_ice_fraction_f - lake_ice_fraction_c, axis=avg_axis, lake_fraction=lake_fraction) row += 1 ax = fig.add_subplot(gs[row, 0]) vmax = max(lake_ice_fraction.max(), 0) vmin = min(lake_ice_fraction.min(), 0) vmax = max(abs(vmin), abs(vmax)) # norm = MidpointNormalize(vmin=vmin, vmax=vmax) clevs = MaxNLocator(cmap.N + 1).tick_values(-vmax, vmax) cs = ax.contourf(num_dates_2d, z_agg_2d, lake_ice_fraction, cmap=cmap, levels=clevs, extend="both") ax.set_title("Lake ice fraction") print("Mean change in ice fraction: {}".format(lake_ice_fraction.mean(axis=1)[winter_points].mean())) all_axes.append(ax) # Colorbar for value plots cax = fig.add_subplot(gs[row, -1]) sfmt = ScalarFormatter(useMathText=True) sfmt.set_powerlimits((-2, 2)) plt.colorbar(cs, cax=cax, format=sfmt) cax.set_xlabel("") cax.yaxis.get_offset_text().set_position((-2, 10)) # ----------------------------------Lake depth---------------------------------- level = 0 varname = "CLDP" _, lake_depth_c = analysis.get_daily_climatology_for_rconf(current_config, var_name=varname, level=level) _, lake_depth_f = analysis.get_daily_climatology_for_rconf(future_config, var_name=varname, level=level) lake_depth_cc = _avg_along(lake_depth_f - lake_depth_c, axis=avg_axis, lake_fraction=lake_fraction) row += 1 ax = fig.add_subplot(gs[row, 0]) clevs = [0.01, 0.1, 0.5, 0.75, 1, 2, 3] clevs = [-c for c in reversed(clevs)] + clevs cmap = cm.get_cmap("bwr", len(clevs) - 1) norm = BoundaryNorm(boundaries=clevs, ncolors=len(clevs) - 1) cs = ax.contourf(num_dates_2d, z_agg_2d, lake_depth_cc, cmap=cmap, levels=clevs, norm=norm, extend="both") ax.set_title("Lake level") all_axes.append(ax) # Colorbar for value plots cax = fig.add_subplot(gs[row, -1]) sfmt = ScalarFormatter(useMathText=True) sfmt.set_powerlimits((-2, 2)) plt.colorbar(cs, cax=cax, format=sfmt, ticks=clevs) cax.set_xlabel("m") cax.yaxis.get_offset_text().set_position((-2, 10)) for i, the_ax in enumerate(all_axes): the_ax.xaxis.set_major_formatter(FuncFormatter(lambda d, pos: num2date(d).strftime("%b")[0])) the_ax.xaxis.set_major_locator(MonthLocator(bymonthday=15)) the_ax.xaxis.set_minor_locator(MonthLocator(bymonthday=1)) the_ax.grid(which="minor") the_ax.set_ylabel(ztitle) img_file = Path(img_folder).joinpath("cc_{}_Lake_props_current_{}_avg_{}-{}_vs_{fsy}-{fey}.png".format( base_config.label, avg_axis, start_year_c, end_year_c, fsy=future_config.start_year, fey=future_config.end_year)) fig.tight_layout() fig.savefig(str(img_file), bbox_inches="tight") plt.show()
def main(): start_year_c = 1980 end_year_c = 2010 img_folder = "cc_paper" current_path = "/RESCUE/skynet3_rech1/huziy/hdf_store/cc-canesm2-driven/quebec_0.1_crcm5-hcd-rl-intfl-cc-canesm2-1980-2010.hdf5" base_label = "CRCM5-LI" # Need to read land fraction geo_file_path = "/RESCUE/skynet3_rech1/huziy/hdf_store/pm1979010100_00000000p" r_obj = RPN(geo_file_path) mg_field = r_obj.get_first_record_for_name("MG") lons, lats = r_obj.get_longitudes_and_latitudes_for_the_last_read_rec() r_obj.close() future_shift_years = 90 params = dict( data_path=current_path, start_year=start_year_c, end_year=end_year_c, label=base_label ) base_config_c = RunConfig(**params) base_config_f = base_config_c.get_shifted_config(future_shift_years) varname = "INTF" level = 0 daily_dates, intf_c = analysis.get_daily_climatology(path_to_hdf_file=base_config_c.data_path, var_name=varname, level=level, start_year=base_config_c.start_year, end_year=base_config_c.end_year) _, intf_f = analysis.get_daily_climatology(path_to_hdf_file=base_config_f.data_path, var_name=varname, level=level, start_year=base_config_f.start_year, end_year=base_config_f.end_year) mg_fields = np.asarray([mg_field for d in daily_dates]) mg_crit = 0.0001 the_mask = mg_fields <= mg_crit # Convert to mm/day as well intf_c = _avg_along_lon(intf_c, the_mask) * 24 * 3600 intf_f = _avg_along_lon(intf_f, the_mask) * 24 * 3600 lats_agg = lats.mean(axis=0) num_dates = date2num(daily_dates) lats_agg_2d, num_dates_2d = np.meshgrid(lats_agg, num_dates) # Do the plotting fig = plt.figure() gs = GridSpec(2, 3, width_ratios=[1, 1, 0.05]) norm = SymLogNorm(5e-5) all_axes = [] # Current ax = fig.add_subplot(gs[0, 0]) cs = ax.contourf(num_dates_2d, lats_agg_2d, intf_c[:], 60, norm=norm) ax.set_title("Current ({}-{})".format( base_config_c.start_year, base_config_c.end_year)) all_axes.append(ax) # Future ax = fig.add_subplot(gs[0, 1]) ax.set_title("Future ({}-{})".format( base_config_f.start_year, base_config_f.end_year)) cs = ax.contourf(num_dates_2d, lats_agg_2d, intf_f[:], levels=cs.levels, norm=norm) all_axes.append(ax) # Colorbar for value plots cax = fig.add_subplot(gs[0, 2]) sfmt = ScalarFormatter(useMathText=True) sfmt.set_powerlimits((-1, 2)) plt.colorbar(cs, cax=cax, format=sfmt) cax.set_xlabel("mm/day") cax.yaxis.get_offset_text().set_position((-2, 10)) # CC diff_cmap = cm.get_cmap("RdBu_r", 20) diff = (intf_f - intf_c) / (0.5 * (intf_c + intf_f)) * 100 diff[(intf_f == 0) & (intf_c == 0)] = 0 print(np.min(diff), np.max(diff)) print(np.any(diff.mask)) print(np.any(intf_c.mask)) print(np.any(intf_f.mask)) delta = 200 vmin = -delta vmax = delta locator = MaxNLocator(nbins=20, symmetric=True) clevs = locator.tick_values(vmin=vmin, vmax=vmax) ax = fig.add_subplot(gs[1, 1]) cs = ax.contourf(num_dates_2d, lats_agg_2d, diff, cmap=diff_cmap, levels=clevs, extend="both") ax.set_title("Future - Current") # ax.set_aspect("auto") all_axes.append(ax) cb = plt.colorbar(cs, cax=fig.add_subplot(gs[1, -1])) cb.ax.set_xlabel(r"%") for i, the_ax in enumerate(all_axes): the_ax.xaxis.set_minor_formatter(FuncFormatter(lambda d, pos: num2date(d).strftime("%b")[0])) the_ax.xaxis.set_major_formatter(FuncFormatter(lambda d, pos: "")) the_ax.xaxis.set_minor_locator(MonthLocator(bymonthday=15)) the_ax.xaxis.set_major_locator(MonthLocator()) the_ax.grid() if i != 1: the_ax.set_ylabel(r"Latitude ${\rm \left(^\circ N \right)}$") # identify approximately the melting period and lower latitudes march1 = date2num(datetime(daily_dates[0].year, 3, 1)) june1 = date2num(datetime(daily_dates[0].year, 6, 1)) sel_mask = (num_dates_2d >= march1) & (num_dates_2d < june1) & (lats_agg_2d <= 50) print("Mean interflow decrease in the southern regions: {}%".format(diff[sel_mask].mean())) # identify the regions of max interflow rates in current and future climates lat_min = 55 lat_max = 57.5 may1 = date2num(datetime(daily_dates[0].year, 5, 1)) july1 = date2num(datetime(daily_dates[0].year, 7, 1)) mean_max_current = intf_c[(lats_agg_2d >= lat_min) & (lats_agg_2d <= lat_max) & (num_dates_2d <= july1) & (num_dates_2d >= june1)].mean() mean_max_future = intf_f[(lats_agg_2d >= lat_min) & (lats_agg_2d <= lat_max) & (num_dates_2d <= june1) & (num_dates_2d >= may1)].mean() print("Mean change in the maximum interflow rate: {} %".format((mean_max_future - mean_max_current) * 100 / mean_max_current)) img_file = Path(img_folder).joinpath("INTF_rate_longit_avg.png") fig.tight_layout() from crcm5.analyse_hdf import common_plot_params fig.savefig(str(img_file), bbox_inches="tight", transparent=True, dpi=common_plot_params.FIG_SAVE_DPI)