def set_oggm_cmaps(use_hcl=None): # Set global colormaps global OGGM_CMAPS if use_hcl is None: use_hcl = HAS_HCL_CMAP OGGM_CMAPS['terrain'] = colormap.terrain if HAS_HCL_CMAP and use_hcl: cm_divs = 100 # number of discrete colours from continuous colormaps tcmap = sequential_hcl("Blue-Yellow", rev=True).cmap(cm_divs) OGGM_CMAPS['section_thickness'] = tcmap OGGM_CMAPS['glacier_thickness'] = tcmap else: OGGM_CMAPS['section_thickness'] = plt.cm.get_cmap('YlOrRd') OGGM_CMAPS['glacier_thickness'] = plt.get_cmap('viridis')
def setColorConf(ngroups, colors="tab20", alternative="grey") -> list: """ Parameters: ---------- ngroups:int Number of tags need to be colored. colors:str Built-in colormaps accessible in the matplotlib. See more:https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html alternative: If <ngroups> is greater than the maximum number of colorPalette, the rest tags would be colored with <alternative>. Returns: -------- colors_list:list a list of colors(hex). """ if colors == "hcl": try: from colorspace import sequential_hcl color_repo = sequential_hcl(h=[15, 375], l=65, c=70) colors_list = color_repo.colors(ngroups + 1) except ImportError: print('hcl colorspace package has not being installed.') print('please try the following command:') print( 'pip install git+https://github.com/retostauffer/python-colorspace' ) else: colors = list(plt.get_cmap(colors).colors) colors_list = [to_hex(color) for color in colors] colors_list = colors_list[:ngroups] # if len of colors_list less than ngroups, use grey to fullfill. if len(colors_list) < ngroups: for i in range(ngroups - len(colors_list)): colors_list.append(to_hex(alternative)) return colors_list
from colorspace import sequential_hcl USE_HCL_CMAP = True except ImportError: USE_HCL_CMAP = False from oggm.core.flowline import FileModel from oggm import cfg, utils # Module logger log = logging.getLogger(__name__) # Set global colormaps ALTITUDE_CMAP = colormap.terrain if USE_HCL_CMAP: CMAP_DIVS = 100 # number of discrete colours from continuous colormaps THICKNESS_CMAP = sequential_hcl("Blue-Yellow", rev=True).cmap(CMAP_DIVS) SECTION_THICKNESS_CMAP = THICKNESS_CMAP GLACIER_THICKNESS_CMAP = THICKNESS_CMAP else: SECTION_THICKNESS_CMAP = plt.cm.get_cmap('YlOrRd') GLACIER_THICKNESS_CMAP = plt.get_cmap('viridis') def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=256): """Remove extreme colors from a colormap.""" new_cmap = colors.LinearSegmentedColormap.from_list( 'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval), cmap(np.linspace(minval, maxval, n))) return new_cmap
def past_simulation_and_params(glcdict, pout, y_len=5): for glid, df in glcdict.items(): # take care of merged glaciers rgi_id = glid.split('_')[0] fig = plt.figure(figsize=[20, 7]) gs = GridSpec(1, 4) # 1 rows, 4 columns ax1 = fig.add_subplot(gs[0, 0:3]) ax2 = fig.add_subplot(gs[0, 3]) df.loc[:, 'obs'].plot(ax=ax1, color='k', marker='o', label='Observations') # OGGM standard for run in df.columns: if run == 'obs': continue para = ast.literal_eval('{' + run + '}') if ((np.abs(para['prcp_scaling_factor'] - 1.75) < 0.01) and (para['mbbias'] == 0) and (para['glena_factor'] == 1)): df.loc[:, run].rolling(y_len, center=True). \ mean().plot(ax=ax1, linewidth=2, color='k', label='OGGM default parameter run') oggmdefault = run maes = mae_weighted(df).sort_values() idx2plot = optimize_cov(df.loc[:, maes.index[:150]], df.loc[:, 'obs'], glid, minuse=5) ensmean = df.loc[:, idx2plot].mean(axis=1) ensmeanmean = ensmean.rolling(y_len, center=True).mean() ensstdmean = df.loc[:, idx2plot].std(axis=1).rolling(y_len, center=True).mean() # coverage cov = calc_coverage(df, idx2plot, df['obs']) ax1.fill_between(ensmeanmean.index, ensmeanmean - ensstdmean, ensmeanmean + ensstdmean, color='xkcd:teal', alpha=0.5) # nolbl = df.loc[:, idx2plot2].rolling(y_len, center=True).mean().copy() # nolbl.columns = ['' for i in range(len(nolbl.columns))] #df.loc[:, idx2plot2].rolling(y_len, center=True).mean().plot( # ax=ax1, linewidth=0.8) # plot ens members ensmeanmean.plot(ax=ax1, linewidth=4.0, color='xkcd:teal', label='ensemble parameters runs') # reference run (basically min mae) df.loc[:, maes.index[0]].rolling(y_len, center=True).mean(). \ plot(ax=ax1, linewidth=3, color='xkcd:lavender', label='minimum wMAE parameter run') name = name_plus_id(rgi_id) mae_ens = mae_weighted(pd.concat([ensmean, df['obs']], axis=1))[0] mae_best = maes[0] ax1.set_title('%s' % name, fontsize=28) ax1.text(2030, -4900, 'wMAE ensemble mean = %.2f m\n' 'wMAE minimum run = %.2f m' % (mae_ens, mae_best), fontsize=18, horizontalalignment='right') ax1.text(2040, -4900, '%d ensemble members\n' 'coverage = %.2f' % (len(idx2plot), cov), fontsize=18) ax1.set_ylabel('relative length change [m]', fontsize=26) ax1.set_xlabel('Year', fontsize=26) ax1.set_xlim([1850, 2020]) ax1.set_ylim([-3500, 1000]) ax1.tick_params(axis='both', which='major', labelsize=22) ax1.grid(True) ax1.legend(bbox_to_anchor=(-0.1, -0.15), loc='upper left', fontsize=18, ncol=2) # parameter plots from colorspace import sequential_hcl col = sequential_hcl('Blue-Yellow').colors(len(idx2plot) + 3) for i, run in enumerate(idx2plot): para = ast.literal_eval('{' + run + '}') psf = para['prcp_scaling_factor'] gla = para['glena_factor'] mbb = para['mbbias'] mbb = (mbb - -1400) * (4-0.5) / (1000 - -1400) + 0.5 ax2.plot([1, 2, 3], [psf, gla, mbb], color=col[i], linewidth=2) ax2.set_xlabel('calibration parameters', fontsize=18) ax2.set_ylabel('Precipitation scaling factor\nGlen A factor', fontsize=18) ax2.set_xlim([0.8, 3.2]) ax2.set_ylim([0.3, 4.2]) ax2.set_xticks([1, 2, 3]) ax2.set_xticklabels(['Psf', 'GlenA', 'MB bias'], fontsize=16) ax2.tick_params(axis='y', which='major', labelsize=16) ax2.grid(True) ax3 = ax2.twinx() # scale to same y lims scale = (4.2-0.3)/(4.0-0.5) dy = (2400*scale-2400)/2 ax3.set_ylim([-1400-dy, 1000+dy]) ax3.set_ylabel('mass balance bias [m w.e. ]', fontsize=18) ax3.set_yticks(np.arange(-1400, 1100, 400)) ax3.set_yticklabels(['-1.4', '-1.0', '-0.6', '-0.2', '0.2', '0.6', '1.0']) ax3.tick_params(axis='both', which='major', labelsize=16) fig.subplots_adjust(left=0.08, right=0.95, bottom=0.24, top=0.93, wspace=0.5) fn1 = os.path.join(pout, 'histalp_%s.png' % glid) fig.savefig(fn1) used = dict() used['oggmdefault'] = oggmdefault used['minmae'] = idx2plot[0] used['ensemble'] = idx2plot pickle.dump(used, open(os.path.join(pout, 'runs_%s.p' % glid), 'wb'))