def test_DivergingNorm_autoscale_None_vmin(): norm = mcolors.DivergingNorm(2, vmin=0, vmax=None) norm.autoscale_None([1, 2, 3, 4, 5]) assert norm(5) == 1 assert norm.vmax == 5
def do_plots(ad, ad_ref): """ Generate diagnostic plots. Parameters ---------- ad : AstroData ad_ref : AstroData """ n_hlines = 25 n_vlines = 25 output_dir = "./plots/geminidr/gmos/test_gmos_spect_ls_distortion_determine" os.makedirs(output_dir, exist_ok=True) name, _ = os.path.splitext(ad.filename) grating = ad.disperser(pretty=True) bin_x = ad.detector_x_bin() bin_y = ad.detector_y_bin() central_wavelength = ad.central_wavelength() * 1e9 # in nanometers # -- Show distortion map --- for ext_num, ext in enumerate(ad): fname, _ = os.path.splitext(os.path.basename(ext.filename)) n_rows, n_cols = ext.shape x = np.linspace(0, n_cols, n_vlines, dtype=int) y = np.linspace(0, n_rows, n_hlines, dtype=int) X, Y = np.meshgrid(x, y) model = ext.wcs.get_transform("pixels", "distortion_corrected")[1] U = X - model(X, Y) V = np.zeros_like(U) fig, ax = plt.subplots( num="Distortion Map {:s} #{:d}".format(fname, ext_num)) vmin = U.min() if U.min() < 0 else -0.1 * U.ptp() vmax = U.max() if U.max() > 0 else +0.1 * U.ptp() vcen = 0 Q = ax.quiver(X, Y, U, V, U, cmap="coolwarm", norm=colors.DivergingNorm(vcenter=vcen, vmin=vmin, vmax=vmax)) ax.set_xlabel("X [px]") ax.set_ylabel("Y [px]") ax.set_title("Distortion Map\n{:s} #{:d}- Bin {:d}x{:d}".format( fname, ext_num, bin_x, bin_y)) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = fig.colorbar(Q, extend="max", cax=cax, orientation="vertical") cbar.set_label("Distortion [px]") fig.tight_layout() fig_name = os.path.join( output_dir, "{:s}_{:d}_{:s}_{:.0f}_distMap.png".format(fname, ext_num, grating, central_wavelength)) fig.savefig(fig_name) del fig, ax # -- Show distortion model difference --- for num, (ext, ext_ref) in enumerate(zip(ad, ad_ref)): name, _ = os.path.splitext(ext.filename) shape = ext.shape data = generate_fake_data(shape, ext.dispersion_axis() - 1) model_out = ext.wcs.get_transform("pixels", "distortion_corrected") model_ref = ext_ref.wcs.get_transform("pixels", "distortion_corrected") transform_out = transform.Transform(model_out) transform_ref = transform.Transform(model_ref) data_out = transform_out.apply(data, output_shape=ext.shape) data_ref = transform_ref.apply(data, output_shape=ext.shape) data_out = np.ma.masked_invalid(data_out) data_ref = np.ma.masked_invalid(data_ref) fig, ax = plt.subplots(dpi=150, num="Distortion Comparison: {:s} #{:d}".format( name, num)) im = ax.imshow(data_ref - data_out) ax.set_xlabel("X [px]") ax.set_ylabel("Y [px]") ax.set_title( "Difference between output and reference: \n {:s} #{:d} ".format( name, num)) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = fig.colorbar(im, extend="max", cax=cax, orientation="vertical") cbar.set_label("Distortion [px]") fig_name = os.path.join( output_dir, "{:s}_{:d}_{:s}_{:.0f}_distDiff.png".format( name, num, grating, central_wavelength)) fig.savefig(fig_name)
def test_DivergingNorm_autoscale(): norm = mcolors.DivergingNorm(vcenter=20) norm.autoscale([10, 20, 30, 40]) assert norm.vmin == 10. assert norm.vmax == 40.
Ix = Cnorm_top * np.array([np.real(E * np.conj(E)) for E in Ex]) #um².kg².s-6.A-2 Iy = Cnorm_top * np.array([np.real(E * np.conj(E)) for E in Ey]) Iz = Cnorm_top * np.array([np.real(E * np.conj(E)) for E in Ez]) It = Ix + Iy + Iz xp = np.linspace(-SX / 2, SX / 2, It.shape[0], endpoint=False) yp = np.linspace(-SY / 2, SY / 2, It.shape[1], endpoint=False) plt.xlabel('y (um)') plt.ylabel('x (um)') plt.xlim([-SX / 2, SX / 2]) plt.ylim([-SY / 2, SY / 2]) plt.title('|E|² at time t = ' + str(titer)) plt.imshow(It, norm=colors.DivergingNorm(vmin=0, vcenter=1.5e13, vmax=3e13), cmap=plt.cm.hot, extent=[xp[0], xp[-1], yp[0], yp[-1]]) #,interpolation='none') cbar = plt.colorbar() cbar.set_label('Light intensity [in W.m-2]', rotation=270, labelpad=20) plt.tight_layout() plt.savefig( 'D:/Users/Antoine/Documents/copenhague-1/togit/MyMCPython/nanofiber_conveyor_belt/Total_light_intensity_time_' + str(titer) + '.png') plt.figure(100 + titer) Nanofiber_potential = potential(It, 2 * np.pi * cst.c / w1) r0 = 0.150 for i, x in enumerate(xp):
def cross_section(variable_name, date, time, start_lat, start_lon, end_lat, end_lon, save=False): '''This function plots a vertical cross section of the chosen variable. Supported variables for plotting procedure are vertical_velocity, rh, omega, absolute_vorticity, theta_e and reflectivity.''' ### Predefine some variables ### # Define data filename data_dir = '/scratch3/thomasl/work/data/casestudy_baden/' filename = '{}wrfout_d02_{}_{}:00'.format(data_dir, date, time) # Define save directory save_dir = '/scratch3/thomasl/work/retrospective_part/' 'casestudy_baden/cross_section/' # Create the start point and end point for the cross section start_point = CoordPair(lat=start_lat, lon=start_lon) end_point = CoordPair(lat=end_lat, lon=end_lon) ### Start plotting procedure ### # Open NetCDF file ncfile = Dataset(filename) # Extract the model height, terrain height and variables ht = getvar(ncfile, 'z') / 1000 # change to km ter = getvar(ncfile, 'ter') / 1000 if variable_name == 'vertical_velocity': variable = getvar(ncfile, 'wa', units='kt') title_name = 'Vertical Velocity' colorbar_label = 'Vertical Velocity [$kn$]' variable_min = -2 variable_max = 2 elif variable_name == 'rh': variable = getvar(ncfile, 'rh') title_name = 'Relative Humidity' colorbar_label = 'Relative Humidity [$pct$]' variable_min = 0 variable_max = 100 elif variable_name == 'omega': variable = getvar(ncfile, 'omega') title_name = 'Vertical Motion (Omega)' colorbar_label = 'Omega [$Pa$ $s^-$$^1$]' variable_min = -5 variable_max = 5 elif variable_name == 'absolute_vorticity': variable = getvar(ncfile, 'avo') title_name = 'Absolute Vorticity' colorbar_label = 'Absolute Vorticity [$10^{-5}$' '$s^{-1}$]' variable_min = -50 variable_max = 100 elif variable_name == 'theta_e': variable = getvar(ncfile, 'theta_e') title_name = 'Theta-E' colorbar_label = 'Theta-E [$K$]' variable_min = 315 variable_max = 335 elif variable_name == 'reflectivity': variable = getvar(ncfile, 'dbz') #, timeidx=-1 title_name = 'Reflectivity' colorbar_label = 'Reflectivity [$dBZ$]' variable_min = 5 variable_max = 75 # Linear Z for interpolation Z = 10**(variable / 10) # Compute the vertical cross-section interpolation z_cross = vertcross(Z, ht, wrfin=ncfile, start_point=start_point, end_point=end_point, latlon=True, meta=True) # Convert back after interpolation variable_cross = 10.0 * np.log10(z_cross) # Make a copy of the z cross data variable_cross_filled = np.ma.copy(to_np(variable_cross)) # For each cross section column, find the first index with # non-missing values and copy these to the missing elements below for i in range(variable_cross_filled.shape[-1]): column_vals = variable_cross_filled[:, i] first_idx = int(np.transpose((column_vals > -200).nonzero())[0]) variable_cross_filled[0:first_idx, i] = variable_cross_filled[first_idx, i] ter_line = interpline(ter, wrfin=ncfile, start_point=start_point, end_point=end_point) # Get latitude and longitude points lats, lons = latlon_coords(variable) # Create the figure fig = plt.figure(figsize=(15, 10)) ax = plt.axes() ys = to_np(variable_cross.coords['vertical']) xs = np.arange(0, variable_cross.shape[-1], 1) # Make contour plot if variable_name == 'reflectivity': levels = np.arange(variable_min, variable_max, 5) # Create the dbz color table found on NWS pages. dbz_rgb = np.array( [[4, 233, 231], [1, 159, 244], [3, 0, 244], [2, 253, 2], [1, 197, 1], [0, 142, 0], [253, 248, 2], [229, 188, 0], [253, 149, 0], [253, 0, 0], [212, 0, 0], [188, 0, 0], [248, 0, 253], [152, 84, 198]], np.float32) / 255.0 dbz_cmap, dbz_norm = from_levels_and_colors(levels, dbz_rgb, extend='max') else: levels = np.linspace(variable_min, variable_max, 11) if variable_name == 'omega' or variable_name == 'vertical_velocity': def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100): 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 old_cmap = plt.get_cmap('RdYlBu') cmap = truncate_colormap(old_cmap, 0.05, 0.9) norm = colors.DivergingNorm(vmin=variable_min, vcenter=0, vmax=variable_max) else: cmap = ListedColormap(sns.cubehelix_palette(20, start=.5, rot=-.75)) if variable_name == 'omega' or variable_name == 'vertical_velocity': variable_contours = ax.contourf(xs, ys, to_np(variable_cross_filled), levels=levels, cmap=cmap, extend='both', norm=norm) elif variable_name == 'rh': variable_contours = ax.contourf(xs, ys, to_np(variable_cross_filled), levels=levels, cmap=cmap, extend='max') elif variable_name == 'reflectivity': variable_contours = ax.contourf(xs, ys, to_np(variable_cross_filled), levels=levels, cmap=dbz_cmap, norm=dbz_norm, extend='both') else: variable_contours = ax.contourf(xs, ys, to_np(variable_cross_filled), levels=levels, cmap=cmap, extend='both') # Plot wind barbs if variable_name == 'vertical_velocity': u = getvar(ncfile, 'ua', units='kt') U = 10**(u / 10) u_cross = vertcross(U, ht, wrfin=ncfile, start_point=start_point, end_point=end_point, latlon=True, meta=True) u_cross = 10.0 * np.log10(u_cross) u_cross_filled = np.ma.copy(to_np(u_cross)) for i in range(u_cross_filled.shape[-1]): column_vals = u_cross_filled[:, i] first_idx = int(np.transpose((column_vals > -200).nonzero())[0]) u_cross_filled[0:first_idx, i] = u_cross_filled[first_idx, i] ax.barbs(xs[::3], ys[::3], to_np(u_cross_filled[::3, ::3]), to_np(variable_cross_filled[::3, ::3]), length=7, zorder=1) if variable_name == 'omega': u = getvar(ncfile, 'ua', units='kt') U = 10**(u / 10) u_cross = vertcross(U, ht, wrfin=ncfile, start_point=start_point, end_point=end_point, latlon=True, meta=True) u_cross = 10.0 * np.log10(u_cross) u_cross_filled = np.ma.copy(to_np(u_cross)) for i in range(u_cross_filled.shape[-1]): column_vals = u_cross_filled[:, i] first_idx = int(np.transpose((column_vals > -200).nonzero())[0]) u_cross_filled[0:first_idx, i] = u_cross_filled[first_idx, i] w = getvar(ncfile, 'wa', units='kt') W = 10**(w / 10) w_cross = vertcross(W, ht, wrfin=ncfile, start_point=start_point, end_point=end_point, latlon=True, meta=True) w_cross = 10.0 * np.log10(w_cross) w_cross_filled = np.ma.copy(to_np(w_cross)) for i in range(w_cross_filled.shape[-1]): column_vals = w_cross_filled[:, i] first_idx = int(np.transpose((column_vals > -200).nonzero())[0]) w_cross_filled[0:first_idx, i] = w_cross_filled[first_idx, i] ax.barbs(xs[::3], ys[::3], to_np(u_cross_filled[::3, ::3]), to_np(w_cross_filled[::3, ::3]), length=7, zorder=1, color='grey') # Add color bar cbar = mpu.colorbar(variable_contours, ax, orientation='vertical', aspect=40, shrink=.05, pad=0.05) cbar.set_label(colorbar_label, fontsize=15) cbar.set_ticks(levels) # Set x-ticks to use latitude and longitude labels coord_pairs = to_np(variable_cross.coords['xy_loc']) x_ticks = np.arange(coord_pairs.shape[0]) x_labels = [ pair.latlon_str(fmt='{:.2f}, {:.2f}') for pair in to_np(coord_pairs) ] # Set desired number of x ticks below num_ticks = 5 thin = int((len(x_ticks) / num_ticks) + .5) ax.set_xticks(x_ticks[::thin]) ax.set_xticklabels(x_labels[::thin], rotation=45, fontsize=10) ax.set_xlim(x_ticks[0], x_ticks[-1]) # Set y-ticks and limit the height ax.set_yticks(np.linspace(0, 12, 13)) ax.set_ylim(0, 12) # Set x-axis and y-axis labels ax.set_xlabel('Latitude, Longitude', fontsize=12.5) ax.set_ylabel('Height [$km$]', fontsize=12.5) # Fill in mountian area ht_fill = ax.fill_between(xs, 0, to_np(ter_line), facecolor='saddlebrown', zorder=2) # Make nicetime xr_file = xr.open_dataset(filename) nicetime = pd.to_datetime(xr_file.QVAPOR.isel(Time=0).XTIME.values) # Add title ax.set_title('Vertical Cross-Section of {}'.format(title_name), fontsize=20, loc='left') ax.set_title('Valid time: {} {}'.format( nicetime.strftime('%Y-%m-%d %H:%M'), 'UTC'), fontsize=15, loc='right') # Add grid for y axis ax.grid(axis='y', linestyle='--', color='grey') plt.show() ### Save figure ### if save == True: fig.savefig('{}cross_section_{}.png'.format(save_dir, variable_name), bbox_inches='tight', dpi=300)
def test_DivergingNorm_scaleout_center(): # test the vmin never goes above vcenter norm = mcolors.DivergingNorm(vcenter=0) x = norm([1, 2, 3, 5]) assert norm.vmin == 0 assert norm.vmax == 5
def test_DivergingNorm_Even(): norm = mcolors.DivergingNorm(vmin=-1, vcenter=0, vmax=4) vals = np.array([-1.0, -0.5, 0.0, 1.0, 2.0, 3.0, 4.0]) expected = np.array([0.0, 0.25, 0.5, 0.625, 0.75, 0.875, 1.0]) assert_array_equal(norm(vals), expected)
topo = dem['topo'] longitude = dem['longitude'] latitude = dem['latitude'] fig, ax = plt.subplots(constrained_layout=True) # make a colormap that has land and ocean clearly delineated and of the # same length (256 + 256) colors_undersea = plt.cm.terrain(np.linspace(0, 0.17, 256)) colors_land = plt.cm.terrain(np.linspace(0.25, 1, 256)) all_colors = np.vstack((colors_undersea, colors_land)) terrain_map = colors.LinearSegmentedColormap.from_list('terrain_map', all_colors) # make the norm: Note the center is offset so that the land has more # dynamic range: divnorm = colors.DivergingNorm(vmin=-500, vcenter=0, vmax=4000) pcm = ax.pcolormesh( longitude, latitude, topo, rasterized=True, norm=divnorm, cmap=terrain_map, ) ax.set_xlabel('Lon $[^o E]$') ax.set_ylabel('Lat $[^o N]$') ax.set_aspect(1 / np.cos(np.deg2rad(49))) fig.colorbar(pcm, shrink=0.6, extend='both', label='Elevation [m]') plt.show()
def pareto_front_plot(name, percent=False, *args): # scores1 = scores('phosphorus', 33) ''' return: xx = kg P/ha removed from baseline, if percent=False; xx= % reduction/ha from baseline, if percent=True: yy = $/ha; z: $/kg P removed score = all raw data before averaging df_score2: data used for plot in pandas dataframe yield_baseline: kg/ha for one subwatershed or all subwatersheds ''' if not args: score = np.zeros((45, 54, 2)) yield_baseline = np.zeros((45)) for i in range(45): score[i, :, :], yield_baseline[i] = scores(name, i, percent) score2 = np.delete(score, [7, 30], axis=0).mean(axis=0) df_score2 = pd.DataFrame(score2) df_score2['z'] = df_score2[1] * -1 / df_score2[0] df_score2['BMP'] = ['BMP' + str(i) for i in range(1, 55)] df_score2 = df_score2.fillna(0) xx = score2[:, 0] yy = score2[:, 1] * -1 z = yy / (xx) z[np.isnan(z)] = 0 if percent == True: label = '_ave' + '_pct' else: label = '_ave' data_list = [xx, yy, z, score, df_score2, yield_baseline] else: score2, yield_baseline = scores(name, args[0], percent) df_score2 = pd.DataFrame(score2) df_score2['z'] = df_score2[1] * -1 / df_score2[0] df_score2['BMP'] = ['BMP' + str(i) for i in range(1, 55)] df_score2 = df_score2.fillna(0) xx = score2[:, 0] yy = score2[:, 1] * -1 z = yy / xx z[np.isnan(z)] = 0 if percent == True: label = '_single_sw_' + str(args[0] + 1) + '_pct' else: label = '_single_sw_' + str(args[0] + 1) data_list = [xx, yy, z, score2, df_score2, yield_baseline] if name == 'phosphorus': z[6] = 0 pareto = identify_pareto(score2) pareto = np.insert(pareto, [0], 0) pareto_front = score2[pareto] pareto_front[:, 1] = pareto_front[:, 1] * -1 pareto_front_df = pd.DataFrame(pareto_front) pareto_front_df.sort_values(0, inplace=True) pareto_front = pareto_front_df.values BMP_list = ['BMP' + str(i) for i in range(1, 55)] BMP_list2 = ['' for i in range(1, 55)] for i in range(len(pareto)): index = pareto[i] BMP_list2[index] = BMP_list[index] f, ax = plt.subplots(figsize=(10, 5)) vmin = z.min() vmax = z.max() norm = colors.DivergingNorm(vmin=vmin, vcenter=0, vmax=vmax) cmap = cm.get_cmap('seismic') points = ax.scatter(xx, yy, c=z, s=50, edgecolor='k', cmap=cmap, norm=norm) ax.plot(pareto_front[:, 0], pareto_front[:, 1], color='r') for i, txt in enumerate(BMP_list2): ax.annotate(txt, (xx[i], yy[i])) if percent == False: ax.set_xlabel(name + ' reduction (kg/ha)', fontsize=12) f.colorbar(points, label='Cost ($/kg removal)', orientation="horizontal", aspect=40) elif percent == True: ax.set_xlabel(name + ' reduction (%)', fontsize=12) f.colorbar(points, label='Cost ($/% removal)', orientation="horizontal", aspect=40) ax.set_ylabel('Crop net revenue loss ($/ha)', fontsize=12) # f.colorbar(points, label = 'Cost ($/kg removal)', orientation="horizontal", aspect=40) plt.tight_layout() plt.savefig( './model_SWAT/BMP_cost_eff_analysis/cost_eff_analysis_figures/plot_' + name + label + '.tif', dpi=150) plt.show() return data_list
def test_DivergingNorm_premature_scaling(): norm = mcolors.DivergingNorm(vcenter=2) with pytest.raises(ValueError): norm.inverse(np.array([0.1, 0.5, 0.9]))
def E1_near_boundaries_dendro(domains, boundaries, separate_boundaries, averaged=None): ######################## dendrogramm ################# fig_path = "results/" + os.path.basename(domains_file) + "_E1dendro.png" if os.path.isfile(fig_path) and not redraw_figs: return print("Drawing boundaries dendrogramm") # set colormaps domainlengths = (domains.end - domains.start).values.tolist() domain_insulations = np.hstack( (domains.insulation_l.values, domains.insulation_r.values)) length_norms = colors.BoundaryNorm(np.percentile(np.unique(domainlengths), range(0, 100, 20)), ncolors=256) insulation_norms = colors.BoundaryNorm(np.percentile( np.unique(domain_insulations), range(0, 100, 10)), ncolors=256) length2color_mapper = cm.ScalarMappable(length_norms, cmap="Greys") length2color_mapper.set_array(domain_insulations) insulation2color_mapper = cm.ScalarMappable(insulation_norms, cmap="RdBu") inscolors_l = list( map(insulation2color_mapper.to_rgba, domains.insulation_l)) inscolors_r = list( map(insulation2color_mapper.to_rgba, domains.insulation_r)) lencolors = list(map(length2color_mapper.to_rgba, domainlengths)) if separate_boundaries: # colors_list = [lencolors*2,inscolors_l+inscolors_r] colors_list = [inscolors_l + inscolors_r] else: colors_list = [lencolors, inscolors_l, inscolors_r] E1_values = boundaries.flatten() try: E1mapper = colors.TwoSlopeNorm( vcenter=0, vmin=np.percentile(E1_values[E1_values < 0], 5), vmax=np.percentile(E1_values[E1_values > 0], 95)) except: E1mapper = colors.DivergingNorm( vcenter=0, vmin=np.percentile(E1_values[E1_values < 0], 5), vmax=np.percentile(E1_values[E1_values > 0], 95)) from scipy.spatial.distance import pdist from scipy.cluster.hierarchy import linkage if separate_boundaries: distances = pdist(averaged, metric=lambda x, y: abs((x[0] - x[1]) - (y[0] - y[1]))) # distances = np.nan_to_num(distances,nan=0) link = linkage(distances, optimal_ordering=True) assert (boundaries.shape[1] - 1) % 2 == 0 k = (boundaries.shape[1] - 1) // 2 else: link = linkage(pdist(boundaries), optimal_ordering=True) assert (boundaries.shape[1] % 2) == 0 k = (boundaries.shape[1] - 2) // 2 labels = (-1*(E1_resolution//1000)*(np.arange(k)+1))[::-1].tolist() + \ ["B"] + \ ((E1_resolution//1000)*(np.arange(k)+1)).tolist() labels = map(str, labels) boundaries = pd.DataFrame(data=boundaries, columns=labels) ax = sns.clustermap( boundaries, row_cluster=True, row_linkage=link, col_cluster=False, #metric="seuclidean", #figsize=(max(1,(k*2+1)*2//10), # max(20,len(boundaries)//100)), figsize=(3, 10), yticklabels=False, # row_colors=colors_list, norm=E1mapper, cmap="bwr", cbar_pos=(1, .2, .04, .3), cbar_kws={"label": "cePC1 value"}) ax.ax_row_dendrogram.set_visible(False) ax.ax_heatmap.axvline(x=k + 0.5, linewidth=2) ax.ax_heatmap.set_xlabel("Distance to boundary, kb", fontsize=14) hm = ax.ax_heatmap.get_position() ax.ax_heatmap.set_position([hm.x0, hm.y0, hm.width, hm.height * 1.25]) ax.ax_heatmap.set_title(shortname, fontsize=16, fontstyle="italic") if not separate_boundaries: ax.ax_heatmap.axvline(x=2 * k + 1 + k + 0.5) ax.ax_heatmap.axvline(x=2 * k + 1, ls="--") #c = plt.colorbar(length2color_mapper, ax=ax.ax_col_dendrogram, # orientation="horizontal", # fraction=0.5) #c.set_label("Domain size") #plt.tight_layout() ax.savefig(fig_path) plt.clf()
def test_DivergingNorm_VcenterGTVmax(): with pytest.raises(ValueError): mcolors.DivergingNorm(vmin=10, vcenter=25, vmax=20)
def test_DivergingNorm_VmaxEqualsVcenter(): with pytest.raises(ValueError): mcolors.DivergingNorm(vmin=-2, vcenter=2, vmax=2)
#import GH_generate as gen #import GH_solve as solv #import GH_displayGeoid as dgeo #import GH_displaySat as dsat #import GH_export as exp #import GH_displayTopo as dtopo #import GH_terminal as term #import GH_harmonics as harm #import GH_geoMath as gmath #import GH_earthMap as emap # ============================================================================= # SETUP # ============================================================================= colors.DivergingNorm(vmin=-10000, vcenter=0., vmax=10000) # ============================================================================= # FIGURE FUNCTIONS # ============================================================================= def Make_Map_Fig (proj, fignum, ax_pos, shape, limits): """ Generates a mpl figure with the wanted coordiates system projection """ FIG = plt.figure(*fignum, figsize=shape) AX = FIG.add_subplot(ax_pos, projection=proj(central_longitude=0)) AX.set_extent(limits, crs=ccrs.PlateCarree()) plt.show(block=False) return FIG, AX def Make_Map (proj=ccrs.PlateCarree, fignum=[], ax_pos=111, shape=(7,5), limits=np.array([-180,180,-90,90])):
def test_DivergingNorm_autoscale_None_vmax(): norm = mcolors.DivergingNorm(2, vmin=None, vmax=10) norm.autoscale_None([1, 2, 3, 4, 5]) assert norm(1) == 0 assert norm.vmin == 1
#swith the sign of first component so that the trend is growing LFC[0]=-LFC[0] LFP[0]=-LFP[0] #create map lon_axis=np.linspace(-179,179,180) lat_axis=np.linspace(-89,89,90) lat_axis=np.flip(lat_axis) xx, yy = np.meshgrid(lon_axis,lat_axis) map0=Basemap(projection='cyl') #set colour scale vmin=-1 vmax=1 divnorm = mcolors.DivergingNorm(vmin=vmin, vcenter=0, vmax=vmax) time=np.linspace(1979,2018,len(LFC[0])) fig=plt.figure(constrained_layout=True,figsize=(20,12)) widths=[10,10] heights=[5,1,5,1] spec=fig.add_gridspec(ncols=2,nrows=4,width_ratios=widths,height_ratios=heights) for i in range(2): for j in range(2): ax=fig.add_subplot(spec[i*2,j]) #map0.contourf(xx,yy,LFP[i*2+j],15,cmap=my_cmap,norm=divnorm,ax=ax) map0.pcolormesh(xx,yy,LFP[i*2+j],cmap=my_cmap,norm=divnorm,ax=ax) map0.drawcoastlines(ax=ax) smoothed=tukey(LFC[i*2+j],0.5,10)
def test_DivergingNorm_scale(): norm = mcolors.DivergingNorm(2) assert norm.scaled() is False norm([1, 2, 3, 4]) assert norm.scaled() is True
def CMD_comaprison_plot(colour1, mag1, colour2, mag2, colour3, mag3, vertex_list, region, file_type): distance_modulus = 18.9 scale = 2 plt.rc('text', usetex=True) plt.rc('font', family='serif') plt.rcParams.update({'font.size':scale*18}) fig = plt.figure(figsize=(scale*16,scale*7.45)) gs = GridSpec(1, 4, figure=fig, wspace=0) #gs.tight_layout(fig, w_pad=0.) ax1 = fig.add_subplot(gs[0]) ax2 = fig.add_subplot(gs[1]) ax3 = fig.add_subplot(gs[2]) ax4 = fig.add_subplot(gs[3]) axis_list = [ax1, ax2, ax3, ax4] xbinsize = 0.01 ybinsize = 0.03 xbins = np.arange( start = -2, stop = 3.5+xbinsize, step = xbinsize) ybins = np.arange( start = 13.-distance_modulus, stop = 24-distance_modulus+ybinsize, step = ybinsize) density1 = ax1.hist2d(colour1, mag1, bins=[xbins, ybins], cmap='magma', norm=colors.LogNorm(vmin=1), rasterized = True) density2 = ax2.hist2d(colour2, mag2, bins=[xbins, ybins], cmap='magma', norm=colors.LogNorm(vmin=1), rasterized = True) density3 = ax3.hist2d(colour3, mag3, bins=[xbins, ybins], cmap='magma', norm=colors.LogNorm(vmin=1), rasterized = True) ax4.imshow(density1[0].T-density2[0].T-density3[0].T, extent=[np.min(xbins), np.max(xbins), np.min(ybins), np.max(ybins)], origin='lower', cmap='seismic_r', norm=colors.DivergingNorm(vcenter=0.), rasterized=True) xy = (-1.6,-4.1) ax1.annotate('Observed', xy) ax2.annotate('Galaxy model', xy) ax3.annotate('Field model', xy) ax4.annotate('Residuals', xy) colour_polygons = 'cyan' for pol in vertex_list: for axs in axis_list: polygon = Polygon(pol, edgecolor=colour_polygons, fill=False, linewidth=scale*1.2, ls='--') axs.add_patch(polygon) for axs in axis_list: axs.minorticks_on() axs.tick_params(which='both', direction='inout') axs.tick_params(which='major', length=scale*6) axs.tick_params(which='minor', length=scale*3) axs.set_xlabel('$(g-i)_0$') axs.set_ylabel('$I_{0}$') axs.set_xlim((-2,3.5)) axs.set_ylim((24-distance_modulus, 14.-distance_modulus)) axs.autoscale(False) axs.label_outer() fig.savefig('/home/polmassana/Documents/PhD/SFH/Plots/CMD_comparison_plots/CMD_comparison_sfh_solve_%s.%s'%(region, file_type), bbox_inches='tight') plt.close()
def test_DivergingNorm_scaleout_center_max(): # test the vmax never goes below vcenter norm = mcolors.DivergingNorm(vcenter=0) x = norm([-1, -2, -3, -5]) assert norm.vmax == 0 assert norm.vmin == -5
def test_DivergingNorm_deprecated(): with pytest.warns(cbook.MatplotlibDeprecationWarning): norm = mcolors.DivergingNorm(vcenter=0)
def test_DivergingNorm_Odd(): norm = mcolors.DivergingNorm(vmin=-2, vcenter=0, vmax=5) vals = np.array([-2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) expected = np.array([0.0, 0.25, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) assert_array_equal(norm(vals), expected)
else: Nanofiber_potential[i, j] -= (5.6E-49) / ( ((r - r0) * 1e-6)**3) #add vanderwals potential #plot 2D image of the potential plt.figure(1) plt.xlabel('y (um)') plt.ylabel('x (um)') plt.xlim([-1.5, 1.5]) plt.ylim([-1.5, 1.5]) levels = [-2.5, -2, -1.5, -1, -0.5, 0, 1, 2, 3, 4, 5] plt.title('Trap potential nanofiber experiment') plt.imshow(Nanofiber_potential / kb * 1e3, norm=colors.DivergingNorm(vmin=-0.2, vcenter=0, vmax=1.0), cmap=plt.cm.RdYlBu, extent=[xp[0], xp[-1], yp[0], yp[-1]]) #,interpolation='none') cbar = plt.colorbar() cbar.set_label('Trap Potential [in mK]', rotation=270, labelpad=20) plt.tight_layout() plt.savefig( 'D:/Users/Antoine/Documents/copenhague-1/togit/MyMCPython/nanofiber_experiment/Nanofiber_Trap_potential.png' ) # plot 2D projection of the atoms # back of all images #3D trajectories simulation_name = "Nanofiber_experiment" data = np.load(