def make_spatial(self): print("\n") print("Creating position space movie...") plt.figure() n=1 for fname in self.fname_list: wholedata = fits.open(fname) for i in xrange(1,len(wholedata)): data = wholedata[i].data plt.scatter(data['X'],data['Y'],c=data['MASS']) cb = plt.colorbar() plt.clim(0,50) cb.set_label('Particle mass') plt.scatter(0,0,marker="x", color="black") t = n*self.dt circle1 = plt.Circle((0,0), radius = self.get_event_horizon(t), color = 'r', fill = False) fig = plt.gcf() fig.gca().add_artist(circle1) fig.gca().axes.get_xaxis().set_visible(False) fig.gca().axes.get_yaxis().set_visible(False) plt.xlim(-30,30) plt.ylim(-30,30) plt.axes().set_aspect('equal') plt.title('Nparticles: {}'.format(len(data['X']))) fname = "{}/movies/spatial/frames/{}.png".format(self.dirname,n) plt.savefig(fname) plt.clf() sys.stdout.write('\rFrame {} completed'.format(n)) sys.stdout.flush() n+=1 wholedata.close() print('\n') os.system("ffmpeg -framerate 300 -i {}/movies/spatial/frames/%d.png -c:v libx264 -r 30 -pix_fmt yuv420p {}/movies/spatial/out.mp4".format(self.dirname,self.dirname))
def showNormDistFunct(model, coords, *args, **kwargs): """Show normalized distance fluctuation matrix using :func:`~matplotlib.pyplot.imshow`. By default, *origin=lower* keyword arguments are passed to this function, but user can overwrite these parameters.""" import math import matplotlib import matplotlib.pyplot as plt normdistfunct = model.getNormDistFluct(coords) if not 'origin' in kwargs: kwargs['origin'] = 'lower' matplotlib.rcParams['font.size'] = '14' fig = plt.figure(num=None, figsize=(10,8), dpi=100, facecolor='w') show = plt.imshow(normdistfunct, *args, **kwargs), plt.colorbar() plt.clim(math.floor(np.min(normdistfunct[np.nonzero(normdistfunct)])), \ round(np.amax(normdistfunct),1)) plt.title('Normalized Distance Fluctution Matrix') plt.xlabel('Indices', fontsize='16') plt.ylabel('Indices', fontsize='16') if SETTINGS['auto_show']: showFigure() return show
def cplot(data, limits=[None,None], CM = 'jet', fname='', ext='png'): """Make a color contour plot of data Usage: cplot(data, limits=[None,None], fname='') If no filename is specified a plot is displayed File format is ext (default is png) """ SIZE = 12 DPI = 100 nx, ny = data.shape[0], data.shape[1] data = data.reshape(nx,ny) scale = SIZE/float(max(nx,ny)) plt.figure(figsize=(scale*nx, scale*ny+1.0)) plt.clf() c = plt.imshow(np.transpose(data), cmap=CM) plt.clim(limits) plt.axis([0,nx,0,ny]) #cbar = plt.colorbar(c, ticks=np.arange(0.831,0.835,0.001), aspect = 20, orientation='vertical', shrink=0.72, extend='neither', spacing='proportional') #cbar = plt.colorbar(c, aspect = 40, orientation='vertical', shrink=0.72, extend='neither', spacing='proportional') #cbar = plt.colorbar(c, orientation='horizontal', shrink=1.0) cbar = plt.colorbar(c, orientation='vertical', shrink=0.72, extend='neither', spacing='proportional') cbar.ax.tick_params(labelsize=21,size=10) #cbar.ax.yaxis.set_ticks_position('left') #c.cmap.set_under(color='black') if len(fname) == 0: plt.show() else: plt.savefig(fname+'.'+ ext, format=ext, dpi=DPI, bbox_inches='tight', pad_inches=0.1) plt.close()
def color_plot(targets,k_DD,f_DD,coherence,azimuths): f_DD_boundaries = ( f_DD - (f_DD[1]-f_DD[0])/2 ) d_phi = 1/coherence.shape[1] angles_over_pi = np.arange(0,1+d_phi,1/coherence.shape[1]) plt.pcolor(angles_over_pi,f_DD_boundaries,coherence) if show_azimuths: for azimuth in azimuths: plt.axvline(mod(azimuth),color="k",linewidth=2) plt.xlim(0,1) plt.ylim(0,f_DD_boundaries[-1]) plt.clim(-1,1) plt.xlabel(r"$\phi_{DD}/\pi$") plt.ylabel("$f_{}$".format(k_DD)) cbar = plt.colorbar() cbar.set_label("Coherence") plt.tight_layout() plt.savefig(figname(targets)) if show: plt.show()
def showMechStiff(model, coords, *args, **kwargs): """Show mechanical stiffness matrix using :func:`~matplotlib.pyplot.imshow`. By default, *origin=lower* keyword arguments are passed to this function, but user can overwrite these parameters.""" import math import matplotlib import matplotlib.pyplot as plt arange = np.arange(model.numAtoms()) model.buildMechStiff(coords) if not 'origin' in kwargs: kwargs['origin'] = 'lower' if 'jet_r' in kwargs: import matplotlib.cm as plt kwargs['jet_r'] = 'cmap=cm.jet_r' MechStiff = model.getStiffness() matplotlib.rcParams['font.size'] = '14' fig = plt.figure(num=None, figsize=(10,8), dpi=100, facecolor='w') show = plt.imshow(MechStiff, *args, **kwargs), plt.colorbar() plt.clim(math.floor(np.min(MechStiff[np.nonzero(MechStiff)])), \ round(np.amax(MechStiff),1)) #plt.title('Mechanical Stiffness Matrix')# for {0}'.format(str(model))) plt.xlabel('Indices', fontsize='16') plt.ylabel('Indices', fontsize='16') if SETTINGS['auto_show']: showFigure() return show
def plot_2d_stats(stats, name): for ck in stats: if ck != "ID": for ak in stats[ck]: context_values_keys = sorted(stats[ck][ak].keys()) context_values = dict(zip(context_values_keys, range(len(context_values_keys)))) action_values_keys = sorted(set(flatten(list(map(lambda x: x.keys(), stats[ck][ak].values()))))) action_values = dict(zip(action_values_keys, range(len(action_values_keys)))) ck_ak_stats = np.zeros((len(context_values), len(action_values))) maximum = 0 for cv in sorted(stats[ck][ak]): for av in sorted(stats[ck][ak][cv]): ck_ak_stats[context_values[cv], action_values[av]] = stats[ck][ak][cv][av]["rate"] maximum = max(maximum, stats[ck][ak][cv][av]["rate"]) plt.imshow(ck_ak_stats.T, interpolation="none") plt.clim([0, maximum]) if ck_ak_stats.shape[0] > ck_ak_stats.shape[1]: plt.colorbar(orientation="horizontal") else: plt.colorbar(orientation="vertical") plt.xticks(list(range(len(context_values))), list(context_values_keys), rotation='vertical') plt.yticks(list(range(len(action_values))), list(action_values_keys)) plt.xlabel(ck) plt.ylabel(ak) plt.title("Revenue / show") dir = "stats/" + name + "/rate_interaction/" create_directory(dir) plt.savefig(dir + ck + "-" + ak) plt.close()
def on_keypress(self,event): global colmax global colmin if event.key in ['1', '2', '3', '4', '5', '6', '7','8', '9', '0']: if not os.path.exists(write_dir + runtag): os.mkdir(write_dir + runtag) recordtag = write_dir + runtag + "/" + runtag + "_" + event.key + ".txt" print "recording filename in " + recordtag f = open(recordtag, 'a+') f.write(self.filename+"\n") f.close() if event.key == 'p': if not os.path.exists(write_dir + runtag): os.mkdir(write_dir + runtag) pngtag = write_dir + runtag + "/%s.png" % (self.filename) print "saving image as " + pngtag P.savefig(pngtag) if event.key == 'e': if not os.path.exists(write_dir + runtag): os.mkdir(write_dir + runtag) epstag = write_dir + runtag + "/%s.eps" % (self.filename) print "saving image as " + epstag P.savefig(epstag, format='eps') if event.key == 'r': colmin = self.inarr.min() colmax = self.inarr.max() P.clim(colmin, colmax) P.draw()
def func(n): plt.matshow(z[n]) plt.title('%i%s'%(freq.f_scaled[n],freq.unit)) plt.grid(0) plt.colorbar() if clims is not None: plt.clim(clims)
def create_animation_rate(rate, frames=100, interval=1, fps=10, dpi=90, filename='default.mp4', format='.mp4'): """ Documentation needed """ filename = filename + '-rate_animation' + format # Initiate figure fig = plt.figure() ims = plt.imshow(rate[::,::,1]) plt.xlabel('Neuron\'s x coordinate') plt.ylabel('Neuron\'s y coordinate') plt.title('Firing rate in a 20 ms window') cbar = plt.colorbar() cbar.ax.set_ylabel('Firing Rate (Hz)') plt.clim(0,70) # Define how to update frames def updatefig(i): ims.set_array( rate[:,:,i] ) return ims, # run and save the animation image_animation = animation.FuncAnimation(fig,updatefig, frames=frames, interval=interval, blit = True) image_animation.save(filename, fps=fps, dpi=dpi) plt.show()
def latlon_plot(varnm, reg, day_or_season, coeff='m', stipple_kw={}, axlims=(-60, 60, 40, 120)): regdata = reg[varnm + '_latlon'] keys = [key for key in regdata if key.endswith('_' + coeff)] clim = atm.climits(regdata[keys].to_array(), symmetric=True, percentile=99.9) xname, yname = 'lon', 'lat' lat = atm.get_coord(regdata, 'lat') if max(np.diff(lat)) > 1: xsample, ysample = 1, 1 else: xsample, ysample = 2, 2 if isinstance(day_or_season, int): key = varnm + '_DAILY_' var = regdata[key + coeff].sel(dayrel=day_or_season) p = regdata[key + 'p'].sel(dayrel=day_or_season) titlestr = varnm + ' Day %d' % day_or_season else: key = varnm + '_' + day_or_season + '_' var = regdata[key + coeff] p = regdata[key + 'p'] titlestr = varnm + ' ' + day_or_season pts_mask = stipple_mask(p) atm.pcolor_latlon(var, axlims=axlims, fancy=False) plt.clim(clim) atm.stipple_pts(pts_mask, xname, yname, xsample, ysample, **stipple_kw) plt.title(titlestr)
def my_plot(c_plot, step): filename = "chs-step" + str(step) + ".png" plt.imshow(c_plot) plt.colorbar() plt.clim(0, 1) plt.savefig(filename) plt.clf()
def reduce_and_plot_clusters(X, model, title="", just_labelled=False, event_clusters=[]): if not type(model.labels_) is list: n_clus = len(set(model.labels_.tolist())) labels_ = model.labels_.tolist() else: labels_ = model.labels_ n_clus = len(set(model.labels_)) if just_labelled: idx = [i for i, label in enumerate(labels_) if label in event_clusters] print idx X = X[idx, :] labels_ = [labels_[i] for i in idx] label_dict = dict(zip(set(labels_), range(0, len(set(labels_))))) labels_ = [label_dict[label] for label in labels_] print labels_ n_clus = len(event_clusters) print n_clus X_reduced = TruncatedSVD().fit_transform(X) X_embedded = TSNE(learning_rate=100).fit_transform(X_reduced) plt.figure(figsize=(10, 10)) plt.title(title) plt.scatter(X_embedded[:, 0], X_embedded[:, 1], marker="x", c=labels_, cmap=plt.cm.get_cmap("jet", n_clus)) plt.colorbar(ticks=min(range(500), range(n_clus))) plt.clim(-0.5, (n_clus - 0.5)) plt.savefig('i/reduce_and_plot_clusters' + str(datetime.now()) + '.png') plt.show()
def main(unused_argv): global heat_map tf_records_file_names = sorted(os.listdir(utils.HEAT_MAP_TF_RECORDS_DIR)) print(tf_records_file_names) tf_records_file_names = tf_records_file_names[2:3] for wsi_filename in tf_records_file_names: print('Generating heatmap for: %s' % wsi_filename) tf_records_dir = os.path.join(utils.HEAT_MAP_TF_RECORDS_DIR, wsi_filename) raw_patches_dir = os.path.join(utils.HEAT_MAP_RAW_PATCHES_DIR, wsi_filename) heatmap_rgb_path = os.path.join(utils.HEAT_MAP_WSIs_PATH, wsi_filename) assert os.path.exists(heatmap_rgb_path), 'heatmap rgb image %s does not exist' % heatmap_rgb_path heatmap_rgb = Image.open(heatmap_rgb_path) heatmap_rgb = np.array(heatmap_rgb) heatmap_rgb = heatmap_rgb[:, :, :1] heatmap_rgb = np.reshape(heatmap_rgb, (heatmap_rgb.shape[0], heatmap_rgb.shape[1])) heat_map = np.zeros((heatmap_rgb.shape[0], heatmap_rgb.shape[1]), dtype=np.float32) assert os.path.exists(raw_patches_dir), 'raw patches directory %s does not exist' % raw_patches_dir num_patches = len(os.listdir(raw_patches_dir)) assert os.path.exists(tf_records_dir), 'tf-records directory %s does not exist' % tf_records_dir dataset = Dataset(DATA_SET_NAME, utils.data_subset[4], tf_records_dir=tf_records_dir, num_patches=num_patches) build_heatmap(dataset) # Image.fromarray(heat_map).save(os.path.join(utils.HEAT_MAP_DIR, wsi_filename), 'PNG') plt.imshow(heat_map, cmap='hot', interpolation='nearest') plt.colorbar() plt.clim(0.00, 1.00) plt.axis([0, heatmap_rgb.shape[1], 0, heatmap_rgb.shape[0]]) plt.savefig(str(os.path.join(utils.HEAT_MAP_DIR, wsi_filename))+'_heatmap.png') plt.show()
def plot_table_as_heatmap(self, intensity_min = 10**4, intensity_max = 10**9): table = self.get_table() # Numpy does not like dealing with NaN unless things are floats evidently. table_values = np.array(table.values, dtype=np.float64) # Since we will probably plot this with a log scale, let us set all NaN values to 1. table_values[np.isnan(table_values)] = 1 # Do the plotting ski.io.imshow(table_values, norm=LogNorm(), cmap='cubehelix', interpolation='None') plt.clim(intensity_min, intensity_max) plt.grid(False) # Label the axis ticks so that they look like a plate ytick_positions = np.arange(0, self.well_rows) ytick_labels = ytick_positions + 1 # We actually want the ytick labels to be letters ytick_labels = [chr(z + LOWERCASE_TO_INT).upper() for z in ytick_labels] plt.yticks(ytick_positions, ytick_labels) xtick_positions = np.arange(0, self.well_columns) xtick_labels = xtick_positions + 1 plt.xticks(xtick_positions, xtick_labels)
def _colormap_plot_array_response(cmaps): """ Plot for illustrating colormaps: array response. :param cmaps: list of :class:`~matplotlib.colors.Colormap` :rtype: None """ import matplotlib.pyplot as plt from obspy.signal.array_analysis import array_transff_wavenumber # generate array coordinates coords = np.array([[10., 60., 0.], [200., 50., 0.], [-120., 170., 0.], [-100., -150., 0.], [30., -220., 0.]]) # coordinates in km coords /= 1000. # set limits for wavenumber differences to analyze klim = 40. kxmin = -klim kxmax = klim kymin = -klim kymax = klim kstep = klim / 100. # compute transfer function as a function of wavenumber difference transff = array_transff_wavenumber(coords, klim, kstep, coordsys='xy') # plot for cmap in cmaps: plt.figure() plt.pcolor(np.arange(kxmin, kxmax + kstep * 1.1, kstep) - kstep / 2., np.arange(kymin, kymax + kstep * 1.1, kstep) - kstep / 2., transff.T, cmap=cmap) plt.colorbar() plt.clim(vmin=0., vmax=1.) plt.xlim(kxmin, kxmax) plt.ylim(kymin, kymax) plt.show()
def plotDiffer(cube, hdr, index): diff = cube[index]- cube[index+1] mp.clf() mp.subplot(221) plotTpf.plotCadence(cube[index], hdr) mp.colorbar() mp.subplot(222) plotTpf.plotCadence(cube[index+1], hdr) mp.colorbar() mp.subplot(223) plotTpf.plotCadence(diff, hdr) mp.colorbar() mp.subplot(224) noise = np.sqrt(cube[index]+cube[index+1]) z = diff/noise plotTpf.plotCadence(z, hdr) idx = np.isfinite(z) zmax = max( -np.min(z[idx]), np.max(z[idx])) mp.clim([-zmax, zmax]) mp.colorbar()
def plot_gridsearch_result(tau_sses, tau_ranges, tau_opt, ptitle='default title',save=False): fig = plt.figure(figsize=(24,20), facecolor='white') subrows = np.ceil(np.sqrt(tau_ranges[-1].shape)) subcols = np.ceil(tau_ranges[-1].shape/subrows) gs = gridspec.GridSpec(int(subrows), int(subcols), left=0.1, right=0.90, bottom=0.1, top=0.9) gs.update(hspace=0.5, wspace=0.5) for ctau3_idx,ctau3 in enumerate(tau_ranges[-1]): plt.subplot(gs[ctau3_idx]) img = plt.imshow(tau_sses[:,:,ctau3_idx], aspect='auto', interpolation='none', origin='lower') img.axes.set_yticks(np.arange(len(tau_ranges[0]))) img.axes.set_yticklabels(tau_ranges[0]) img.axes.set_xticks(np.arange(len(tau_ranges[1]),step=2)) img.axes.set_xticklabels(np.arange(tau_ranges[1][0],np.max(tau_ranges[1]),step=10)) plt.xlabel('Second time constant [ms]',fontsize=12) plt.ylabel('First time constant [ms]',fontsize=12) plt.title('Total SSE, for tau 3 = '+str(ctau3) + 'ms',fontsize=12) plt.colorbar() plt.clim(tau_sses.min(),tau_sses.min()*1.5) plt.suptitle(ptitle,fontsize=20) fig.text(0.8,0.95, 'Optimal set of taus: '+str(tau_opt.squeeze())) if save==True: if not os.path.exists(figure_path): os.makedirs(figure_path) plt.savefig(figure_path + ptitle, dpi=120) plt.close(fig)
def plot_colors(hist,options): Za=ma.array(hist.content) default=options.get('default',1e6) Zm=ma.masked_where(Za>default, Za) #FIXME: there must be a better way of doing this palette=plt.get_cmap(options.get('cmap','jet')) palette.set_bad(alpha=0.0) # xmin, xmax, ymin, ymax ext=[hist.xedges[0],hist.xedges[-1],hist.yedges[0], hist.yedges[-1]] # collecting arguments imshow_args={ 'interpolation' : 'nearest', 'extent' : ext, 'aspect' : 'auto', 'origin' : 'lower', 'cmap' : palette, } # the real function call plot = plt.imshow(Zm,**imshow_args) # also plot the bar plt.colorbar(plot) plt.clim( *options["zrange"] )
def makeGridPlots( histos, filename, ext="png" ) : # old code : doesnt owrk nplot = len( histos.keys() ) sh = sqrt( nplot ) fl = floor( sh ) ce = ceil( sh ) if sh - fl > 0.5 : fl = ce f = r2m.RootFile(filename) hists = [ f.get(hist) for hist in sorted(histos.keys()) ] opts = [ histos[key] for key in sorted(histos.keys()) ] fig = plt.figure(figsize=[ce*(sml_plot_size[0]+fl),fl*(sml_plot_size[1]+fl)]) #fig.subplots_adjust(left=1, right=2, top=2, bottom=1) ax_list = [] for h, (hist,opt) in enumerate(zip(hists,opts)) : ax_list.append( fig.add_subplot(ce, fl, h )) ax_list[-1].set_xlabel( hist.xlabel ) ax_list[-1].set_ylabel( hist.ylabel ) xmin, xmax = hist.xedges[0], hist.xedges[-1] ymin, ymax = hist.yedges[0], hist.yedges[-1] plt.axis([xmin, xmax, ymin, ymax]) hist.contour( levels=opt["contours"], colors = opt["colors"], linewidths=2 ) hist.colz() plt.axis([xmin, xmax, ymin, ymax]) plt.clim(opt["zrange"][0],opt["zrange"][1]) pylab.yticks(pylab.arange(ymin, ymax, opt["yticks"])) pylab.xticks(pylab.arange(xmin, xmax, opt["xticks"])) ax_list[-1].set_title( opt["title"] ) #plt.show() plt.savefig( grid_name( filename ) + ".%s" % ext )
def plotColor(filename): fig = plt.figure(figsize=(10,20)) plt.xlabel('$ x $') plt.ylabel('$ y $') z = F[0] im = plt.imshow(z, animated=True) plt.clim(0,0.5) plt.colorbar(im, label='wave function probability $ \parallel \psi ( x, y ) \parallel ^ 2 $ ') def updatefig(i): try: im.set_array(F[i]) except TypeError: quit() return im, # UNDER CONSTRUCTION # Set up formatting for the movie files #Writer = animation.writers['mencoder'] #writer = Writer(fps=30, metadata=dict(artist='Me'), bitrate=1800) ani = animation.FuncAnimation(fig, updatefig, interval=speed, blit=True) # UNDER CONSTRUCTION #ani.save(filename + '.mp4', writer=writer) show()
def field(domain, z, title, clim = None, path=None, save=True, show = False, ics=1, ext='.png', cmap=plt.cm.jet): """ Given a domain, plot the nodal value z :param domain: :class:`~polyadcirc.run_framework.domain` :param z: :class:`np.array` :param string title: plot title :param clim: :class:`np.clim` :type path: string or None :param path: directory to store plots :type save: boolean :param save: flag for whether or not to save plots :type show: boolean :param show: flag for whether or not to show plots :param int ics: polar coordinate option (1 = cart coords, 2 = polar coords) :param string ext: file extension """ if path == None: path = os.getcwd() plt.figure() plt.tripcolor(domain.triangulation, z, shading='gouraud', cmap=cmap) plt.gca().set_aspect('equal') plt.autoscale(tight=True) if clim: plt.clim(clim[0], clim[1]) add_2d_axes_labels(ics) colorbar() #plt.title(title) save_show(path+'/figs/'+title, save, show, ext)
def plot(self,vmin=np.NaN,vmax=np.NaN,colorbarcenter=False,colorbar=cm.jet): ''' plot the image2d :param vmin: minimum value for the colorbar :type vmin: float :param vmax: maximun value for the colorbar :type vmax: float :param colorbarcenter: do you want center the colorbar around 0 :type colorbarcenter: bool :param colorbar: colorbar from matplotlib.cm .. note:: colorbar : cm.jet for eqstrain-stress ''' if np.isnan(vmin): vmin=np.nanmin(self.field) if np.isnan(vmax): vmax=np.nanmax(self.field) # size of the image2d ss=np.shape(self.field) # create image img=plt.imshow(self.field,aspect='equal',extent=(0,ss[1]*self.res,0,ss[0]*self.res),cmap=colorbar,vmin=vmin,vmax=vmax) if colorbarcenter: zcolor=np.max(np.max(np.abs(self.field))) plt.clim(-zcolor, zcolor) # set up colorbar plt.colorbar(img,orientation='vertical',aspect=4)
def plotSVM(solver, lowerBound, upperBound, step): assert lowerBound < upperBound X = arange(lowerBound, upperBound, step) Y = arange(lowerBound, upperBound, step) X,Y = meshgrid(X,Y) Z = zeros(X.shape) for i in range(len(X)): for j in range(len(Y)): #Classify the result result = int( svm_predict([0.], [[ X[i][j], Y[i][j] ]], solver, '-q')[0][0] ) if result == 0: Z[i][j] = 0 #lower limit else: Z[i][j] = 100 #higher limit plot.imshow(Z) plot.gcf() plot.clim() plot.title("SVM Activation") return plot
def plot_fld(fldname, step, cra=None, xlim=None, ylim=None): flds = psc.PscFields(path, step, "p") fld = flds[fldname] crd_nc = flds.crd_nc plt.figure() kwargs = {} plt.pcolormesh(crd_nc[1], crd_nc[2], fld[:,:,0], **kwargs) if cra: plt.clim(*cra) plt.colorbar() plt.title(fldname) plt.xlabel("y") plt.ylabel("z") if xlim: plt.xlim(*xlim) else: plt.xlim(crd_nc[1][0], crd_nc[1][-1]) if ylim: plt.ylim(*ylim) else: plt.ylim(crd_nc[2][0], crd_nc[2][-1]) plt.axes().set_aspect('equal') plt.savefig("%s-%06d.png" % (fldname, step), dpi=100) plt.close()
def data_movie(data, fig=None, pause=None, **kwargs): """ Display all images of a data cube as a movie. Arguments --------- data: ndarray A data cube. Third dimension should be the image index. fig: Figure instance (optional). A figure instance where the images will be displayed. kwargs: Keywor arguments. Other keyword arguments are passed to imshow. Returns ------- Nothing. """ if fig is None: fig = plt.figure() a = fig.gca() dmin, dmax = data.min(), data.max() n = data.shape[-1] im0 = a.imshow(data[..., 0].T, origin="lower", **kwargs) plt.draw() for k in xrange(n): im0.set_data(data[..., k].T) plt.title("Image " + str(k)) plt.clim([dmin, dmax]) plt.draw() if pause is not None: time.sleep(pause)
def animate(i): plt.clf() m, _ = atm.pcolor_latlon(animdata[i], axlims=axlims, cmap=cmap) plt.clim(cmin, cmax) day = animdata[daynm + 'rel'].values[i] plt.title('%s %s RelDay %d' % (var, yearstr, day)) return m
def plot_grammar_matrices(self, folder_path, folder_name, A_matrix = np.zeros(0), B_matrix = np.zeros(0)): if folder_name in os.listdir(folder_path): shutil.rmtree(folder_path + '/' + folder_name, True) os.mkdir(folder_path + '/' + folder_name) if(len(A_matrix) == 0): A_matrix = self.A if(len(B_matrix) == 0): B_matrix = self.B assert(A_matrix.shape[0] == A_matrix.shape[1] == A_matrix.shape[2] == B_matrix.shape[0]) N = A_matrix.shape[0] for i in xrange(N): plt.subplot(211) plt.title('A %d' % i) plt.imshow(A_matrix[i], interpolation = 'None') plt.clim(0, 1.0) plt.subplot(212) plt.plot(range(len(B_matrix[i])), B_matrix[i], linestyle = 'None', marker = 'o') plt.ylim(-0.2, 1.0) plt.xlim(-1, len(B_matrix[i])) plt.title('B %d' % i) plt.savefig(folder_path + '/' + folder_name + '/' + string.lower(folder_name) + '_rule_' + str(i) + '.png', dpi = 300) plt.close()
def main(): import matplotlib.pyplot as plt x, y = np.mgrid[-1:1:200j, -1:1:200j] rho = np.sqrt(x**2 + y**2) theta = np.arctan(y / x) theta[(theta.shape[0] / 2):] += np.pi nm_pairs = list(n_m_upto(4, 2)) plt.ioff() cur_max = -np.inf cur_min = np.inf main_axes = plt.gca() for index, (n, m) in enumerate(nm_pairs): image = zernike_exp(rho, theta, n, m) cur_max = max(cur_max, np.max(np.real(image[~np.isnan(image)])), np.max(np.imag(image[~np.isnan(image)]))) cur_min = min(cur_min, np.min(np.real(image[~np.isnan(image)])), np.min(np.imag(image[~np.isnan(image)]))) plt.subplot(2, len(nm_pairs), index + 1) plt.imshow(np.real(image), cmap=plt.cm.gray) plt.title('$\\mathrm{real}(V_{%d,%d}(\\rho, \\theta))$' % (n, m)) plt.axis('off') plt.subplot(2, len(nm_pairs), len(nm_pairs) + index + 1) plt.imshow(np.imag(image), cmap=plt.cm.gray) plt.title('$\\mathrm{imag}(V_{%d,%d}(\\rho, \\theta))$' % (n, m)) plt.axis('off') for index in range(2 * len(nm_pairs)): plt.subplot(2, len(nm_pairs), index + 1) plt.clim(cur_min, cur_max) print "cur_min =", cur_min print "cur_max =", cur_max plt.show() plt.ion()
def heat_map(self,DL): fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.imshow(DL) plt.clim(DL.mean()-3*DL.std(),DL.mean()+3*DL.std()) plt.colorbar() plt.show(block=False)
def field(domain, z, title, clim = None, path=None, save=True, show = False, ics=1, ext='.png', cmap=plt.cm.jet, fmt=None): """ Given a domain, plot the nodal value z :param domain: :class:`~polyadcirc.run_framework.domain` :param z: :class:`numpy.ndarray` :param string title: plot title :param clim: :class:`numpy.clim` :type path: string or None :param path: directory to store plots :type save: bool :param save: flag for whether or not to save plots :type show: bool :param show: flag for whether or not to show plots :param int ics: polar coordinate option (1 = cart coords, 2 = polar coords) :param string ext: file extension :param callable fmt: formatter for color bar, takes ``(x, pos)`` returns ``string`` """ if path is None: path = os.getcwd() plt.figure() plt.tripcolor(domain.triangulation, z, shading='gouraud', cmap=cmap) plt.gca().set_aspect('equal') plt.autoscale(tight=True) if clim: plt.clim(clim[0], clim[1]) add_2d_axes_labels(ics=ics) colorbar(fmt=fmt) #plt.title(title) save_show(os.path.join(path, 'figs', title), save, show, ext)
lat = np.asarray(data['lat']) col = np.asarray(data['rhorc_655']) Col = np.zeros(col.shape) Lon = np.zeros(col.shape) Lat = np.zeros(col.shape) for i in np.arange(0, col.shape[0]): for j in np.arange(0, col.shape[1]): Col[i, j] = np.float(col[i, j]) Lon[i, j] = np.float(lon[i, j]) Lat[i, j] = np.float(lat[i, j]) ### plt.figure(figsize=[9, 7]) plt.pcolormesh(Lon, Lat, Col, cmap="rainbow") plt.colorbar() plt.clim([0, 0.1]) plt.xlabel('Longitude') plt.ylabel('Latitude') plt.title("L8 09/03/2018") plt.tight_layout() plt.savefig("./Figs/Fig_map_raw655.png", dpi=600) #plt.figure(figsize=[9,7]) #plt.pcolormesh(Lon,Lat,Col,cmap="rainbow") #plt.colorbar() #plt.clim([0,0.012]) #plt.xlabel('Longitude') #plt.ylabel('Latitude') #plt.title("L8 09/03/2018") #plt.tight_layout() #plt.savefig("./Figs/Fig_map_lake655.png",dpi=600)
def generateVoltChart(tree, rawOut, modelDir, neatoLayout=True): ''' Map the voltages on a feeder over time using a movie.''' # We need to timestamp frames with the system clock to make sure the browser caches them appropriately. genTime = str(datetime.datetime.now()).replace(':', '.') # Detect the feeder nominal voltage: for key in tree: ob = tree[key] if type(ob) == dict and ob.get('bustype', '') == 'SWING': feedVoltage = float(ob.get('nominal_voltage', 1)) # Make a graph object. fGraph = omf.feeder.treeToNxGraph(tree) if neatoLayout: # HACK: work on a new graph without attributes because graphViz tries to read attrs. cleanG = nx.Graph(fGraph.edges()) cleanG.add_nodes_from(fGraph) # was formerly : positions = nx.graphviz_layout(cleanG, prog='neato') but this threw an error positions = nx.nx_agraph.graphviz_layout(cleanG, prog='neato') else: rawPositions = {n: fGraph.node[n].get('pos', (0, 0)) for n in fGraph} #HACK: the import code reverses the y coords. def yFlip(pair): try: return (pair[0], -1.0 * pair[1]) except: return (0, 0) positions = {k: yFlip(rawPositions[k]) for k in rawPositions} # Plot all time steps. nodeVolts = {} for step, stamp in enumerate(rawOut['aVoltDump.csv']['# timestamp']): # Build voltage map. nodeVolts[step] = {} for nodeName in [ x for x in list(rawOut.get('aVoltDump.csv', {}).keys()) + list(rawOut.get('1nVoltDump.csv', {}).keys()) + list(rawOut.get('1mVoltDump.csv', {}).keys()) if x != '# timestamp' ]: allVolts = [] for phase in ['a', 'b', 'c', '1n', '2n', '1m', '2m']: try: voltStep = rawOut[phase + 'VoltDump.csv'][nodeName][step] except: continue # the nodeName doesn't have the phase we're looking for. # HACK: Gridlab complex number format sometimes uses i, sometimes j, sometimes d. WTF? if type(voltStep) is str: voltStep = voltStep.replace('i', 'j') v = complex(voltStep) phaseVolt = abs(v) if phaseVolt != 0.0: if _digits(phaseVolt) > 3: # Normalize to 120 V standard phaseVolt = phaseVolt * (120 / feedVoltage) allVolts.append(phaseVolt) # HACK: Take average of all phases to collapse dimensionality. nodeVolts[step][nodeName] = avg(allVolts) # Line current calculations lineCurrents = {} if os.path.exists(pJoin(modelDir, 'OH_line_current_phaseA.csv')): for step, stamp in enumerate( rawOut['OH_line_current_phaseA.csv']['# timestamp']): lineCurrents[step] = {} currentArray = [] # Finding currents of all phases on the line for key in [ x for x in rawOut.get('OH_line_current_phaseA.csv', {}).keys() if x != '# timestamp' ]: currA = rawOut['OH_line_current_phaseA.csv'][key][step] currB = rawOut['OH_line_current_phaseB.csv'][key][step] currC = rawOut['OH_line_current_phaseC.csv'][key][step] flowDir = rawOut['OH_line_flow_direc.csv'][key][step] lineRating = rawOut['OH_line_cont_rating.csv'][key][step] if 'R' in flowDir: direction = -1 else: direction = 1 if type(currA) is str: currA = stringToMag(currA) currB = stringToMag(currB) currC = stringToMag(currC) maxCurrent = max(abs(currA), abs(currB), abs(currC)) directedCurrent = float(maxCurrent / lineRating * direction) for objt in tree: if 'name' in tree[objt].keys(): if tree[objt]['name'] == str(int(key)): keyTup = (tree[objt]['to'], tree[objt]['from']) lineCurrents[step][keyTup] = directedCurrent # Underground Lines if os.path.exists(pJoin(modelDir, 'UG_line_current_phaseA.csv')): for step, stamp in enumerate( rawOut['UG_line_current_phaseA.csv']['# timestamp']): currentArray = [] # Finding currents of all phases on the line for key in [ x for x in rawOut.get('UG_line_current_phaseA.csv', {}).keys() if x != '# timestamp' ]: currA = rawOut['UG_line_current_phaseA.csv'][key][step] currB = rawOut['UG_line_current_phaseB.csv'][key][step] currC = rawOut['UG_line_current_phaseC.csv'][key][step] flowDir = rawOut['UG_line_flow_direc.csv'][key][step] lineRating = rawOut['UG_line_cont_rating.csv'][key][step] if 'R' in flowDir: direction = -1 else: direction = 1 if type(currA) is str: currA = stringToMag(currA) currB = stringToMag(currB) currC = stringToMag(currC) maxCurrent = max(abs(currA), abs(currB), abs(currC)) directedCurrent = float(maxCurrent / lineRating * direction) for objt in tree: if 'name' in tree[objt].keys(): if tree[objt]['name'] == str(int(key)): keyTup = (tree[objt]['to'], tree[objt]['from']) lineCurrents[step][keyTup] = directedCurrent for step in lineCurrents: for edge in fGraph.edges(): if edge not in lineCurrents[step].keys(): lineCurrents[step][edge] = 0 # Draw animation. voltChart = plt.figure(figsize=(15, 15)) plt.axes(frameon=0) plt.axis('off') #set axes step equal voltChart.gca().set_aspect('equal') custom_cm = matplotlib.colors.LinearSegmentedColormap.from_list( 'custColMap', [(0.0, 'blue'), (0.25, 'darkgray'), (0.75, 'darkgray'), (1.0, 'yellow')]) custom_cm.set_under(color='black') current_cm = matplotlib.colors.LinearSegmentedColormap.from_list( 'custColMap', [(0.0, 'green'), (0.999999, 'green'), (1.0, 'red')]) # current_cm = matplotlib.colors.LinearSegmentedColormap.from_list('custColMap',[(-1.0,'green'),(0.0, 'gray'),(1.0,'red'),(1.0,'red')]) # use edge color to set color and dashness of overloaded/negative currents if len(lineCurrents) > 0: edgeIm = nx.draw_networkx_edges( fGraph, pos=positions, edge_color=[lineCurrents[0].get(n, 0) for n in fGraph.edges()], edge_cmap=current_cm) else: edgeIm = nx.draw_networkx_edges(fGraph, positions) nodeIm = nx.draw_networkx_nodes( fGraph, pos=positions, node_color=[nodeVolts[0].get(n, 0) for n in fGraph.nodes()], linewidths=0, node_size=30, cmap=custom_cm) plt.sci(nodeIm) plt.clim(110, 130) plt.colorbar() plt.title(rawOut['aVoltDump.csv']['# timestamp'][0]) def update(step): nodeColors = np.array( [nodeVolts[step].get(n, 0) for n in fGraph.nodes()]) if len(lineCurrents) > 0: edgeColors = np.array( [lineCurrents[step].get(n, 0) for n in fGraph.edges()]) edgeIm.set_array(edgeColors) plt.title(rawOut['aVoltDump.csv']['# timestamp'][step]) nodeIm.set_array(nodeColors) return nodeColors, mapTimestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S") anim = FuncAnimation(voltChart, update, frames=len(rawOut['aVoltDump.csv']['# timestamp']), interval=200, blit=False) anim.save(pJoin(modelDir, 'voltageChart_' + mapTimestamp + '.mp4'), codec='h264', extra_args=['-pix_fmt', 'yuv420p']) # Reclaim memory by closing, deleting and garbage collecting the last chart. voltChart.clf() plt.close() del voltChart gc.collect() return genTime, mapTimestamp
print med, sigG = median_sigmaG(xi) print "mu from median", med print "gamma from quartiles:", sigG / 1.483 # Equation 3.54 #------------------------------------------------------------ # Plot the results fig = plt.figure(figsize=(5, 3.75)) plt.imshow(logL, origin='lower', cmap=plt.cm.binary, extent=(mu[0], mu[-1], gamma[0], gamma[-1]), aspect='auto') plt.colorbar().set_label(r'$\log(L)$') plt.clim(-5, 0) plt.contour(mu, gamma, convert_to_stdev(logL), levels=(0.683, 0.955, 0.997), colors='k') plt.text(0.5, 0.93, r'$L(\mu,\gamma)\ \mathrm{for}\ \bar{x}=0,\ \gamma=2,\ n=10$', bbox=dict(ec='k', fc='w', alpha=0.9), ha='center', va='center', transform=plt.gca().transAxes)
# Set border. Sand falls off grid. if np.any(a[0] != 0) or np.any(a[init['size'] - 1] != 0) or np.any( a[:, 0] != 0) or np.any(a[:, init['size'] - 1] != 0): a[0] = 0 a[init['size'] - 1] = 0 a[:, 0] = 0 a[:, init['size'] - 1] = 0 if np.max(a) > grid_max: grid_max = np.max(a) plt.figure(2) plt.clf() plt.imshow(a) # plt.title('Step Number: {}'.format(i)) plt.clim(0, grid_max) plt.colorbar() plt.show() plt.pause(0.001) print('############## Corners reached ##############') for i in range(init['steps'] + 1): a[init['midsize'], init['midsize']] += 1 shift = spill_shift(init, a) while np.any(shift['down'] >= init['spillsize']) or np.any( shift['up'] >= init['spillsize']) or np.any( shift['left'] >= init['spillsize']) or np.any( shift['right'] >= init['spillsize']): a = grid_shift(init, shift, a)
print(iris.target.shape) print(iris.target_names) print(iris.feature_names) import numpy as np import matplotlib.pyplot as plt x_index = 2 y_index = 0 formater = plt.FuncFormatter(lambda i, *args: iris.target_names[int(i)]) plt.scatter(iris.data[:, x_index], iris.data[:, y_index], c=iris.target, cmap=plt.cm.get_cmap('RdYlBu', 3)) plt.colorbar(ticks=[0, 1, 2], format=formater) plt.clim(-0.5, 2.5) plt.xlabel(iris.feature_names[x_index]) plt.ylabel(iris.feature_names[y_index]) plt.show() from sklearn import neighbors, datasets X, y = iris.data, iris.target # create the model knn = neighbors.KNeighborsClassifier(n_neighbors=3, weights='uniform') # fit the model knn.fit(X, y) # predict a sample
from shapes.shapes3DProj import Shape3, sphereprojfn import numpy as np shp = Shape3() # sphere parameters: radius, density, alpha, beta, gamma (Euler angles) # note for sphere euler angles are not necessary, but this prototype still # requires them shp.addtype(sphereprojfn, [50, 2, 1, 1, 1], bboxdims=[100, 100]) shp.addtype(sphereprojfn, [10, 2, 1, 1, 1], bboxdims=[100, 100]) shp.addunits([200, 200, 340], typeno=0) shp.addunits([300, 200, 300], typeno=1) shp.addunits([400, 200, 300], typeno=0) shp.project() img1 = np.copy(shp.img) # makes a rotation matrix about the [1,1,1] direction mat = rotation_matrix([1, 1, 1], 5. / 57.3) for i in range(100): shp.transform3D(mat) shp.project() print("{}".format(i)) plt.figure(0) plt.cla() plt.imshow(shp.img) plt.figure(1) plt.cla() plt.imshow(shp.fimg2) plt.clim(0, 1e5) plt.draw() plt.pause(.001)
plt.imshow(ferha) plt.colorbar() plt.title(" N inputs from fertilizer (kg N ha-1 yr-1)") plt.subplot(1, 2, 2) plt.imshow(manha) plt.colorbar() plt.title(" N inputs from manure (kg N ha-1 yr-1)") #plt.show() # Critical inputs plt.subplot(3, 2, 1) plt.imshow(mancritswha) plt.colorbar(extend='both') plt.clim(0, 350) plt.title("Manure - surface water quality") plt.subplot(3, 2, 2) plt.imshow(fercritswha) plt.colorbar(extend='both') plt.clim(0, 350) plt.title("Fertilizer - surface water quality") plt.subplot(3, 2, 3) plt.imshow(mancritgwha) plt.colorbar(extend='both') plt.clim(0, 350) plt.title("Manure - groundwater quality") plt.subplot(3, 2, 4)
OSSPSQPLow240 = to_numpy( stir.FloatVoxelsOnCartesianGrid.read_from_file('OSSPS_QP_Low_240.hv')) OSLQPHigh240 = to_numpy( stir.FloatVoxelsOnCartesianGrid.read_from_file('OSL_QP_High_240.hv')) OSSPSQPHigh240 = to_numpy( stir.FloatVoxelsOnCartesianGrid.read_from_file('OSSPS_QP_High_240.hv')) #%% bitmap display of images OSEM vs OSL vs OSSPS maxforplot = OSEM240.max() # pick central slice slice = numpy.int(OSEM240.shape[0] / 2) #%% plt.figure() ax = plt.subplot(1, 4, 1) plt.imshow(OSEM240[slice, :, :, ]) plt.clim(0, maxforplot) plt.colorbar() plt.axis('off') ax.set_title('OSEM\n240 subiters.') ax = plt.subplot(1, 4, 2) plt.imshow(OSLQP240[slice, :, :, ]) plt.clim(0, maxforplot) plt.colorbar() plt.axis('off') ax.set_title('OSL') ax = plt.subplot(1, 4, 3) plt.imshow(OSSPSQP240[slice, :, :, ]) plt.clim(0, maxforplot) plt.colorbar()
plt.pcolormesh(X,Y,EZ1,cmap='plasma',shading='gouraud') elif i == 2: plt.pcolormesh(X,Y,EZ2,cmap='plasma',shading='gouraud') elif i == 3: plt.pcolormesh(X,Y,EZ3,cmap='plasma',shading='gouraud') else: plt.pcolormesh(X,Y,EZ4,cmap='plasma',shading='gouraud') #define plot properties plt.xlabel('X (m)',size=10) plt.ylabel('Y (m)',size=10) plt.title(str(fname[i-1]),size=12) plt.xlim(0.2,0.5) plt.ylim(0.2,0.5) #specify colorbar title using the variable plt.clim(-0.08,0.09) plt.tight_layout() #trim unwanted whitespace in the figure cbar = plt.colorbar(format='%.0e') #assign a variable for colorbar cbar.set_label('Electric Field, Ez (V/m)',rotation=270,size=12,labelpad=15) #print('\nSaving figure in the "Working Folder"') #plt.savefig('New4.png',dpi=200) #save figure in "working folder" #print('\n***figure saved***') plt.gca().set_aspect('equal',adjustable='box') #sets the aspect ratio of the plot plt.subplots_adjust(left=0.225,right=0.9,hspace=0.4,wspace=0.1) plt.show() #show plot
vis_x = vis_data[:, 0] vis_y = vis_data[:, 1] fig, ax = plt.subplots(1) ax.set_yticklabels([]) ax.set_xticklabels([]) plt.scatter(vis_x, vis_y, marker='.', c=reindexed_indexes.numpy(), cmap=plt.cm.get_cmap("jet", 10), alpha=0.5) ax.set_title('Content PCA') plt.axis('off') plt.clim(-0.5, 9.5) plt.show() pca = PCA(n_components=2) vis_data = pca.fit_transform(style_latent_embeddings.data.numpy()) # vis_data = TSNE(n_components=2, verbose=1, perplexity=30.0, n_iter=1000).fit_transform(style_latent_embeddings.data.numpy()) # plot the result vis_x = vis_data[:, 0] vis_y = vis_data[:, 1] fig, ax = plt.subplots(1) ax.set_title('Style PCA') ax.set_yticklabels([]) ax.set_xticklabels([]) plt.scatter(vis_x, vis_y, marker='.',
def process(p_in: Path, acoustic_converter: AcousticConverter, super_resolution: SuperResolution): try: if p_in.suffix in ['.npy', '.npz']: p_in = Path( glob.glob(str(dataset_input_wave_dir / p_in.stem) + '.*')[0]) w_in = acoustic_converter.load_wave(p_in) w_in.wave *= input_wave_scale f_in = acoustic_converter.extract_acoustic_feature(w_in) f_in_effective, effective = acoustic_converter.separate_effective( wave=w_in, feature=f_in) f_low = acoustic_converter.convert_loop(f_in_effective) f_low = acoustic_converter.combine_silent(effective=effective, feature=f_low) if filter_size is not None: f_low.f0 = AcousticConverter.filter_f0(f_low.f0, filter_size=filter_size) f_low = acoustic_converter.decode_spectrogram(f_low) s_high = super_resolution.convert_loop(f_low.sp.astype(numpy.float32)) # target paths = glob.glob(str(dataset_target_wave_dir / p_in.stem) + '.*') has_true = len(paths) > 0 if has_true: p_true = Path(paths[0]) w_true = acoustic_converter.load_wave(p_true) f_true = acoustic_converter.extract_acoustic_feature(w_true) vmin, vmax = numpy.log(f_true.sp).min(), numpy.log(f_true.sp).max() else: vmin, vmax = None, None # save figure fig = plt.figure(figsize=[36, 22]) plt.subplot(4, 1, 1) plt.imshow(numpy.log(f_in.sp).T, aspect='auto', origin='reverse') plt.plot(f_in.f0, 'w') plt.colorbar() plt.clim(vmin=vmin, vmax=vmax) plt.subplot(4, 1, 2) plt.imshow(numpy.log(f_low.sp).T, aspect='auto', origin='reverse') plt.plot(f_low.f0, 'w') plt.colorbar() plt.clim(vmin=vmin, vmax=vmax) plt.subplot(4, 1, 3) plt.imshow(numpy.log(s_high).T, aspect='auto', origin='reverse') plt.colorbar() plt.clim(vmin=vmin, vmax=vmax) if has_true: plt.subplot(4, 1, 4) plt.imshow(numpy.log(f_true.sp).T, aspect='auto', origin='reverse') plt.plot(f_true.f0, 'w') plt.colorbar() plt.clim(vmin=vmin, vmax=vmax) fig.savefig(output / (p_in.stem + '.png')) # save wave f_low_sr = BYAcousticFeature( f0=f_low.f0, spectrogram=f_low.sp, aperiodicity=f_low.ap, mfcc=f_low.mc, voiced=f_low.voiced, ) rate = acoustic_converter.out_sampling_rate wave = super_resolution.convert_to_audio(s_high, acoustic_feature=f_low_sr, sampling_rate=rate) librosa.output.write_wav(y=wave.wave, path=str(output / (p_in.stem + '.wav')), sr=rate) except: import traceback traceback.print_exc()
nlevs = len(clevs) - 1 cmap = plt.get_cmap(name='pyart_NWSRef', lut=nlevs) pm = plt.pcolormesh(R_gpm / 1000., y, d0_nan, cmap='pyart_NWSRef', vmin=vmin, vmax=vmax) pm2 = plt.plot(R_gpm / 1000., zero_deg_isotherm, '--', color='k') plt.xlabel('Along Track Distance (km)', size=20) plt.ylabel('Altitude (km)', size=20) plt.title(r'GPM Overpass 7/31 0838-1011 UTC $D_{M}$ ', size=20) plt.xlim(dist[0], dist[1]) plt.ylim(0, 15) plt.colorbar().set_label(label='[mm]', size=18) plt.clim(0, 3) plt.text(x_loc, y_loc, label) plt.show() ####Number concentration (liquid water content) plt.figure(figsize=(10, 10)) vmax = 70 vmin = 0 R_min = R_gpm.min() R_max = R_gpm.max()
if first: cmin = np.amin(data) cmax = np.amax(data) if 'eta' in filename: cmin = 1e-4 cmax = -1e-4 #cmin *= 1.2 #cmax *= 1.2 plt.figure(figsize=figsize) #plt.imshow(data, interpolation='nearest', extent=extent, origin='lower', aspect='auto') plt.imshow(data, interpolation='nearest', origin='lower', aspect='auto', cmap=plt.get_cmap('seismic')) plt.clim(cmin, cmax) cbar = plt.colorbar() cbar.ax.tick_params(labelsize=fontsize) plt.title(filename, fontsize=fontsize) if 'diag_vort' in filename: # plt.contour(data, colors="black", origin='lower', extent=extent, vmin=cmin, vmax=cmax, levels=eta_contour_levels, linewidths=0.5) plt.contour(data, colors="black", origin='lower', vmin=cmin, vmax=cmax, levels=eta_contour_levels, linewidths=0.5) elif 'prog_h' in filename: #plt.contour(data, colors="black", origin='lower', extent=extent, vmin=cmin, vmax=cmax, levels=h_contour_levels, linewidths=0.5) plt.contour(data, colors="black", origin='lower', vmin=cmin, vmax=cmax, levels=h_contour_levels, linewidths=0.5) # elif '_u' in filename: # hs = 0.001
def plotLocus(df, color=0, save=0, type="", timestamp=""): if color: plt.figure(figsize=(8, 8)) plt.scatter(df["i-z"], df["g-r"], c=df["7DCD"], s=2, alpha=0.8, norm=matplotlib.colors.LogNorm()) plt.xlim(-0.75, 1) plt.clim(0.1, 1000) plt.ylim(-0.5, 2) plt.xlabel("i-z") plt.ylabel("g-r") cbar = plt.colorbar() cbar.set_label("3D Color Distance") if save: plt.savefig("PS1_%s_StellarLocus_%s_Colored.pdf" % (type, timestamp)) else: plt.show() else: #read the stellar locus table from PS1 skt = at.Table.read('./tonry_ps1_locus.txt', format='ascii') gr = scinterp.interp1d(skt['ri'], skt['gr'], kind='cubic', fill_value='extrapolate') iz = scinterp.interp1d(skt['ri'], skt['iz'], kind='cubic', fill_value='extrapolate') zy = scinterp.interp1d(skt['ri'], skt['zy'], kind='cubic', fill_value='extrapolate') ri = np.arange(-0.4, 2.01, 0.001) gr_new = gr(ri) iz_new = iz(ri) if type == 'Gals': c = '#087e8b' elif type == "Stars": c = '#ffbf00' else: c = 'violet' g = sns.JointGrid(x="i-z", y="g-r", data=df, height=9, ratio=5, xlim=(-0.4, 0.8), ylim=(-0.2, 2.0), space=0) g = g.plot_joint(sns.kdeplot, color=c, gridsize=200) plt.plot(iz_new, gr_new, '--', c='#8c837c', lw=2) plt.xlabel(r"$i-z$", fontsize=18) plt.ylabel(r"$g-r$", fontsize=18) g = g.plot_marginals(sns.kdeplot, color=c, shade=True) if save: g.savefig("PS1_%s_StellarLocus_%s.pdf" % (type, timestamp))
distances = distances / 0.704 #kpc R_stellar = stellar_mass_min / stellar_mass_max R_DM = DM_mass_min / DM_mass_max path_to_save_ims = path_to_save + 'newImages/' makedir(path_to_save_ims) #plot 1: 2D histogram of radial and tangential velocity f1 = plt.figure() plt.subplot(211) plt.hist2d(tangential_vels, radial_vels, norm=mpl.colors.LogNorm(), bins=64) plt.xlim([0, 200]) plt.ylim([-200, 100]) plt.colorbar() plt.clim(1e0, 1e4) someX, someY = 0, -127 currentAxis = plt.gca() currentAxis.add_patch(Rectangle((someX, someY), 22, 8, fill=None, alpha=1)) plt.text(15, -100, s='M31-MW', fontsize=10) plt.xlabel('Tangential Velocity [km/s]', fontsize=10) plt.ylabel('Radial Velocity [km/s]', fontsize=10) plt.title(sample + ' distribution of velocities after ' + args.vis_step, fontsize=12) #print('cociente dM: ',R_DM) #plot 2: 2D histogram of mass ratio stellar y DM plt.subplot(212) plt.hist2d(R_DM, R_stellar, norm=mpl.colors.LogNorm(), bins=64) someX, someY = 0.435, 0.472 currentAxis = plt.gca()
def traj_plot_monthly(state, month, seaice_, levels=[ '780', '1000', '1400', '1850', '2850', '3950', '5220', '6730', '8600' ]): """Function to plot monthly clear or cloudy state plots with option of monthly seaice data. Arguments: state, month, masked seaice, levels to be plotted as a list levels = ['780', '1000', '1400', '1850', '2850', '3950', '5220', '6730', '8600'] """ # Extract seaice concentration value based on month # Better to ask user to give the sea ice data with proper masking path = 'H:/IUP/Student_job_AWI/Ollie_data/traj_sheba_sounding/winter_all/' # checking for clear or cloudy if (state == 'cloudy'): dates_ = open( 'C:\\Users\\Mub\\Documents\\Python_AWI\\Avg_dates\\3havg_cloudy_' + month, 'r').read().split('\n') else: dates_ = open( 'C:\\Users\\Mub\\Documents\\Python_AWI\\Avg_dates\\3havg_clear_' + month, 'r').read().split('\n') # specifying the levels or ask user to give levels as a list #levels = ['780', '1000', '1400', '1850', '2850', '3950', '5220', '6730', '8600'] for lvl in levels: #to loop over all levels fig = plt.figure(figsize=(12, 10)) # plt.figure(figsize=(10,8)) m = Basemap(projection='ortho', lat_0=80, lon_0=270, resolution='l') m.fillcontinents(color='0.75') m.drawparallels(np.arange(-80., 81., 20.), color='grey') m.drawmeridians(np.arange(-180., 181., 20.)) m.pcolormesh(lon_ice, lat_ice, seaice_, latlon=True, cmap='Blues') plt.clim(0, 100) # Set the color limits of the current image plt.colorbar(label='Sea Ice Concentration') # inner loop for plotting all the trajectories on one map # read the monthly file for line_ in dates_: df = pd.read_csv(path + 'tdump_' + lvl + '_' + line_, skiprows=7, header=None, delim_whitespace=True) lat = np.array(df.iloc[:, 9].copy()) lon = np.array(df.iloc[:, 10].copy()) #Convert lat lon to map coordinates x, y = m(lon, lat) #Plot the points on the map plt.plot(x, y, linewidth=1.0, color='red') #source point xpt, ypt = m(lon[-1], lat[-1]) plt.plot(xpt, ypt, marker='*', markerfacecolor='red', markersize=8) plt.title("Level: {} m AGL".format(lvl)) plt.savefig(path1 + lvl + '_' + state + month + '_test_level.png') plt.close(fig)
# evalute it in a vectorized way (and reshape into a matrix) data = expand(x, y) z = f(data, thetaFinal) z = z.reshape(x.shape) #Prints scatter plot of data plt.figure(1) plt.title("Gradient Descent w/ Quadratic Features: Synthetic-6") plt.scatter(trainData1[:, 0], trainData1[:, 1], c=trainData1[:, 2], alpha=0.5) # show the function value in the background plt.set_cmap('prism') cs = plt.imshow( z, extent=(x_min, x_max, y_max, y_min), # define limits of grid, note reversed y axis cmap=plt.cm.jet) plt.clim(0, 1) # defines the value to assign the min/max color # draw the line on top levels = np.array([.5]) cs_line = plt.contour(x, y, z, levels) # add a color bar CB = plt.colorbar(cs) plt.show() #Misclassification rate p = predict(thetaFinal, finalDataQuad, labels) print("The misclassification rate is ", 1 - p, " %")
def SPDC(wavep, angle, L, distz, wp): wavep = wavep / 1000.0 # wavelength of pump field in 405nm ### angle = 28.9 # Angle in degree thetap = np.radians(angle) # thetap in radians45.64, 42.58 40.5 42.148 L = L * 1000.00 # Crystal thickness in 2mm distz = distz * 10000.0 # distz in cm 100cm , wp in um ######################################## #*******Dispersion relation o ray*************** def noo(n): global wavep n2 = 2.7405 + ((0.0184) / ((n**2) - 0.0179)) - (0.0155 * n**2) rio = round(math.sqrt(n2), 4) return rio #********Dispersion relation e ray*************** def neo(n): global wavep n2 = 2.3730 + ((0.0128) / ((n**2) - 0.0156)) - (0.0044 * n**2) rio = round(math.sqrt(n2), 4) return rio ############################################# #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #####Two photon wavefunction############## def two_photon_wavefunction(xs, ys, xi, yi, wp): ss = (np.square(xs) + np.square(ys)) + (np.square(xi) + np.square(yi)) + ( 2 * np.sqrt((np.square(xs) + np.square(ys)) * (np.square(xi) + np.square(yi))) * np.cos(np.arctan2(ys, xs) - np.arctan2(yi, xi))) kp = (2 * (np.pi)) / wavep kpz = (kp * etap) + (alphap * (xs + xi)) - ( (1 / (2 * kp * etap)) * (np.square(betap * (xs + xi)) + np.square(gammap * (ys + yi)))) ksz = (kp * nobar / 2) - ((1 / (kp * nobar)) * (np.square(xs) + np.square(ys))) kiz = (kp * nobar / 2) - ((1 / (kp * nobar)) * (np.square(xi) + np.square(yi))) tmp = ((ksz + kiz - kpz) * (L / 2)) #------------------------------------------------------------------------------------- ksze = ((kp / 2.0) * etas) + (alphas * (xs)) - ( (1 / (kp * etas)) * (np.square(betas * xs) + np.square(gammas * ys))) tmpeo = ((ksze + kiz - kpz) * (L / 2)) #---------------------------------------------------------------------------------------------- kize = ((kp / 2.0) * etai) + (alphai * (xi)) - ( (1 / (kp * etai)) * (np.square(betai * xi) + np.square(gammai * yi))) tmpoe = ((ksz + kize - kpz) * (L / 2)) #-------------------------------------------------------------------------------------------- pumpfield = np.exp(-(wp**2 + ((2j) * (distz / (kp * etap)))) * (ss / 4.0)) fullfunction = pumpfield * ( (np.sinc(tmpeo / (np.pi)) * np.exp(-1.0j * tmpeo)) + (np.sinc(tmpoe / (np.pi)) * np.exp(-1.0j * tmpoe)) + (np.sinc(tmp / (np.pi)) * np.exp(-1.0j * tmp))) return fullfunction #----------------------------------------------------- #*************************************************** if angle <= 41.0: rho = 0.6 elif angle > 41 and angle < 41.5: rho = 0.8 elif angle >= 41.5 and angle < 41.8: rho = 0.9 elif angle > 41.8 and angle < 45: rho = 1.0 elif angle >= 45.0 and angle < 50.0: rho = 1.5 elif angle >= 50.0 and angle < 65.0: rho = 2.0 elif angle >= 65: rho = 2.8 ###print (rho) ###rho=2.8 grdpnt = 200 dx = (2 * rho / grdpnt) xs, ys = np.meshgrid(np.linspace(-rho, rho, grdpnt), np.linspace(-rho, rho, grdpnt)) # alpha ,beta ,gamma, eta *********************** no = noo(wavep) ne = neo(wavep) den = np.square(no * np.sin(thetap)) + np.square(ne * np.cos(thetap)) alphap = ((np.square(no) - np.square(ne)) * (np.sin(thetap)) * (np.cos(thetap))) / den betap = (no * ne) / den gammap = no / math.sqrt(den) etap = ne * gammap nobar = noo(2 * wavep) #------------------8888888888888------------------------ nos = noo(2 * wavep) nes = neo(2 * wavep) thetas = thetap - np.arctan2(ys, xs) dens = np.square(nos * np.sin(thetap)) + np.square(nes * np.cos(thetap)) alphas = ((np.square(nos) - np.square(nes)) * (np.sin(thetap)) * (np.cos(thetap))) / dens betas = (nos * nes) / dens gammas = nos / np.sqrt(dens) etas = nes * gammas nobar = noo(2 * wavep) ###etapp = (no*ne)/math.sqrt(den) #########For wavefunction(e --> oo) ################### funcmat = np.zeros([grdpnt, grdpnt]) funcmat1 = np.zeros([grdpnt, grdpnt]) for k in np.arange(-5, 5): for m in np.arange(-5, 5): #//////////////////////////////////////////////////////// noi = noo(2 * wavep) nei = neo(2 * wavep) thetai = thetap + np.arctan2(-ys + m * dx, -xs + k * dx) deni = np.square(noi * np.sin(thetap)) + np.square( nei * np.cos(thetap)) alphai = ((np.square(noi) - np.square(nei)) * (np.sin(thetap)) * (np.cos(thetap))) / deni betai = (noi * nei) / deni gammai = noi / np.sqrt(deni) etai = nei * gammai nobar = noo( 2 * wavep ) #88888888888888__________________----************************////////////////////// funcmat = funcmat + (np.square( np.absolute( two_photon_wavefunction(xs, ys, -xs + k * dx, -ys + m * dx, wp)))) * dx * dx plt.imshow(funcmat) plt.colorbar() plt.clim(0.0000001, 0.000045) # (0.0000001,0.000045) plt.title('Angle =%g' % (angle)) ##__________________________________________________________________________________________________## if not os.path.isdir('static'): os.mkdir('static') else: # Remove old plot files for filename in glob.glob(os.path.join('static', '*.png')): os.remove(filename) # Use time since Jan 1, 1970 in filename in order make # a unique filename that the browser has not chached plotfile = os.path.join('static', str(time.time()) + '.png') plt.savefig(plotfile) plt.cla() plt.clf() return plotfile
def plot(self, title="", ptype="Temperature", savefig=None): ''' Plots the grid. Args: + title (str): Title fo the plot. Default ''. + ptype (str): The type of plot to make, default "Temperature". The input string is *not* case sensitive! Options: - "Temperature" - "Albedo" - "Pops" or "Populations" + savefig (string or None): if a string, saves the figure to that location. If None, does nothing (should display if the user calls plt.show() after this method. ''' plt.figure() ptype = ptype.lower() if ptype == "temperature": # Plot the grid temps = [] only_parcels = [] for row in self.grid: temprow = [] for area in row: temprow.append(area.Teff) if isinstance(area, Parcel): only_parcels.append(area.Teff) temps.append(temprow) plt.imshow(temps, extent=[0, 360, -self.maxtheta, self.maxtheta], aspect='equal') plt.colorbar() plt.clim(240, 320) plt.clim(np.amin(only_parcels), np.amax(only_parcels)) plt.title(title) plt.xlabel("Longitude [deg]") plt.ylabel("Latitude [deg]") plt.grid(b=False) elif ptype == "albedo": # Plot the grid albedos = [] only_parcels = [] for row in self.grid: temprow = [] for area in row: temprow.append(area.A) # Get parcels only for the colorbar if isinstance(area, Parcel): only_parcels.append(area.A) albedos.append(temprow) plt.imshow(albedos, extent=[0, 360, -self.maxtheta, self.maxtheta], aspect='equal', cmap='gray') plt.colorbar() plt.clim(np.amin(only_parcels), np.amax(only_parcels)) plt.title(title) plt.xlabel("Longitude [deg]") plt.ylabel("Latitude [deg]") plt.grid(b=False) elif ptype in ['pops', 'population']: # Plot the grid pops = [] only_parcels = [] for row in self.grid: temprow = [] for area in row: # Get parcels to get pops and for colorbar not including # the ground. if isinstance(area, Parcel): only_parcels.append(np.sum(area.a_vec[:-1])) temprow.append(np.sum(area.a_vec[:-1])) else: temprow.append(0.) pops.append(temprow) plt.imshow(pops, extent=[0, 360, -self.maxtheta, self.maxtheta], aspect='equal', cmap='gray') plt.colorbar() plt.clim(np.amin(only_parcels), np.amax(only_parcels)) plt.title(title) plt.xlabel("Longitude [deg]") plt.ylabel("Latitude [deg]") plt.grid(b=False) elif ptype in [str(_d) for _d in range(len(self.a_vec))]: # Plot the grid pops = [] only_parcels = [] for row in self.grid: temprow = [] for area in row: # Get parcels to get pops and for colorbar not including # the ground. if isinstance(area, Parcel): only_parcels.append(np.sum(area.a_vec[int(ptype)])) temprow.append(np.sum(area.a_vec[int(ptype)])) else: temprow.append(0.) pops.append(temprow) plt.imshow(pops, extent=[0, 360, -self.maxtheta, self.maxtheta], aspect='equal', cmap='gray') plt.colorbar() plt.clim(np.amin(only_parcels), np.amax(only_parcels)) plt.title(title) plt.xlabel("Longitude [deg]") plt.ylabel("Latitude [deg]") plt.grid(b=False) else: # Incorrect plot type passed raise ValueError("Unrecognized ptype passed. Please select from" " the options listed in the documentation.") if savefig is not None: # Save the figure plt.gcf().savefig(savefig) plt.close(plt.gcf())
#-------------------- # First axes: ax = plt.subplot(131, xticks=[4000, 5000, 6000, 7000, 8000]) plt.imshow(np.log10(N.T), origin='lower', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], aspect='auto', interpolation='nearest', cmap=cmap) plt.xlim(xedges[-1], xedges[0]) plt.ylim(yedges[-1], yedges[0]) plt.xlabel(r'$\mathrm{T_{eff}}$') plt.ylabel(r'$\mathrm{log(g)}$') cb = plt.colorbar(ticks=[0, 1, 2, 3], pad=0.2, format=r'$10^{%i}$', orientation='horizontal') cb.set_label(r'$\mathrm{number\ in\ pixel}$') plt.clim(0, 3) #-------------------- # Second axes: ax = plt.subplot(132, xticks=[4000, 5000, 6000, 7000, 8000]) plt.imshow(FeH_mean.T, origin='lower', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], aspect='auto', interpolation='nearest', cmap=cmap) plt.xlim(xedges[-1], xedges[0]) plt.ylim(yedges[-1], yedges[0]) plt.xlabel(r'$\mathrm{T_{eff}}$') cb = plt.colorbar(ticks=np.arange(-2.5, 1, 1), pad=0.2, format=r'$%.1f$', orientation='horizontal') cb.set_label(r'$\mathrm{mean\ [Fe/H]\ in\ pixel}$') plt.clim(-2.5, 0.5)
o2.run(steps=20) #%% # Store final field of x-component of (convolved) current convolved_current = reader_norkyst.var_block_after[ "['x_sea_water_velocity', 'y_sea_water_velocity']"].data_dict[ 'x_sea_water_velocity'] plt.subplot(2, 1, 1) plt.imshow(original_current, interpolation='nearest') plt.title('Original current field (x-component)') clim = plt.gci().get_clim() plt.colorbar() plt.subplot(2, 1, 2) plt.imshow(convolved_current, interpolation='nearest') plt.clim(clim) # Make sure plots are comparable plt.colorbar() plt.title('Final, convolved current field (x-component)') plt.show() #%% # Print and plot results, with convolved currents as background print(o) o.animation(compare=o2, fast=True, legend=[ 'Original currents', 'Current convoled with kernel of size %s' % N ], background=['x_sea_water_velocity', 'y_sea_water_velocity'])
## W Linop print("Define W Linop") W = sp.linop.Wavelet(img_shape) wav = W * S.H * F.H * ksp #pl.ImagePlot(wav**0.1, title=r'$W S^H F^H y$') print(np.amax(np.abs(wav))) print(np.amin(np.abs(wav))) print(np.shape(wav)) plt.figure(1) lala = ksp[0, :, :, 160] print(np.shape(lala)) plt.imshow(np.abs(wav[:, :, 160])) plt.clim(0.0001, 0.001) plt.show() pl.ImagePlot(wav, title=r'$W S^H F^H y$') A = P * F * S * W.H ## Prox print("Define Prox") lamda = 0.005 proxg = sp.prox.L1Reg(wav.shape, lamda) alpha = 1 wav_thresh = proxg(alpha, wav) pl.ImagePlot(wav_thresh**0.1)
task_node = np.where(task_patterns == np.max(task_patterns))[1] hidden_byTask = np.zeros((task_units, hidden_units)) # could use any test_hidden that has been logged for node in range(task_units): hidden_byTask[node, :] = np.mean(test_hidden[task_node == node, :], axis=0) task_corrMat = np.corrcoef(hidden_byTask) plt.figure('Hidden Representation Similarity ST') plt.imshow(task_corrMat, cmap='rainbow', interpolation='nearest') plt.colorbar() plt.clim(-1, 1) plt.xticks(np.arange(task_units)) plt.yticks(np.arange(task_units)) plt.show() #%% Export variables import pickle with open('singleTasks.pickle', 'wb') as handle: pickle.dump([ units_perdim, input_dim, output_dim, w_IH_log, w_HO_log, w_TH_log, w_TO_log, bias_H, bias_O ], handle, protocol=pickle.HIGHEST_PROTOCOL)
# AcquisitionData are organised by sinograms, so we need to use the first index # of the accquisition_array. plt.figure() slice_num = acquisition_array.shape[0] / 2 imshow(acquisition_array[slice_num, :, :, ], [], 'Forward projection') #%% Display some different 'views' in a movie # See note at start of file about your backend if this doesn't work. bitmaps = [] fig = plt.figure() # views are the second index in the data num_views = acquisition_array.shape[1] # first construct all the plots for view in range(0, num_views, 4): bitmap = plt.imshow(acquisition_array[:, view, :, ]) plt.clim(0, acquisition_array.max()) plt.axis('off') bitmaps.append([bitmap]) # Display as animation ani = animation.ArtistAnimation(fig, bitmaps, interval=100, blit=True, repeat_delay=1000) #%% Let's do a back-projection # Backprojection uses the transpose of the forward-projection matrix to # go from AcquisitionData to an ImageData backprojected = am.backward(acquired_data) # let's display a slice plt.figure()
for yidx, deps in enumerate(list(x)): plt.text(X_idx[xidx][yidx], Y_idx[xidx][yidx] - 2.2 * sc, round(deps, 1), ha="center", va="bottom", bbox=dict( boxstyle="square", ec=(1., 0.5, 0.5), fc=(1., 0.8, 0.8), )) plt.colorbar(shrink=0.5, aspect=10, label="cumulative stress over gait") plt.clim(0, 200) plt.xticks(X_idx.T[0], [round(x, 1) for x in X2]) plt.yticks(Y_idx[0], [round(x, 1) for x in X1]) plt.xlabel('steering $q_2$') plt.ylabel('step length $q_1$') plt.axis('scaled') plt.grid() ax = fig.gca() ax.spines['top'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) # plt.axis('off')
def show_array_as_image(arr): plt.imshow(arr, cmap='gray') plt.clim(0, 1)
num = np.arange(0,999+1) for i in range(len(num)): name = prefix + str(num[i]).zfill(4) + ".h5" print("start process ", name) f = h5.File(name) PR = np.array(f['PR']) PX = np.array(f['Pposition']) px = PX[0:-2:3] py = PX[1:-1:3] Nx = int(f['Nx'][0]) Ny = int(f['Ny'][0]) con = np.array(f['Con']) con = con.reshape((Ny,Nx)) ax = plt.figure().add_subplot(111) plt.pcolormesh(con, shading='gouraud',cmap='jet') plt.clim(vmin=0, vmax=20) for j in range(np.size(PX)/6): ppx = px[j] ppy = py[j] cir = Circle(xy=(ppx,ppy), radius=PR[j]-d, alpha=1.0, facecolor='k') ax.add_patch(cir) plt.axis('equal') plt.axis('off') plt.tight_layout() name = 'c' + str(i) + '.jpg' plt.savefig(name, dpi=500) plt.clf() plt.close()
def main(): #"what is start time?" start = 0 #"what is end time?" end = 2 #"what is slow time?, .01" slow = 0.002 #0.01 # #"what is fast time?, .001" fast = 0.007 #0.001 # #"what is sample rate?, 1" SampleRateRedux = 1 #"what is the pipe?, 01, 02, 03 , ... (H=01, S=02, ...)" pipe = 1 #"what Mic?, 1, 2, 3, 4, 5, 6 " inital = 3 #"start Take?, 1, 2, 3, 4, 5, 6, 7" startPos = 1 #"end Take?, 1, 2, 3, 4, 5, 6, 7" endPos = 7 cfd = os.path.abspath(__file__) #basepath = '/media/TerraSAR-X/Acoustics/data/20171115_cropped_NNC_R' basepath = '/media/TerraSAR-X/Acoustics/data/20171115_cropped_NNC_JPI1' print "the data is taken from :" print basepath os.chdir(basepath) fillist = os.listdir(basepath) fillist.sort() nbr = len([ name for name in os.listdir(basepath) if os.path.isfile(os.path.join(basepath, name)) ]) rounds = {} #creates dictionary segmented by mic for x in range(1, 9): rounds['mi{0}'.format(x)] = [ k for k in fillist if 'mi{0}'.format(x) in k ] sub1 = rounds['mi{0}'.format(inital)] print sub1 pipes1 = {} #creates dictionary of take 1 segmented by pipes (takes) for x in range(1, 9): pipes1['pi{0}'.format(x)] = [k for k in sub1 if 'pi{0}'.format(x) in k] print pipes1['pi{0}'.format(pipe)] sub11 = pipes1['pi{0}'.format(pipe)] lfile1 = {} for k in range(startPos - 1, endPos): lfile1['log{0}'.format(k)] = read(sub11[k]) fafotr1 = {} for o in range(startPos - 1, endPos): ttMat, fftt, fafotr1['fftt{0}'.format(o)] = syntheticAperture( start, end, slow, fast, lfile1['log{0}'.format(o)], SampleRateRedux) print ' ' print "the number of files in the full directory is: {0}".format(nbr) print 'energy difference between takes for microphone {0}'.format(inital) print ' ' print 'start: {0}'.format(start) print 'end: {0}'.format(end) print 'slow: {0}'.format(slow) print 'fast: {0}'.format(fast) print 'SampleRateRedux: {0}'.format(SampleRateRedux) print 'pipe: {0}'.format(pipe) print 'microphone: {0}'.format(inital) print 'start take: {0}'.format(startPos) print 'end take: {0}'.format(endPos) print ' ' row1 = fafotr1['fftt{0}'.format(startPos)].shape[0] col1 = fafotr1['fftt{0}'.format(startPos)].shape[1] energyMat = np.zeros((row1, col1), dtype=complex) eAvgMat = np.zeros((endPos - startPos + 1, endPos - startPos + 1), dtype=complex) for q in range(0, endPos - startPos + 1): for p in range(0, endPos - startPos + 1): for i in range(0, row1): for j in range(0, col1): mat1 = fafotr1['fftt{0}'.format(q)] mat2 = fafotr1['fftt{0}'.format(p)] energyMat[i, j] = 20 * np.abs( (np.log10(np.linalg.norm(mat1[i, j])) - np.log10(np.linalg.norm(mat2[i, j])))) eAvgMat[q, p] = np.average(energyMat) print eAvgMat im = plt.imshow(abs(eAvgMat), interpolation='none', cmap=cm.coolwarm) plt.clim(0, 4) plt.suptitle('ner diff b/t takes for microphone {0}'.format(inital), fontsize=15) plt.colorbar(im, cmap=cm.hot) plt.show()
def pacplot(self, pac, xvec, yvec, xlabel='', ylabel='', cblabel='', title='', cmap='viridis', vmin=None, vmax=None, under=None, over=None, bad=None, pvalues=None, p=0.05, interp=None, rmaxis=False, dpaxis=False, plotas='imshow', ncontours=5, levels=None, levelcmap='Reds', polar=False, y=1.02, subplot=111): """Main plotting pac function. This method can be used to plot any 2D array. Parameters ---------- pac : array_like A 2D array. xvec : array_like The vector to use for the x-axis. yvec : array_like The vector to use for the y-axis. xlabel : string | '' Label for the x-axis. ylabel : string | '' Label for the y-axis. cblabel : string | '' Label for the colorbar. title : string | '' Title of the plot. y : float | 1.02 Title location. cmap : string | 'viridis' Name of one Matplotlib's colomap. vmin : float | None Threshold under which set the color to the uner parameter. vmax : float | None Threshold over which set the color in the over parameter. under : string | 'gray' Color for values under the vmin parameter. over : string | 'red' Color for values over the vmax parameter. bad : string | None Color for non-significant values. pvalues : array_like | None P-values to use for masking PAC values. The shape of this parameter must be the same as the shape as pac. p : float | .05 If pvalues is pass, use this threshold for masking non-significant PAC. interp : tuple | None Tuple for controlling the 2D interpolation. For example, (.1, .1) will multiply the number of row and columns by 10. rmaxis : bool | False Remove unecessary axis. dpaxis : bool | False Despine axis. plotas : {'imshow', 'contour', 'pcolor'} Choose how to display the comodulogram, either using imshow ('imshow') or contours ('contour'). If you choose 'contour', use the ncontours parameter for controlling the number of contours. ncontours : int | 5 Number of contours if plotas is 'contour'. levels : list | None Add significency levels. This parameter must be a sorted list of p-values to use as levels. levelcmap : string | Reds Colormap of signifiency levels. Returns ------- gca: axes The current matplotlib axes. """ # Check if pac is 2 dimensions : if pac.ndim is not 2: raise ValueError("The PAC variable must have two dimensions.") # Try import matplotlib : try: import matplotlib.pyplot as plt except: raise ValueError("Matplotlib not installed.") # Define p-values (if needed) : if pvalues is None: pvalues = np.zeros_like(pac) # 2D interpolation (if needed) if interp is not None: pac, xvec, yvec = mapinterpolation(pac, xvec, yvec, interp[0], interp[1]) pvalues = mapinterpolation(pvalues, self.xvec, self.yvec, interp[0], interp[1])[0] pac = np.ma.masked_array(pac, mask=pvalues >= p) # Polar plot : if polar: plotas = 'pcolor' plt.subplot(subplot, projection='polar') # Check vmin / vmax if (vmin is None) and (vmax is None) and self._autovmM: vmin, vmax = min(0, np.nanmin(pac)), max(0, np.nanmax(pac)) if vmin < 0 and vmax > 0: vmax = max(vmax, -vmin) vmin = -vmax # Plot type : toplot = pac.data if levels is not None else pac if plotas is 'imshow': im = plt.imshow(toplot, aspect='auto', cmap=cmap, origin='upper', vmin=vmin, vmax=vmax, interpolation='none', extent=[xvec[0], xvec[-1], yvec[-1], yvec[0]]) plt.gca().invert_yaxis() elif plotas is 'contour': im = plt.contourf(xvec, yvec, toplot, ncontours, cmap=cmap, vmin=vmin, vmax=vmax) elif plotas is 'pcolor': im = plt.pcolormesh(xvec, yvec, toplot, cmap=cmap, vmin=vmin, vmax=vmax, antialiased=True) else: raise ValueError("The plotas parameter must either be 'imshow' or " "'contour'") # Add levels : if levels is not None: plt.contour(pvalues, extent=[xvec[0], xvec[-1], yvec[0], yvec[-1]], levels=levels, cmap=levelcmap) # Under/Over/Bad : if under is not None: im.cmap.set_under(color=under) if over is not None: im.cmap.set_over(color=over) if bad is not None: im.cmap.set_bad(color=bad) # Title/Xlabel/Ylabel : plt.axis('tight') plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title, y=y) plt.clim(vmin=vmin, vmax=vmax) # Colorbar cb = plt.colorbar(im, shrink=0.7, pad=0.01, aspect=10) cb.set_label(cblabel) cb.outline.set_visible(False) ax = plt.gca() # Remove axis : if rmaxis: for loc, spine in ax.spines.items(): if loc in ['top', 'right']: spine.set_color('none') ax.tick_params(**{loc: False}) # Despine axis : if dpaxis: for loc, spine in ax.spines.items(): if loc in ['left', 'bottom']: spine.set_position(('outward', 10)) spine.set_smart_bounds(True) return plt.gca()
###### plot the temperature distribution ke_salinity_plot = plt.figure() # create the figure # for some reason it wants all the dimensions to be square, so plot everything up to 75 # plt.pcolormesh(ke_time[0:75],ke_depth[0:75],ke_salinity_data[0:75,:]) plt.pcolormesh( ke_time, ke_depth, ke_temp_data.T) # need to transpose the matrix data! then all is good print("ke" + str(ke_time.shape)) ke_salinity_plot.show() plt.gca().invert_yaxis() # inverts the depth axis plt.title('Temp from model', fontsize=30) plt.xlabel('Time', fontsize=20) plt.ylabel('Depth', fontsize=20) cb = plt.colorbar() cb.ax.tick_params(labelsize=35) plt.clim(None) # to set the colour bar limits pylab.ylim([150, 0]) # set the y axis limits plt.tick_params(labelsize=35) # plt.set_cmap('gray') # set the plot to grayscale for SASAS paper # print(ke_salinity_data[0:2,:]) # plt.show() ############################### # # ########################################################## # # testing the observed data from PAPA # # get temp # ttemper = fh11.variables['T_20'][:] # # print(ttemper.shape) # # print(ttemper) # # print(fh10)