def plot_clouds( tag: str, offset: Optional[Tuple[float, float]] = None, output: Optional[str] = "clouds.pdf", radtrans: Optional[read_radtrans.ReadRadtrans] = None, composition: str = "MgSiO3", ) -> None: """ Function to plot the size distributions for a given cloud composition as function as pressure. The size distributions are calculated for the median sample by using the radius_g (as function of pressure) and sigma_g. Parameters ---------- tag : str Database tag with the posterior samples. offset : tuple(float, float), None Offset of the x- and y-axis label. Default values are used if set to ``None``. output : str Output filename for the plot. The plot is shown in an interface window if the argument is set to ``None``. radtrans : read_radtrans.ReadRadtrans, None Instance of :class:`~species.read.read_radtrans.ReadRadtrans`. Not used if set to ``None``. composition : str Cloud composition (e.g. 'MgSiO3', 'Fe', 'Al2O3', 'Na2S', 'KCl'). Returns ------- NoneType None """ species_db = database.Database() box = species_db.get_samples(tag) median = box.median_sample if ( f"{composition.lower()}_fraction" not in median and "log_tau_cloud" not in median and f"{composition}(c)" not in median ): raise ValueError( f"The mass fraction of the {composition} clouds is not found. The median " f"sample contains the following parameters: {list(median.keys())}" ) if output is None: print(f"Plotting {composition} clouds...", end="", flush=True) else: print(f"Plotting {composition} clouds: {output}...", end="", flush=True) mpl.rcParams["font.serif"] = ["Bitstream Vera Serif"] mpl.rcParams["font.family"] = "serif" plt.rc("axes", edgecolor="black", linewidth=2.5) plt.figure(1, figsize=(4.0, 3.0)) gridsp = mpl.gridspec.GridSpec(1, 2, width_ratios=[4, 0.25]) gridsp.update(wspace=0.1, hspace=0.0, left=0, right=1, bottom=0, top=1) ax1 = plt.subplot(gridsp[0, 0]) ax2 = plt.subplot(gridsp[0, 1]) radtrans.get_model(median) cloud_index = radtrans.rt_object.cloud_species.index(f"{composition}(c)") radius_g = radtrans.rt_object.r_g[:, cloud_index] * 1e4 # (cm) -> (um) sigma_g = median["sigma_lnorm"] r_bins = np.logspace(-3.0, 3.0, 1000) radii = (r_bins[1:] + r_bins[:-1]) / 2.0 dn_dr = np.zeros((radius_g.shape[0], radii.shape[0])) for i, item in enumerate(radius_g): dn_dr[ i, ] = lognorm.pdf(radii, s=np.log(sigma_g), loc=0.0, scale=item) ax1.tick_params( axis="both", which="major", colors="black", labelcolor="black", direction="in", width=1, length=5, labelsize=12, top=True, bottom=True, left=True, right=True, labelbottom=True, ) ax1.tick_params( axis="both", which="minor", colors="black", labelcolor="black", direction="in", width=1, length=3, labelsize=12, top=True, bottom=True, left=True, right=True, labelbottom=True, ) ax2.tick_params( axis="both", which="major", colors="black", labelcolor="black", direction="in", width=1, length=5, labelsize=12, top=True, bottom=True, left=True, right=True, ) ax2.tick_params( axis="both", which="minor", colors="black", labelcolor="black", direction="in", width=1, length=3, labelsize=12, top=True, bottom=True, left=True, right=True, ) xx_grid, yy_grid = np.meshgrid(radii, 1e-6 * radtrans.rt_object.press) fig = ax1.pcolormesh( xx_grid, yy_grid, dn_dr, cmap="viridis", shading="auto", norm=LogNorm(vmin=1e-10 * np.amax(dn_dr), vmax=np.amax(dn_dr)), ) cb = Colorbar(ax=ax2, mappable=fig, orientation="vertical", ticklocation="right") cb.ax.set_ylabel("dn/dr", rotation=270, labelpad=20, fontsize=11) for item in radtrans.rt_object.press * 1e-6: # (bar) ax1.axhline(item, ls="-", lw=0.1, color="white") for item in radtrans.rt_object.cloud_radii * 1e4: # (um) ax1.axvline(item, ls="-", lw=0.1, color="white") ax1.text( 0.07, 0.07, fr"$\sigma_\mathrm{{g}}$ = {sigma_g:.2f}", ha="left", va="bottom", transform=ax1.transAxes, color="black", fontsize=13.0, ) ax1.set_ylabel("Pressure (bar)", fontsize=13) ax1.set_xlabel("Grain radius (µm)", fontsize=13) ax1.set_xlim(radii[0], radii[-1]) ax1.set_ylim( radtrans.rt_object.press[-1] * 1e-6, radtrans.rt_object.press[0] * 1e-6 ) if offset is not None: ax1.get_xaxis().set_label_coords(0.5, offset[0]) ax1.get_yaxis().set_label_coords(offset[1], 0.5) else: ax1.get_xaxis().set_label_coords(0.5, -0.1) ax1.get_yaxis().set_label_coords(-0.15, 0.5) ax1.set_xscale("log") ax1.set_yscale("log") ax2.set_yscale("log") print(" [DONE]") if output is None: plt.show() else: plt.savefig(output, bbox_inches="tight") plt.clf() plt.close()
gzc_68[:,i] = err(gzc[(gzh >= b) & (gzh < b+db)]) gzh_68[:,i] = err(gzh[(gzc >= b) & (gzc < b+db)]) gzc_avg[-1] = np.median(gzc[(gzh > bins[-2]) & (gzh <= bins[-1])]) gzh_avg[-1] = np.median(gzh[(gzc > bins[-2]) & (gzc <= bins[-1])]) gzc_std[-1] = np.std(gzc[(gzh > bins[-2]) & (gzh <= bins[-1])]) gzh_std[-1] = np.std(gzh[(gzc > bins[-2]) & (gzc <= bins[-1])]) try: gzc_68[:,-1] = err(gzc[(gzh > bins[-2]) & (gzh <= bins[-1])]) except: gzc_68[:,-1] = 0,0 try: gzh_68[:,-1] = err(gzh[(gzc > bins[-2]) & (gzc <= bins[-1])]) except: gzh_68[:,-1] = 0,0 hex1 = ax.hexbin(gzc,gzh,gridsize=50,cmap=plt.cm.gray_r,norm=LogNorm()) cb = plt.colorbar(hex1,ax=ax) #cb.set_label(r'$N$',fontsize=16) plotbins = bins[:-1] + db/2. ax.errorbar(gzc_avg,plotbins,xerr=gzc_68,color=blue,marker='o',ls='-',markersize=10) ax.errorbar(plotbins,gzh_avg,yerr=gzh_68,color=red,marker='o',ls='-',markersize=10) from scipy.stats.stats import pearsonr #print "Correlation {0}: {1:.2f}".format(p['label'],pearsonr(gzh,gzc)[0]) ax.set_xlim(-0.05,1.05) ax.set_ylim(-0.05,1.05) ax.set_xlabel(r'GZC {0} vote fraction'.format(p['label']),fontsize=16) ax.set_ylabel(r'GZH {0} vote fraction'.format(p['label']),fontsize=16)
def plotMultipleCuts(): area = '1' # read binary Pairs for corridor file1 = f'input/2018-08-himster2-misalign-200u/binaryPairFiles/pairs-30{area}-cm.bin' pairs1 = readBinaryFile(file1, '0') dHit1 = pairs1[:, 3:6] - pairs1[:, :3] Nbins = 150 Srasterized = True # plot difference hit array fig = plt.figure(figsize=(15 / 2.54, 5 / 2.54)) ax1 = fig.add_subplot(1, 4, 1) ax1.hist2d(dHit1[:, 0] * 10, dHit1[:, 1] * 10, bins=Nbins, norm=LogNorm(), rasterized=Srasterized) ax1.set_title('No Cut') ax1.yaxis.set_ticks_position('both') ax1.set_xlabel('dx [mm]') ax1.set_ylabel('dy [mm]') ax1.tick_params(direction='in') ax1.yaxis.set_label_position('left') ax1.set_xlim([-01.2, 01.2]) ax1.set_ylim([-01.2, 01.2]) pairs1 = dynamicCut(pairs1, 0.5) dHit1 = pairs1[:, 3:6] - pairs1[:, :3] ax2 = fig.add_subplot(1, 4, 2, sharey=ax1) ax2.hist2d(dHit1[:, 0] * 10, dHit1[:, 1] * 10, bins=Nbins, norm=LogNorm(), rasterized=Srasterized) ax2.set_title('0.5 \% Cut') ax2.yaxis.set_ticks_position('both') ax2.set_xlabel('dx [mm]') ax2.tick_params(direction='in') ax2.set_xlim([-01.2, 01.2]) ax2.set_ylim([-01.2, 01.2]) ax2.set_yticklabels([]) pairs1 = dynamicCut(pairs1, 1.0) dHit1 = pairs1[:, 3:6] - pairs1[:, :3] ax3 = fig.add_subplot(1, 4, 3, sharey=ax1) ax3.hist2d(dHit1[:, 0] * 10, dHit1[:, 1] * 10, bins=Nbins, norm=LogNorm(), rasterized=Srasterized) ax3.set_title('1.0 \% Cut') ax3.yaxis.set_ticks_position('both') ax3.set_xlabel('dx [mm]') ax3.tick_params(direction='in') ax3.set_xlim([-01.2, 01.2]) ax3.set_ylim([-01.2, 01.2]) ax3.set_yticklabels([]) pairs1 = dynamicCut(pairs1, 2.0) dHit1 = pairs1[:, 3:6] - pairs1[:, :3] ax4 = fig.add_subplot(1, 4, 4, sharey=ax1) ax4.hist2d(dHit1[:, 0] * 10, dHit1[:, 1] * 10, bins=Nbins, norm=LogNorm(), rasterized=Srasterized) ax4.set_title('2.0 \% Cut') ax4.yaxis.set_ticks_position('both') ax4.set_xlabel('dx [mm]') ax4.tick_params(direction='in') ax4.set_xlim([-01.2, 01.2]) ax4.set_ylim([-01.2, 01.2]) ax4.set_yticklabels([]) fig.tight_layout() fig.subplots_adjust(hspace=.001) fig.savefig('pairs-dxdy-cuts.pdf', dpi=300, bbox_inches='tight', pad_inches=0)
cmaplist[0] = (1.0, 1.0, 1.0, 1.0) # create the new map cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N) #Set Color For Values less than plot Bounds cmap.set_under('w') # Set up figure fig = plt.figure(figsize=(15, 5)) ### MLO ### ax1 = fig.add_subplot(411, ylabel='Altitude (km)', ylim=(16.5, 31)) MLO = ax1.pcolor(Dates_MLO, Alts_MLO, MLO_data_masked_array, norm=LogNorm(vmin=MLO_data_masked_array.min(), vmax=MLO_data_masked_array.max()), cmap=cmap) plt.grid() ax1.set_xlim([datetime.date(1991, 6, 1), datetime.date(1992, 2, 28)]) ax1.tick_params(axis='x', which='both', labelbottom='off') # Adds measurement dates as blue diamonds and the Mount Pinatubo eruption as a red triangle. plt.plot(Dates_MLO, np.ones((len(Dates_MLO), )) * 30.000, 'bd', markersize=1.5) plt.plot('1991-06-16', 16.800, 'r^', markersize=12) test = np.genfromtxt( '/nfs/see-fs-01_users/gy11s2s/Python/Layers_over_time_analysis/Lidar/' + 'all_layer_heights.txt') #test = np.genfromtxt('C:/Users/s_sha/Documents/PhD/Python/Layers_over_time_analysis/Lidar/' + 'all_layer_heights.txt') for i in range(test.shape[0]):
ax.hist(blw, bins=100, range=[0, 100], label='blw') ax.axvline(x=blw_cut, ymin=0, ymax=1, color='k') ax.set_yscale('log') ax.legend() ax = fig.add_subplot(222) ax.hist(rec['init'], bins=100, label='init', histtype='step') ax.hist(init, bins=100, label='init over height cut', histtype='step') ax.legend() ax = fig.add_subplot(223) ax.hist(rec['height'], bins=100, range=[0, 400], label='height', histtype='step') ax.hist(h, bins=100, range=[0, 400], label='the height', histtype='step') ax.axvline(x=height_cut, ymin=0, ymax=1, color='k') ax.legend() ax = fig.add_subplot(224) ax.hist2d(rec['init'], rec['height'], bins=[100, 100], range=[[0, 1000], [0, 600]], norm=LogNorm()) ax.axhline(y=height_cut, xmin=0, xmax=1, color='k') ax.legend() plt.show()
def patchMatrix(mat, xmap=None, ymap=None, ax=None, cMin=None, cMax=None, logScale=None, label=None, dx=1, **kwargs): """Plot previously generated (generateVecMatrix) matrix. Parameters ---------- mat : numpy.array2d matrix to show xmap : dict {i:num} dict (must match A.shape[0]) ymap : iterable vector for x axis (must match A.shape[0]) ax : mpl.axis axis to plot, if not given a new figure is created cMin/cMax : float minimum/maximum color values logScale : bool logarithmic colour scale [min(A)>0] label : string colorbar label dx : float width of the matrix elements (by default 1) """ mat = np.ma.masked_where(mat == 0.0, mat, False) if cMin is None: cMin = np.min(mat) if cMax is None: cMax = np.max(mat) if logScale is None: logScale = (cMin > 0.0) if logScale: norm = LogNorm(vmin=cMin, vmax=cMax) else: norm = Normalize(vmin=cMin, vmax=cMax) if 'ax' is None: ax = plt.subplots()[1] iy, ix = np.nonzero(mat) # != 0) recs = [] vals = [] for i, _ in enumerate(ix): recs.append(Rectangle((ix[i] - dx / 2, iy[i] - 0.5), dx, 1)) vals.append(mat[iy[i], ix[i]]) pp = PatchCollection(recs) col = ax.add_collection(pp) pp.set_edgecolor(None) pp.set_linewidths(0.0) if 'cmap' in kwargs: pp.set_cmap(kwargs.pop('cmap')) if 'cMap' in kwargs: pp.set_cmap(kwargs.pop('cMap')) pp.set_norm(norm) pp.set_array(np.array(vals)) pp.set_clim(cMin, cMax) xval = [k for k in xmap.keys()] ax.set_xlim(min(xval) - dx / 2, max(xval) + dx / 2) ax.set_ylim(len(ymap) + 0.5, -0.5) updateAxes_(ax) cbar = None if kwargs.pop('colorBar', True): ori = kwargs.pop('orientation', 'horizontal') cbar = pg.mplviewer.createColorBar(col, cMin=cMin, cMax=cMax, nLevs=5, label=label, orientation=ori) return ax, cbar
def patchValMap(vals, xvec=None, yvec=None, ax=None, cMin=None, cMax=None, logScale=None, label=None, dx=1, dy=None, cTrim=0, **kwargs): """Plot previously generated (generateVecMatrix) y map (category). Parameters ---------- vals : iterable Data values to show. xvec : dict {i:num} dict (must match vals.shape[0]) ymap : iterable vector for x axis (must match vals.shape[0]) ax : mpl.axis axis to plot, if not given a new figure is created cMin/cMax : float minimum/maximum color values cTrim : float [0] use trim value to exclude outer cTrim percent of data from color scale logScale : bool logarithmic colour scale [min(vals)>0] label : string colorbar label ** kwargs: * circular : bool Plot in polar coordinates. """ if cMin is None: cMin = np.min(vals) # cMin = np.nanquantile(vals, cTrim/100) if cMax is None: cMax = np.max(vals) # cMin = np.nanquantile(vals, 1-cTrim/100) if logScale is None: logScale = (cMin > 0.0) norm = None if logScale and cMin > 0: norm = LogNorm(vmin=cMin, vmax=cMax) else: norm = Normalize(vmin=cMin, vmax=cMax) if ax is None: ax = plt.subplots()[1] recs = [] circular = kwargs.pop('circular', False) if circular: recs = [None] * len(xvec) if dy is None: # map y values to unique ymap = {xy: ii for ii, xy in enumerate(np.unique(yvec))} xyMap = {} for i, y in enumerate(yvec): if y not in xyMap: xyMap[y] = [] xyMap[y].append(i) # maxR = max(ymap.values()) # what's that for? not used dR = 1 / (len(ymap.values()) + 1) # dOff = np.pi / 2 # what's that for? not used for y, xIds in xyMap.items(): r = 1. - dR * (ymap[y] + 1) # ax.plot(r * np.cos(xvec[xIds]), # r * np.sin(xvec[xIds]), 'o') # print(y, ymap[y]) for i in xIds: phi = xvec[i] # x = r * np.cos(phi) # what's that for? not used y = r * np.sin(phi) dPhi = (xvec[1] - xvec[0]) recs[i] = Wedge((0., 0.), r + dR / 1.5, (phi - dPhi) * 360 / (2 * np.pi), (phi + dPhi) * 360 / (2 * np.pi), width=dR, zorder=1 + r) # if i < 5: # ax.text(x, y, str(i)) # pg.wait() else: raise ("Implementme") else: if dy is None: # map y values to unique ymap = {xy: ii for ii, xy in enumerate(np.unique(yvec))} for i in range(len(vals)): recs.append( Rectangle((xvec[i] - dx / 2, ymap[yvec[i]] - 0.5), dx, 1)) else: for i in range(len(vals)): recs.append( Rectangle((xvec[i] - dx / 2, yvec[i] - dy / 2), dx, dy)) ax.set_xlim(min(xvec) - dx / 2, max(xvec) + dx / 2) ax.set_ylim(len(ymap) - 0.5, -0.5) pp = PatchCollection(recs) # ax.clear() col = ax.add_collection(pp) pp.set_edgecolor(None) pp.set_linewidths(0.0) if 'alpha' in kwargs: pp.set_alpha(kwargs['alpha']) if circular: pp.set_edgecolor('black') pp.set_linewidths(0.1) cmap = pg.mplviewer.cmapFromName(**kwargs) if kwargs.pop('markOutside', False): cmap.set_bad('grey') cmap.set_under('darkgrey') cmap.set_over('lightgrey') cmap.set_bad('black') pp.set_cmap(cmap) pp.set_norm(norm) pp.set_array(vals) pp.set_clim(cMin, cMax) updateAxes_(ax) cbar = kwargs.pop('colorBar', True) ori = kwargs.pop('orientation', 'horizontal') if cbar in ['horizontal', 'vertical']: ori = cbar cbar = True if cbar is True: # not for cbar=1, which is really confusing! cbar = pg.mplviewer.createColorBar(col, cMin=cMin, cMax=cMax, nLevs=5, label=label, orientation=ori) elif cbar is not False: # .. cbar is an already existing cbar .. so we update its values pg.mplviewer.updateColorBar(cbar, cMin=cMin, cMax=cMax, nLevs=5, label=label) updateAxes_(ax) return ax, cbar, ymap
def find_cut(ds, ds_lo, write_db=False): #Make tier2 dataframe, get e_ftp and first pass calibration constants, then calibrate t2 = ds.get_t2df() t2 = t2.reset_index(drop=True) calDB = ds.calDB query = db.Query() table = calDB.table("cal_pass1") vals = table.all() df_cal = pd.DataFrame(vals) # <<---- omg awesome df_cal = df_cal.loc[df_cal.ds==ds_lo] p1cal = df_cal.iloc[0]["p1cal"] cal = p1cal * np.asarray(t2["e_ftp"]) hist, bins = np.histogram(cal, bins=2000, range=[0,2000]) b = (bins[:-1] + bins[1:]) / 2 # np.savez('ds{}'.format(ds_lo), cal) # np.savez('bins_ds{}'.format(ds_lo), b) # plt.clf() plt.title('DS{}'.format(ds_lo)) plt.plot(b, hist, ls="steps", linewidth=1.5) plt.ylabel('Counts') plt.xlabel('keV') plt.tight_layout() plt.show() exit() current = "current_max" e_over_unc = cal / np.asarray(t2["e_ftp"]) y0 = np.asarray(t2[current]) a_over_e = y0 * e_over_unc / cal y = linear_correction(cal, a_over_e) # dep_range = [1530,1620] # hist, bins = np.histogram(cal, bins=450, range=dep_range) # hist = hist * 5 # def gauss(x, *params): y = np.zeros_like(x) for i in range(0, len(params) - 1, 3): x0 = params[i] a = params[i + 1] sigma = params[i + 2] y += a * np.exp(-(x - x0)**2 / (2 * sigma**2)) y = y + params[-1] return y # # p0_list = [1591, 200, 3, 4] # # par, pcov = curve_fit( # gauss, bins[1:], hist, p0=p0_list) # print(par) # perr = np.sqrt(np.diag(pcov)) # print(perr) # # mu, amp, sig, bkg = par[0], par[1], par[2], par[-1] # print("Scanning ", mu, " peak") # ans = quad(gauss, 1583, 1600, args=(mu, amp, sig, bkg)) # counts = ans[0] - ((1600-1583)*bkg) # print("Counts in ", mu, " peak is ", counts) # # cut = counts # line = .4 # # y1 = y[np.where(line < y)] # x1 = cal[np.where(line < y)] # # hist1, bins1 = np.histogram(x1, bins=500, range=[1500,1700]) # hist1, bins1 = np.histogram(x1, bins=450, range=[1530,1620]) # hist1 = hist1*5 # # print("Finding optimal cut, keeping 90% of 1592 DEP") # while cut > .9 * counts: # # y1 = y[np.where(line < y)] # x1 = cal[np.where(line < y)] # # hist1, bins1 = np.histogram(x1, bins=450, range=dep_range) # hist1 = hist1*5 # # par1, pcov1 = curve_fit( # gauss, bins1[1:], hist1, p0=p0_list) # perr1 = np.sqrt(np.diag(pcov1)) # # mu1, amp1, sig1, bkg1 = par1[0], par1[1], par1[2], par1[-1] # ans1 = quad(gauss, 1583, 1600, args=(mu1, amp1, sig1, bkg1)) # cut = ans1[0] - ((1600-1583)*bkg1) # # line += .0005 line = .95 y1 = y[np.where(line < y)] x1 = cal[np.where(line < y)] y2 = y[np.where(line > y)] x2 = cal[np.where(line > y)] np.savez('thorium', x1) np.savez('Ac', x2) # print(line, cut) plt.hist2d(cal, y, bins=[1000,200], range=[[0, 2000], [0, 2]], norm=LogNorm(), cmap='jet') plt.hlines(line, 0, 2000, color='r', linewidth=1.5) cbar = plt.colorbar() plt.title("Dataset {}".format(ds_lo)) plt.xlabel("Energy (keV)", ha='right', x=1) plt.ylabel("A/Eunc", ha='right', y=1) cbar.ax.set_ylabel('Counts') plt.tight_layout() plt.show() hist, bins = np.histogram(cal, bins=2000, range=[0,2000]) hist1, bins1 = np.histogram(x1, bins=2000, range=[0,2000]) hist2, bins2 = np.histogram(x2, bins=2000, range=[0,2000]) p0_list = [1593, 200, 3, 4] par, pcov = curve_fit( gauss, bins1[1:], hist1, p0=p0_list) print(par) perr = np.sqrt(np.diag(pcov)) print(perr) plt.clf() # plt.semilogy(bins[1:], hist, color='black', ls="steps", linewidth=1.5, label='Calibrated Energy: Dataset {}'.format(ds_lo)) plt.semilogy(bins1[1:], hist1, '-r', ls="steps", linewidth=1.5, label='AvsE Cut: Dataset {}'.format(ds_lo)) plt.ylabel('Counts') plt.xlabel('keV') plt.legend() plt.tight_layout() plt.show() plt.clf() plt.semilogy(bins2[1:], hist2, ls="steps", linewidth=1.5) plt.title('Ac spectra') plt.ylabel('Counts') plt.xlabel('keV') plt.tight_layout() plt.show() if write_db: table = calDB.table("A/E_cut") for dset in ds.ds_list: row = {"ds":dset, "line":line} table.upsert(row, query.ds == dset)
print('Visualizing J(theta0, theta1) ...') # 依照定义间隔生成均匀分布的数值 theta0_vals = np.linspace(start=-10, stop=10, num=100) theta1_vals = np.linspace(start=-1, stop=4, num=100) xs, ys = np.meshgrid(theta0_vals, theta1_vals) J_vals = np.zeros(xs.shape) # Fill out J_vals for i in range(0, theta0_vals.size): for j in range(0, theta1_vals.size): t = np.array([theta0_vals[i], theta1_vals[j]]) J_vals[i][j] = compute_cost(X, y, t) J_vals = np.transpose(J_vals) fig1 = plt.figure(2) ax = fig1.gca(projection='3d') ax.plot_surface(xs, ys, J_vals) plt.xlabel(r'$\theta_0$') plt.ylabel(r'$\theta_1$') plt.figure(3) # logspace 创建等比数列 lvls = np.logspace(start=-2, stop=3, num=20) plt.contour(xs, ys, J_vals, levels=lvls, norm=LogNorm()) plt.plot(theta[0], theta[1], c='r', marker="x") input('ex1 Finished. Press ENTER to exit')
A = A + A.T X = A.copy() ct = 0 f, ax = plt.subplots(2,nprint,sharey=True,figsize=(12,6)) for i in range(niter): Q, R = np.linalg.qr(X) X = R @ Q if i % niterprint == 0: I, J = np.where(np.abs(X) < 1e-13) Xtmp = X.copy() Xtmp[I,J] = 0.0 im = ax[0,ct].imshow(np.abs(Xtmp.real), cmap=plt.cm.winter, norm=LogNorm()) ax[0,ct].axis('off') if np.abs(Xtmp.imag).max() > 1e-13: im = ax[1,ct].imshow(np.abs(Xtmp.imag), cmap=plt.cm.winter, norm=LogNorm()) ax[1,ct].axis('off') ct += 1 f.colorbar(im, ax=ax.ravel().tolist(), shrink=0.95) # In[79]: Xtmp
def plot_contour(*opts, fxn_name, animate_gif=True, fig_size=None, save_f=True, f_name='v1', in_type=None): def init(): for line in lines: line.set_data([], []) return lines def animate(i): num1 = int(x2[i]) for lnum, (line, scat) in enumerate(zip(lines, scats)): if num1 < dp[lnum]: # print(i, dp[lnum]) line.set_data( xlist[lnum][:num1], ylist[lnum][:num1]) # set data for each line separately. scat.set_offsets([xlist[lnum][num1], ylist[lnum][num1]]) line.set_label(nn[lnum]) # set the label and draw the legend plt.legend(loc="upper left") return lines if fig_size == 'small': fig, ax = plt.subplots(figsize=(6, 4)) else: fig, ax = plt.subplots(figsize=(8.5, 6.8)) plt.tight_layout() data, minima, x_lims, y_lims = plot_fxn(fxn_name, 'contour') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_xlim(x_lims) ax.set_ylim(y_lims) ax.contour(*data, levels=np.logspace(-.5, 5, 35), norm=LogNorm(), cmap='viridis', alpha=0.7) #cmap=plt.cm.jet) ax.plot(*minima[0:2], 'x', markersize=12, mew=2, color='k') xlist, ylist, zlist, nn, dp = get_dlists(opts, in_type) n = len(xlist) # print(len(xlist)) if fxn_name == 'rosenbrock': if in_type == 'sdict': c = cm.rainbow_r(np.linspace(0, 1, n)) else: c = cm.jet(np.linspace(0, 1, n)) else: c = cm.rainbow(np.linspace(0, 1, n)) if animate_gif == False: for k in range(n): x_history = np.array(xlist[k]) y_history = np.array(ylist[k]) path = np.concatenate( (np.expand_dims(x_history, 1), np.expand_dims(y_history, 1)), axis=1).T ax.quiver(path[0, :-1], path[1, :-1], path[0, 1:] - path[0, :-1], path[1, 1:] - path[1, :-1], scale_units='xy', angles='xy', width=0.003, scale=1, color=c[k], label=nn[k]) plt.legend(loc="upper left") if save_f == True: plt.savefig('images/{}_path.png'.format(fxn_name)) else: line, = ax.plot([], [], lw=2) #, markersize=12) lines = [] scats = [] for index in range(n): l_obj = ax.plot([], [], lw=2, color=c[index])[0] lines.append(l_obj) s_obj = ax.scatter([], [], lw=2, color=c[index]) scats.append(s_obj) num_min = int(len(xlist[0]) / 50) # print(num_min) x2 = np.rint(np.linspace(0, len(xlist[1]), endpoint=False, num=200)) # fix this # print(x2) # x2 = np.arange(len(xlist[0])) # blit=True --> only re-draw the parts that have changed. scat = ax.scatter( [], []) # Set the dot at some arbitrary position initially anim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(x2), interval=1, blit=True) anim.save('images/{}_contour_{}.gif'.format(fxn_name, f_name), dpi=60, writer="imagemagick") plt.show()
""" Launch the stream and the original spectrogram """ stream, pa = mic_read.open_mic() data = get_sample(stream, pa) arr2D, freqs, bins = get_specgram(data, rate) """ Setup the plot paramters """ extent = (bins[0], bins[-1] * SAMPLES_PER_FRAME, freqs[-1], freqs[0]) im = plt.imshow(arr2D, aspect='auto', extent=extent, interpolation="none", cmap='jet', norm=LogNorm(vmin=.01, vmax=1)) plt.xlabel('Time (s)') plt.ylabel('Frequency (Hz)') plt.title('Real Time Spectogram') plt.gca().invert_yaxis() ##plt.colorbar() #enable if you want to display a color bar ############### Animate ############### anim = animation.FuncAnimation(fig, update_fig, blit=False, interval=mic_read.CHUNK_SIZE / 1000) try: plt.show() except: print("Plot Closed")
def plot_single_heatmap_general(self, heatmap_metric_specification, heatmap_axes_specification): # data extraction output_path, filename = self._construct_output_path_and_filename( heatmap_metric_specification, heatmap_axes_specification) logger.debug("output_path is {};\t filename is {}".format( output_path, filename)) if not self.overwrite_existing_files and os.path.exists(filename): logger.info( "Skipping generation of {} as this file already exists".format( filename)) return xaxis_parameters = self.extract_parameter_values( heatmap_axes_specification['x_axis_parameter']) yaxis_parameters = self.extract_parameter_values( heatmap_axes_specification['y_axis_parameter']) # all heatmap values will be stored in X X = np.zeros((len(yaxis_parameters), len(xaxis_parameters))) fig, ax = plt.subplots(figsize=(FIGSIZE[0] - 0.75, FIGSIZE[1])) min_number_of_observed_values = 10000000000000 max_number_of_observed_values = 0 observed_values = np.empty(0) for x_index, x_val in enumerate(xaxis_parameters): # all scenario indices which has x_val as xaxis parameter (e.g. node_resource_factor = 0.5 sub_dict = self.data_dict[x_val] for y_index, y_val in enumerate(yaxis_parameters): results = self.data_dict[x_val][y_val] values = [ heatmap_metric_specification['lookup_function'](result) for result in results ] if 'metric_filter' in heatmap_metric_specification: values = [ value for value in values if heatmap_metric_specification['metric_filter'](value) ] observed_values = np.append(observed_values, values) if len(values) < min_number_of_observed_values: min_number_of_observed_values = len(values) if len(values) > max_number_of_observed_values: max_number_of_observed_values = len(values) logger.debug("values are {}".format(values)) if heatmap_metric_specification[ "plot_type"] == HeatmapPlotType.Simple_Treewidth_Evaluation_Max: m = np.max(values) logger.debug("max is {}".format(m)) elif heatmap_metric_specification[ "plot_type"] == HeatmapPlotType.Simple_Treewidth_Evaluation_Average: m = np.mean(values) logger.debug("mean is {}".format(m)) else: raise ValueError("Invalid HeatmapPlotType") if 'rounding_function' in heatmap_metric_specification: rounded_m = heatmap_metric_specification[ 'rounding_function'](m) else: rounded_m = float("{0:.1f}".format(round(m, 2))) X[y_index, x_index] = rounded_m if not self.paper_mode: if min_number_of_observed_values == max_number_of_observed_values: solution_count_string = "{} values per square".format( min_number_of_observed_values) else: solution_count_string = "between {} and {} values per square".format( min_number_of_observed_values, max_number_of_observed_values) ax.tick_params(axis="both", **HEATMAP_MAJOR_TICK_PARAMS) if self.paper_mode: ax.set_title(heatmap_metric_specification['name'], fontsize=PLOT_TITLE_FONT_SIZE) else: title = heatmap_metric_specification['name'] + "\n" title += solution_count_string + "\n" title += "min: {:.2f}; mean: {:.2f}; max: {:.2f}".format( np.nanmin(observed_values), np.nanmean(observed_values), np.nanmax(observed_values)) ax.set_title(title) norm = LogNorm(vmin=X[X > 0].min(), vmax=X.max()) heatmap = ax.pcolor( X, cmap=heatmap_metric_specification['cmap'], vmin=heatmap_metric_specification['vmin'], vmax=heatmap_metric_specification['vmax'], norm=norm, ) if not self.paper_mode: fig.colorbar(heatmap, label=heatmap_metric_specification['name'] + ' - mean in blue') else: cbar = fig.colorbar(heatmap) if 'colorbar_ticks' in heatmap_metric_specification: ticks = heatmap_metric_specification['colorbar_ticks'] tick_labels = [str(tick).ljust(3) for tick in ticks] cbar.set_ticks(ticks) cbar.set_ticklabels(tick_labels) cbar.ax.tick_params(labelsize=TICK_LABEL_FONT_SIZE) else: print "No colorbar tick labels were specified for {}".format( heatmap_metric_specification["name"]) # for label in cbar.ax.get_yticklabels(): # label.set_fontproperties(font_manager.FontProperties(family="Courier New",weight='bold')) cbar.ax.tick_params(**HEATMAP_COLORBAR_TICK_PARAMS) if "x_axis_ticks" in heatmap_axes_specification: tick_locations = [ xaxis_parameters.index(x) for x in heatmap_axes_specification["x_axis_ticks"] ] tick_locations = np.array(tick_locations) + 0.5 ax.set_xticks(tick_locations, minor=False) tick_locations_minor = [ xaxis_parameters.index(x) for x in heatmap_axes_specification["x_axis_ticks_minor"] ] ax.set_xticks(tick_locations_minor, minor=True) x_labels = map( heatmap_axes_specification["x_axis_tick_formatting"], heatmap_axes_specification["x_axis_ticks"]) ax.set_xticklabels(x_labels, minor=False, fontsize=TICK_LABEL_FONT_SIZE) else: ax.set_xticks(np.arange(X.shape[1]) + 0.5, minor=False) if "y_axis_ticks" in heatmap_axes_specification: tick_locations = [ yaxis_parameters.index(x) for x in heatmap_axes_specification["y_axis_ticks"] ] tick_locations = np.array(tick_locations) + 0.5 ax.set_yticks(tick_locations, minor=False) tick_locations_minor = [ yaxis_parameters.index(x) for x in heatmap_axes_specification["y_axis_ticks_minor"] ] ax.set_yticks(tick_locations_minor, minor=True) y_labels = map( heatmap_axes_specification["y_axis_tick_formatting"], heatmap_axes_specification["y_axis_ticks"]) ax.set_yticklabels(y_labels, minor=False, fontsize=TICK_LABEL_FONT_SIZE) else: ax.set_yticks(np.arange(X.shape[0]) + 0.5, minor=False) # column_labels = yaxis_parameters ax.set_xlabel(heatmap_axes_specification['x_axis_title'], fontsize=X_AXIS_LABEL_FONT_SIZE) ax.set_ylabel(heatmap_axes_specification['y_axis_title'], fontsize=Y_AXIS_LABEL_FONT_SIZE) # ax.set_yticklabels(column_labels, minor=False, fontsize=Y_AXIS_TICK_LABEL_FONT_SIZE) self._show_and_or_save_plots(output_path, filename)
def plot_opacities( tag: str, radtrans: read_radtrans.ReadRadtrans, offset: Optional[Tuple[float, float]] = None, output: Optional[str] = "opacities.pdf", ) -> None: """ Function to plot the line and continuum opacity structure from the median posterior samples. Parameters ---------- tag : str Database tag with the posterior samples. radtrans : read_radtrans.ReadRadtrans Instance of :class:`~species.read.read_radtrans.ReadRadtrans`. The parameter is not used if set to ``None``. offset : tuple(float, float), None Offset of the x- and y-axis label. Default values are used if set to ``None``. output : str, None Output filename for the plot. The plot is shown in an interface window if the argument is set to ``None``. Returns ------- NoneType None """ if output is None: print("Plotting opacities...", end="", flush=True) else: print(f"Plotting opacities: {output}...", end="", flush=True) species_db = database.Database() box = species_db.get_samples(tag) median = box.median_sample mpl.rcParams["font.serif"] = ["Bitstream Vera Serif"] mpl.rcParams["font.family"] = "serif" plt.rc("axes", edgecolor="black", linewidth=2.5) plt.figure(1, figsize=(10.0, 6.0)) gridsp = mpl.gridspec.GridSpec(2, 5, width_ratios=[4, 0.25, 1.5, 4, 0.25]) gridsp.update(wspace=0.1, hspace=0.1, left=0, right=1, bottom=0, top=1) ax1 = plt.subplot(gridsp[0, 0]) ax2 = plt.subplot(gridsp[1, 0]) ax3 = plt.subplot(gridsp[0, 1]) ax4 = plt.subplot(gridsp[1, 1]) ax5 = plt.subplot(gridsp[0, 3]) ax6 = plt.subplot(gridsp[1, 3]) ax7 = plt.subplot(gridsp[0, 4]) ax8 = plt.subplot(gridsp[1, 4]) radtrans.get_model(median) # Line opacities wavelength, opacity = radtrans.rt_object.get_opa(radtrans.rt_object.temp) wavelength *= 1e4 # (um) opacity_line = np.zeros( (radtrans.rt_object.freq.shape[0], radtrans.rt_object.press.shape[0]) ) for item in opacity.values(): opacity_line += item # Continuum opacities opacity_cont_abs = radtrans.rt_object.continuum_opa opacity_cont_scat = radtrans.rt_object.continuum_opa_scat # opacity_cont_scat = radtrans.rt_object.continuum_opa_scat_emis opacity_total = opacity_line + opacity_cont_abs + opacity_cont_scat albedo = opacity_cont_scat / opacity_total # if radtrans.scattering: # opacity_cont = radtrans.rt_object.continuum_opa_scat_emis # else: # opacity_cont = radtrans.rt_object.continuum_opa_scat ax1.tick_params( axis="both", which="major", colors="black", labelcolor="black", direction="in", width=1, length=5, labelsize=12, top=True, bottom=True, left=True, right=True, labelbottom=False, ) ax1.tick_params( axis="both", which="minor", colors="black", labelcolor="black", direction="in", width=1, length=3, labelsize=12, top=True, bottom=True, left=True, right=True, labelbottom=False, ) ax2.tick_params( axis="both", which="major", colors="black", labelcolor="black", direction="in", width=1, length=5, labelsize=12, top=True, bottom=True, left=True, right=True, ) ax2.tick_params( axis="both", which="minor", colors="black", labelcolor="black", direction="in", width=1, length=3, labelsize=12, top=True, bottom=True, left=True, right=True, ) ax3.tick_params( axis="both", which="major", colors="black", labelcolor="black", direction="in", width=1, length=5, labelsize=12, top=True, bottom=True, left=True, right=True, ) ax3.tick_params( axis="both", which="minor", colors="black", labelcolor="black", direction="in", width=1, length=3, labelsize=12, top=True, bottom=True, left=True, right=True, ) ax4.tick_params( axis="both", which="major", colors="black", labelcolor="black", direction="in", width=1, length=5, labelsize=12, top=True, bottom=True, left=True, right=True, ) ax4.tick_params( axis="both", which="minor", colors="black", labelcolor="black", direction="in", width=1, length=3, labelsize=12, top=True, bottom=True, left=True, right=True, ) ax5.tick_params( axis="both", which="major", colors="black", labelcolor="black", direction="in", width=1, length=5, labelsize=12, top=True, bottom=True, left=True, right=True, labelbottom=False, ) ax5.tick_params( axis="both", which="minor", colors="black", labelcolor="black", direction="in", width=1, length=3, labelsize=12, top=True, bottom=True, left=True, right=True, labelbottom=False, ) ax6.tick_params( axis="both", which="major", colors="black", labelcolor="black", direction="in", width=1, length=5, labelsize=12, top=True, bottom=True, left=True, right=True, ) ax6.tick_params( axis="both", which="minor", colors="black", labelcolor="black", direction="in", width=1, length=3, labelsize=12, top=True, bottom=True, left=True, right=True, ) ax7.tick_params( axis="both", which="major", colors="black", labelcolor="black", direction="in", width=1, length=5, labelsize=12, top=True, bottom=True, left=True, right=True, ) ax7.tick_params( axis="both", which="minor", colors="black", labelcolor="black", direction="in", width=1, length=3, labelsize=12, top=True, bottom=True, left=True, right=True, ) ax8.tick_params( axis="both", which="major", colors="black", labelcolor="black", direction="in", width=1, length=5, labelsize=12, top=True, bottom=True, left=True, right=True, ) ax8.tick_params( axis="both", which="minor", colors="black", labelcolor="black", direction="in", width=1, length=3, labelsize=12, top=True, bottom=True, left=True, right=True, ) ax1.xaxis.set_major_locator(MultipleLocator(1.0)) ax2.xaxis.set_major_locator(MultipleLocator(1.0)) ax1.xaxis.set_minor_locator(MultipleLocator(0.2)) ax2.xaxis.set_minor_locator(MultipleLocator(0.2)) ax5.xaxis.set_major_locator(MultipleLocator(1.0)) ax6.xaxis.set_major_locator(MultipleLocator(1.0)) ax5.xaxis.set_minor_locator(MultipleLocator(0.2)) ax6.xaxis.set_minor_locator(MultipleLocator(0.2)) # ax1.yaxis.set_major_locator(LogLocator(base=10.)) # ax2.yaxis.set_major_locator(LogLocator(base=10.)) # ax3.yaxis.set_major_locator(LogLocator(base=10.)) # ax4.yaxis.set_major_locator(LogLocator(base=10.)) # ax1.yaxis.set_minor_locator(LogLocator(base=1.)) # ax2.yaxis.set_minor_locator(LogLocator(base=1.)) # ax3.yaxis.set_minor_locator(LogLocator(base=1.)) # ax4.yaxis.set_minor_locator(LogLocator(base=1.)) xx_grid, yy_grid = np.meshgrid(wavelength, 1e-6 * radtrans.rt_object.press) fig = ax1.pcolormesh( xx_grid, yy_grid, np.transpose(opacity_line), cmap="viridis", shading="gouraud", norm=LogNorm(vmin=1e-6 * np.amax(opacity_line), vmax=np.amax(opacity_line)), ) cb = Colorbar(ax=ax3, mappable=fig, orientation="vertical", ticklocation="right") cb.ax.set_ylabel("Line opacity (cm$^2$/g)", rotation=270, labelpad=20, fontsize=11) fig = ax2.pcolormesh( xx_grid, yy_grid, np.transpose(albedo), cmap="viridis", shading="gouraud", norm=LogNorm(vmin=1e-4*np.amax(albedo), vmax=np.amax(albedo)), ) cb = Colorbar(ax=ax4, mappable=fig, orientation="vertical", ticklocation="right") cb.ax.set_ylabel( "Single scattering albedo", rotation=270, labelpad=20, fontsize=11 ) fig = ax5.pcolormesh( xx_grid, yy_grid, np.transpose(opacity_cont_abs), cmap="viridis", shading="gouraud", norm=LogNorm( vmin=1e-6 * np.amax(opacity_cont_abs), vmax=np.amax(opacity_cont_abs) ), ) cb = Colorbar(ax=ax7, mappable=fig, orientation="vertical", ticklocation="right") cb.ax.set_ylabel( "Continuum absorption (cm$^2$/g)", rotation=270, labelpad=20, fontsize=11 ) fig = ax6.pcolormesh( xx_grid, yy_grid, np.transpose(opacity_cont_scat), cmap="viridis", shading="gouraud", norm=LogNorm( vmin=1e-6 * np.amax(opacity_cont_scat), vmax=np.amax(opacity_cont_scat) ), ) cb = Colorbar(ax=ax8, mappable=fig, orientation="vertical", ticklocation="right") cb.ax.set_ylabel( "Continuum scattering (cm$^2$/g)", rotation=270, labelpad=20, fontsize=11 ) ax1.set_ylabel("Pressure (bar)", fontsize=13) ax2.set_xlabel("Wavelength (µm)", fontsize=13) ax2.set_ylabel("Pressure (bar)", fontsize=13) ax5.set_ylabel("Pressure (bar)", fontsize=13) ax6.set_xlabel("Wavelength (µm)", fontsize=13) ax6.set_ylabel("Pressure (bar)", fontsize=13) ax1.set_xlim(wavelength[0], wavelength[-1]) ax2.set_xlim(wavelength[0], wavelength[-1]) ax5.set_xlim(wavelength[0], wavelength[-1]) ax6.set_xlim(wavelength[0], wavelength[-1]) ax1.set_ylim( radtrans.rt_object.press[-1] * 1e-6, radtrans.rt_object.press[0] * 1e-6 ) ax2.set_ylim( radtrans.rt_object.press[-1] * 1e-6, radtrans.rt_object.press[0] * 1e-6 ) ax5.set_ylim( radtrans.rt_object.press[-1] * 1e-6, radtrans.rt_object.press[0] * 1e-6 ) ax6.set_ylim( radtrans.rt_object.press[-1] * 1e-6, radtrans.rt_object.press[0] * 1e-6 ) if offset is not None: ax1.get_xaxis().set_label_coords(0.5, offset[0]) ax1.get_yaxis().set_label_coords(offset[1], 0.5) ax2.get_xaxis().set_label_coords(0.5, offset[0]) ax2.get_yaxis().set_label_coords(offset[1], 0.5) ax5.get_xaxis().set_label_coords(0.5, offset[0]) ax5.get_yaxis().set_label_coords(offset[1], 0.5) ax6.get_xaxis().set_label_coords(0.5, offset[0]) ax6.get_yaxis().set_label_coords(offset[1], 0.5) else: ax1.get_xaxis().set_label_coords(0.5, -0.1) ax1.get_yaxis().set_label_coords(-0.14, 0.5) ax2.get_xaxis().set_label_coords(0.5, -0.1) ax2.get_yaxis().set_label_coords(-0.14, 0.5) ax5.get_xaxis().set_label_coords(0.5, -0.1) ax5.get_yaxis().set_label_coords(-0.14, 0.5) ax6.get_xaxis().set_label_coords(0.5, -0.1) ax6.get_yaxis().set_label_coords(-0.14, 0.5) ax1.set_yscale("log") ax2.set_yscale("log") ax3.set_yscale("log") ax4.set_yscale("log") ax5.set_yscale("log") ax6.set_yscale("log") ax7.set_yscale("log") ax8.set_yscale("log") print(" [DONE]") if output is None: plt.show() else: plt.savefig(output, bbox_inches="tight") plt.clf() plt.close()
def plot_planes(cpx_seq, title=None, logZ=[False], use_axis=True, vlim=[None, None], subplt_cols=3, dx=None, first=False): """ view plot of intensity in each wavelength bin at a single (last) timestep will pull out the plane(s) of sp.save_list at last tstep of cpx_sequence, convert to intensity, and sum over wavelength and object Currently, the atmosphere and enterance pupil are plotted in units of phase vs intensity. I think we should change this later for user-specification :param cpx_seq: :param title: string, must be set or will error! :param logZ: turn logscale plotting for z-axis on or off :param use_axis: turn on/off using axis ticks, colorbar, etc :param vlim: tuple of colorbar axis limits (min,max) :param subplt_cols: number of subplots per row :param dx: sampling of the image at each saved plane :return: """ # Create figure & adjust subplot number, layout, size, whitespace fig = plt.figure() n_planes = len(sp.save_list) n_rows = int(np.ceil(n_planes / float(subplt_cols))) plt.axis('off') gs = gridspec.GridSpec(n_rows, subplt_cols, wspace=0.08) # Main Title if title is None: warnings.warn("Plots without titles: Don't Do It!") title = input("Please Enter Title: ") pass fig.suptitle(title, fontweight='bold', fontsize=16) # Small Hack to repeat axis if defaults used np.array(vlim) if len(logZ) == 1: logZ = np.repeat(logZ, len(sp.save_list)) if len(vlim) == 2: vlim = [ vlim, ] * len(sp.save_list) # Select first or last plane to plot (useful if CDI probes are being applied) if not first: f = -1 else: f = 0 # select first or last timestep for p in range(n_planes): ax = fig.add_subplot(gs[p]) ################### # Retreiving Data ################## # Standard-Way # [timestep, plane, wavelength, object, x, y] # converts to intensity of last timestep, THEN sums over wavelength, then sums over object plot_plane = sp.save_list[p] plane = opx.extract_plane(cpx_seq, plot_plane) # Distinguish plotting z-axis in phase units or intensity units if plot_plane == "atmosphere" or plot_plane == "entrance_pupil": plane = np.sum(np.angle(plane[f]), axis=(0, 1)) plane = opx.extract_center(plane, new_size=sp.grid_size * sp.beam_ratio + 6) logZ[p] = False vlim[p] = [None, None] phs = " phase" elif plot_plane == "woofer" or plot_plane == "tweeter" or plot_plane == "DM": # only show the star phase map since phase at other bodies just offsets to shift focal plane position plane = np.sum(np.angle(plane[f]), axis=(0)) # only sum over object plane = plane[0] # plot the shortest wavelength plane = opx.extract_center(plane, new_size=sp.grid_size * sp.beam_ratio + 6) # zoom in on DM logZ[p] = False vlim[p] = [-np.pi, np.pi] phs = ' phase' elif plot_plane == "SubaruPupil": plane = np.sum(opx.cpx_to_intensity(plane[f]), axis=(0, 1)) plane = opx.extract_center(plane, new_size=sp.grid_size * sp.beam_ratio + 6) phs = '' else: plane = np.sum(opx.cpx_to_intensity(plane[f]), axis=(0, 1)) phs = '' ### Retreiving Data- Custom selection of plane ### # plot_plane = sp.save_list[w] # plane = opx.extract_plane(cpx_seq, plot_plane) # # plane = opx.cpx_to_intensity(plane[-1]) # plane = opx.extract_center(np.angle(plane[0,1,1])) # wavelengths, objects # X,Y lables if dx is not None: # Converting Sampling Units to Readable numbers if dx[p, 0] < 1e-5: # dx[p, :] *= 1e6 # [convert to um] # axlabel = 'um' tic_spacing, tic_labels, axlabel = scale_lD( dx[p, :], tp.fn_fp, size=plane.shape[0] ) # Assumes that this is the focal plane! else: if dx[p, 0] < 1e-3: dx[p, :] *= 1e3 # [convert to mm] axlabel = 'mm' elif 1e-2 > dx[p, 0] > 1e-3: dx[p, :] *= 1e2 # [convert to cm] axlabel = 'cm' else: axlabel = 'm' tic_spacing = np.linspace( 0, plane.shape[0], 5 ) # 5 (# of ticks) is just set by hand, arbitrarily chosen tic_labels = np.round( np.linspace(-dx[p, 0] * plane.shape[0] / 2, dx[p, 0] * plane.shape[0] / 2, 5)).astype( int) # nsteps must be same as tic_spacing tic_spacing[0] = tic_spacing[0] + 1 # hack for edge effects tic_spacing[-1] = tic_spacing[-1] - 1 # hack for edge effects plt.xticks(tic_spacing, tic_labels, fontsize=6) plt.yticks(tic_spacing, tic_labels, fontsize=6) plt.ylabel(axlabel, fontsize=8) # Z-axis scale if phs == ' phase': cmap = sunlight else: cmap = "YlGnBu_r" ax.set_title(f"{sp.save_list[p]}" + phs) if logZ[p]: if vlim[p][0] is not None and vlim[p][0] <= 0: im = ax.imshow(plane, interpolation='none', origin='lower', vmin=vlim[p][0], vmax=vlim[p][1], norm=SymLogNorm(linthresh=1e-5), cmap=cmap) add_colorbar(im) # clabel = "Log Normalized Intensity" else: im = ax.imshow(plane, interpolation='none', origin='lower', vmin=vlim[p][0], vmax=vlim[p][1], norm=LogNorm(), cmap=cmap) #(1e-6,1e-3) add_colorbar(im) # clabel = "Log Normalized Intensity" # cb.set_label(clabel) else: im = ax.imshow(plane, interpolation='none', origin='lower', vmin=vlim[p][0], vmax=vlim[p][1], cmap=cmap) # "twilight" add_colorbar(im) # clabel = "Normalized Intensity" # cb.set_label(clabel) if use_axis: warnings.simplefilter("ignore", category=UserWarning) gs.tight_layout(fig, pad=1.08, rect=(0, 0.02, 1, 0.9)) # rect = (left, bottom, right, top)
alpha[np.isnan(alpha)] = 0.0 np.clip(alpha, a_min=0.0, a_max=1.0, out=alpha) Rd = convolve(R, kernel) Bd = convolve(B, kernel) Gd = convolve(G, kernel) A = convolve(alpha, kernel) rgb = np.transpose(np.array([Rd, Gd, Bd]), axes=(1, 2, 0)).astype("float32") rgb *= alpha[:, :, np.newaxis] cmap = plt.cm.viridis cmap.set_bad(color="black") fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(20, 10)) ax1.imshow(cts, origin='lower', norm=LogNorm(), cmap=cmap) ax2.imshow(rgb, origin='lower') fig.savefig("%s_%sdeg.png" % (basenm, angle)) hdur = fits.ImageHDU(data=Rd * A) hdur.name = "red" hdur.writeto("%s_red_%sdeg.fits" % (basenm, angle), overwrite=True) hdub = fits.ImageHDU(data=Bd * A) hdub.name = "blue" hdub.writeto("%s_blue_%sdeg.fits" % (basenm, angle), overwrite=True) hdug = fits.ImageHDU(data=Gd * A) hdug.name = "green" hdug.writeto("%s_green_%sdeg.fits" % (basenm, angle), overwrite=True) fits.ImageHDU(data=rgb).writeto("%s_rgb_%sdeg.fits" % (basenm, angle), overwrite=True)
ncols = len(ray_list) else: nrows = 2 ncols = int(len(ray_list) / nrows) fig, axes, colorbars = get_multi_plot(ncols, nrows, colorbar=None, bw=4) for i, ray_id in enumerate(ray_list): row = int(i / ncols) col = i - ncols * row print(row, col) img_data = np.array(frb['ray_%i_%s' % (ray_id, field[1])]) # img_data = ipd.crop_imshow(img_data, data_min, data_max, data_min, data_max) ax = axes[row][col] # note: the extent call makes the units of the plot 0 to 1200 (physical) instead of 0 to 1600 (number of pixels) print(img_data.min(), img_data.max()) im = ax.imshow(img_data, origin = 'lower', norm = LogNorm(),vmin = zlims[0], vmax = zlims[1], \ extent = [rmin, rmax, rmin, rmax], zorder = 1) ax.scatter(600, 600, marker='+', s=200, c='white', zorder=10) im.set_cmap(cmap) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) if i == 0: cbax = inset_axes(ax, width="90%", height="3%", loc=9) cbar = fig.colorbar(im, cax=cbax, orientation='horizontal') cbar.set_label(cbar_title, color='white') ax.axhline(rmin + 0.1 * img_width, rmax - 200, rmax - 100, zorder=10) ax.annotate('', xy = (1000, 100),xycoords = 'data', xytext=(1100, 100), textcoords='data', \ arrowprops=dict(arrowstyle="-", connectionstyle = "arc3", linewidth = 3, edgecolor = "white", facecolor = "white")) ax.annotate('100 kpc', xy=(970, 130))
def showStitchedModels_Redundant(mods, ax=None, cmin=None, cmax=None, **kwargs): """Show several 1d block models as (stitched) section.""" x = kwargs.pop('x', np.arange(len(mods))) topo = kwargs.pop('topo', x * 0) nlay = int(np.floor((len(mods[0]) - 1) / 2.)) + 1 if cmin is None or cmax is None: cmin = 1e9 cmax = 1e-9 for model in mods: res = np.asarray(model)[nlay - 1:nlay * 2 - 1] cmin = min(cmin, min(res)) cmax = max(cmax, max(res)) if kwargs.pop('sameSize', True): # all having the same width dx = np.ones_like(x) * np.median(np.diff(x)) else: dx = np.diff(x) * 1.05 dx = np.hstack((dx, dx[-1])) x1 = x - dx / 2 if ax is None: fig, ax = plt.subplots() else: ax = ax fig = ax.figure # ax.plot(x, x * 0., 'k.') zm = kwargs.pop('zm', None) maxz = 0. if zm is not None: maxz = zm recs = [] RES = [] for i, mod in enumerate(mods): mod1 = np.asarray(mod) res = mod1[nlay - 1:] RES.extend(res) thk = mod1[:nlay - 1] thk = np.hstack((thk, thk[-1])) z = np.hstack((0., np.cumsum(thk))) if zm is not None: thk[-1] = zm - z[-2] z[-1] = zm else: maxz = max(maxz, z[-1]) for j, _ in enumerate(thk): recs.append(Rectangle((x1[i], topo[i] - z[j]), dx[i], -thk[j])) pp = PatchCollection(recs, edgecolors=kwargs.pop('edgecolors', 'none')) pp.set_edgecolor(kwargs.pop('edgecolors', 'none')) pp.set_linewidths(0.0) ax.add_collection(pp) if 'cmap' in kwargs: pp.set_cmap(kwargs['cmap']) print(cmin, cmax) norm = LogNorm(cmin, cmax) pp.set_norm(norm) pp.set_array(np.array(RES)) # pp.set_clim(cmin, cmax) ax.set_ylim((-maxz, max(topo))) ax.set_xlim((x1[0], x1[-1] + dx[-1])) cbar = None if kwargs.pop('colorBar', True): cbar = plt.colorbar(pp, ax=ax, norm=norm, orientation='horizontal', aspect=60) # , ticks=[1, 3, 10, 30, 100, 300]) if 'ticks' in kwargs: cbar.set_ticks(kwargs['ticks']) # cbar.autoscale_None() if ax is None: # newly created fig+ax return fig, ax else: # already given, better give back color bar return cbar
def plotMatrix(mat, xmap=None, ymap=None, ax=None, cMin=None, cMax=None, logScale=None, label=None, **kwargs): """Plot previously generated (generateVecMatrix) matrix. Parameters ---------- mat : numpy.array2d matrix to show xmap : dict {i:num} dict (must match A.shape[0]) ymap : iterable vector for x axis (must match A.shape[0]) ax : mpl.axis axis to plot, if not given a new figure is created cMin/cMax : float minimum/maximum color values logScale : bool logarithmic colour scale [min(A)>0] label : string colorbar label Returns ------- ax : matplotlib axes object axes object cb : matplotlib colorbar colorbar object """ if xmap is None: xmap = {i: i for i in range(mat.shape[0])} if ymap is None: ymap = {i: i for i in range(mat.shape[1])} if isinstance(mat, np.ma.MaskedArray): mat_ = mat else: mat_ = np.ma.masked_where(mat == 0.0, mat, False) if cMin is None: cMin = np.min(mat_) if cMax is None: cMax = np.max(mat_) if logScale is None: logScale = (cMin > 0.0) if logScale: norm = LogNorm(vmin=cMin, vmax=cMax) else: norm = Normalize(vmin=cMin, vmax=cMax) if ax is None: ax = plt.subplots()[1] im = ax.imshow(mat_, norm=norm, interpolation='nearest') if 'cmap' in kwargs: im.set_cmap(kwargs.pop('cmap')) if 'cMap' in kwargs: im.set_cmap(kwargs.pop('cMap')) ax.set_aspect(kwargs.pop('aspect', 1)) cbar = None if kwargs.pop('colorBar', True): ori = kwargs.pop('orientation', 'horizontal') cbar = pg.mplviewer.createColorBar(im, cMin=cMin, cMax=cMax, nLevs=5, label=label, orientation=ori) ax.grid(True) xt = np.unique(ax.get_xticks().clip(0, len(xmap) - 1)) yt = np.unique(ax.get_xticks().clip(0, len(ymap) - 1)) if kwargs.pop('showally', False): yt = np.arange(len(ymap)) else: yt = np.round(np.linspace(0, len(ymap) - 1, 5)) xx = np.sort([k for k in xmap]) ax.set_xticks(xt) ax.set_xticklabels(['{:g}'.format(round(xx[int(ti)], 2)) for ti in xt]) yy = np.unique([k for k in ymap]) ax.set_yticks(yt) ax.set_yticklabels(['{:g}'.format(round(yy[int(ti)], 2)) for ti in yt]) return ax, cbar
det = condor.Detector(distance=2., pixel_size=110E-6*ds, nx=1024/ds+1, ny=1024/ds+1, solid_angle_correction=False) psphere = {"particle_sphere": condor.ParticleSphere(diameter=1E-9, material_type="water")} pmap = {"particle_map": condor.ParticleMap(diameter=1E-9, material_type="water", geometry="icosahedron")} patoms = {"particle_atoms": condor.ParticleAtoms(pdb_filename="%s/../../DNA.pdb" % this_dir)} particles = [psphere, pmap, patoms] if do_plot: fig, (axs1, axs2) = pyplot.subplots(2, len(particles), figsize=(3*len(particles), 3*2)) for i,par in enumerate(particles): E = condor.Experiment(src, par, det) res = E.propagate() data = res["entry_1"]["data_1"]["data"] if do_plot: axs1[i].set_title("2D: " + par.keys()[0]) lims = (data.min(), data.max()) axs1[i].imshow(data, norm=LogNorm(lims[0], lims[1]), cmap="gnuplot") res = E.propagate3d() data = res["entry_1"]["data_1"]["data"][int(1024/ds/2),:,:] if do_plot: axs2[i].set_title("3D slice: " + par.keys()[0]) axs2[i].imshow(data, norm=LogNorm(lims[0], lims[1]), cmap="gnuplot") if do_plot: fig.savefig("2Dvs3D.png", dpi=300) pyplot.show()
# circle.set_zorder(9) # ax2.add_artist(circle) IDX = 0 sigma = sigma[..., IDX, IDX][None, ...] if len(sigma.shape) == 4 else sigma[..., IDX][None, ...] mu = mu[..., IDX][None, ...] prior = prior[None, ...] Y = np.linspace(y_train.min() * 1.5, y_train.max()*1.5, 300)[::-1, None, None] var = 2 * sigma ** 2 num = np.exp(-(Y - mu) ** 2 / var) Z = (prior * (num / (np.pi * var) ** 0.5)).sum(2) X, Y2 = np.meshgrid(x_test.flatten(), Y.flatten()) # plt.contourf(X, Y2, MinMaxScaler((1e-3,1)).fit_transform(Z), norm=LogNorm(vmin=1e-3, vmax=1.), levels=np.logspace(-3, 0, 7), zorder=5, cmap='plasma', alpha=.1) ax.contour(X, Y2, MinMaxScaler((1e-3,1)).fit_transform(Z), norm=LogNorm(vmin=1e-3, vmax=1.), levels=np.logspace(-3, 0, 5), zorder=5, cmap='inferno', alpha=.5) # ax.scatter(x_test.flatten(), np.array([Y2[Z.argmax(0)[i], i] for i in range(Y2.shape[1])]), 3, label='Max Probability') # kde = sns.kdeplot(x_train.flatten(), y_train.flatten(), shade=False, ax=ax, bw='scott', n_levels=10, legend=False, gridsize=100, color='red') # kde.collections[2].set_alpha(0) if False: ax3.cla() ax3.plot(losses[::10]) ax3.set_yscale('log') else: ax3.cla() (prior, mu, sigma), likely = model.session.run([model.coefs, model.most_likely], feed_dict={model.x: x_nonoise}) # prior, mu, sigma = predict(model, x_nonoise) # likely = MDN.get_most_likely_estimates((prior, mu, sigma))
def grid(fields, title='body spectra', logZ=False, show=True, nstd=1, vlim=(None, None), cmap='inferno'): """ General purpose plotter for multi-dimensional input tensors from 2D up to 6D. The tensor will be converted to 4D and plot as a grid of 2D images :param fields: :param title: :param logZ: :param show: :return: """ if cmap == 'sunlight': cmap = sunlight fields = np.array(fields) # just in case its a list assert fields.ndim > 2 if np.iscomplexobj(fields.flat[0]): fields = np.abs(fields)**2 # convert to intensity if complex while len(fields.shape) > 4: try: boring_ind = fields.shape.index(1) fields = np.mean(fields, axis=boring_ind) except ValueError: fields = fields[0] # if none are zero slice out first dimension while len(fields.shape) < 4: fields = fields[:, np.newaxis] slices = np.int_(np.ceil(np.array(fields.shape)[:2] / 5)) fields = fields[::slices[0], ::slices[1]] print( f'fields being sliced by {slices} making new fields size {fields.shape}' ) nwave, nobj, x, y = fields.shape try: std = np.std(fields) mean = np.mean(fields) except ValueError: std = np.std(fields[0]) mean = np.mean(fields[0]) if vlim == (None, None): vmin, vmax = mean - nstd * std, mean + nstd * std else: vmin, vmax = vlim fig = plt.figure(figsize=(16, 9)) fig.suptitle(title) norm = None if not logZ else (LogNorm() if vmin > 0 else SymLogNorm(1e-7)) imgrid = ImageGrid( fig, 111, # as in plt.subplot(111) nrows_ncols=(nobj, nwave), axes_pad=0.15, share_all=True, cbar_location="right", cbar_mode="single", cbar_size="7%", cbar_pad=0.15, ) for i, ax in enumerate(imgrid): x, y = i % nwave, i // nwave im = ax.imshow(fields[x, y], norm=norm, vmin=vmin, vmax=vmax, cmap=cmap) ax.cax.colorbar(im) ax.cax.toggle_label(True) plt.tight_layout() plt.subplots_adjust(right=0.9) if show: plt.show(block=True)
plt.tight_layout() # Plot LML landscape plt.figure(2) theta0 = np.logspace(-2, 3, 49) theta1 = np.logspace(-2, 0, 50) Theta0, Theta1 = np.meshgrid(theta0, theta1) LML = [[ gp.log_marginal_likelihood(np.log([0.36, Theta0[i, j], Theta1[i, j]])) for i in range(Theta0.shape[0]) ] for j in range(Theta0.shape[1])] LML = np.array(LML).T vmin, vmax = (-LML).min(), (-LML).max() vmax = 50 level = np.around(np.logspace(np.log10(vmin), np.log10(vmax), 50), decimals=1) plt.contour(Theta0, Theta1, -LML, levels=level, norm=LogNorm(vmin=vmin, vmax=vmax)) plt.colorbar() plt.xscale("log") plt.yscale("log") plt.xlabel("Length-scale") plt.ylabel("Noise-level") plt.title("Log-marginal-likelihood") plt.tight_layout() plt.show()
def view_spectra(datacube, title=None, show=True, logZ=False, use_axis=True, vlim=(None, None), subplt_cols=3, dx=None): """ view plot of intensity in each wavelength bin at a single (last) timestep :param datacube: 3D spectral cube (n_wavelengths, nx, ny) at single timestep :param title: string, must be set or will error! :param show: flag possibly useful for plotting loops of things? :param logZ: turn logscale plotting for Z axis on or off :param use_axis: turn on/off using axis ticks, colorbar, etc :param vlim: tuple of colorbar axis limits (min,max) :param subplt_cols: number of subplots per row :param dx: sampling of the image in m. Hardcoded to convert to um :return: """ # Create figure & adjust subplot number, layout, size, whitespace fig = plt.figure() n_colors = len(datacube) n_rows = int(np.ceil(n_colors / float(subplt_cols)) + 1) plt.axis('off') gs = gridspec.GridSpec(n_rows, subplt_cols, wspace=0.08, top=0.9) # Title if title is None: warnings.warn("Plots without titles: Don't Do It!") title = input("Please Enter Title: ") pass fig.suptitle(title, fontweight='bold', fontsize=16) # Wavelength Strings for Subplot Titles w_string = np.array(np.linspace(ap.wvl_range[0] * 1e9, ap.wvl_range[1] * 1e9, ap.n_wvl_final, dtype=int), dtype=str) for w in range(n_colors): ax = fig.add_subplot(gs[w]) ax.set_title(r'$\lambda$ = ' + f"{w_string[w]} nm") slice = opx.extract_center(datacube[w]) # X,Y lables if dx is not None: dx[w] = dx[w] * 1e6 # [convert to um] # dprint(f"sampling = {sampl[w]}") tic_spacing = np.linspace( 0, slice.shape[0], 5) # 5 (number of ticks) is set by hand, arbitrarily chosen tic_lables = np.round( np.linspace(-dx[w] * sp.maskd_size / 2, dx[w] * sp.maskd_size / 2, 5)).astype( int) # nsteps must be same as tic_spacing tic_spacing[0] = tic_spacing[0] + 1 # hack for edge effects tic_spacing[-1] = tic_spacing[-1] - 1 # hack for edge effects plt.xticks(tic_spacing, tic_lables, fontsize=6) plt.yticks(tic_spacing, tic_lables, fontsize=6) # plt.xlabel('[um]', fontsize=8) # plt.ylabel('[um]', fontsize=8) # Z-axis scale if logZ: if np.min(slice) < 0: im = ax.imshow(slice, interpolation='none', origin='lower', vmin=vlim[0], vmax=vlim[1], norm=SymLogNorm(linthresh=1e-5), cmap="YlGnBu_r") clabel = "Log Normalized Intensity" else: im = ax.imshow(slice, interpolation='none', origin='lower', vmin=vlim[0], vmax=vlim[1], norm=LogNorm(), cmap="YlGnBu_r") clabel = "Log Normalized Intensity" else: im = ax.imshow(slice, interpolation='none', origin='lower', vmin=vlim[0], vmax=vlim[1], cmap="YlGnBu_r") clabel = "Normalized Intensity" if use_axis == 'anno': ax.annotate_axis(im, ax, datacube.shape[1]) if use_axis is None: plt.axis('off') if use_axis: warnings.simplefilter("ignore", category=UserWarning) gs.tight_layout(fig, pad=1.08, rect=(0, 0, 1, 0.85)) # rect = (left, bottom, right, top) # fig.tight_layout(pad=50) cbar_ax = fig.add_axes([ 0.55, 0.3, 0.2, 0.05 ]) # Add axes for colorbar @ position [left,bottom,width,height] cb = fig.colorbar(im, cax=cbar_ax, orientation='horizontal') # cb.set_label(clabel) if show is True: plt.show(block=False)
Created on Wed Oct 31 19:54:46 2018 @author: adria """ import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LogNorm from scipy import fftpack from scipy.fftpack import fft, fftfreq ###Sacado de https://matplotlib.org/users/colormapnorms.html### ### Sacado de https://www.scipy-lectures.org/intro/scipy/auto_examples/solutions/plot_fft_image_denoise.html### arbol = plt.imread('Arboles.png') fourier_arbol = np.fft.fft(arbol) plt.figure() plt.imshow(np.abs(fourier_arbol), norm=LogNorm(vmin=2)) ##Escala plt.colorbar() plt.savefig('CaipaAdriana_FT2D.pdf') r, c = fourier_arbol.shape # r y c to son el numero de filas y columnas del arreglo. a_filter = 25 #Filtro que escogi fourier_arbol[:, a_filter:r - a_filter] = 0 #Volver ceros columnas aplicando el filtro fourier_arbol[a_filter:r - a_filter, :] = 0 #Volver ceros las filas aplicando el filtro plt.figure() plt.imshow(np.abs(fourier_arbol), norm=LogNorm(vmin=2)) plt.colorbar() plt.savefig('CaipaAdriana_FT2D_filtrada.pdf') filtro = fftpack.ifft2(fourier_arbol)
def view_timeseries(img_tseries, cdi, title=None, logZ=False, vlim=(None, None), dx=None, subplt_cols=3, box={ 'use': False, 'threshold': 1e-7 }): """ view white light images in the timeseries :param img_tseries: intensity timeseries [n_tsteps, nx,ny] :param cdi: struct that contains the CDI params (from CDI.py) :param title: string, must be set or will error! :param logZ: turn logscale plotting for Z-axis on or off :param use_axis: turn on/off using axis ticks, colorbar, etc :param vlim: tuple of colorbar axis limits (min,max) :param subplt_cols: number of subplots per row :param dx: sampling of the image in m. Hardcoded to convert to um :param box: if True, draw box around CDI region :return: """ # Recreate CDI phase stream for plot titles if cdi.use_cdi: phases = cdi.phase_series # Create figure & adjust subplot number, layout, size, whitespace n_tsteps = len(img_tseries) n_rows = int(np.ceil(n_tsteps / float(subplt_cols))) fig, subplot = plt.subplots(n_rows, subplt_cols, figsize=(12, 10)) fig.subplots_adjust( bottom=0.1, top=0.85, left=0.01, hspace=.4, wspace=0.02, right=0.9, ) # wspace=0.2, right=0.95, left=0.05, # Title if title is None: warnings.warn("Plots without titles: Don't Do It!") title = input("Please Enter Title: ") pass fig.suptitle(title, fontweight='bold', fontsize=16) for ax, t in zip(subplot.flatten(), range(n_rows * subplt_cols)): # range(n_tsteps) if t > n_tsteps - 1: ax.axis('off') # hides axis pass else: # Axis (Subplot) title if cdi.use_cdi and not np.isnan(phases[t]): ax.set_title(f"probe " r'$\theta$' + f"={phases[t] / np.pi:.2f}" + r'$\pi$') else: ax.set_title(f"t={t * sp.sample_time}") if logZ: if vlim[0] is not None and vlim[0] <= 0: im = ax.imshow(img_tseries[t], interpolation='none', origin='lower', vmin=vlim[0], vmax=vlim[1], norm=SymLogNorm(linthresh=1e-5), cmap="YlGnBu_r") clabel = "Log Normalized Intensity" else: im = ax.imshow(img_tseries[t], interpolation='none', origin='lower', vmin=vlim[0], vmax=vlim[1], norm=LogNorm(), cmap="YlGnBu_r") clabel = "Log Normalized Intensity" else: im = ax.imshow(img_tseries[t], interpolation='none', origin='lower', vmin=vlim[0], vmax=vlim[1], cmap="YlGnBu_r") clabel = "Normalized Intensity" # XY axis Labels tic_spacing, tic_labels, xylabel = scale_lD(dx, tp.fn_fp) ax.set_xticks(tic_spacing) ax.set_xticklabels(tic_labels) ax.set_yticks(tic_spacing) ax.set_yticklabels(tic_labels) ax.set_xlabel(xylabel) if box['use']: from medis.CDI import get_fp_mask fp_mask, edges, _, _, _, _ = get_fp_mask( cdi, thresh=box['threshold']) cl = LineCollection(edges, colors='r') ax.add_collection(cl) warnings.simplefilter("ignore", category=UserWarning) cbar_ax = fig.add_axes([ 0.86, 0.1, 0.04, 0.8 ]) # Add axes for colorbar @ position [left,bottom,width,height] cb = fig.colorbar(im, cax=cbar_ax, orientation='vertical') # cb.set_label(clabel, fontsize=14) cb.ax.tick_params(labelsize=10)
def plotFourPlanes(): """ This plots the hit pair residuals on planes 1 through 4 """ area = '1' # read binary Pairs for corridor file1 = f'input/2018-08-himster2-misalign-200u/binaryPairFiles/pairs-{area}-cm.bin' file2 = f'input/2018-08-himster2-misalign-200u/binaryPairFiles/pairs-10{area}-cm.bin' file3 = f'input/2018-08-himster2-misalign-200u/binaryPairFiles/pairs-20{area}-cm.bin' file4 = f'input/2018-08-himster2-misalign-200u/binaryPairFiles/pairs-30{area}-cm.bin' pairs1 = readBinaryFile(file1, '0') pairs2 = readBinaryFile(file2, '0') pairs3 = readBinaryFile(file3, '0') pairs4 = readBinaryFile(file4, '0') dHit1 = pairs1[:, :3] - pairs1[:, 3:6] dHit2 = pairs2[:, :3] - pairs2[:, 3:6] dHit3 = pairs3[:, :3] - pairs3[:, 3:6] dHit4 = pairs4[:, :3] - pairs4[:, 3:6] dHit1 = dHit1 * -1 dHit2 = dHit2 * -1 dHit3 = dHit3 * -1 dHit4 = dHit4 * -1 Nbins = 150 Srasterized = True # plot difference hit array fig = plt.figure(figsize=(15 / 2.54, 5 / 2.54)) ax1 = fig.add_subplot(1, 4, 1) ax1.hist2d(dHit1[:, 0] * 10, dHit1[:, 1] * 10, bins=Nbins, norm=LogNorm(), rasterized=Srasterized) ax1.set_title('Plane 1') ax1.yaxis.set_ticks_position('both') ax1.set_xlabel('dx [mm]') ax1.set_ylabel('dy [mm]') ax1.tick_params(direction='in') ax1.yaxis.set_label_position('left') ax1.set_xlim([-01.2, 01.2]) ax1.set_ylim([-01.2, 01.2]) ax2 = fig.add_subplot(1, 4, 2, sharey=ax1) ax2.hist2d(dHit2[:, 0] * 10, dHit2[:, 1] * 10, bins=Nbins, norm=LogNorm(), rasterized=Srasterized) ax2.set_title('Plane 2') ax2.yaxis.set_ticks_position('both') ax2.set_xlabel('dx [mm]') ax2.tick_params(direction='in') ax2.set_xlim([-01.2, 01.2]) ax2.set_ylim([-01.2, 01.2]) ax2.set_yticklabels([]) ax3 = fig.add_subplot(1, 4, 3, sharey=ax1) ax3.hist2d(dHit3[:, 0] * 10, dHit3[:, 1] * 10, bins=Nbins, norm=LogNorm(), rasterized=Srasterized) ax3.set_title('Plane 3') ax3.yaxis.set_ticks_position('both') ax3.set_xlabel('dx [mm]') ax3.tick_params(direction='in') ax3.set_xlim([-01.2, 01.2]) ax3.set_ylim([-01.2, 01.2]) ax3.set_yticklabels([]) ax4 = fig.add_subplot(1, 4, 4, sharey=ax1) ax4.hist2d(dHit4[:, 0] * 10, dHit4[:, 1] * 10, bins=Nbins, norm=LogNorm(), rasterized=Srasterized) ax4.set_title('Plane 4') ax4.yaxis.set_ticks_position('both') ax4.set_xlabel('dx [mm]') ax4.tick_params(direction='in') ax4.set_xlim([-01.2, 01.2]) ax4.set_ylim([-01.2, 01.2]) ax4.set_yticklabels([]) fig.tight_layout() fig.subplots_adjust(hspace=.001) fig.savefig('pairs-dxdy.pdf', dpi=300, bbox_inches='tight', pad_inches=0)
def quick2D(image, dx=None, title=None, logZ=False, vlim=(None, None), colormap='YlGnBu_r', zlabel='Intensity', show=True): """ Looks at a 2D array, has bunch of handles for plot.imshow :param image: 2D array to plot (data) :param dx: sampling of the image in m. Hardcoded to convert to um on axis :param title: string--must be set or will error! :param logZ: flag to set logscale plotting on z-axis :param vlim: tuple of limits on the colorbar axis, otherwise default matplotlib (pass in logscale limits if logZ=True) :param colormap: specify colormap as string :param zlabel: string label of the colorbar axis :param show: if true, shows the image now and blocks the sim, else false waits until the next plt.show() call :return: """ # Create figure & adjust subplot number, layout, size, whitespace fig = plt.figure() ax = fig.add_subplot(111) # Title while title is None: warnings.warn("Plots without titles: Don't Do It!") title = input("Please Enter Title: ") # X,Y lables if dx is not None: # if dx < 1e-4: # dx *= 1e6 # scale = np.round( # np.linspace(-dx * sp.maskd_size / 2, dx * sp.maskd_size / 2, 5)).astype(int) # tic_spacing = np.linspace(0, sp.maskd_size, 5) # tic_spacing[0] = tic_spacing[0] + 1 # hack for edge effects # tic_spacing[-1] = tic_spacing[-1] -1 # hack for edge effects tic_spacing, tic_labels, axlabel = scale_lD(dx, tp.fn_fp) plt.xticks(tic_spacing, tic_labels) plt.yticks(tic_spacing, tic_labels) plt.xlabel(axlabel) # Setting z-axis by mean # if vlim == (None, None): if vlim == ( -1, -1 ): # Hack this to have it not be default. Only use it if you want it purposely nstd = 2 std = np.std(image) mean = np.mean(image) vlim = mean - nstd * std, mean + nstd * std # Setting Logscale if colormap == 'sunlight': colormap = sunlight if not logZ: norm = None elif vlim[0] is None or vlim[0] > 0: norm = LogNorm() else: norm = SymLogNorm() # norm = None if not logZ else LogNorm() if vlim[0] > 0 else SymLogNorm(1e-7)) # Plot the damn thing cax = ax.imshow(image, interpolation='none', origin='lower', vmin=vlim[0], vmax=vlim[1], norm=norm, cmap=colormap) # Plotting plt.title(title, fontweight='bold', fontsize=16) cb = plt.colorbar(cax) cb.set_label(zlabel) if show: plt.show(block=False)
def plot1Dvs2DCuts(): area = '1' # read binary Pairs for corridor file1 = f'input/2018-08-himster2-misalign-200u/binaryPairFiles/pairs-30{area}-cm.bin' pairs1 = readBinaryFile(file1, '0') dHit1 = pairs1[:, 3:6] - pairs1[:, :3] Nbins = 150 Srasterized = True # plot difference hit array fig = plt.figure(figsize=(15 / 2.54, 10.5 / 2.54)) ax1 = fig.add_subplot(2, 3, 4) ax1.hist2d(dHit1[:, 0] * 10, dHit1[:, 1] * 10, bins=Nbins, norm=LogNorm(), rasterized=Srasterized) ax1.yaxis.set_ticks_position('both') ax1.set_xlabel('dx [mm]') ax1.set_ylabel('dy [mm]') ax1.tick_params(direction='in') ax1.yaxis.set_label_position('left') ax1.set_xlim([-01.2, 01.2]) ax1.set_ylim([-01.2, 01.2]) ax4 = fig.add_subplot(2, 3, 1) ax4.hist(pairs1[:, 6] * 1e1, bins=150, log=True, range=[0.25, 1.2], rasterized=Srasterized) # this is only the z distance ax4.set_title('No Cut') ax4.set_xlabel('d [mm]') ax4.set_ylabel('Entries (log)') pairsN = dynamicCut(pairs1, 2, False) dHit1 = pairsN[:, 3:6] - pairsN[:, :3] ax5 = fig.add_subplot(2, 3, 2, sharey=ax4) ax5.hist(pairsN[:, 6] * 1e1, bins=150, log=True, range=[0.25, 1.2], rasterized=Srasterized) # this is only the z distance ax5.set_title('1D Cut') ax5.set_xlabel('d [mm]') ax2 = fig.add_subplot(2, 3, 5, sharey=ax1) ax2.hist2d(dHit1[:, 0] * 10, dHit1[:, 1] * 10, bins=Nbins, norm=LogNorm(), rasterized=Srasterized) ax2.yaxis.set_ticks_position('both') ax2.set_xlabel('dx [mm]') ax2.tick_params(direction='in') ax2.set_xlim([-01.2, 01.2]) ax2.set_ylim([-01.2, 01.2]) pairsN = dynamicCut(pairs1, 2) dHit1 = pairsN[:, 3:6] - pairsN[:, :3] ax6 = fig.add_subplot(2, 3, 3, sharey=ax4) ax6.hist(pairsN[:, 6] * 1e1, bins=150, log=True, range=[0.25, 1.2], rasterized=Srasterized) # this is only the z distance ax6.set_title('2D Cut') ax6.set_xlabel('d [mm]') ax3 = fig.add_subplot(2, 3, 6, sharey=ax1) ax3.hist2d(dHit1[:, 0] * 10, dHit1[:, 1] * 10, bins=Nbins, norm=LogNorm(), rasterized=Srasterized) ax3.yaxis.set_ticks_position('both') ax3.set_xlabel('dx [mm]') ax3.tick_params(direction='in') ax3.set_xlim([-01.2, 01.2]) ax3.set_ylim([-01.2, 01.2]) fig.tight_layout() # fig.subplots_adjust(hspace = .25) fig.savefig('pairs-dxdy-1Dvs2D.pdf', dpi=300, bbox_inches='tight', pad_inches=0.05)
def colorNearHist(galaxies, f): r""" Creates a 2d histogram of galaxies with color on the x-axis and number of nearby neighbors on the y-axis Parameters galaxies - Type: dict. A dictionary of galaxy objects to be plotted f - Type: str. The name of the plot's output file Returns none but prints two plots to the specified output files. """ errFlag = -9999 galaxyList = list(galaxies.values()) color = [galaxy.color for galaxy in galaxyList if galaxy.color > errFlag] colorSmall = [ galaxy.color for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn > 0 ] colorSmall2 = [ galaxy.color for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn == 0 ] numNear = [ galaxy.nearby for galaxy in galaxyList if galaxy.color > errFlag ] numNearSmall = [ galaxy.nearby for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn > 0 ] numNearSmall2 = [ galaxy.nearby for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn == 0 ] # Plot the histograms plt.hist2d(colorSmall2, numNearSmall2, bins=100, norm=LogNorm(), cmin=1, cmap=plt.cm.inferno) plt.title("Color vs. Number of Neighbors", fontsize=14) plt.xlabel("Color (u - r)", fontsize=14) plt.ylabel("Number of nearby neighbors", fontsize=14) plt.colorbar() plt.savefig(f + 'NoAGN.png') print("Created near hist 1") plt.hist2d(colorSmall, numNearSmall, bins=100, norm=LogNorm(), cmin=1, cmap=plt.cm.inferno) plt.savefig(f + 'AGNonly.png') print("Created near hist 2") plt.clf() # Perform the KS test on the groups colorZeroes = [ galaxy.color for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 0 ] colorZeroes2 = [ galaxy.color for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 0 ] colorOnes = [ galaxy.color for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 1 ] colorOnes2 = [ galaxy.color for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 1 ] colorTwos = [ galaxy.color for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 2 ] colorTwos2 = [ galaxy.color for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 2 ] colorThrees = [ galaxy.color for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 3 ] colorThrees2 = [ galaxy.color for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 3 ] colorFours = [ galaxy.color for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 4 ] colorFours2 = [ galaxy.color for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 4 ] # print("Color KS Test:", ks_2samp(np.array(colorSmall), np.array(colorSmall2))) # print("NumNear KS Test:", ks_2samp(np.array(numNearSmall), np.array(numNearSmall2))) print("KS Test 0:", stats.ks_2samp(np.array(colorZeroes), np.array(colorZeroes2))) print("KS Test 1:", stats.ks_2samp(np.array(colorOnes), np.array(colorOnes2))) print("KS Test 2:", stats.ks_2samp(np.array(colorTwos), np.array(colorTwos2))) print("KS Test 3:", stats.ks_2samp(np.array(colorThrees), np.array(colorThrees2))) print("KS Test 4:", stats.ks_2samp(np.array(colorFours), np.array(colorFours2))) colorZeroes = [ (galaxy.objId, galaxy.color) for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 0 ] colorZeroes2 = [ (galaxy.objId, galaxy.color) for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 0 ] colorOnes = [ (galaxy.objId, galaxy.color) for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 1 ] colorOnes2 = [ (galaxy.objId, galaxy.color) for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 1 ] colorTwos = [ (galaxy.objId, galaxy.color) for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 2 ] colorTwos2 = [ (galaxy.objId, galaxy.color) for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 2 ] colorThrees = [ (galaxy.objId, galaxy.color) for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 3 ] colorThrees2 = [ (galaxy.objId, galaxy.color) for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 3 ] colorFours = [ (galaxy.objId, galaxy.color) for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn > 0 and galaxy.nearby == 4 ] colorFours2 = [ (galaxy.objId, galaxy.color) for galaxy in galaxyList if galaxy.color > errFlag and galaxy.agn == 0 and galaxy.nearby == 4 ] with open('galaxyData/withAGN.csv', 'w') as f: f.write("objID,numNear,color\n") for i in range(0, len(colorZeroes)): f.write( str(colorZeroes[i][0]) + ",0," + str(colorZeroes[i][1]) + "\n") for i in range(0, len(colorOnes)): f.write(str(colorOnes[i][0]) + ",1," + str(colorOnes[i][1]) + "\n") for i in range(0, len(colorTwos)): f.write(str(colorTwos[i][0]) + ",2," + str(colorTwos[i][1]) + "\n") for i in range(0, len(colorThrees)): f.write( str(colorThrees[i][0]) + ",3," + str(colorThrees[i][1]) + "\n") for i in range(0, len(colorFours)): f.write( str(colorFours[i][0]) + ",4," + str(colorFours[i][1]) + "\n") f.close() with open('galaxyData/withoutAGN.csv', 'w') as f: f.write("objID,numNear,color\n") for i in range(0, len(colorZeroes2)): f.write( str(colorZeroes2[i][0]) + ",0," + str(colorZeroes2[i][1]) + "\n") for i in range(0, len(colorOnes2)): f.write( str(colorOnes2[i][0]) + ",1," + str(colorOnes2[i][1]) + "\n") for i in range(0, len(colorTwos2)): f.write( str(colorTwos2[i][0]) + ",2," + str(colorTwos2[i][1]) + "\n") for i in range(0, len(colorThrees2)): f.write( str(colorThrees2[i][0]) + ",3," + str(colorThrees2[i][1]) + "\n") for i in range(0, len(colorFours2)): f.write( str(colorFours2[i][0]) + ",4," + str(colorFours2[i][1]) + "\n") f.close()