def plot_wave_coherence(wave1, wave2, sample_times, min_freq=1, max_freq=256, sig=False, ax=None, title="Wavelet Coherence", plot_arrows=True, plot_coi=True, plot_period=False, resolution=12, all_arrows=True, quiv_x=5, quiv_y=24, block=None): """ Calculate wavelet coherence between wave1 and wave2 using pycwt. TODO fix min_freq, max_freq and add parameters to control arrows. TODO also test out sig on a large dataset Parameters ---------- wave1 : np.ndarray The values of the first waveform. wave2 : np.ndarray The values of the second waveform. sample_times : np.ndarray The times at which waveform samples occur. min_freq : float Supposed to be minimum frequency, but not quite working. max_freq : float Supposed to be max frequency, but not quite working. sig : bool, default False Optional Should significance of waveform coherence be calculated. ax : plt.axe, default None Optional ax object to plot into. title : str, default "Wavelet Coherence" Optional title for the graph plot_arrows : bool, default True Should phase arrows be plotted. plot_coi : bool, default True Should the cone of influence be plotted plot_period : bool Should the y-axis be in period or in frequency (Hz) resolution : int How many wavelets should be at each level of the graph all_arrows : bool Should phase arrows be plotted uniformly or only at high coherence quiv_x : float sets quiver window in time domain in seconds quiv_y : float sets number of quivers evenly distributed across freq limits block : [int, int] Plots only points between ints. Returns ------- tuple : (fig, result) Where fig is a matplotlib Figure and result is a tuple consisting of WCT, aWCT, coi, freq, sig WCT - 2D numpy array with coherence values aWCT - 2D numpy array with same shape as aWCT indicating phase angles coi - 1D numpy array with a frequency value for each time freq - 1D numpy array with the frequencies wavelets were calculated at sig - 2D numpy array indicating where data is significant by monte carlo """ t = np.asarray(sample_times) dt = np.mean(np.diff(t)) # Set up the scales to match min max input frequencies dj = resolution s0 = min_freq * dt if s0 < 2 * dt: s0 = 2 * dt max_J = max_freq * dt J = dj * np.int(np.round(np.log2(max_J / np.abs(s0)))) # freqs = np.geomspace(max_freq, min_freq, num=50) freqs = None # Do the actual calculation print("Calculating coherence...") start_time = time.time() WCT, aWCT, coi, freq, sig = wavelet.wct( wave1, wave2, dt, # Fixed params dj=(1.0 / dj), s0=s0, J=J, sig=sig, normalize=True, freqs=freqs, ) print("Time Taken: %s s" % (time.time() - start_time)) if np.max(WCT) > 1 or np.min(WCT) < 0: print('WCT was out of range: min {},max {}'.format( np.min(WCT), np.max(WCT))) WCT = np.clip(WCT, 0, 1) # Convert frequency to period if necessary if plot_period: y_vals = np.log2(1 / freq) if not plot_period: y_vals = np.log2(freq) # Calculates the phase between both time series. The phase arrows in the # cross wavelet power spectrum rotate clockwise with 'north' origin. # The relative phase relationship convention is the same as adopted # by Torrence and Webster (1999), where in phase signals point # upwards (N), anti-phase signals point downwards (S). If X leads Y, # arrows point to the right (E) and if X lags Y, arrow points to the # left (W). angle = 0.5 * np.pi - aWCT u, v = np.cos(angle), np.sin(angle) if ax is None: fig, ax = plt.subplots() else: fig = None # Set the x and y axes of the plot extent_corr = [t.min(), t.max(), 0, max(y_vals)] # Fill the plot with the magnitude squared coherence values # That is, MSC = abs(Pxy) ^ 2 / (Pxx * Pyy) # TODO I think this might be the wrong way to plot this # It assumes that the samples are linearly spaced im = NonUniformImage(ax, interpolation='bilinear', extent=extent_corr) if plot_period: im.set_data(t, y_vals, WCT) else: im.set_data(t, y_vals[::-1], WCT[::-1, :]) ax.images.append(im) # pcm = ax.pcolormesh(WCT) # Plot the cone of influence - Periods greater than # those are subject to edge effects. if plot_coi: # Performed by plotting a polygon x_positions = np.zeros(shape=(len(t), )) x_positions = t y_positions = np.zeros(shape=(len(t), )) if plot_period: y_positions = np.log2(coi) else: y_positions = np.log2(1 / coi) ax.plot(x_positions, y_positions, 'w--', linewidth=2, c="w") # Plot the significance level contour plot if sig: ax.contour(t, y_vals, sig, [-99, 1], colors='k', linewidths=2, extent=extent_corr) # Add limits, titles, etc. ax.set_ylim(min(y_vals), max(y_vals)) if block: ax.set_xlim(t[block[0]], t[int(block[1] * 1 / dt)]) else: ax.set_xlim(t.min(), t.max()) # TODO split graph into smaller time chunks # Test for smaller timescale # quiv_x = 1 # Plot the arrows on the plot if plot_arrows: # TODO currently this is a uniform grid, could be changed to WCT > 0.5 x_res = int(1 / dt * quiv_x) y_res = int(np.floor(len(y_vals) / quiv_y)) if all_arrows: ax.quiver( t[::x_res], y_vals[::y_res], u[::y_res, ::x_res], v[::y_res, ::x_res], units='height', angles='uv', pivot='mid', linewidth=1, edgecolor='k', scale=30, headwidth=10, headlength=10, headaxislength=5, minshaft=2, ) else: # t[::x_res], y_vals[::y_res], # u[::y_res, ::x_res], v[::y_res, ::x_res] high_points = np.nonzero(WCT[::y_res, ::x_res] > 0.5) sub_t = t[::x_res][high_points[1]] sub_y = y_vals[::y_res][high_points[0]] sub_u = u[::y_res, ::x_res][np.array(high_points[0]), np.array(high_points[1])] sub_v = v[::y_res, ::x_res][high_points[0], high_points[1]] res = 1 ax.quiver( sub_t[::res], sub_y[::res], sub_u[::res], sub_v[::res], units='height', angles='uv', pivot='mid', linewidth=1, edgecolor='k', scale=30, headwidth=10, headlength=10, headaxislength=5, minshaft=2, ) # splits = [0, 60, 120 ...] # Add the colorbar to the figure if fig is not None: fig.colorbar(im) else: plt.colorbar(im, ax=ax, use_gridspec=True) if plot_period: y_ticks = np.linspace(min(y_vals), max(y_vals), 8) # TODO improve ticks y_ticks = [ np.log2(x) for x in [0.004, 0.008, 0.016, 0.032, 0.064, 0.125, 0.25, 0.5, 1] ] y_labels = [str(x) for x in (np.round(np.exp2(y_ticks), 3))] ax.set_ylabel("Period") else: y_ticks = np.linspace(min(y_vals), max(y_vals), 8) # TODO improve ticks # y_ticks = [np.log2(x) for x in [256, 128, 64, 32, 16, 8, 4, 2, 1]] y_ticks = [np.log2(x) for x in [64, 32, 16, 8, 4, 2, 1]] y_labels = [str(x) for x in (np.round(np.exp2(y_ticks), 3))] ax.set_ylabel("Frequency (Hz)") plt.yticks(y_ticks, y_labels) ax.set_title(title) ax.set_xlabel("Time (s)") return (fig, [WCT, aWCT, coi, freq, sig])
def plot_spectrogram(spec, Xd=(0,1), Yd=(0,1)): import matplotlib #matplotlib.use('GTKAgg') import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.image import NonUniformImage import matplotlib.colors as colo # x_min, x_max = Xd y_min, y_max = Yd # fig = plt.figure() nf = len(spec) for ch, data in enumerate(spec): #print ch, data.shape x = numpy.linspace(x_min, x_max, data.shape[0]) y = numpy.linspace(y_min, y_max, data.shape[1]) #print x[0],x[-1],y[0],y[-1] ax = fig.add_subplot(nf*100+11+ch) im = NonUniformImage(ax, interpolation='bilinear', cmap=cm.gray_r, norm=colo.LogNorm(vmin=.00001)) im.set_data(x, y, data.T) ax.images.append(im) ax.set_xlim(x_min, x_max) ax.set_ylim(y_min, y_max) ax.set_title('Channel %d' % ch) #ax.set_xlabel('timeline') ax.set_ylabel('frequency') print 'Statistics: max<%.3f> min<%.3f> mean<%.3f> median<%.3f>' % (data.max(), data.min(), data.mean(), numpy.median(data)) # plt.show()
def _update3(itr,D,x,soln,t,ax,time): N = 100 #ax.clear() buff = 200.0 minx = np.min(x[:,0]) maxx = np.max(x[:,0]) miny = np.min(x[:,1]) maxy = np.max(x[:,1]) ax.set_xlim((minx-buff/2,maxx+buff/2)) ax.set_ylim((miny-buff/2,maxy+buff/2)) square = Polygon([(minx-buff,miny-buff), (minx-buff,maxy+buff), (maxx+buff,maxy+buff), (maxx+buff,miny-buff), (minx-buff,miny-buff)]) ax.add_artist(PolygonPatch(square.difference(D),alpha=1.0,color='k',zorder=1)) xitp = np.linspace(minx,maxx,N) yitp = np.linspace(miny,maxy,N) xgrid,ygrid = np.meshgrid(xitp,yitp) xflat = xgrid.flatten() yflat = ygrid.flatten() ax.images = [] im =NonUniformImage(ax,interpolation='bilinear', cmap='cubehelix', extent=(minx,maxx,miny,maxy)) val = soln[itr](zip(xflat,yflat)) val = np.sqrt(np.sum(val**2,1)) im.set_data(xitp,yitp,np.reshape(val,(N,N))) ax.images.append(im) t.set_text('t: %s s' % time[itr]) return ax,t
def plot_spectrogram(spec, Xd=(0,1), Yd=(0,1), norm=colo.LogNorm(vmin=0.000001), figname=None): # x_min, x_max = Xd y_min, y_max = Yd # fig = plt.figure(num=figname) nf = len(spec) for ch, data in enumerate(spec): #print ch, data.shape x = np.linspace(x_min, x_max, data.shape[0]) y = np.linspace(y_min, y_max, data.shape[1]) #print x[0],x[-1],y[0],y[-1] ax = fig.add_subplot(nf*100+11+ch) im = NonUniformImage(ax, interpolation='bilinear', cmap=cm.gray_r, norm=norm) im.set_data(x, y, data.T) ax.images.append(im) ax.set_xlim(x_min, x_max) ax.set_ylim(y_min, y_max) ax.set_title('Channel %d' % ch) #ax.set_xlabel('timeline') ax.set_ylabel('frequency') print 'Statistics: max<%.3f> min<%.3f> mean<%.3f> median<%.3f>' % (data.max(), data.min(), data.mean(), np.median(data)) # plt.show()
def plotDensity(ax, x, result): N = len(result["moments"][0]) y = np.linspace(0, 1, len(result["density"][0])) z = np.log(1 + np.array(zip(*result["density"]))) im = NonUniformImage(ax, norm=Normalize(0, 5, clip=True), interpolation="nearest", cmap=cm.Greys) im.set_data(x, y, z) ax.images.append(im)
def _do_plot2(x, y, z, fname, min_pitch): fig = figure(figsize=(15,7.5+7.5/2)) #fig.suptitle('Narmour') ax = fig.add_subplot(111) im = NonUniformImage(ax, interpolation=None, extent=(min(x)-1, max(x)+1, min(y)-1, max(y)+1)) im.set_data(x, y, z) ax.images.append(im) ax.set_xlim(min(x)-1, max(x)+1) ax.set_ylim(min(y)-1, max(y)+1) def format_pitch(i, pos=None): if int(i) != i: import ipdb;ipdb.set_trace() return Note(int(i + min_pitch)%12).get_pitch_name()[:-1] ax.set_xlabel('Segunda nota') ax.axes.xaxis.set_major_formatter(ticker.FuncFormatter(format_pitch)) ax.axes.xaxis.set_major_locator(ticker.MultipleLocator(base=1.0)) ax.set_ylabel('Primer nota') ax.axes.yaxis.set_major_formatter(ticker.FuncFormatter(format_pitch)) ax.axes.yaxis.set_major_locator(ticker.MultipleLocator()) cb = plt.colorbar(im) pylab.grid(True) pylab.savefig(fname) pylab.close()
def test_nonuniformimage_setdata(): ax = plt.gca() im = NonUniformImage(ax) x = np.arange(3, dtype=np.float64) y = np.arange(4, dtype=np.float64) z = np.arange(12, dtype=np.float64).reshape((4, 3)) im.set_data(x, y, z) x[0] = y[0] = z[0, 0] = 9.9 assert im._A[0, 0] == im._Ax[0] == im._Ay[0] == 0, 'value changed'
def plot_interpolant(D,interp,x,title='',dim=1,ax=None,scatter=False): if ax is None: fig,ax = plt.subplots() plt.gca().set_aspect('equal', adjustable='box') ax.set_title(title) buff = 400.0 N = 150 minx = np.min(x[:,0]) maxx = np.max(x[:,0]) miny = np.min(x[:,1]) maxy = np.max(x[:,1]) square = Polygon([(minx-buff,miny-buff), (minx-buff,maxy+buff), (maxx+buff,maxy+buff), (maxx+buff,miny-buff), (minx-buff,miny-buff)]) ax.add_artist(PolygonPatch(square.difference(D),alpha=1.0,color='k',zorder=1)) ax.set_xlim((minx-buff,maxx+buff)) ax.set_ylim((miny-buff,maxy+buff)) if dim == 1: xitp = np.linspace(minx,maxx,N) yitp = np.linspace(miny,maxy,N) xgrid,ygrid = np.meshgrid(xitp,yitp) xflat = xgrid.flatten() yflat = ygrid.flatten() points = np.zeros((len(xflat),2)) points[:,0] = xflat points[:,1] = yflat val = interp(points) #val[(np.sqrt(xflat**2+yflat**2) > 6371),:] = 0.0 im =NonUniformImage(ax,interpolation='bilinear',cmap='cubehelix_r',extent=(minx,maxx,miny,maxy)) im.set_data(xitp,yitp,np.reshape(val,(N,N))) ax.images.append(im) if scatter == True: p = ax.scatter(x[:,0], x[:,1], c='gray',edgecolor='none',zorder=2,s=10) cbar = plt.colorbar(im) if dim == 2: ax.quiver(x[::3,0],x[::3,1],interp(x)[::3,0],interp(x)[::3,1],color='gray',scale=4000.0,zorder=20) return ax
def execute(self): pylab.ioff() self.figure = pylab.figure() self.figure.canvas.mpl_connect('motion_notify_event', self.dataPrinter) x = self.fieldContainer.dimensions[-1].data y = self.fieldContainer.dimensions[-2].data xmin=scipy.amin(x) xmax=scipy.amax(x) ymin=scipy.amin(y) ymax=scipy.amax(y) #Support for images with non uniform axes adapted #from python-matplotlib-doc/examples/pcolor_nonuniform.py ax = self.figure.add_subplot(111) vmin = self.fieldContainer.attributes.get('vmin', None) vmax = self.fieldContainer.attributes.get('vmax', None) if vmin is not None: vmin /= self.fieldContainer.unit if vmax is not None: vmax /= self.fieldContainer.unit if MPL_LT_0_98_1 or self.fieldContainer.isLinearlyDiscretised(): pylab.imshow(self.fieldContainer.maskedData, aspect='auto', interpolation='nearest', vmin=vmin, vmax=vmax, origin='lower', extent=(xmin, xmax, ymin, ymax)) pylab.colorbar(format=F(self.fieldContainer), ax=ax) else: im = NonUniformImage(ax, extent=(xmin,xmax,ymin,ymax)) if vmin is not None or vmax is not None: im.set_clim(vmin, vmax) im.set_data(x, y, self.fieldContainer.maskedData) else: im.set_data(x, y, self.fieldContainer.maskedData) im.autoscale_None() ax.images.append(im) ax.set_xlim(xmin,xmax) ax.set_ylim(ymin,ymax) pylab.colorbar(im,format=F(self.fieldContainer), ax=ax) pylab.xlabel(self.fieldContainer.dimensions[-1].shortlabel) pylab.ylabel(self.fieldContainer.dimensions[-2].shortlabel) pylab.title(self.fieldContainer.label) #ax=pylab.gca() if self.show: pylab.ion() pylab.show()
def plot_interpolant(D,interp,x,title='figure'): buff = 100.0 fig,ax = plt.subplots() plt.gca().set_aspect('equal', adjustable='box') plt.title(title,fontsize=16) N = 200 minx = np.min(x[:,0]) maxx = np.max(x[:,0]) miny = np.min(x[:,1]) maxy = np.max(x[:,1]) xitp = np.linspace(minx,maxx,N) yitp = np.linspace(miny,maxy,N) xgrid,ygrid = np.meshgrid(xitp,yitp) xflat = xgrid.flatten() yflat = ygrid.flatten() points = np.zeros((len(xflat),2)) points[:,0] = xflat points[:,1] = yflat val = interp(points) val[(np.sqrt(xflat**2+yflat**2) > 6371),:] = 0.0 square = Polygon([(minx-buff,miny-buff), (minx-buff,maxy+buff), (maxx+buff,maxy+buff), (maxx+buff,miny-buff), (minx-buff,miny-buff)]) #help(D) im =NonUniformImage(ax,interpolation='bilinear',cmap='cubehelix',extent=(minx,maxx,miny,maxy)) im.set_data(xitp,yitp,np.reshape(val,(N,N))) ax.images.append(im) ax.add_artist(PolygonPatch(square.difference(D),alpha=1.0,color='k',zorder=1)) p = ax.scatter(x[:,0], x[:,1], c='gray',edgecolor='none',zorder=2,s=10) cbar = plt.colorbar(im) cbar.ax.set_ylabel(title) ax.set_xlim((minx-buff,maxx+buff)) ax.set_ylim((miny-buff,maxy+buff)) #fig.colorbar(p) return fig
def _do_plot(x, y, z, fname, max_interval, reference_note=None): fig = figure(figsize=(15,7.5+7.5/2)) #fig.suptitle('Narmour') ax = fig.add_subplot(111) im = NonUniformImage(ax, interpolation=None, extent=(min(x), max(x), min(y), max(y))) im.set_data(x, y, z) ax.images.append(im) ax.set_xlim(min(x), max(x)) ax.set_ylim(min(y), max(y)) def format_interval_w_ref_note(reference_note): def format_interval(i, pos=None): if int(i) != i: import ipdb;ipdb.set_trace() return Note(int(reference_note.pitch + i - max_interval-1)%12).get_pitch_name()[:-1] return format_interval def format_interval_wo_ref_note(x, pos=None): if int(x) != x: import ipdb;ipdb.set_trace() return int(x-max_interval-1) if reference_note is not None: format_interval= format_interval_w_ref_note(reference_note) else: format_interval= format_interval_wo_ref_note ax.set_xlabel('Intervalo realizado') ax.axes.xaxis.set_major_formatter(ticker.FuncFormatter(format_interval_wo_ref_note)) ax.axes.xaxis.set_major_locator(ticker.MultipleLocator(base=1.0)) if reference_note is not None: ax.set_ylabel('Segunda nota') else: ax.set_ylabel('Intervalo implicativo') ax.axes.yaxis.set_major_formatter(ticker.FuncFormatter(format_interval)) ax.axes.yaxis.set_major_locator(ticker.MultipleLocator()) cb = plt.colorbar(im) pylab.grid(True) pylab.savefig(fname) pylab.close()
def plot_time_frequency(spectrum, interpolation='bilinear', background_color=None, clim=None, dbscale=True, **kwargs): """ Time-frequency plot. Modeled after image_nonuniform.py example spectrum is a dataframe with frequencies in columns and time in rows """ if spectrum is None: return None times = spectrum.index freqs = spectrum.columns if dbscale: z = 10 * np.log10(spectrum.T) else: z = spectrum.T ax = plt.figure().add_subplot(111) extent = (times[0], times[-1], freqs[0], freqs[-1]) im = NonUniformImage(ax, interpolation=interpolation, extent=extent) if background_color: im.get_cmap().set_bad(kwargs['background_color']) else: z[np.isnan(z)] = 0.0 # replace missing values with 0 color if clim: im.set_clim(clim) if 'cmap' in kwargs: im.set_cmap(kwargs['cmap']) im.set_data(times, freqs, z) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) ax.images.append(im) if 'colorbar_label' in kwargs: plt.colorbar(im, label=kwargs['colorbar_label']) else: plt.colorbar(im, label='Power (dB/Hz)') plt.xlabel('Time (s)') plt.ylabel('Frequency (Hz)') return plt.gcf()
def plot_img(img, filename='image.png', xlim=None, ylim=None, title="", xlabel="", ylabel=""): # if not xlim: xlim = (0, img.shape[1] - 1) if not ylim: ylim = (0, img.shape[0] - 1) x = numpy.linspace(xlim[0], xlim[1], img.shape[1]) y = numpy.linspace(ylim[0], ylim[1], img.shape[0]) # fig = plt.figure() ax = fig.add_subplot(111) im = NonUniformImage(ax, cmap=cm.Greys)#, norm=colo.LogNorm(vmin=.00001)) im.set_data(x, y, img) ax.images.append(im) # ax.set_xlim(*xlim) ax.set_ylim(*ylim) if title: ax.set_title(title) if xlabel: ax.set_xlabel(xlabel) if ylabel: ax.set_ylabel(ylabel) # plt.show() plt.savefig(filename)
def plot_stacked_time_series_image(self, fig, ax, x, y, z, title='', ylabel='', cbar_title='', title_font={}, axis_font={}, tick_font = {}, **kwargs): ''' This plot is a stacked time series that uses NonUniformImage with regualrly spaced ydata from a linear interpolation. Designed to support FRF ADCP data. ''' if not title_font: title_font = title_font_default if not axis_font: axis_font = axis_font_default # z = np.ma.array(z, mask=np.isnan(z)) h = NonUniformImage(ax, interpolation='bilinear', extent=(min(x), max(x), min(y), max(y)), cmap=plt.cm.jet) h.set_data(x, y, z) ax.images.append(h) ax.set_xlim(min(x), max(x)) ax.set_ylim(min(y), max(y)) # h = plt.pcolormesh(x, y, z, shading='gouraud', **kwargs) # h = plt.pcolormesh(x, y, z, **kwargs) if ylabel: ax.set_ylabel(ylabel, **axis_font) if title: ax.set_title(title, **title_font) # plt.axis('tight') ax.xaxis_date() date_list = mdates.num2date(x) self.get_time_label(ax, date_list) fig.autofmt_xdate() # if invert: ax.invert_yaxis() cbar = plt.colorbar(h) if cbar_title: cbar.ax.set_ylabel(cbar_title, **axis_font) ax.grid(True) if tick_font: ax.tick_params(**tick_font)
def plot2d(x, y, z, ax=None, cmap='RdGy', norm=None, **kw): """ Plot dataset using NonUniformImage class Parameters ---------- x : (nx,) y : (ny,) z : (nx,nz) """ from matplotlib.image import NonUniformImage if ax is None: fig = plt.gcf() ax = fig.add_subplot(111) xlim = (x.min(), x.max()) ylim = (y.min(), y.max()) im = NonUniformImage(ax, interpolation='bilinear', extent=xlim + ylim, cmap=cmap) if norm is not None: im.set_norm(norm) im.set_data(x, y, z, **kw) ax.images.append(im) #plt.colorbar(im) ax.set_xlim(xlim) ax.set_ylim(ylim) def update(z): return im.set_data(x, y, z, **kw) return im, update
def visuSimple(rasterTransfo, resAnalysis, newRasters, cfgPath, cfgFlags): """ Plot and save the Peak Pressure Peak Flow depth and Peak speed fields after coord transfo """ # read paths pathResult = cfgPath['pathResult'] projectName = cfgPath['dirName'] # read data scoord = rasterTransfo['s'] lcoord = rasterTransfo['l'] indRunoutPoint = rasterTransfo['indRunoutPoint'] sBeta = scoord[indRunoutPoint] rasterArea = rasterTransfo['rasterArea'] dataPressure = newRasters['newRasterPressure'] rasterdataPres = dataPressure[0] # ana3AIMEC.makeRasterAverage(dataPressure) dataDepth = newRasters['newRasterDepth'] rasterdataDepth = dataDepth[0] dataSpeed = newRasters['newRasterSpeed'] rasterdataSpeed = dataSpeed[0] runout = resAnalysis['runout'][0] + sBeta runoutMean = resAnalysis['runoutMean'][0] + sBeta fig = plt.figure(figsize=(figW*3, figH), dpi=figReso) ax1 = plt.subplot(131) ax1.title.set_text('Peak Pressure') ref1 = ax1.axhline(y=scoord[indRunoutPoint], color='k', linewidth=lw, linestyle='-', label='Beta point') ref2 = ax1.axhline(y=runout[0], color='b', linewidth=lw, linestyle='-', label='runout') # ref3 = ax1.plot(np.zeros(np.shape(scoord)), scoord,'.r', linewidth=0.1) isosurf = copy.deepcopy(rasterdataPres) xx, yy = np.meshgrid(lcoord, scoord) maskedArray = np.ma.masked_where(isosurf == 0, isosurf) cmap = cmapPres cmap.set_bad('w', 1.) im = NonUniformImage(ax1, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap=cmap) # im.set_interpolation('bilinear') im.set_data(lcoord, scoord, maskedArray) ref0 = ax1.images.append(im) cbar = ax1.figure.colorbar(im, ax=ax1, use_gridspec=True) cbar.ax.set_ylabel('peak pressure [kPa]') plt.autoscale(False) ax1.set_xlim([xx.min(), xx.max()]) ax1.set_ylim([yy.min(), yy.max()]) ax1.set_xlabel(r'$l\;[m]$') ax1.set_ylabel(r'$s\;[m]$') ax1.legend(loc=0) ax2 = plt.subplot(132) ax2.title.set_text('Peak Flow Depth') ref1 = ax2.axhline(y=scoord[indRunoutPoint], color='k', linewidth=lw, linestyle='-', label='Beta point') ref2 = ax2.axhline(y=runout[0], color='b', linewidth=lw, linestyle='-', label='runout') # ref3 = ax1.plot(np.zeros(np.shape(scoord)), scoord,'.r', linewidth=0.1) isosurf = copy.deepcopy(rasterdataDepth) xx, yy = np.meshgrid(lcoord, scoord) maskedArray = np.ma.masked_where(isosurf == 0, isosurf) cmap = cmapDepth cmap.set_bad('w', 1.) im = NonUniformImage(ax2, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap=cmap) # im.set_interpolation('bilinear') im.set_data(lcoord, scoord, maskedArray) ref0 = ax2.images.append(im) cbar = ax2.figure.colorbar(im, ax=ax2, use_gridspec=True) cbar.ax.set_ylabel('peak flow depth [m]') plt.autoscale(False) ax2.set_xlim([xx.min(), xx.max()]) ax2.set_ylim([yy.min(), yy.max()]) ax2.set_xlabel(r'$l\;[m]$') ax2.set_ylabel(r'$s\;[m]$') ax2.legend(loc=0) ax3 = plt.subplot(133) ax3.title.set_text('Peak Speed') ref1 = ax3.axhline(y=scoord[indRunoutPoint], color='k', linewidth=lw, linestyle='-', label='Beta point') ref2 = ax3.axhline(y=runout[0], color='b', linewidth=lw, linestyle='-', label='runout') # ref3 = ax1.plot(np.zeros(np.shape(scoord)), scoord,'.r', linewidth=0.1) isosurf = copy.deepcopy(rasterdataSpeed) xx, yy = np.meshgrid(lcoord, scoord) maskedArray = np.ma.masked_where(isosurf == 0, isosurf) cmap = cmapSpeed cmap.set_bad('w', 1.) im = NonUniformImage(ax3, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap=cmap) # im.set_interpolation('bilinear') im.set_data(lcoord, scoord, maskedArray) ref0 = ax3.images.append(im) cbar = ax3.figure.colorbar(im, ax=ax3, use_gridspec=True) cbar.ax.set_ylabel('peak speed [m/s]') plt.autoscale(False) ax3.set_xlim([xx.min(), xx.max()]) ax3.set_ylim([yy.min(), yy.max()]) ax3.set_xlabel(r'$l\;[m]$') ax3.set_ylabel(r'$s\;[m]$') ax3.legend(loc=0) fig.tight_layout() if cfgFlags.getboolean('savePlot'): outname = ''.join([pathResult, os.path.sep, 'pics', os.path.sep, projectName, '_referenceFields', '.pdf']) if not os.path.exists(os.path.dirname(outname)): os.makedirs(os.path.dirname(outname)) fig.savefig(outname, transparent=True) if cfgFlags.getboolean('plotFigure'): plt.show() else: plt.ioff() plt.close(fig)
def wavelet(self, signal, mother='morlet', plot=True): """ Takes a 1D signal and perfroms a continous wavelet transform. Parameters ---------- time: ndarray The 1D time series for the data data: ndarray The actual 1D data mother: string The name of the family. Acceptable values are Paul, Morlet, DOG, Mexican_hat plot: bool If True, will return a plot of the result. Returns ------- Examples -------- """ sig_level = 0.95 std2 = signal.std() ** 2 signal_orig = signal[:] signal = (signal - signal.mean())/ signal.std() t1 = np.linspace(0,self.period*signal.size,signal.size) wave, scales, freqs, coi, fft, fftfreqs = wavelet.cwt(signal, self.period, wavelet=mother, dj=1/100) power = (np.abs(wave)) ** 2 period = 1/freqs # alpha, _, _ = wavelet.ar1(signal) alpha = 0.0 ## (variance=1 for the normalized SST) signif, fft_theor = wavelet.significance(1.0, self.period, scales, 0, alpha, significance_level=sig_level, wavelet=mother) sig95 = np.ones([1, signal.size]) * signif[:, None] sig95 = power / sig95 glbl_power = std2 * power.mean(axis=1) dof = signal.size - scales glbl_signif, tmp = wavelet.significance(std2, self.period, scales, 1, alpha, significance_level=sig_level, dof=dof, wavelet=mother) ## indices for stuff idx = self.find_closest(period,coi.max()) ## Into minutes t1 /= 60 period /= 60 coi /= 60 if plot: plt.figure(figsize=(12,12)) ax = plt.axes([0.1, 0.75, 0.65, 0.2]) ax.plot(t1, signal_orig-signal_orig.mean(), 'k', linewidth=1.5) extent = [t1.min(),t1.max(),0,max(period)] bx = plt.axes([0.1, 0.1, 0.65, 0.55], sharex=ax) im = NonUniformImage(bx, interpolation='nearest', extent=extent) im.set_cmap('cubehelix') im.set_data(t1, period[:idx], power[:idx,:]) bx.images.append(im) bx.contour(t1, period[:idx], sig95[:idx,:], [-99,1], colors='w', linewidths=2, extent=extent) bx.fill(np.concatenate([t1, t1[-1:]+self.period, t1[-1:]+self.period,t1[:1]-self.period, t1[:1]-self.period]), (np.concatenate([coi,[1e-9], period[-1:], period[-1:], [1e-9]])), 'k', alpha=0.3,hatch='x', zorder=100) bx.set_xlim(t1.min(),t1.max()) cx = plt.axes([0.77, 0.1, 0.2, 0.55], sharey=bx) cx.plot(glbl_signif[:idx], period[:idx], 'k--') cx.plot(glbl_power[:idx], period[:idx], 'k-', linewidth=1.5) cx.set_ylim(([min(period), period[idx]])) plt.setp(cx.get_yticklabels(), visible=False) plt.show() return wave, scales, freqs, coi, power
def plot(self): plt.clf() ax = self.figure.add_subplot(111) slice_str = '[?]' # extension = [] if self.view == 'X-Y': image = self.data[:,:,self.slider.value()] slice_str = 'z = %f ' % self.b.z[self.slider.value()] ax.set_ylabel('y-direction') ax.set_xlabel('x-direction') # extension = [0, self.param['mx'], 0, self.param['my']] elif self.view == 'X-Z': image = self.data[:,self.slider.value(),:] slice_str = 'y = %f ' % self.b.y[self.slider.value()] ax.set_ylabel('z-direction') ax.set_xlabel('x-direction') # extension = [0, self.param['mx'], 0, self.param['mz']] elif self.view == 'Y-Z': image = self.data[self.slider.value(),:,:] slice_str = 'x = %f ' % self.b.x[self.slider.value()] ax.set_ylabel('z-direction') ax.set_xlabel('y-direction') # extension = [0, self.param['my'], 0, self.param['mz']] # image = np.fliplr(image) # image = np.rot90(image,k=3) label = "Value" color = cm.get_cmap('jet') ax.set_title("[%s] %s (Snap: %s) for %s \n[time: %s]" % (self.tag, self.base_name, self.snap_n, slice_str, str(datetime.timedelta(seconds=self.param['t']*self.param['u_t'])))) # ax.xaxis.set_major_locator(ticker.MultipleLocator(int(64))) # ax.yaxis.set_major_locator(ticker.MultipleLocator(int(64))) if self.check_si.isChecked(): if self.tag == 'r': image = image * self.param['u_r'] unit_label = "[g/cm3]" label = "Value %s" % unit_label elif (self.tag == 'bx' or self.tag == 'by' or self.tag == 'bz'): image = image * self.param['u_b'] unit_label = "[G]" label = "Value %s" % unit_label elif (self.tag == 'px' or self.tag == 'py' or self.tag == 'pz'): image = image * self.param['u_p'] unit_label = "[Ba]" label = "Value %s" % unit_label elif self.tag == 'e': image = image * self.param['u_e'] unit_label = "[erg]" label = "Value %s" % unit_label if self.check_abs.isChecked(): image = np.absolute(image) label = "ABS( %s )" % label if self.check_log.isChecked(): image = np.log10(image) label = "Log10( %s )" % label if self.check_bw.isChecked(): # color = cm.get_cmap('gist_yarg') color = cm.get_cmap('Greys_r') # Mats favorite color palette if self.view == 'X-Y': ax.set_ylabel('y-direction [Mm]') ax.set_xlabel('x-direction [Mm]') im = NonUniformImage(ax, interpolation='bilinear', extent=(self.b.x.min(),self.b.x.max(),self.b.y.min(),self.b.y.max()), cmap=color) im.set_data(self.b.x, self.b.y, np.fliplr(zip(*image[::-1]))) ax.images.append(im) ax.set_xlim(self.b.x.min(),self.b.x.max()) ax.set_ylim(self.b.y.min(),self.b.y.max()) ax.xaxis.set_major_locator(ticker.MultipleLocator(int(4))) ax.yaxis.set_major_locator(ticker.MultipleLocator(int(4))) elif self.view == 'X-Z': ax.set_ylabel('z-direction [Mm]') ax.set_xlabel('x-direction [Mm]') im = NonUniformImage(ax, interpolation='bilinear', extent=(self.b.x.min(),self.b.x.max(),self.b.z.min(),self.b.z.max()), cmap=color) im.set_data(self.b.x, self.b.z[::-1], np.flipud(np.fliplr(zip(*image[::-1])))) ax.images.append(im) ax.set_xlim(self.b.x.min(),self.b.x.max()) ax.set_ylim(self.b.z.max(),self.b.z.min()) ax.xaxis.set_major_locator(ticker.MultipleLocator(int(4))) ax.yaxis.set_major_locator(ticker.MultipleLocator(int(2))) elif self.view == 'Y-Z': ax.set_ylabel('z-direction [Mm]') ax.set_xlabel('y-direction [Mm]') im = NonUniformImage(ax, interpolation='bilinear', extent=(self.b.y.min(),self.b.y.max(),self.b.z.min(),self.b.z.max()), cmap=color) im.set_data(self.b.y, self.b.z[::-1], np.flipud(np.fliplr(zip(*image[::-1])))) ax.images.append(im) ax.set_xlim(self.b.y.min(),self.b.y.max()) ax.set_ylim(self.b.z.max(),self.b.z.min()) ax.xaxis.set_major_locator(ticker.MultipleLocator(int(4))) ax.yaxis.set_major_locator(ticker.MultipleLocator(int(2))) # im = ax.imshow(image, interpolation='none', origin='lower', cmap=color, extent=extension) # ax.text(0.025, 0.025, (r'$\langle B_{z} \rangle = %2.2e$'+'\n'+r'$\langle |B_{z}| \rangle = %2.2e$') % (np.average(img),np.average(np.absolute(img))), ha='left', va='bottom', transform=ax.transAxes) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax,label=label) self.canvas.draw()
def plot2D(ma, xs, ys, kind='imshow', fnc_x=lambda x:x, fnc_y=lambda y:y, fnc_z=lambda z:z , axis_label = None, appto = None, **kwargs): import pylab from matplotlib.image import NonUniformImage from numpy import linspace from scipy.interpolate import splrep, splev from mpl_toolkits.mplot3d import Axes3D if appto is None or kind not in ['imshow', 'contour', 'contourf']: f=pylab.figure() if kind in ['imshow', 'contour', 'contourf']: ax=f.add_subplot(111) else: ax = f.gca(projection='3d') else: ax = appto CS=None try: pylab.array(xs) x_min = max(transpose(xs)[0]); x_max = min(transpose(xs)[-1]) x_axis = linspace(x_min, x_max,400) for i in xrange(len(xs)): ma[i] = splev(x_axis, splrep(xs[i], ma[i], k=3)) xs[i] = x_axis except: x_axis = fnc_x(xs) y_axis = fnc_y(ys) if kind == 'imshow': im = NonUniformImage(ax, interpolation='bilinear' ) im.set_cmap(kwargs.get('cmap',None)) im.set_data( x_axis, y_axis, fnc_z(ma) ) if kwargs.has_key('vmin'): im.set_clim(vmin=kwargs['vmin']) if kwargs.has_key('vmax'): im.set_clim(vmax=kwargs['vmax']) ax.images.append( im ) #~ xlabel( r'Wavelength [nm]' ) #~ ylabel( r'Delay [ps]' ) pylab.show() if kwargs.has_key('bar'): bar = kwargs['bar'] kwargs.pop('bar') else: bar = True if bar: ax.get_figure().colorbar(im) ax.set_xlim(x_axis[0],x_axis[-1]) ax.set_ylim(y_axis[0],y_axis[-1]) pylab.draw() elif kind == 'contour': N=kwargs.get('N', 8) X, Y = pylab.meshgrid(x_axis, y_axis) CS=ax.contour(X, Y, fnc_z(ma), N, **kwargs) if kwargs.has_key('labels'): labels = kwargs['labels'] kwargs.pop('labels') fmt = {} for l, s in zip( CS.levels, labels ): fmt[l] = s elif kwargs.has_key('fmt'): fmt = kwargs('fmt') else: fmt = '%1.2f' if kwargs.has_key('fontsize'): fontsize = kwargs['fontsize'] else: fontsize = 12 ax.clabel(CS, CS.levels, inline=1, fmt = fmt, fontsize = fontsize) pylab.show() ax.set_xlim(x_axis[0],x_axis[-1]) ax.set_ylim(y_axis[0],y_axis[-1]) pylab.draw() elif kind == 'contourf': N=kwargs.get('N', 8) X, Y = pylab.meshgrid(x_axis, y_axis) CS=ax.contourf(X, Y, fnc_z(ma), N, **kwargs) ax.get_figure().colorbar(CS) pylab.show() ax.set_xlim(x_axis[0],x_axis[-1]) ax.set_ylim(y_axis[0],y_axis[-1]) pylab.draw() elif kind == 'surf': X, Y = pylab.meshgrid(x_axis, y_axis) CS=ax.plot_surface(X, Y, fnc_z(pylab.array(ma)), **kwargs) #ax.get_figure().colorbar(CS, shrink=0.5, aspect=5) pylab.show() ax.set_xlim(x_axis[0],x_axis[-1]) ax.set_ylim(y_axis[0],y_axis[-1]) pylab.draw() elif kind == 'contour3d': N=kwargs.get('N', 8) X, Y = pylab.meshgrid(x_axis, y_axis) CS=ax.contourf(X, Y, fnc_z(ma), N, **kwargs) if kwargs.has_key('labels'): labels = kwargs['labels'] kwargs.pop('labels') fmt = {} for l, s in zip( CS.levels, labels ): fmt[l] = s elif kwargs.has_key('fmt'): fmt = kwargs('fmt') else: fmt = '%1.2f' if kwargs.has_key('fontsize'): fontsize = kwargs['fontsize'] else: fontsize = 12 ax.clabel(CS, CS.levels, inline=1, fmt = fmt, fontsize = fontsize) pylab.show() ax.set_xlim(x_axis[0],x_axis[-1]) ax.set_ylim(y_axis[0],y_axis[-1]) pylab.draw() if axis_label is not None: ax.set_xlabel(axis_label[0]) ax.set_ylabel(axis_labe[1]) pylab.show() return ax, CS
def plot(self, data, fmt, xmin, xmax, ymin, ymax, zmin, zmax, **opts): """ Plot the data entry. Raises NeXusError if the data cannot be plotted. """ try: import matplotlib.pyplot as plt except ImportError: raise NeXusError("Default plotting package (matplotlib) not available.") over = opts.pop("over", False) image = opts.pop("image", False) log = opts.pop("log", False) logx = opts.pop("logx", False) logy = opts.pop("logy", False) if fmt == '': fmt = 'o' if over: plt.autoscale(enable=False) else: plt.autoscale(enable=True) plt.clf() signal = data.nxsignal axes = data.nxaxes errors = data.nxerrors title = data.nxtitle # Provide a new view of the data if there is a dimension of length 1 if 1 in signal.shape: data, axes = _fixaxes(signal, axes) else: data = signal.nxdata # Find the centers of the bins for histogrammed data axis_data = centers(data, axes) #One-dimensional Plot if len(data.shape) == 1: if hasattr(signal, 'units'): if not errors and signal.units == 'counts': errors = NXfield(np.sqrt(data)) if errors: ebars = errors.nxdata plt.errorbar(axis_data[0], data, ebars, fmt=fmt, **opts) else: plt.plot(axis_data[0], data, fmt, **opts) if not over: ax = plt.gca() xlo, xhi = ax.set_xlim(auto=True) ylo, yhi = ax.set_ylim(auto=True) if xmin: xlo = xmin if xmax: xhi = xmax ax.set_xlim(xlo, xhi) if ymin: ylo = ymin if ymax: yhi = ymax ax.set_ylim(ylo, yhi) if logx: ax.set_xscale('symlog') if log or logy: ax.set_yscale('symlog') plt.xlabel(label(axes[0])) plt.ylabel(label(signal)) plt.title(title) #Two dimensional plot else: from matplotlib.image import NonUniformImage from matplotlib.colors import LogNorm, Normalize if len(data.shape) > 2: slab = [] if image: for _dim in data.shape[:-3]: slab.append(0) slab.extend([slice(None), slice(None), slice(None)]) else: for _dim in data.shape[:-2]: slab.append(0) slab.extend([slice(None), slice(None)]) data = data[slab] if 0 in slab: print "Warning: Only the top 2D slice of the data is plotted" if image: x, y = axis_data[-2], axis_data[-3] xlabel, ylabel = label(axes[-2]), label(axes[-3]) else: x, y = axis_data[-1], axis_data[-2] xlabel, ylabel = label(axes[-1]), label(axes[-2]) if not zmin: zmin = np.nanmin(data[data>-np.inf]) if not zmax: zmax = np.nanmax(data[data<np.inf]) if not image: if log: zmin = max(zmin, 0.01) zmax = max(zmax, 0.01) opts["norm"] = LogNorm(zmin, zmax) else: opts["norm"] = Normalize(zmin, zmax) ax = plt.gca() if image: im = ax.imshow(data, **opts) ax.set_aspect('equal') else: extent = (x[0],x[-1],y[0],y[-1]) im = NonUniformImage(ax, extent=extent, **opts) im.set_data(x, y, data) im.get_cmap().set_bad('k', 1.0) ax.set_xlim(x[0], x[-1]) ax.set_ylim(y[0], y[-1]) ax.set_aspect('auto') ax.images.append(im) if not image: plt.colorbar(im) if 'origin' in opts and opts['origin'] == 'lower': image = False if xmin: ax.set_xlim(left=xmin) if xmax: ax.set_xlim(right=xmax) if ymin: if image: ax.set_ylim(top=ymin) else: ax.set_ylim(bottom=ymin) if ymax: if image: ax.set_ylim(bottom=ymax) else: ax.set_ylim(top=ymax) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.gcf().canvas.draw_idle() plt.ion() plt.show()
ni = np.zeros([nx, ny, ts]) nt = np.zeros([nx, ny, ts]) nm = np.zeros([nx, ny, ts]) temp = np.fromfile('output/ne.dat', dtype=float) Ex = temp.reshape([ts, ny, nx]) interp = 'bilinear' fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(4, 4)) im = NonUniformImage(ax, interpolation=interp, cmap='plasma', extent=(x[0], x[-1], y[0], y[-1]), zorder=-20) #ax.set_rasterization_zorder(-10) im.set_data(x, y, Ex[0, :, :]) ax.images.append(im) ax.set_xlim(x[0] - 0.1, x[-1] + 0.1) ax.set_ylim(y[0] - 0.1, y[-1] + 0.1) tx = plt.title(r'$n_e$ : time = 0 $\mu$s') ax.set_xlabel('x [mm]') ax.set_ylabel('y [mm]') plt.tight_layout() def anim(i): im.set_data(x, y, Ex[i, :, :]) ax.set_xlim(x[0] - 0.1, x[-1] + 0.1) ax.set_ylim(y[0] - 0.1, y[-1] + 0.1) tx.set_text(r'$n_e$ : time = {:.2f} $\mu$s'.format(t[i])) im.autoscale()
fig = plt.figure(figsize=(20, 4)) ax1 = fig.add_subplot(121) Pxx, freq, t, im = specgram(senial_indep_2500_muestras, NFFT=NFFT, Fs=500, noverlap=noverlap, scale_by_freq='magnitude', detrend=mlab.detrend_linear, window=mlab.window_hanning) # Plot Spectrogram im1 = NonUniformImage(ax1, interpolation='bilinear', extent=(min(t), max(t), 10, 55), cmap='jet') im1.set_data(t, freq, Pxx) im1.set_clim() ax1.images.append(im1) cbar1 = fig.colorbar(im1) plt.yscale('linear') plt.ylabel('Frequency [Hz]', fontsize=18) #xlab = 'Time [seconds] from ' + str(startutc) + ' UTC' plt.xlabel('Time', fontsize=18) plt.title('Espectrograma sujeto control', fontsize=18) plt.xlim(0, max(t)) plt.ylim(0, 36) # Sujeto dislexia ax1 = fig.add_subplot(122) Pxx_d, freq_d, t_d, im_d = specgram(senial_indep_2500_muestras_dislexia,
#interp='nearest' # "raw" (non smooth) map interp = 'bilinear' # "smooth" map # NonUniformImage permet de définir la position des éléments de 'z_matrix' sur # les axes. # Sans NonUniformImage, une matrice 'z_matrix' de taille (sx, sy) serait # dessinée sur un repère avec un axe des abscisses allant de 0 a sx et un axe # des ordonnées allant de 0 a sy. im = NonUniformImage(ax, interpolation=interp, extent=(X_MIN, X_MAX, Y_MIN, Y_MAX), cmap=cm.binary) # im.set_data(x, y, A) # Set the grid for the pixel centers, and the pixel values. # *x* and *y* are 1-D ndarrays of lengths N and M, respectively, specifying pixel centers # *A* is an (M,N) ndarray or masked array of values to be colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA array. im.set_data(x, y, z_matrix) ax.images.append(im) ax.set_xlim(X_MIN, X_MAX) ax.set_ylim(Y_MIN, Y_MAX) fig.colorbar(im) # draw colorbar # Save file and plot ######## plt.savefig("colour_map_with_custom_axes.png") plt.show()
def main(self, args): command.Command.main(self, args) if args.colorbar and not args.heatmap: logger.error("Can't specify --colorbar without --heatmap") sys.exit(1) j = json.load(open(args.model, "rt")) klass = getattr(model, j['model']['class']) m = klass.from_dict(j['model']) files = estimation_tools.files_from_command_line_args(args.data) contigs = estimation_tools.load_data(files) if len(set(c.key for c in contigs)) > 1: logger.error( "All data sets must be from same population and have same sample size" ) sys.exit(1) hidden_states = estimation_tools.balance_hidden_states( m.distinguished_model, args.M + 1) / (2. * m.distinguished_model.N0) logger.debug("hidden states (balanced w/r/t model): %s", np.array(hidden_states).round(3)) all_obs = [] n = a = None for contig in contigs: obs = contig.data if ((n is not None and np.any(contig.n != n)) or (a is not None and np.any(contig.a != a))): logger.error("Mismatch between n/a from different contigs") sys.exit(1) n = contig.n a = contig.a npop = obs.shape[1] // 2 - 1 assert len(n) == npop lb = 0 if args.start is None else args.start ub = obs[:, 0].sum() if args.end is None else args.end ## FIXME? Due to the compressed input format the endpoints are only ## approximately picked out. pos = np.cumsum(obs[:, 0]) obs = obs[(pos >= lb) & (pos <= ub)] obs = np.insert(obs, 0, [[1] + [-1, 0, 0] * npop], 0) all_obs.append(obs) # Perform thinning, if requested if args.thinning > 1: all_obs = estimation_tools.thin_dataset(all_obs, [args.thinning] * len(all_obs)) if npop == 1: im = _smcpp.PyOnePopInferenceManager(n[0], all_obs, hidden_states, contig.key, args.polarization_error) else: assert npop == 2 im = _smcpp.PyTwoPopInferenceManager(*n, *a, all_obs, hidden_states, contig.key, args.polarization_error) im.theta = j['theta'] im.save_gamma = True im.model = m im.E_step() gammas = im.gammas for g in gammas: Lr = g.sum(axis=0) g /= Lr L = Lr.sum() if os.environ.get("SMCPP_DEBUG"): import ipdb ipdb.set_trace() kwargs = {path: g for path, g in zip(args.data, gammas)} kwargs.update({ path + "_sites": obs[:, 0] for path, obs in zip(args.data, all_obs) }) np.savez_compressed(args.output, hidden_states=hidden_states, **kwargs) if args.heatmap: if len(args.data) > 1: logger.error("--heatmap is only supported for one data set") sys.exit(1) # Plotting code gamma = g fig, ax = plt.subplots() x = np.insert(np.cumsum(obs[:, 0]), 0, 0) y = hidden_states[:-1] img = NonUniformImage(ax, interpolation="bilinear", extent=(0, x.max(), y[0], y[-1])) img.set_data(x, y, gamma) ax.images.append(img) ax.set_xlim((0, x.max())) ax.set_ylim((y[0], y[-1])) if L > 1e7: ax.set_xlabel("Position (Mb)") fac = 1e-6 elif L > 1e5: ax.set_xlabel("Position (Kb)") fac = 1e-3 else: ax.set_xlabel("Position (bp)") fac = 1 label_text = [int(loc * fac) for loc in ax.get_xticks()] ax.set_xticklabels(label_text) ax.set_ylabel("TMRCA") if args.colorbar: plt.colorbar(img) plt.savefig(args.heatmap) plt.close()
def visuTransfo(rasterTransfo, inputData, cfgPath, cfgFlags): """ Plot and save the domain transformation figure """ # read paths pathResult = cfgPath['pathResult'] projectName = cfgPath['dirName'] # read rasterdata sourceData = inputData['sourceData'] header = sourceData['header'] xllc = rasterTransfo['xllc'] yllc = rasterTransfo['yllc'] cellsize = rasterTransfo['cellsize'] rasterdata = sourceData['rasterData'] # read avaPath with scale Avapath = inputData['Avapath'] xPath = Avapath['x'] yPath = Avapath['y'] # read domain boundarries with scale DBXl = rasterTransfo['DBXl']*cellsize+xllc DBXr = rasterTransfo['DBXr']*cellsize+xllc DBYl = rasterTransfo['DBYl']*cellsize+yllc DBYr = rasterTransfo['DBYr']*cellsize+yllc fig = plt.figure(figsize=(figW*2, figH), dpi=figReso) # for figure: referenz-simulation bei pLim=1 ax1 = plt.subplot(121) indRunoutPoint = rasterTransfo['indRunoutPoint'] xx = rasterTransfo['x'][indRunoutPoint] yy = rasterTransfo['y'][indRunoutPoint] newRasterdata = rasterdata maskedArray = newRasterdata # np.ma.masked_where(np.isnan(newRasterdata), newRasterdata) cmap = cmapPres cmap.set_under(color='w') n, m = np.shape(newRasterdata) x = np.arange(m)*cellsize+xllc y = np.arange(n)*cellsize+yllc im0 = NonUniformImage(ax1, extent=[x.min(), x.max(), y.min(), y.max()], cmap=cmap) # im.set_interpolation('bilinear') im0.set_clim(vmin=0.000000001) im0.set_data(x, y, maskedArray) ref1 = ax1.images.append(im0) # cbar = ax1.figure.colorbar(im0, ax=ax1, use_gridspec=True) plt.autoscale(False) ref0 = plt.plot(xx, yy, 'ro', markersize=ms, label='Beta point') ref2 = plt.plot(xPath, yPath, 'b-', linewidth=lw, label='flow path') ref3 = plt.plot(DBXl, DBYl, 'g-', linewidth=lw, label='domain') ref3 = plt.plot(DBXr, DBYr, 'g-', linewidth=lw, label='domain') ref3 = plt.plot([DBXl, DBXr], [DBYl, DBYr], 'g-', linewidth=lw, label='domain') refs = [ref0[0], ref2[0], ref3[0]] labels = ['Beta point', 'flow path', 'domain'] ax1.title.set_text('XY Domain') ax1.legend(refs, labels, loc=0) ax1.set_xlim([x.min(), x.max()]) ax1.set_ylim([y.min(), y.max()]) ax1.set_xlabel(r'$x\;[m]$') ax1.set_ylabel(r'$y\;[m]$') ax2 = plt.subplot(122) ax2.title.set_text('sl Domain \n Black = out of raster') isosurf = copy.deepcopy(inputData['avalData']) lcoord = rasterTransfo['l'] scoord = rasterTransfo['s'] ref1 = ax2.axhline(y=scoord[indRunoutPoint], color='r', linewidth=lw, linestyle='-', label='Beta point') maskedArray = isosurf # np.ma.array(isosurf,mask=np.isnan(isosurf)) im = NonUniformImage(ax2, extent=[lcoord.min(), lcoord.max(), scoord.min(), scoord.max()], cmap=cmap) # im.set_interpolation('bilinear') im.set_clim(vmin=0.000000001) im.set_data(lcoord, scoord, maskedArray) ref0 = ax2.images.append(im) cbar = ax2.figure.colorbar(im, ax=ax2, use_gridspec=True) cbar.ax.set_ylabel('peak pressure [kPa]') ax2.set_xlim([lcoord.min(), lcoord.max()]) ax2.set_ylim([scoord.min(), scoord.max()]) ax2.set_xlabel(r'$l\;[m]$') ax2.set_ylabel(r'$s\;[m]$') ax2.legend() fig.tight_layout() if cfgFlags.getboolean('plotFigure'): plt.show() else: plt.ioff() if cfgFlags.getboolean('savePlot'): outname = ''.join([pathResult, os.path.sep, 'pics', os.path.sep, projectName, '_domTransfo', '.pdf']) if not os.path.exists(os.path.dirname(outname)): os.makedirs(os.path.dirname(outname)) fig.savefig(outname, transparent=True) plt.close(fig)
ni = np.zeros([nx, ny, ts]) nt = np.zeros([nx, ny, ts]) nm = np.zeros([nx, ny, ts]) temp = np.fromfile('output/ne.dat', dtype=float) ne = temp.reshape([ts, ny, nx]) interp = 'bilinear' fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(4, 4)) im = NonUniformImage(ax, interpolation=interp, cmap='plasma', extent=(x[0], x[-1], y[0], y[-1]), zorder=-20) #ax.set_rasterization_zorder(-10) im.set_data(x, y, ne[0, :, :]) ax.images.append(im) ax.set_xlim(x[0] - 0.1, x[-1] + 0.1) ax.set_ylim(y[0] - 0.1, y[-1] + 0.1) tx = plt.title(r'$n_e$ : time = 0 $\mu$s') ax.set_xlabel('x [mm]') ax.set_ylabel('y [mm]') plt.tight_layout() def anim(i): im.set_data(x, y, ne[i, :, :]) ax.set_xlim(x[0] - 0.1, x[-1] + 0.1) ax.set_ylim(y[0] - 0.1, y[-1] + 0.1) tx.set_text(r'$n_e$ : time = {:.2f} $\mu$s'.format(t[i])) im.autoscale()
def plot_cross_wavelet(wave1, wave2, sample_times, min_freq=1, max_freq=256, sig=False, ax=None, title="Cross-Wavelet", plot_coi=True, plot_period=False, resolution=12, all_arrows=True, quiv_x=5, quiv_y=24, block=None): """ Plot cross wavelet correlation between wave1 and wave2 using pycwt. TODO Fix this function TODO also test out sig on a large dataset Parameters ---------- wave1 : np.ndarray The values of the first waveform. wave2 : np.ndarray The values of the second waveform. sample_times : np.ndarray The times at which waveform samples occur. min_freq : float Supposed to be minimum frequency, but not quite working. max_freq : float Supposed to be max frequency, but not quite working. sig : bool, default False Optional Should significance of waveform coherence be calculated. ax : plt.axe, default None Optional ax object to plot into. title : str, default "Wavelet Coherence" Optional title for the graph plot_coi : bool, default True Should the cone of influence be plotted plot_period : bool Should the y-axis be in period or in frequency (Hz) resolution : int How many wavelets should be at each level of the graph all_arrows : bool Should phase arrows be plotted uniformly or only at high coherence quiv_x : float sets quiver window in time domain in seconds quiv_y : float sets number of quivers evenly distributed across freq limits block : [int, int] Plots only points between ints. Returns ------- tuple : (fig, result) Where fig is a matplotlib Figure and result is a tuple consisting of WCT, aWCT, coi, freq, sig WCT - 2D numpy array with coherence values aWCT - 2D numpy array with same shape as aWCT indicating phase angles coi - 1D numpy array with a frequency value for each time freq - 1D numpy array with the frequencies wavelets were calculated at sig - 2D numpy array indicating where data is significant by monte carlo """ t = np.asarray(sample_times) dt = np.mean(np.diff(t)) # Set up the scales to match min max input frequencies dj = resolution s0 = 1 / max_freq if s0 < (2 * dt): s0 = 2 * dt max_J = 1 / min_freq J = dj * np.int(np.round(np.log2(max_J / np.abs(s0)))) # Do the actual calculation W12, coi, freq, signif = wavelet.xwt( wave1, wave2, dt, # Fixed params dj=(1.0 / dj), s0=s0, J=J, significance_level=0.8646, normalize=True, ) cross_power = np.abs(W12)**2 if np.max(W12) > 6**2 or np.min(W12) < 0: print('W12 was out of range: min{},max{}'.format( np.min(W12), np.max(W12))) cross_power = np.clip(cross_power, 0, 6**2) # print('cross max:', np.max(cross_power)) # print('cross min:', np.min(cross_power)) cross_sig = np.ones([1, len(t)]) * signif[:, None] cross_sig = cross_power / cross_sig # Power is significant where ratio > 1 # Convert frequency to period if necessary if plot_period: y_vals = np.log2(1 / freq) if not plot_period: y_vals = np.log2(freq) if ax is None: fig, ax = plt.subplots() else: fig = None # Set the x and y axes of the plot extent_corr = [t.min(), t.max(), 0, max(y_vals)] # Fill the plot with the magnitude squared correlation values # That is, MSC = abs(Pxy) ^ 2 / (Pxx * Pyy) # TODO I think this might be the wrong way to plot this # It assumes that the samples are linearly spaced im = NonUniformImage(ax, interpolation='bilinear', extent=extent_corr) if plot_period: im.set_data(t, y_vals, cross_power) else: im.set_data(t, y_vals[::-1], cross_power[::-1, :]) ax.images.append(im) # pcm = ax.pcolormesh(WCT) # Plot the cone of influence - Periods greater than # those are subject to edge effects. if plot_coi: # Performed by plotting a polygon x_positions = np.zeros(shape=(len(t), )) x_positions = t y_positions = np.zeros(shape=(len(t), )) if plot_period: y_positions = np.log2(coi) else: y_positions = np.log2(1 / coi) ax.plot(x_positions, y_positions, 'w--', linewidth=2, c="w") # Plot the significance level contour plot if sig: ax.contour(t, y_vals, cross_sig, [-99, 1], colors='k', linewidths=2, extent=extent_corr) # Add limits, titles, etc. ax.set_ylim(min(y_vals), max(y_vals)) if block: ax.set_xlim(t[block[0]], t[int(block[1] * 1 / dt)]) else: ax.set_xlim(t.min(), t.max()) # TODO split graph into smaller time chunks # Test for smaller timescale # quiv_x = 1 # Add the colorbar to the figure if fig is not None: fig.colorbar(im) else: plt.colorbar(im, ax=ax, use_gridspec=True) if plot_period: y_ticks = np.linspace(min(y_vals), max(y_vals), 8) # TODO improve ticks y_ticks = [ np.log2(x) for x in [0.004, 0.008, 0.016, 0.032, 0.064, 0.125, 0.25, 0.5, 1] ] y_labels = [str(x) for x in (np.round(np.exp2(y_ticks), 3))] else: y_ticks = np.linspace(min(y_vals), max(y_vals), 8) # TODO improve ticks # y_ticks = [np.log2(x) for x in [256, 128, 64, 32, 16, 8, 4, 2, 1]] y_ticks = [np.log2(x) for x in [64, 32, 16, 8, 4, 2, 1]] y_labels = [str(x) for x in (np.round(np.exp2(y_ticks), 3))] plt.yticks(y_ticks, y_labels) ax.set_title(title) ax.set_xlabel("Time (s)") if plot_period: ax.set_ylabel("Period") else: ax.set_ylabel("Frequency (Hz)") return (fig, [W12, coi, freq, sig])
_, _, Z = peaks(x, y) table = NDTable(Z, (x, y)) xi = yi = np.linspace(-6, 6, 200) XI, YI = np.meshgrid(xi, yi, indexing='ij') figure, axes = plt.subplots(ncols=2, nrows=2, sharex=True, sharey=True) figure.canvas.set_window_title('Inter- & Extrapolation Methods') figure.set_facecolor('white') axes = axes.flatten() ax = axes[0] ax.set_title('original') im = NonUniformImage(ax) im.set_data(x, y, Z) im.set_extent((-3, 3, -3, 3)) ax.images.append(im) ax.set_xlim([-6, 6]) ax.set_ylim([-6, 6]) methods = [('nearest', 'hold'), ('linear', 'linear'), ('akima', 'linear')] for ax, method in zip(axes[1:], methods): ZI = table.evaluate((XI, YI), interp=method[0], extrap=method[1]) ax.set_title("interp='%s', extrap='%s'" % method) im = NonUniformImage(ax) im.set_data(xi, yi, ZI) im.set_extent((-6, 6, -6, 6)) ax.images.append(im)
# First sub-plot, the original time series anomaly. ax = plt.axes([0.1, 0.75, 0.65, 0.2]) ax.plot(time, iwave, '-', linewidth=1, color=[0.5, 0.5, 0.5]) ax.plot(time, var, 'k', linewidth=1.5) ax.set_title('a) %s' % (title, )) if units != '': ax.set_ylabel(r'%s [$%s$]' % (label, units,)) else: ax.set_ylabel(r'%s' % (label, )) extent = [time.min(),time.max(),0,max(period)] # Second sub-plot, the normalized wavelet power spectrum and significance level # contour lines and cone of influece hatched area. bx = plt.axes([0.1, 0.37, 0.65, 0.28], sharex=ax) im = NonUniformImage(bx, interpolation='bilinear', extent=extent) im.set_data(time, period, power/scales[:, None]) bx.images.append(im) bx.contour(time, period, sig95, [-99, 1], colors='k', linewidths=2, extent=extent) bx.fill(np.concatenate([time, time[-1:]+dt, time[-1:]+dt,time[:1]-dt, time[:1]-dt]), (np.concatenate([coi,[1e-9], period[-1:], period[-1:], [1e-9]])), 'k', alpha=0.3,hatch='x') bx.set_title('b) %s Wavelet Power Spectrum (%s)' % (label, mother.name)) bx.set_ylabel('Period (years)') # Third sub-plot, the global wavelet and Fourier power spectra and theoretical # noise spectra. cx = plt.axes([0.77, 0.37, 0.2, 0.28], sharey=bx) cx.plot(glbl_signif, (period), 'k--') cx.plot(glbl_power, (period), 'k-', linewidth=1.5) cx.set_title('c) Global Wavelet Spectrum')
x = np.random.normal(2, 1, 100) y = np.random.normal(1, 1, 100) H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges)) H = H.T # Let each row list bins with common y range. # :func:`imshow <matplotlib.pyplot.imshow>` can only display square bins: fig = plt.figure(figsize=(7, 3)) ax = fig.add_subplot(131, title='imshow: square bins') plt.imshow(H, interpolation='nearest', origin='low', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]]) # :func:`pcolormesh <matplotlib.pyplot.pcolormesh>` can display actual edges: ax = fig.add_subplot(132, title='pcolormesh: actual edges', aspect='equal') X, Y = np.meshgrid(xedges, yedges) ax.pcolormesh(X, Y, H) # :class:`NonUniformImage <matplotlib.image.NonUniformImage>` can be used to # display actual bin edges with interpolation: ax = fig.add_subplot(133, title='NonUniformImage: interpolated', aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]]) im = NonUniformImage(ax, interpolation='bilinear') xcenters = (xedges[:-1] + xedges[1:]) / 2 ycenters = (yedges[:-1] + yedges[1:]) / 2 im.set_data(xcenters, ycenters, H) ax.images.append(im) plt.show()
def contourplot(self, dat=None, config=None, xvals=None, yvals=None, zgrid=None, xlab='m/z (Th)', ylab="Charge", title='', normflag=1, normrange=[0, 1], repaint=True, nticks=None, test_kda=False, discrete=None, ticloc=None, ticlab=None): """ Make 2D plot. Data can be added using two methods: 1. If dat is specified, it will look for an N x 3 list of x,y,z values 2. If xvals, yvals, and zgrid are filled, it will plot zgrid assuming its shape is (len(xvals),len(yvals)) :param dat: N x 3 list in [x,y,z] format of data to be plotted :param config: UniDecConfig object :param xvals: x-axis values :param yvals: y-axis values :param zgrid: numpy array of shape (len(xvals),len(yvals)) :param xlab: Label for x-axis :param ylab: Label for y-axis :param title: Plot title :param normflag: Set to 1 to normalize the plot range from min to max. If 0, will not normalize. :param normrange: Range to normalize to if normflag is 0. :param repaint: If true, will repaint the plot after it is done. :param nticks: Number of ticks on the x-axis. If None, will use default. :param test_kda: If true, will decide if the x-axis is better displayed in Da or kDa units. :return: None """ # Clear Plot self.clear_plot('nopaint') # Set xlabel and ylabel self.xlabel = xlab self.ylabel = ylab # Get values from config if config is not None: speedplot = config.discreteplot publicationmode = config.publicationmode self.cmap = config.cmap else: speedplot = 0 publicationmode = 0 self.cmap = u"jet" if discrete is not None: speedplot = discrete # Set Tick colors self.set_tickcolor() # If data is coming in as 1D list in dat, reshape it if xvals is None or yvals is None or zgrid is None: zgrid = dat[:, 2] xvals = np.unique(dat[:, 0]) yvals = np.unique(dat[:, 1]) xlen = len(xvals) ylen = len(yvals) newgrid = np.reshape(zgrid, (xlen, ylen)) # Test if we should plot kDa instead of Da if test_kda: self.kda_test(xvals) # Decide whether or not to normalize if normflag == 1: norm = cm.colors.Normalize(vmax=np.amax(newgrid), vmin=np.amin(newgrid)) else: norm = cm.colors.Normalize(vmax=normrange[1], vmin=normrange[0]) # Add axes self.subplot1 = self.figure.add_axes(self._axes) # Plot # speedplot=0 if speedplot == 0: # Slow contour plot that interpolates grid b1 = newgrid > 0.01 * np.amax(newgrid) #If the data is sparse, use the tricontourf, otherwise, use the regular contourf if np.sum(b1)/len(newgrid.ravel()) < 0.1: try: b1 = b1.astype(float) b1 = filt.uniform_filter(b1, size=3) > 0 b1[0, 0] = True b1[0, -1] = True b1[-1, 0] = True b1[-1, -1] = True X2, Y2 = np.meshgrid(xvals, yvals, indexing="ij") X2 = np.ravel(X2[b1]) Y2 = np.ravel(Y2[b1]) Z2 = np.ravel(newgrid[b1].transpose()) cax = self.subplot1.tricontourf(X2 / self.kdnorm, Y2, Z2, 100, cmap=self.cmap, norm=norm) except Exception as e: print("Error with fast tricontourf plot", e) cax = self.subplot1.contourf(xvals / self.kdnorm, yvals, np.transpose(newgrid), 100, cmap=self.cmap, norm=norm) else: cax = self.subplot1.contourf(xvals / self.kdnorm, yvals, np.transpose(newgrid), 100, cmap=self.cmap, norm=norm) datalims = [np.amin(xvals) / self.kdnorm, np.amin(yvals), np.amax(xvals) / self.kdnorm, np.amax(yvals)] else: # Fast discrete plot using imshow try: xdiff = (xvals[1] - xvals[0]) / self.kdnorm ydiff = yvals[1] - yvals[0] except: xdiff = 1 ydiff = 1 extent = (np.amin(xvals) / self.kdnorm - 0.5 * xdiff, np.amax(xvals) / self.kdnorm + 0.5 * xdiff, np.amin(yvals) - 0.5 * ydiff, np.amax(yvals) + 0.5 * ydiff) try: ax = self.subplot1 im = NonUniformImage(ax, interpolation="nearest", extent=extent, cmap=self.cmap, norm=norm,) im.set_data(xvals / self.kdnorm, yvals, np.transpose(newgrid)) ax.images.append(im) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) cax = im except Exception as e: print("Error in NonUniformImage:", e) cax = self.subplot1.imshow(np.transpose(newgrid), origin="lower", cmap=self.cmap, extent=extent, aspect='auto', norm=norm, interpolation='nearest') datalims = [extent[0], extent[2], extent[1], extent[3]] print(newgrid.shape) # Set X and Y axis labels self.subplot1.set_xlabel(self.xlabel) self.subplot1.set_ylabel(self.ylabel) # Set Title if publicationmode == 0: self.subplot1.set_title(title) # Set colorbar if normflag == 1: self.cbar = self.figure.colorbar(cax, ax=None, use_gridspec=True, ticks=[0, np.amax(newgrid) / 2, np.amax(newgrid)]) self.cbar.ax.get_yaxis().set_tick_params(direction='out') self.cbar.ax.set_yticklabels(["0", "%", "100"]) else: self.cbar = self.figure.colorbar(cax, ax=None, use_gridspec=True) # Change tick colors if nticks is not None: self.subplot1.xaxis.set_major_locator(MaxNLocator(nbins=nticks)) if ticloc is not None and ticlab is not None: self.subplot1.xaxis.set_major_locator(FixedLocator(ticloc)) self.subplot1.set_xticklabels(ticlab, rotation=90, fontsize=8) ''' for line in self.subplot1.xaxis.get_ticklines(): line.set_color(self.tickcolor) for line in self.subplot1.yaxis.get_ticklines(): line.set_color(self.tickcolor) ''' # Setup zoom and repaint self.setup_zoom([self.subplot1], 'box', data_lims=datalims) if repaint: self.repaint() self.flag = True
def visuRunout(rasterTransfo, resAnalysis, pLim, newRasters, cfgPath, cfgFlags): """ Plot and save the Peak Pressure distribution after coord transfo """ # read paths pathResult = cfgPath['pathResult'] projectName = cfgPath['dirName'] # read data scoord = rasterTransfo['s'] lcoord = rasterTransfo['l'] indRunoutPoint = rasterTransfo['indRunoutPoint'] sBeta = scoord[indRunoutPoint] rasterArea = rasterTransfo['rasterArea'] dataPressure = newRasters['newRasterPressure'] rasterdataPres = dataPressure[0] # ana3AIMEC.makeRasterAverage(dataPressure) runout = resAnalysis['runout'][0] + sBeta runoutMean = resAnalysis['runoutMean'][0] + sBeta pCrossAll = resAnalysis['pCrossAll'] # prepare for plot pMean = np.mean(pCrossAll, axis=0) pMedian = np.median(pCrossAll, axis=0) pPercentile = sp.percentile(pCrossAll, [2.5, 50, 97.5], axis=0) fig = plt.figure(figsize=(figW*2, figH), dpi=figReso) ax1 = plt.subplot(121) ax1.title.set_text('Peak Pressure 2D plot for the reference') ref1 = ax1.axhline(y=scoord[indRunoutPoint], color='k', linewidth=lw, linestyle='-', label='Beta point') ref1 = ax1.axhline(y=np.max(runout), color='r', linewidth=lw, linestyle='-', label='runout max') ref2 = ax1.axhline(y=np.average(runout), color='y', linewidth=lw, linestyle='-', label='runout mean') ref3 = ax1.axhline(y=np.min(runout), color='g', linewidth=lw, linestyle='-', label='runout min') # ref3 = ax1.plot(np.zeros(np.shape(scoord)), scoord,'.r', linewidth=0.1) isosurf = copy.deepcopy(rasterdataPres) xx, yy = np.meshgrid(lcoord, scoord) maskedArray = np.ma.masked_where(isosurf == 0, isosurf) cmap = cmapPres cmap.set_bad('w', 1.) im = NonUniformImage(ax1, extent=[xx.min(), xx.max(), yy.min(), yy.max()], cmap=cmap) # im.set_interpolation('bilinear') im.set_data(lcoord, scoord, maskedArray) ref0 = ax1.images.append(im) cbar = ax1.figure.colorbar(im, ax=ax1, use_gridspec=True) cbar.ax.set_ylabel('peak pressure [kPa]') plt.autoscale(False) ax1.set_xlim([xx.min(), xx.max()]) ax1.set_ylim([yy.min(), yy.max()]) ax1.set_xlabel(r'$l\;[m]$') ax1.set_ylabel(r'$s\;[m]$') ax1.legend(loc=0) ax2 = plt.subplot(122) ax2.title.set_text('Peak Pressure distribution along the path between runs') ax2.fill_betweenx(scoord, pPercentile[2], pPercentile[0], facecolor=[.8, .8, .8], alpha=0.5, label='quantiles') ref1 = mpatches.Patch(alpha=0.5, color=[.8, .8, .8]) ref2 = ax2.plot(pMedian, scoord, color='r', linewidth=2*lw, label='median') ref3 = ax2.plot(pMean, scoord, color='b', linewidth=lw, label='mean') # ref3 = mlines.Line2D([], [], color='b', linewidth=2) ax2.set_ylabel(r'$l\;[m]$') ax2.set_ylim([yy.min(), yy.max()]) ax2.set_xlim(auto=True) ax2.set_xlabel(r'$P_max(s)\;[kPa]$') ax2.legend(loc=0) fig.tight_layout() if cfgFlags.getboolean('savePlot'): outname = ''.join([pathResult, os.path.sep, 'pics', os.path.sep, projectName, '_dptr', str(int(pLim)), '_slComparison', '.pdf']) if not os.path.exists(os.path.dirname(outname)): os.makedirs(os.path.dirname(outname)) fig.savefig(outname, transparent=True) if cfgFlags.getboolean('plotFigure'): plt.show() else: plt.ioff() plt.close(fig)
def single_plot(data, x, y, axes=None, beta=None, cbar_label='', cmap=plt.get_cmap('RdBu'), vmin=None, vmax=None, phase_speeds=True, manual_locations=False, **kwargs): """ Plot a single frame Time-Distance Diagram on physical axes. This function uses mpl NonUniformImage to plot a image using x and y arrays, it will also optionally over plot in contours beta lines. Parameters ---------- data: np.ndarray The 2D image to plot x: np.ndarray The x coordinates y: np.ndarray The y coordinates axes: matplotlib axes instance [*optional*] The axes to plot the data on, if None, use plt.gca(). beta: np.ndarray [*optional*] The array to contour over the top, default to none. cbar_label: string [*optional*] The title label for the colour bar, default to none. cmap: A matplotlib colour map instance [*optional*] The colourmap to use, default to 'RdBu' vmin: float [*optional*] The min scaling for the image, default to the image limits. vmax: float [*optional*] The max scaling for the image, default to the image limits. phase_speeds : bool Add phase speed lines to the plot manual_locations : bool Array for clabel locations. Returns ------- None """ if axes is None: axes = plt.gca() x = x[:xxlim] data = data[:,:xxlim] im = NonUniformImage(axes,interpolation='nearest', extent=[x.min(),x.max(),y.min(),y.max()],rasterized=False) im.set_cmap(cmap) if vmin is None and vmax is None: lim = np.max([np.nanmax(data), np.abs(np.nanmin(data))]) im.set_clim(vmax=lim,vmin=-lim) else: im.set_clim(vmax=vmax,vmin=vmin) im.set_data(x,y,data) im.set_interpolation('nearest') axes.images.append(im) axes.set_xlim(x.min(),x.max()) axes.set_ylim(y.min(),y.max()) cax0 = make_axes_locatable(axes).append_axes("right", size="5%", pad=0.05) cbar0 = plt.colorbar(im, cax=cax0, ticks=mpl.ticker.MaxNLocator(7)) cbar0.set_label(cbar_label) cbar0.solids.set_edgecolor("face") kwergs = {'levels': [1., 1/3., 1/5., 1/10., 1/20.]} kwergs.update(kwargs) if beta is not None: ct = axes.contour(x,y,beta[:,:xxlim],colors=['k'], **kwergs) plt.clabel(ct,fontsize=14,inline_spacing=3, manual=manual_locations, fmt=mpl.ticker.FuncFormatter(betaswap)) axes.set_xlabel("Time [s]") axes.set_ylabel("Height [Mm]")
power1 = (np.abs(W1))**2 # Normalized wavelet power spectrum power2 = (np.abs(W2))**2 # Normalized wavelet power spectrum period1 = 1 / freqs1 period2 = 1 / freqs2 sig95_1 = np.ones([1, n1]) * signif1[:, None] sig95_1 = power1 / sig95_1 # Where ratio > 1, power is significant sig95_2 = np.ones([1, n2]) * signif2[:, None] sig95_2 = power2 / sig95_2 # Where ratio > 1, power is significant # First plot is of both CWT fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, sharex=True) extent1 = [t1.min(), t1.max(), 0, max(period1)] extent2 = [t2.min(), t2.max(), 0, max(period2)] im1 = NonUniformImage(ax1, interpolation='bilinear', extent=extent1) im1.set_data(t1, period1, power1) ax1.images.append(im1) ax1.contour(t1, period1, sig95_1, [-99, 1], colors='k', linewidths=2, extent=extent1) ax1.fill(np.concatenate( [t1, t1[-1:] + dt, t1[-1:] + dt, t1[:1] - dt, t1[:1] - dt]), np.concatenate([coi1, [1e-9], period1[-1:], period1[-1:], [1e-9]]), 'k', alpha=0.3, hatch='x') ax1.set_title('{} Wavelet Power Spectrum ({})'.format(data1['nick'], mother.name))
from matplotlib.pyplot import figure, show import numpy as npy from matplotlib.image import NonUniformImage x = npy.arange(-4, 4, 0.005) y = npy.arange(-4, 4, 0.005) print 'Size %d points' % (len(x) * len(y)) z = npy.sqrt(x[npy.newaxis,:]**2 + y[:,npy.newaxis]**2) fig = figure() ax = fig.add_subplot(111) im = NonUniformImage(ax, extent=(-4,4,-4,4)) im.set_data(x, y, z) ax.images.append(im) ax.set_xlim(-4,4) ax.set_ylim(-4,4) fig2 = figure() ax = fig2.add_subplot(111) x2 = x**3 im = NonUniformImage(ax, extent=(-64,64,-4,4)) im.set_data(x2, y, z) ax.images.append(im) ax.set_xlim(-64,64) ax.set_ylim(-4,4) show()
def tsys_show_dynspec(out,idx=None,ampscl=None,domedian=True,frq='linear'): ''' Given "standard" output of rd_tsys_multi(), possibly calibrated using calibration.sp_apply_cal() and/or background-subtracted using calibration.sp_bg_subtract(), make a nice image plot of the dynamic spectrum. The plot can contain multiple panels if domedian is False, or plot a single spectrum representing the median of multiple antennas. Only linear frequency scale is supported at this time. ''' from matplotlib.image import NonUniformImage from matplotlib.dates import AutoDateLocator, DateFormatter from matplotlib import colors from matplotlib.pyplot import locator_params from util import Time nant, npol, nf, nt = out['tsys'].shape if idx is None: idx_ = np.arange(nt) else: idx_ = idx ut = Time(out['ut_mjd'][idx_],format='mjd') utd = (ut.mjd - int(ut[0].mjd) + 1).astype('float') good = np.where(out['fghz'] > 2.0)[0] if frq == 'linear': fghz = out['fghz'][good] else: fghz = np.log10(out['fghz'][good]) locator = AutoDateLocator(interval_multiples=True) #maxticks=7,minticks=3, tsys = out['tsys'][:,:,good,idx_] if domedian: medtsys = np.nanmedian(np.nanmedian(tsys,0),0) fig = plt.figure() fig.suptitle('EOVSA Total Power Data for '+ut[0].iso[:10],fontsize=14) # Plot X-feed ax = fig.add_subplot(211) ax.xaxis_date() ax.set_ylabel('Frequency [GHz]') ax.set_title('Median Total Power') extent=[utd[0],utd[-1],fghz[0],fghz[-1]] # extent=[ut[0],ut[-1],fghz[0],fghz[-1]] im = NonUniformImage(ax,extent=extent) if ampscl != None: im.set_norm(colors.Normalize(vmin=ampscl[0],vmax=ampscl[1])) im.set_data(utd,fghz,medtsys) #fig.colorbar(im,ax) ax.images.append(im) ax.set_xlim(extent[0],extent[1]) ax.set_ylim(extent[2],extent[3]) ax.xaxis.set_major_locator(locator) #ax.xaxis.set_minor_locator(MinuteLocator(interval=10)) # Set up date formatting fmt = DateFormatter('%H:%M:%S') ax.xaxis.set_major_formatter(fmt) labels = (10**ax.get_yticks()).astype('str') for i in range(len(labels)): labels[i] = labels[i][:4] ax.set_yticklabels(labels) # Repeat for Y-feed ax = fig.add_subplot(212) ax.xaxis_date() ax.set_xlabel('Start time '+ut[0].iso[:19]+' UT') ax.set_title('Median of Y-poln') ax.set_ylabel('Frequency [GHz]') im = NonUniformImage(ax,extent=extent) if ampscl != None: im.set_norm(colors.Normalize(vmin=ampscl[0],vmax=ampscl[1])) im.set_data(utd,fghz,medytsys) #fig.colorbar(im,ax) ax.images.append(im) ax.set_xlim(extent[0],extent[1]) ax.set_ylim(extent[2],extent[3]) ax.xaxis.set_major_locator(locator) # Set up date formatting ax.xaxis.set_major_formatter(fmt) ax.set_yticklabels(labels) plt.draw() plt.show()
def imshow_field(field, grid=None, ax=None, vmin=None, vmax=None, aspect='equal', norm=None, interpolation=None, non_linear_axes=False, cmap=None, mask=None, mask_color='k', grid_units=1, *args, **kwargs): '''Display a two-dimensional image on a matplotlib figure. This function serves as an easy replacement for the matplotlib.pyplot.imshow() function. Its signature mostly folows that of matplotlib, with a few minor differences. Parameters ---------- field : Field or ndarray The field that we want to display. If this is an ndarray, then the parameter `grid` needs to be supplied. If the field is complex, then it will be automatically fed into :func:`complex_field_to_rgb`. If the field is a vector field with length 3 or 4, these will be interpreted as an RGB or RGBA field. grid : Grid or None If a grid is supplied, it will be used instead of the grid of `field`. ax : matplotlib axes The axes which to draw on. If it is not given, the current axes will be used. vmin : scalar The minimum value on the colorbar. If it is not given, then the minimum value of the field will be used. vmax : scalar The maximum value on the colorbar. If it is not given, then the maximum value of the field will be used. aspect : ['auto', 'equal', scalar] If 'auto', changes the image aspect ratio to match that of the axes. If 'equal', changes the axes aspect ratio to match that of the image. norm : Normalize A Normalize instance is used to scale the input to the (0, 1) range for input to the `cmap`. If it is not given, a linear scale will be used. interpolation : string The interpolation method used. The default is 'nearest'. Supported values are {'nearest', 'bilinear'}. non_linear_axes : boolean If axes are scaled in a non-linear way, for example on a log plot, then imshow_field needs to use a more expensive implementation. This parameter is to indicate that this algorithm needs to be used. cmap : Colormap or None The colormap with which to plot the image. It is ignored if a complex field or a vector field is supplied. mask : field or ndarray If part of the image needs to be masked, this mask is overlayed on top of the image. This is for example useful when plotting a phase pattern on a certain aperture, which has no meaning outside of the aperture. Masks can be partially translucent, and will be automatically scaled between (0, 1). Zero means invisible, one means visible. mask_color : Color The color of the mask, if it is used. grid_units : scalar or array_like The size of a unit square. The grid will be scaled by the inverse of this number before plotting. If this is a scalar, an isotropic scaling will be applied. Returns ------- AxesImage The produced image. ''' import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.image import NonUniformImage if ax is None: ax = plt.gca() ax.set_aspect(aspect) # Set/Find the correct grid and scale according to received grid units. if grid is None: if np.allclose(grid_units, 1): grid = field.grid else: grid = field.grid.scaled(1.0 / grid_units) else: if np.allclose(grid_units, 1): field = Field(field, grid) else: grid = grid.scaled(1.0 / grid_units) field = Field(field, grid) # If field is complex, draw complex if np.iscomplexobj(field): f = complex_field_to_rgb(field, rmin=vmin, rmax=vmax, norm=norm) vmin = None vmax = None norm = None else: f = field # Automatically determine vmin, vmax, norm if not overridden if norm is None and not np.iscomplexobj(field): if vmin is None: vmin = np.nanmin(f) if vmax is None: vmax = np.nanmax(f) norm = mpl.colors.Normalize(vmin, vmax) # Get extent c_grid = grid.as_('cartesian') min_x, min_y, max_x, max_y = c_grid.x.min(), c_grid.y.min(), c_grid.x.max(), c_grid.y.max() if grid.is_separated and grid.is_('cartesian'): # We can draw this directly x, y = grid.coords.separated_coords z = f.shaped if np.iscomplexobj(field) or field.tensor_order > 0: z = np.rollaxis(z, 0, z.ndim) else: # We can't draw this directly. raise NotImplementedError() if non_linear_axes: # Use pcolormesh to display x_mid = (x[1:] + x[:-1]) / 2 y_mid = (y[1:] + y[:-1]) / 2 x2 = np.concatenate(([1.5 * x[0] - 0.5 * x[1]], x_mid, [1.5 * x[-1] - 0.5 * x[-2]])) y2 = np.concatenate(([1.5 * y[0] - 0.5 * y[1]], y_mid, [1.5 * y[-1] - 0.5 * y[-2]])) X, Y = np.meshgrid(x2, y2) im = ax.pcolormesh(X, Y, z, *args, norm=norm, rasterized=True, cmap=cmap, **kwargs) else: # Use NonUniformImage to display im = NonUniformImage(ax, extent=(min_x, max_x, min_y, max_y), interpolation=interpolation , norm=norm, cmap=cmap, *args, **kwargs) im.set_data(x, y, z) from matplotlib.patches import Rectangle patch = Rectangle((min_x, min_y), max_x - min_x, max_y - min_y, facecolor='none') ax.add_patch(patch) im.set_clip_path(patch) ax.images.append(im) ax.set_xlim(min_x, max_x) ax.set_ylim(min_y, max_y) if mask is not None: one = np.ones(grid.size) col = mpl.colors.to_rgb(mask_color) m = np.array([one * col[0], one * col[1], one * col[2], 1 - mask / np.nanmax(mask)]) imshow_field(m, grid, ax=ax) num_rows, num_cols = field.grid.shape def format_coord(x, y): # pragma: no cover col = int(np.round((x - min_x) / (max_x - min_x) * (num_cols - 1))) row = int(np.round((y - min_y) / (max_y - min_y) * (num_rows - 1))) if col >= 0 and col < num_cols and row >= 0 and row < num_rows: z = field.shaped[row, col] if np.iscomplexobj(z): return 'x=%0.3g, y=%0.3g, z=%0.3g + 1j * %0.3g = %0.3g * exp(1j * %0.2f)' % (x, y, z.real, z.imag, np.abs(z), np.angle(z)) else: return 'x=%0.3g, y=%0.3g, z=%0.3g' % (x, y, z) return 'x=%0.3g, y=%0.3g' % (x, y) ax.format_coord = format_coord ax._sci(im) return im
import numpy as np import matplotlib.pyplot as plt from matplotlib.image import NonUniformImage from ndtable import NDTable def peaks(x=np.linspace(-3, 3, 49), y=np.linspace(-3, 3, 49)): X, Y = np.meshgrid(x, y) Z = 3*(1-X)**2 * np.e**(-(X**2) - (Y+1)**2) - 10*(X/5 - X**3 - Y**5) * np.e**(-X**2-Y**2) - 1/3 * np.e**(-(X+1)**2 - Y**2) return X, Y, Z x = y = np.linspace(-3, 3, 20) _, _, Z = peaks(x, y) table = NDTable(Z, (x, y)) xi = yi = np.linspace(-10, 10, 100) XI, YI = np.meshgrid(xi, yi) figure = plt.figure(figsize=(10, 5)) figure.canvas.set_window_title('Extrapolation Methods') for i, method in enumerate(['hold', 'linear']): ZI = table.evaluate((XI, YI), interp='linear', extrap=method) ax = figure.add_subplot(1,2,i+1) ax.set_title(method) im = NonUniformImage(ax) im.set_data(xi, yi, ZI) im.set_extent((-10, 10, -10, 10)) ax.images.append(im) plt.show()
fig = plt.figure() ax = fig.add_subplot(111) #interp='nearest' # "raw" (non smooth) map interp = 'bilinear' # "smooth" map # NonUniformImage permet de définir la position des éléments de 'z_matrix' sur # les axes. # Sans NonUniformImage, une matrice 'z_matrix' de taille (sx, sy) serait # dessinée sur un repère avec un axe des abscisses allant de 0 a sx et un axe # des ordonnées allant de 0 a sy. im = NonUniformImage(ax, interpolation=interp, extent=(X_MIN, X_MAX, Y_MIN, Y_MAX), cmap=cm.binary) # im.set_data(x, y, A) # Set the grid for the pixel centers, and the pixel values. # *x* and *y* are 1-D ndarrays of lengths N and M, respectively, specifying pixel centers # *A* is an (M,N) ndarray or masked array of values to be colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA array. im.set_data(x, y, z_matrix) ax.images.append(im) ax.set_xlim(X_MIN, X_MAX) ax.set_ylim(Y_MIN, Y_MAX) fig.colorbar(im) # draw colorbar # Save file and plot ######## plt.savefig("colour_map_with_custom_axes.png") plt.show()
def tsys_show_dynspec(out,idx=None,ampscl=None,domedian=True,frq='linear'): ''' Given "standard" output of rd_tsys_multi(), possibly calibrated using calibration.sp_apply_cal() and/or background-subtracted using calibration.sp_bg_subtract(), make a nice image plot of the dynamic spectrum. The plot can contain multiple panels if domedian is False, or plot a single spectrum representing the median of multiple antennas. Only linear frequency scale is supported at this time. ''' from matplotlib.image import NonUniformImage from matplotlib.dates import AutoDateLocator, DateFormatter from matplotlib import colors from matplotlib.pyplot import locator_params from util import Time nant, npol, nf, nt = out['tsys'].shape if idx is None: idx_ = np.arange(nt) else: idx_ = idx ut = Time(out['ut_mjd'][idx_],format='mjd') utd = (ut.mjd - int(ut[0].mjd) + 1).astype('float') good = np.where(out['fghz'] > 2.0)[0] if frq == 'linear': fghz = out['fghz'][good] else: fghz = np.log10(out['fghz'][good]) locator = AutoDateLocator(interval_multiples=True) #maxticks=7,minticks=3, tsys = out['tsys'][:,:,good,idx_] if domedian: medtsys = np.nanmedian(np.nanmedian(tsys,0),0) fig = plt.figure() fig.suptitle('EOVSA Total Power Data for '+ut[0].iso[:10],fontsize=14) # Plot X-feed ax = fig.add_subplot(211) ax.xaxis_date() ax.set_ylabel('Frequency [GHz]') ax.set_title('Median Total Power') extent=[utd[0],utd[-1],fghz[0],fghz[-1]] # extent=[ut[0],ut[-1],fghz[0],fghz[-1]] im = NonUniformImage(ax,extent=extent) if ampscl != None: im.set_norm(colors.Normalize(vmin=ampscl[0],vmax=ampscl[1])) im.set_data(utd,fghz,medtsys) #fig.colorbar(im,ax) ax.images.append(im) ax.set_xlim(extent[0],extent[1]) ax.set_ylim(extent[2],extent[3]) ax.xaxis.set_major_locator(locator) #ax.xaxis.set_minor_locator(MinuteLocator(interval=10)) # Set up date formatting fmt = DateFormatter('%H:%M:%S') ax.xaxis.set_major_formatter(fmt) labels = (10**ax.get_yticks()).astype('str') for i in range(len(labels)): labels[i] = labels[i][:4] ax.set_yticklabels(labels) # Repeat for Y-feed ax = fig.add_subplot(212) ax.xaxis_date() ax.set_xlabel('Start time '+ut[0].iso[:19]+' UT') ax.set_title('Median of Y-poln') ax.set_ylabel('Frequency [GHz]') im = NonUniformImage(ax,extent=extent) if ampscl != None: im.set_norm(colors.Normalize(vmin=ampscl[0],vmax=ampscl[1])) im.set_data(utd,fghz,medytsys) #fig.colorbar(im,ax) ax.images.append(im) ax.set_xlim(extent[0],extent[1]) ax.set_ylim(extent[2],extent[3]) ax.xaxis.set_major_locator(locator) # Set up date formatting ax.xaxis.set_major_formatter(fmt) ax.set_yticklabels(labels) plt.draw() plt.show()
def cross_wavelet(self, signal_1, signal_2, mother='morlet', plot=True): signal_1 = (signal_1 - signal_1.mean()) / signal_1.std() # Normalizing signal_2 = (signal_2 - signal_2.mean()) / signal_2.std() # Normalizing W12, cross_coi, freq, signif = wavelet.xwt(signal_1, signal_2, self.period, dj=1/100, s0=-1, J=-1, significance_level=0.95, wavelet=mother, normalize=True) cross_power = np.abs(W12)**2 cross_sig = np.ones([1, signal_1.size]) * signif[:, None] cross_sig = cross_power / cross_sig cross_period = 1/freq WCT, aWCT, corr_coi, freq, sig = wavelet.wct(signal_1, signal_2, self.period, dj=1/100, s0=-1, J=-1, sig=False,significance_level=0.95, wavelet=mother, normalize=True) cor_sig = np.ones([1, signal_1.size]) * sig[:, None] cor_sig = np.abs(WCT) / cor_sig cor_period = 1/freq angle = 0.5 * np.pi - aWCT u, v = np.cos(angle), np.sin(angle) t1 = np.linspace(0,self.period*signal_1.size,signal_1.size) ## indices for stuff idx = self.find_closest(cor_period,corr_coi.max()) ## Into minutes t1 /= 60 cross_period /= 60 cor_period /= 60 cross_coi /= 60 corr_coi /= 60 fig1, ax1 = plt.subplots(nrows=1,ncols=1, sharex=True, sharey=True, figsize=(12,12)) extent_cross = [t1.min(),t1.max(),0,max(cross_period)] extent_corr = [t1.min(),t1.max(),0,max(cor_period)] im1 = NonUniformImage(ax1, interpolation='nearest', extent=extent_cross) im1.set_cmap('cubehelix') im1.set_data(t1, cross_period[:idx], cross_power[:idx,:]) ax1.images.append(im1) ax1.contour(t1, cross_period[:idx], cross_sig[:idx,:], [-99, 1], colors='k', linewidths=2, extent=extent_cross) ax1.fill(np.concatenate([t1, t1[-1:]+self.period, t1[-1:]+self.period,t1[:1]-self.period, t1[:1]-self.period]), (np.concatenate([cross_coi,[1e-9], cross_period[-1:], cross_period[-1:], [1e-9]])), 'k', alpha=0.3,hatch='x') ax1.set_title('Cross-Wavelet') # ax1.quiver(t1[::3], cross_period[::3], u[::3, ::3], # v[::3, ::3], units='width', angles='uv', pivot='mid', # linewidth=1.5, edgecolor='k', headwidth=10, headlength=10, # headaxislength=5, minshaft=2, minlength=5) ax1.set_ylim(([min(cross_period), cross_period[idx]])) ax1.set_xlim(t1.min(),t1.max()) fig2, ax2 = plt.subplots(nrows=1,ncols=1, sharex=True, sharey=True, figsize=(12,12)) fig2.subplots_adjust(right=0.8) cbar_ax_1 = fig2.add_axes([0.85, 0.05, 0.05, 0.35]) im2 = NonUniformImage(ax2, interpolation='nearest', extent=extent_corr) im2.set_cmap('cubehelix') im2.set_data(t1, cor_period[:idx], np.log10(WCT[:idx,:])) ax2.images.append(im2) ax2.contour(t1, cor_period[:idx], cor_sig[:idx,:], [-99, 1], colors='k', linewidths=2, extent=extent_corr) ax2.fill(np.concatenate([t1, t1[-1:]+self.period, t1[-1:]+self.period,t1[:1]-self.period, t1[:1]-self.period]), (np.concatenate([corr_coi,[1e-9], cor_period[-1:], cor_period[-1:], [1e-9]])), 'k', alpha=0.3,hatch='x') ax2.set_title('Cross-Correlation') # ax2.quiver(t1[::3], cor_period[::3], u[::3,::3], v[::3,::3], # units='height', angles='uv', pivot='mid',linewidth=1.5, edgecolor='k', # headwidth=10, headlength=10, headaxislength=5, minshaft=2, minlength=5) ax2.set_ylim(([min(cor_period), cor_period[idx]])) ax2.set_xlim(t1.min(),t1.max()) fig2.colorbar(im2, cax=cbar_ax_1) plt.show() plt.figure(figsize=(12,12)) im3= plt.imshow(np.rad2deg(aWCT), origin='lower',interpolation='nearest', cmap='seismic', extent=extent_corr) plt.fill(np.concatenate([t1, t1[-1:]+self.period, t1[-1:]+self.period,t1[:1]-self.period, t1[:1]-self.period]), (np.concatenate([corr_coi,[1e-9], cor_period[-1:], cor_period[-1:], [1e-9]])), 'k', alpha=0.3,hatch='x') plt.ylim(([min(cor_period), cor_period[idx]])) plt.xlim(t1.min(),t1.max()) plt.colorbar(im3) plt.show() return
def _do_2d_output(self, hist, idims, midpoints, binbounds): enehist = self._ener_zero(hist) log10hist = numpy.log10(hist) if self.hdf5_output_filename: with h5py.File(self.hdf5_output_filename, 'w') as output_h5: h5io.stamp_creator_data(output_h5) output_h5.attrs['source_data'] = os.path.abspath(self.input_h5.filename) output_h5.attrs['source_dimensions'] = numpy.array(idims, numpy.min_scalar_type(max(idims))) output_h5.attrs['source_dimension_labels'] = numpy.array([dim['label'] for dim in self.dimensions]) for idim in idims: output_h5['midpoints_{}'.format(idim)] = midpoints output_h5['histogram'] = hist if self.plot_output_filename: if self.plotscale == 'energy': plothist = enehist label = r'$\Delta F(\vec{x})\,/\,kT$' +'\n' + r'$\left[-\ln\,P(x)\right]$' elif self.plotscale == 'log10': plothist = log10hist label = r'$\log_{10}\ P(\vec{x})$' else: plothist = hist plothist[~numpy.isfinite(plothist)] = numpy.nan label = r'$P(\vec{x})$' try: vmin, vmax = self.plotrange except TypeError: vmin, vmax = None, None pyplot.figure() # Transpose input so that axis 0 is displayed as x and axis 1 is displayed as y # pyplot.imshow(plothist.T, interpolation='nearest', aspect='auto', # extent=(midpoints[0][0], midpoints[0][-1], midpoints[1][0], midpoints[1][-1]), # origin='lower', vmin=vmin, vmax=vmax) # The following reproduces the former calls to imshow and colorbar norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) ax = pyplot.gca() nui = NonUniformImage(ax, extent=(midpoints[0][0], midpoints[0][-1], midpoints[1][0], midpoints[1][-1]), origin='lower', norm=norm) nui.set_data(midpoints[0], midpoints[1], plothist.T) ax.images.append(nui) ax.set_xlim(midpoints[0][0], midpoints[0][-1]) ax.set_ylim(midpoints[1][0], midpoints[1][-1]) cb = pyplot.colorbar(nui) cb.set_label(label) pyplot.xlabel(self.dimensions[0]['label']) pyplot.xlim(self.dimensions[0].get('lb'), self.dimensions[0].get('ub')) pyplot.ylabel(self.dimensions[1]['label']) pyplot.ylim(self.dimensions[1].get('lb'), self.dimensions[1].get('ub')) if self.plottitle: pyplot.title(self.plottitle) if self.postprocess_function: self.postprocess_function(plothist, midpoints, binbounds) if self.plot_contour: pyplot.contour(midpoints[0], midpoints[1],plothist.T) pyplot.savefig(self.plot_output_filename)
def plotAnalysis(self, widget): Xvar = self.cbXAxis.get_active_text() Yvar = self.cbYAxis.get_active_text() Zvar = self.cbZAxis.get_active_text() if Xvar == None or Yvar == None or Zvar == None: return if Zvar == "None": XvarIndex = self.logfile.params().index(Xvar)+1 YvarIndex = self.logfile.params().index(Yvar)+1 rowiter = self.treemodelsorted.get_iter_first() values = defaultdict(list) while rowiter != None: X = self.treemodelsorted.get_value(rowiter,XvarIndex) Y = self.treemodelsorted.get_value(rowiter,YvarIndex) values[float(X)].append(float(Y)) rowiter = self.treemodelsorted.iter_next(rowiter) X = [] Y = [] for k in sorted(values.keys()): X.append(k) Y.append(mean(values[k])) self.axisAN.cla() self.figureAN.clf() self.axisAN = self.figureAN.add_subplot(111) self.axisAN.plot(X,Y, 'k', linewidth=4) self.axisAN.set_xlabel(Xvar) self.axisAN.set_ylabel(Yvar) self.canvasAN.draw() else: XvarIndex = self.logfile.params().index(Xvar)+1 YvarIndex = self.logfile.params().index(Yvar)+1 ZvarIndex = self.logfile.params().index(Zvar)+1 rowiter = self.treemodelsorted.get_iter_first() values = {} Ykeys = [] while rowiter != None: X = self.treemodelsorted.get_value(rowiter,XvarIndex) Y = self.treemodelsorted.get_value(rowiter,YvarIndex) Z = self.treemodelsorted.get_value(rowiter,ZvarIndex) Ykeys.append(Y) values.setdefault(X,defaultdict(list))[Y].append(Z) rowiter = self.treemodelsorted.iter_next(rowiter) Ykeys = unique(Ykeys) XY = [] for k in sorted(values.keys()): tmp = [] for k2 in sorted(Ykeys): if values[k].has_key(k2): tmp.append(mean(values[k][k2])) else: tmp.append(0) XY.append(tmp) Z = array(XY) self.axisAN.cla() self.figureAN.clf() self.axisAN = self.figureAN.add_subplot(111) im = NonUniformImage(self.axisAN, interpolation='nearest', extent=(min(values.keys()),max(values.keys()),min(Ykeys),max(Ykeys))) im.set_data(values.keys(), Ykeys, Z.transpose()) self.axisAN.images.append(im) self.axisAN.set_xlim(min(values.keys()),max(values.keys())) self.axisAN.set_ylim(min(Ykeys),max(Ykeys)) self.axisAN.set_xlabel(Xvar) self.axisAN.set_ylabel(Yvar) self.axisAN.set_title(Zvar) self.figureAN.colorbar(im) self.canvasAN.draw()
def go(self): '''Plot the evolution of the histogram for iterations self.iter_start to self.iter_stop''' idim = self.dimensions[0]['idim'] n_iters = self.input_h5['n_iter'][...] iiter_start = numpy.searchsorted(n_iters, self.iter_start) iiter_stop = numpy.searchsorted(n_iters, self.iter_stop) binbounds = self.input_h5['binbounds_{}'.format(idim)][...] midpoints = self.input_h5['midpoints_{}'.format(idim)][...] hists_ds = self.input_h5['histograms'] itercount = self.iter_stop - self.iter_start # We always round down, so that we don't have a dangling partial block at the end nblocks = itercount // self.iter_step block_iters = numpy.empty((nblocks,2), dtype=n_iters.dtype) blocked_hists = numpy.zeros((nblocks,hists_ds.shape[1+idim]), dtype=hists_ds.dtype) for iblock, istart in enumerate(xrange(iiter_start, iiter_start+nblocks*self.iter_step, self.iter_step)): istop = min(istart+self.iter_step, iiter_stop) histslice = hists_ds[istart:istop] # Sum over time histslice = numpy.add.reduce(histslice, axis=0) # Sum over other dimensions blocked_hists[iblock] = sum_except_along(histslice, idim) # Normalize normhistnd(blocked_hists[iblock], [binbounds]) block_iters[iblock,0] = n_iters[istart] block_iters[iblock,1] = n_iters[istop-1]+1 #enehists = -numpy.log(blocked_hists) enehists = self._ener_zero(blocked_hists) log10hists = numpy.log10(blocked_hists) if self.hdf5_output_filename: with h5py.File(self.hdf5_output_filename, 'w') as output_h5: h5io.stamp_creator_data(output_h5) output_h5.attrs['source_data'] = os.path.abspath(self.input_h5.filename) output_h5.attrs['source_dimension'] = idim output_h5['midpoints'] = midpoints output_h5['histograms'] = blocked_hists output_h5['n_iter'] = block_iters if self.plot_output_filename: if self.plotscale == 'energy': plothist = enehists label = r'$\Delta F(x)\,/\,kT$' +'\n' + r'$\left[-\ln\,P(x)\right]$' elif self.plotscale == 'log10': plothist = log10hists label = r'$\log_{10}\ P(x)$' else: plothist = blocked_hists label = r'$P(x)$' try: vmin, vmax = self.plotrange except TypeError: vmin, vmax = None, None pyplot.figure() norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) ax = pyplot.gca() nui = NonUniformImage(ax, extent=(midpoints[0], midpoints[-1], block_iters[0,-1], block_iters[-1,-1]), origin='lower', norm=norm) # not sure why plothist works but plothist.T doesn't, and the opposite is true # for _do_2d_output nui.set_data(midpoints, block_iters[:,-1], plothist) ax.images.append(nui) ax.set_xlim(midpoints[0], midpoints[-1]) ax.set_ylim(block_iters[0,-1], block_iters[-1,-1]) cb = pyplot.colorbar(nui) cb.set_label(label) pyplot.xlabel(self.dimensions[0]['label']) pyplot.xlim(self.dimensions[0].get('lb'), self.dimensions[0].get('ub')) pyplot.ylabel('WE Iteration') if self.plottitle: pyplot.title(self.plottitle) if self.postprocess_function: self.postprocess_function(plothist, midpoints, binbounds) pyplot.savefig(self.plot_output_filename)
x = np.linspace(-4, 4, 9) # Highly nonlinear x array: x2 = x**3 y = np.linspace(-4, 4, 9) z = np.sqrt(x[np.newaxis, :]**2 + y[:, np.newaxis]**2) fig, axs = plt.subplots(nrows=2, ncols=2) fig.subplots_adjust(bottom=0.07, hspace=0.3) fig.suptitle('NonUniformImage class', fontsize='large') ax = axs[0, 0] im = NonUniformImage(ax, interpolation=interp, extent=(-4, 4, -4, 4), cmap=cm.Purples) im.set_data(x, y, z) ax.images.append(im) ax.set_xlim(-4, 4) ax.set_ylim(-4, 4) ax.set_title(interp) ax = axs[0, 1] im = NonUniformImage(ax, interpolation=interp, extent=(-64, 64, -4, 4), cmap=cm.Purples) im.set_data(x2, y, z) ax.images.append(im) ax.set_xlim(-64, 64) ax.set_ylim(-4, 4) ax.set_title(interp) interp = 'bilinear'
power1 = (np.abs(W1)) ** 2 # Normalized wavelet power spectrum power2 = (np.abs(W2)) ** 2 # Normalized wavelet power spectrum period1 = 1/freqs1 period2 = 1/freqs2 sig95_1 = np.ones([1, n1]) * signif1[:, None] sig95_1 = power1 / sig95_1 # Where ratio > 1, power is significant sig95_2 = np.ones([1, n2]) * signif2[:, None] sig95_2 = power2 / sig95_2 # Where ratio > 1, power is significant # First plot is of both CWT fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, sharex=True) extent1 = [t1.min(), t1.max(), 0, max(period1)] extent2 = [t2.min(), t2.max(), 0, max(period2)] im1 = NonUniformImage(ax1, interpolation='bilinear', extent=extent1) im1.set_data(t1, period1, power1) ax1.images.append(im1) ax1.contour(t1, period1, sig95_1, [-99, 1], colors='k', linewidths=2, extent=extent1) ax1.fill(np.concatenate([t1, t1[-1:]+dt, t1[-1:]+dt, t1[:1]-dt, t1[:1]-dt]), np.concatenate([coi1, [1e-9], period1[-1:], period1[-1:], [1e-9]]), 'k', alpha=0.3, hatch='x') ax1.set_title('{} Wavelet Power Spectrum ({})'.format(data1['nick'], mother.name)) im2 = NonUniformImage(ax2, interpolation='bilinear', extent=extent2) im2.set_data(t2, period2, power2) ax2.images.append(im2) ax2.contour(t2, period2, sig95_2, [-99, 1], colors='k', linewidths=2, extent=extent2) ax2.fill(np.concatenate([t2, t2[-1:]+dt, t2[-1:]+dt, t2[:1]-dt, t2[:1]-dt]),
def _do_2d_output(self, hist, idims, midpoints, binbounds): enehist = self._ener_zero(hist) log10hist = numpy.log10(hist) if self.hdf5_output_filename: with h5py.File(self.hdf5_output_filename, 'w') as output_h5: h5io.stamp_creator_data(output_h5) output_h5.attrs['source_data'] = os.path.abspath( self.input_h5.filename) output_h5.attrs['source_dimensions'] = numpy.array( idims, numpy.min_scalar_type(max(idims))) output_h5.attrs['source_dimension_labels'] = numpy.array( [dim['label'] for dim in self.dimensions]) for idim in idims: output_h5['midpoints_{}'.format(idim)] = midpoints[idim] output_h5['histogram'] = hist if self.plot_output_filename: if self.plotscale == 'energy': plothist = enehist label = r'$-\ln\,P(x)\ [kT^{-1}]$' elif self.plotscale == 'log10': plothist = log10hist label = r'$\log_{10}\ P(\vec{x})$' else: plothist = hist plothist[~numpy.isfinite(plothist)] = numpy.nan label = r'$P(\vec{x})$' try: vmin, vmax = self.plotrange except TypeError: vmin, vmax = None, None pyplot.figure() # Transpose input so that axis 0 is displayed as x and axis 1 is displayed as y # pyplot.imshow(plothist.T, interpolation='nearest', aspect='auto', # extent=(midpoints[0][0], midpoints[0][-1], midpoints[1][0], midpoints[1][-1]), # origin='lower', vmin=vmin, vmax=vmax) # The following reproduces the former calls to imshow and colorbar norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) ax = pyplot.gca() nui = NonUniformImage(ax, extent=(midpoints[0][0], midpoints[0][-1], midpoints[1][0], midpoints[1][-1]), origin='lower', norm=norm) nui.set_data(midpoints[0], midpoints[1], plothist.T) ax.images.append(nui) ax.set_xlim(midpoints[0][0], midpoints[0][-1]) ax.set_ylim(midpoints[1][0], midpoints[1][-1]) cb = pyplot.colorbar(nui) cb.set_label(label) pyplot.xlabel(self.dimensions[0]['label']) pyplot.xlim(self.dimensions[0].get('lb'), self.dimensions[0].get('ub')) pyplot.ylabel(self.dimensions[1]['label']) pyplot.ylim(self.dimensions[1].get('lb'), self.dimensions[1].get('ub')) if self.plottitle: pyplot.title(self.plottitle) if self.postprocess_function: self.postprocess_function(plothist, midpoints, binbounds) if self.plot_contour: pyplot.contour(midpoints[0], midpoints[1], plothist.T) pyplot.savefig(self.plot_output_filename)
def plot_wcohere(WCT, t, freq, coi=None, sig=None, plot_period=False, ax=None, title="Wavelet Coherence", block=None, mask=None, cax=None): """ Plot wavelet coherence using results from calc_wave_coherence. Parameters ---------- *First 5 parameters can be obtained from from calc_wave_coherence WCT: 2D numpy array with coherence values t : 2D numpy array with sample_times freq : 1D numpy array with the frequencies wavelets were calculated at sig : 2D numpy array, default None Optional. Plots significance of waveform coherence contours. coi : 2D numpy array, default None Optional. Pass coi to plot cone of influence plot_period : bool Should the y-axis be in period or in frequency (Hz) ax : plt.axe, default None Optional ax object to plot into. title : str, default "Wavelet Coherence" Optional title for the graph block : [int, int] Plots only points between ints. Returns ------- tuple : (fig, wcohere_pvals) Where fig is a matplotlib Figure and result is a tuple consisting of [WCT, t, y_vals] """ dt = np.mean(np.diff(t)) if plot_period: y_vals = np.log2(1 / freq) if not plot_period: y_vals = np.log2(freq) if ax is None: fig, ax = plt.subplots() else: fig = None if mask is not None: WCT = np.ma.array(WCT, mask=mask) # Set the x and y axes of the plot extent_corr = [t.min(), t.max(), 0, max(y_vals)] # Fill the plot with the magnitude squared coherence values im = NonUniformImage(ax, interpolation='bilinear', extent=extent_corr) if plot_period: im.set_data(t, y_vals, WCT) else: im.set_data(t, y_vals[::-1], WCT[::-1, :]) im.set_clim(0, 1) ax.images.append(im) # Plot the cone of influence - Periods greater thanthose are subject to edge effects. if coi is not None: # Performed by plotting a polygon x_positions = np.zeros(shape=(len(t), )) x_positions = t y_positions = np.zeros(shape=(len(t), )) if plot_period: y_positions = np.log2(coi) else: y_positions = np.log2(1 / coi) ax.plot(x_positions, y_positions, 'w--', linewidth=2, c="w") # Plot the significance level contour plot if sig is not None: ax.contour(t, y_vals, sig, [-99, 1], colors='k', linewidths=2, extent=extent_corr) # Add limits, titles, etc. ax.set_ylim(min(y_vals), max(y_vals)) if block: ax.set_xlim(t[block[0]], t[int(block[1] * 1 / dt)]) else: ax.set_xlim(t.min(), t.max()) if plot_period: y_ticks = np.linspace(min(y_vals), max(y_vals), 8) # TODO improve ticks y_ticks = [ np.log2(x) for x in [0.004, 0.008, 0.016, 0.032, 0.064, 0.125, 0.25, 0.5, 1] ] y_labels = [str(x) for x in (np.round(np.exp2(y_ticks), 3))] ax.set_ylabel("Period") else: y_ticks = np.linspace(min(y_vals), max(y_vals), 8) # TODO improve ticks # y_ticks = [np.log2(x) for x in [256, 128, 64, 32, 16, 8, 4, 2, 1]] y_ticks = [np.log2(x) for x in [64, 32, 16, 8, 4, 2, 1]] y_labels = [str(x) for x in (np.round(np.exp2(y_ticks), 3))] ax.set_ylabel("Frequency (Hz)") ax.set_yticks(y_ticks) ax.set_yticklabels(y_labels) ax.set_title(title) ax.set_xlabel("Time (s)") if cax is not None: plt.colorbar(im, cax=cax, use_gridspec=False) else: if fig is not None: fig.colorbar(im) else: plt.colorbar(im, ax=ax, use_gridspec=True) return fig, [WCT, t, y_vals]
scatf2 = 2.0*scatf1 scatf3 = 3.0*scatf1 scatf4 = 4.0*scatf1 scatf5 = 5.0*scatf1 # print max scatter values and their times print 'max scatter f1 = ' + str(max(scatf1)) + ' Hz' tofmax = times[argmax(scatf2)] tofmaxgps = tofmax + start_time print 'time of max f2 = ' + str(tofmax) + ' s, GPS=' + str(tofmaxgps) fig = plt.figure(figsize=(12,12)) ax1 = fig.add_subplot(211) # Plot Spectrogram if plotspec==1: im1 = NonUniformImage(ax1, interpolation='bilinear',extent=(min(t),max(t),10,55),cmap='jet') im1.set_data(t,freq,20.0*log10(Pxx)) if witness_base=="GDS-CALIB_STRAIN": print "setting color limits for STRAIN" im1.set_clim(-1000,-800) elif witness_base=="ASC-AS_B_RF45_Q_YAW_OUT_DQ" or witness_base=="ASC-AS_B_RF36_Q_PIT_OUT_DQ" or witness_base=="ASC-AS_A_RF45_Q_PIT_OUT_DQ" or witness_base=="LSC-MICH_IN1_DQ": im1.set_clim(-200,20) elif witness_base == "OMC-LSC_SERVO_OUT_DQ": im1.set_clim(-240,-85) ax1.images.append(im1) #cbar1 = fig.colorbar(im1) #cbar1.set_clim(-120,-40) # plot fringe prediction timeseries #ax1.plot(times,scatf5, c='blue', linewidth='0.2', label='f5') ax1.plot(times,scatf4, c='purple', linewidth='0.4', label='f4') ax1.plot(times,scatf3, c='green', linewidth='0.4', label='f3')
def go(self): '''Plot the evolution of the histogram for iterations self.iter_start to self.iter_stop''' idim = self.dimensions[0]['idim'] n_iters = self.input_h5['n_iter'][...] iiter_start = numpy.searchsorted(n_iters, self.iter_start) iiter_stop = numpy.searchsorted(n_iters, self.iter_stop) binbounds = self.input_h5['binbounds_{}'.format(idim)][...] midpoints = self.input_h5['midpoints_{}'.format(idim)][...] hists_ds = self.input_h5['histograms'] itercount = self.iter_stop - self.iter_start # We always round down, so that we don't have a dangling partial block at the end nblocks = itercount // self.iter_step block_iters = numpy.empty((nblocks, 2), dtype=n_iters.dtype) blocked_hists = numpy.zeros((nblocks, hists_ds.shape[1 + idim]), dtype=hists_ds.dtype) for iblock, istart in enumerate( range(iiter_start, iiter_start + nblocks * self.iter_step, self.iter_step)): istop = min(istart + self.iter_step, iiter_stop) histslice = hists_ds[istart:istop] # Sum over time histslice = numpy.add.reduce(histslice, axis=0) # Sum over other dimensions blocked_hists[iblock] = sum_except_along(histslice, idim) # Normalize normhistnd(blocked_hists[iblock], [binbounds]) block_iters[iblock, 0] = n_iters[istart] block_iters[iblock, 1] = n_iters[istop - 1] + 1 #enehists = -numpy.log(blocked_hists) enehists = self._ener_zero(blocked_hists) log10hists = numpy.log10(blocked_hists) if self.hdf5_output_filename: with h5py.File(self.hdf5_output_filename, 'w') as output_h5: h5io.stamp_creator_data(output_h5) output_h5.attrs['source_data'] = os.path.abspath( self.input_h5.filename) output_h5.attrs['source_dimension'] = idim output_h5['midpoints'] = midpoints output_h5['histograms'] = blocked_hists output_h5['n_iter'] = block_iters if self.plot_output_filename: if self.plotscale == 'energy': plothist = enehists label = r'$-\ln\,P(x)\ [kT^{-1}]$' elif self.plotscale == 'log10': plothist = log10hists label = r'$\log_{10}\ P(x)$' else: plothist = blocked_hists label = r'$P(x)$' try: vmin, vmax = self.plotrange except TypeError: vmin, vmax = None, None pyplot.figure() norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) ax = pyplot.gca() nui = NonUniformImage(ax, extent=(midpoints[0], midpoints[-1], block_iters[0, -1], block_iters[-1, -1]), origin='lower', norm=norm) # not sure why plothist works but plothist.T doesn't, and the opposite is true # for _do_2d_output nui.set_data(midpoints, block_iters[:, -1], plothist) ax.images.append(nui) ax.set_xlim(midpoints[0], midpoints[-1]) ax.set_ylim(block_iters[0, -1], block_iters[-1, -1]) cb = pyplot.colorbar(nui) cb.set_label(label) pyplot.xlabel(self.dimensions[0]['label']) pyplot.xlim(self.dimensions[0].get('lb'), self.dimensions[0].get('ub')) pyplot.ylabel('WE Iteration') if self.plottitle: pyplot.title(self.plottitle) if self.postprocess_function: self.postprocess_function(plothist, midpoints, binbounds) pyplot.savefig(self.plot_output_filename)
def animate_xz_density(trajectory, xedges=None, zedges=None, figsize=(7, 7), interval=1, n_frames=10, output_mode='animation', axis_equal=True): """ Animates an density plot of a static simulation trajectory in a z-x projection. Still frames can also be rendered. :param trajectory: Trajectory object with the particle trajectory data to be animated :type trajectory: Trajectory :param xedges: the edges of the bins of the density plot (2d histogram bins) in x direction, if None the maximum extend is used with 50 bins, if a number n, the maximum extend is used with n bins :type xedges: iterable or list / array or int :param zedges: the edges of the bins of the density plot (2d histogram bins) in z direction, if None the maximum extend is used with 50 bins, if a number n, the maximum extend is used with n bins :type zedges: iterable or list / array or int :param figsize: the figure size :type figsize: tuple of two floats :param interval: interval in terms of data frames in the input data between the animation frames :type interval: int :param n_frames: number of frames to render or the frame index to render if single frame mode :type n_frames: int :param output_mode: returns animation object when 'animation', 'singleFrame' returns a single frame figure :type output_mode: str :param axis_equal: if true, the axis are rendered with equal scaling :type axis_equal: bool :return: animation or figure """ if not trajectory.is_static_trajectory: raise TypeError( 'XZ density animation is currently only implemented for static trajectories' ) x_pos = trajectory.positions[:, 0, :] z_pos = trajectory.positions[:, 2, :] x_min = np.min(x_pos) x_max = np.max(x_pos) z_min = np.min(z_pos) z_max = np.max(z_pos) if xedges is None: xedges = np.linspace(x_min, x_max, 50) elif type(xedges) == int: xedges = np.linspace(x_min, x_max, xedges) if zedges is None: zedges = np.linspace(z_min, z_max, 50) elif type(zedges) == int: zedges = np.linspace(z_min, z_max, zedges) hist_vals, xed, zed = np.histogram2d(x_pos[:, 0], z_pos[:, 0], bins=(xedges, zedges)) hist_vals = hist_vals.T fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) im = NonUniformImage(ax, interpolation='nearest') xcenters = xed[:-1] + 0.5 * (xed[1:] - xed[:-1]) zcenters = zed[:-1] + 0.5 * (zed[1:] - zed[:-1]) im.set_data(xcenters, zcenters, hist_vals) ax.images.append(im) im.set_extent(im.get_extent( )) # workaround for minor issue in matplotlib ocurring in jupyter lab ax.set_xlim(xed[0], xed[-1]) ax.set_ylim(zed[0], zed[-1]) if axis_equal: ax.set_aspect('equal') def animate(i): ts_number = i * interval h_vals, _, _ = np.histogram2d(x_pos[:, ts_number], z_pos[:, ts_number], bins=(xedges, zedges)) h_vals = h_vals.T im.set_data(xcenters, zcenters, h_vals) if output_mode == 'animation': anim = animation.FuncAnimation(fig, animate, frames=n_frames, blit=False) return anim elif output_mode == 'singleFrame': animate(n_frames) return fig
def plot_3D( Xdata, Ydata, Zdata, colormap="RdBu_r", color_list=None, x_min=None, x_max=None, y_min=None, y_max=None, z_min=None, z_max=None, title="", xlabel="", ylabel="", zlabel="", xticks=None, yticks=None, fig=None, ax=None, is_logscale_x=False, is_logscale_y=False, is_logscale_z=False, is_disp_title=True, type_plot="stem", save_path=None, is_show_fig=None, is_switch_axes=False, win_title=None, font_name="arial", font_size_title=12, font_size_label=10, font_size_legend=8, ): """Plots a 3D graph ("stem", "surf" or "pcolor") Parameters ---------- Xdata : ndarray array of x-axis values Ydata : ndarray array of y-axis values Zdata : ndarray array of z-axis values colormap : colormap object colormap prescribed by user x_min : float minimum value for the x-axis (no automated scaling in 3D) x_max : float maximum value for the x-axis (no automated scaling in 3D) y_min : float minimum value for the y-axis (no automated scaling in 3D) y_max : float maximum value for the y-axis (no automated scaling in 3D) z_min : float minimum value for the z-axis (no automated scaling in 3D) z_max : float maximum value for the z-axis (no automated scaling in 3D) title : str title of the graph xlabel : str label for the x-axis ylabel : str label for the y-axis zlabel : str label for the z-axis xticks : list list of ticks to use for the x-axis fig : Matplotlib.figure.Figure existing figure to use if None create a new one ax : Matplotlib.axes.Axes object ax on which to plot the data is_logscale_x : bool boolean indicating if the x-axis must be set in logarithmic scale is_logscale_y : bool boolean indicating if the y-axis must be set in logarithmic scale is_logscale_z : bool boolean indicating if the z-axis must be set in logarithmic scale is_disp_title : bool boolean indicating if the title must be displayed type : str type of 3D graph : "stem", "surf", "pcolor" or "scatter" save_path : str full path including folder, name and extension of the file to save if save_path is not None is_show_fig : bool True to show figure after plot is_switch_axes : bool to switch x and y axes """ # Set if figure must be shown if is_show_fig is None if is_show_fig is None: is_show_fig = True if fig is None else False # Set if figure is 3D if type_plot not in ["pcolor", "pcolormesh", "scatter"]: is_3d = True else: is_3d = False # Set figure if needed if fig is None and ax is None: (fig, ax, _, _) = init_fig(fig=None, shape="rectangle", is_3d=is_3d) if color_list is None: color_list = COLORS # Calculate z limits if z_min is None: z_min = np_min(Zdata) if z_max is None: z_max = np_max(Zdata) # Check logscale on z axis if is_logscale_z: Zdata = 10 * log10(np_abs(Zdata)) clb_format = "%0.0f" else: clb_format = "%.4g" # Switch axes if is_switch_axes: Xdata, Ydata = Ydata, Xdata if len(Xdata.shape) > 1: Xdata = Xdata.T if len(Ydata.shape) > 1: Ydata = Ydata.T if len(Zdata.shape) > 1: Zdata = Zdata.T x_min, y_min = y_min, x_min x_max, y_max = y_max, x_max xlabel, ylabel = ylabel, xlabel xticks, yticks = yticks, xticks is_logscale_x, is_logscale_y = is_logscale_y, is_logscale_x # Plot if type_plot == "stem": cmap = matplotlib.cm.get_cmap(colormap) for xi, yi, zi in zip(Xdata, Ydata, Zdata): line = art3d.Line3D(*zip((xi, yi, 0), (xi, yi, zi)), linewidth=2.0, marker="o", markersize=3.0, markevery=(1, 1), color=cmap(0)) ax.add_line(line) ax.set_xlim3d(x_max, x_min) ax.set_ylim3d(y_min, y_max) ax.set_zlim3d(z_min, z_max) # set correct angle ax.view_init(elev=20.0, azim=45) ax.zaxis.set_rotate_label(False) ax.set_zlabel(zlabel, rotation=0) ax.xaxis.labelpad = 5 ax.yaxis.labelpad = 5 ax.zaxis.labelpad = 5 if xticks is not None: ax.xaxis.set_ticks(xticks) if yticks is not None: ax.yaxis.set_ticks(yticks) # white background ax.xaxis.pane.fill = False ax.yaxis.pane.fill = False ax.zaxis.pane.fill = False ax.xaxis.pane.set_edgecolor("w") ax.yaxis.pane.set_edgecolor("w") ax.zaxis.pane.set_edgecolor("w") if is_logscale_z: ax.zscale("log") elif type_plot == "surf": ax.plot_surface(Xdata, Ydata, Zdata, cmap=colormap) ax.set_xlim3d(x_max, x_min) ax.set_ylim3d(y_min, y_max) ax.set_zlim3d(z_min, z_max) ax.zaxis.set_rotate_label(False) ax.set_zlabel(zlabel, rotation=0) ax.xaxis.labelpad = 5 ax.yaxis.labelpad = 5 ax.zaxis.labelpad = 5 if xticks is not None: ax.xaxis.set_ticks(xticks) if yticks is not None: ax.yaxis.set_ticks(yticks) # white background ax.xaxis.pane.fill = False ax.yaxis.pane.fill = False ax.zaxis.pane.fill = False ax.xaxis.pane.set_edgecolor("w") ax.yaxis.pane.set_edgecolor("w") ax.zaxis.pane.set_edgecolor("w") if is_logscale_z: ax.zscale("log") elif type_plot == "pcolor": im = NonUniformImage( ax, interpolation="bilinear", extent=(x_min, x_max, y_max, y_min), cmap=colormap, picker=10, ) im.set_data(Xdata, Ydata, Zdata.T) ax.images.append(im) clb = fig.colorbar(im, ax=ax, format=clb_format) clb.ax.set_title(zlabel, fontsize=font_size_legend, fontname=font_name) clb.ax.tick_params(labelsize=font_size_legend) for l in clb.ax.yaxis.get_ticklabels(): l.set_family(font_name) if xticks is not None: ax.xaxis.set_ticks(xticks) if yticks is not None: ax.yaxis.set_ticks(yticks) ax.set_xlim([x_min, x_max]) ax.set_ylim([y_min, y_max]) elif type_plot == "pcolormesh": c = ax.pcolormesh(Xdata, Ydata, Zdata, cmap=colormap, shading="gouraud", antialiased=True) clb = fig.colorbar(c, ax=ax) clb.ax.set_title(zlabel, fontsize=font_size_legend, fontname=font_name) clb.ax.tick_params(labelsize=font_size_legend) for l in clb.ax.yaxis.get_ticklabels(): l.set_family(font_name) if xticks is not None: ax.xaxis.set_ticks(xticks) if yticks is not None: ax.yaxis.set_ticks(yticks) ax.set_xlim([x_min, x_max]) ax.set_ylim([y_min, y_max]) elif type_plot == "scatter": c = ax.scatter( Xdata, Ydata, # s=10, c=Zdata, marker=".", cmap=colormap, vmin=z_min, vmax=z_max, picker=True, pickradius=5, ) clb = fig.colorbar(c, ax=ax) clb.ax.set_title(zlabel, fontsize=font_size_legend, fontname=font_name) clb.ax.tick_params(labelsize=font_size_legend) for l in clb.ax.yaxis.get_ticklabels(): l.set_family(font_name) if xticks is not None: ax.xaxis.set_ticks(xticks) if yticks is not None: ax.yaxis.set_ticks(yticks) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if is_logscale_x: ax.xscale("log") if is_logscale_y: ax.yscale("log") if is_disp_title: ax.set_title(title) if is_3d: for item in ([ax.xaxis.label, ax.yaxis.label, ax.zaxis.label] + ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()): item.set_fontsize(font_size_label) else: for item in ([ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(font_size_label) item.set_fontname(font_name) ax.title.set_fontsize(font_size_title) ax.title.set_fontname(font_name) if save_path is not None: save_path = save_path.replace("\\", "/") fig.savefig(save_path) plt.close() if is_show_fig: fig.show() if win_title: manager = plt.get_current_fig_manager() if manager is not None: manager.set_window_title(win_title)