def plot_correlation(hist, title="Hit correlation", xlabel=None, ylabel=None, filename=None): logging.info("Plotting correlations") fig = Figure() FigureCanvas(fig) ax = fig.add_subplot(1, 1, 1) cmap = cm.get_cmap('jet') extent = [hist[2][0] - 0.5, hist[2][-1] + 0.5, hist[1][-1] + 0.5, hist[1][0] - 0.5] ax.set_title(title) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) im = ax.imshow(hist[0], extent=extent, cmap=cmap, interpolation='nearest') ax.invert_yaxis() # add colorbar divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) z_max = np.max(hist[0]) bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True) norm = colors.BoundaryNorm(bounds, cmap.N) fig.colorbar(im, boundaries=bounds, cmap=cmap, norm=norm, ticks=np.linspace(start=0, stop=z_max, num=9, endpoint=True), cax=cax) if not filename: fig.show() elif isinstance(filename, PdfPages): filename.savefig(fig) else: fig.savefig(filename)
def basic2DImage(self, dataset, variables, varsToIgnore): fig = Figure(dpi=100) ax = fig.add_subplot(111) indepVars = variables[0] depVars = variables[1] if varsToIgnore == [depVars[ii][0] for ii in range(0,len(depVars))]: return fig dataset = np.asarray(dataset) print dataset[0] xlabel = self.dataChest.getParameter("X Label", True) if xlabel is None: xlabel = indepVars[0][0] ylabel = self.dataChest.getParameter("Y Label", True) if ylabel is None: # For data with more than one dep, recommend ylabel. ylabel = depVars[0][0] plotTitle = self.dataChest.getParameter("Plot Title", True) if plotTitle is None: plotTitle = self.dataChest.getDatasetName() ax.set_title(plotTitle) ax.set_xlabel(xlabel+" "+"("+indepVars[0][3]+")") ax.set_ylabel(ylabel+" "+"("+depVars[0][3]+")") # For multiple deps with different units this is ambiguous. imageType = self.dataChest.getParameter("Image Type", True) if imageType is None: # Add or "scatter" imageType = "Scatter" print "Scatter" for ii in range(0, len(depVars)): x = dataset[::,0] y = dataset[::,1] z = dataset[::,2] im = ax.tricontourf(x,y,z, 100, cmap=cm.gist_rainbow, antialiased=True) fig.colorbar(im, fraction = 0.15) break elif imageType == "Pixel": xGridRes = self.dataChest.getParameter("X Resolution", True) xIncrement = self.dataChest.getParameter("X Increment", True) yGridRes = self.dataChest.getParameter("Y Resolution", True) yIncrement = self.dataChest.getParameter("Y Increment", True) x = dataset[::,0].flatten() y = dataset[::,1].flatten() z = dataset[::,2].flatten() if len(x)>1: if x[0]==x[1]: sweepType = "Y" else: sweepType = "X" print "sweepType=", sweepType new = self.makeGrid(x, xGridRes, xIncrement, y, yGridRes, yIncrement, sweepType, z) #makeGrid(self, x, xGridRes, dX, y, yGridRes, dY, sweepType, z) X = new[0] Y = new[1] Z = new[2] im = ax.imshow(Z, extent=(X.min(), X.max(), Y.min(), Y.max()), interpolation='nearest', cmap=cm.gist_rainbow, origin='lower') fig.colorbar(im, fraction = 0.15) else: print "return jack shit" elif imageType == "Buffered": print "Buffered" return fig
def check_and_plot(self, A_nn, A0_nn, digits, keywords=''): # Construct fingerprint of input matrices for comparison fingerprint = np.array([md5_array(A_nn, numeric=True), md5_array(A0_nn, numeric=True)]) # Compare fingerprints across all processors fingerprints = np.empty((world.size, 2), np.int64) world.all_gather(fingerprint, fingerprints) if fingerprints.ptp(0).any(): raise RuntimeError('Distributed matrices are not identical!') # If assertion fails, catch temporarily while plotting, then re-raise try: self.assertAlmostEqual(np.abs(A_nn-A0_nn).max(), 0, digits) except AssertionError: if world.rank == 0 and mpl is not None: from matplotlib.figure import Figure fig = Figure() ax = fig.add_axes([0.0, 0.1, 1.0, 0.83]) ax.set_title(self.__class__.__name__) im = ax.imshow(np.abs(A_nn-A0_nn), interpolation='nearest') fig.colorbar(im) fig.text(0.5, 0.05, 'Keywords: ' + keywords, \ horizontalalignment='center', verticalalignment='top') from matplotlib.backends.backend_agg import FigureCanvasAgg img = 'ut_hsops_%s_%s.png' % (self.__class__.__name__, \ '_'.join(keywords.split(','))) FigureCanvasAgg(fig).print_figure(img.lower(), dpi=90) raise
def confusion_matrix_(y_test, y_pred, target_names, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): cm = confusion_matrix(y_test, y_pred) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] np.set_printoptions(precision=2) fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) fig.colorbar(im) tick_marks = np.arange(len(target_names)) ax.set_xticks(tick_marks) ax.set_xticklabels(target_names, rotation=45) ax.set_yticks(tick_marks) ax.set_yticklabels(target_names) fig.tight_layout() ax.set_title(title) ax.set_ylabel('True label') ax.set_xlabel('Predicted label') return fig
class PlotFigure(Frame): def __init__(self): Frame.__init__(self, None, -1, "Test embedded wxFigure") self.fig = Figure((5,4), 75) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = NavigationToolbar2Wx(self.canvas) self.toolbar.Realize() # On Windows, default frame size behaviour is incorrect # you don't need this under Linux tw, th = self.toolbar.GetSizeTuple() fw, fh = self.canvas.GetSizeTuple() self.toolbar.SetSize(Size(fw, th)) # Create a figure manager to manage things # Now put all into a sizer sizer = BoxSizer(VERTICAL) # This way of adding to sizer allows resizing sizer.Add(self.canvas, 1, LEFT|TOP|GROW) # Best to allow the toolbar to resize! sizer.Add(self.toolbar, 0, GROW) self.SetSizer(sizer) self.Fit() EVT_TIMER(self, TIMER_ID, self.onTimer) def init_plot_data(self): # jdh you can add a subplot directly from the fig rather than # the fig manager a = self.fig.add_axes([0.075,0.1,0.75,0.85]) cax = self.fig.add_axes([0.85,0.1,0.075,0.85]) self.x = npy.empty((120,120)) self.x.flat = npy.arange(120.0)*2*npy.pi/120.0 self.y = npy.empty((120,120)) self.y.flat = npy.arange(120.0)*2*npy.pi/100.0 self.y = npy.transpose(self.y) z = npy.sin(self.x) + npy.cos(self.y) self.im = a.imshow( z, cmap=cm.jet)#, interpolation='nearest') self.fig.colorbar(self.im,cax=cax,orientation='vertical') def GetToolBar(self): # You will need to override GetToolBar if you are using an # unmanaged toolbar in your frame return self.toolbar def onTimer(self, evt): self.x += npy.pi/15 self.y += npy.pi/20 z = npy.sin(self.x) + npy.cos(self.y) self.im.set_array(z) self.canvas.draw() #self.canvas.gui_repaint() # jdh wxagg_draw calls this already def onEraseBackground(self, evt): # this is supposed to prevent redraw flicker on some X servers... pass
def plot_fig(fld,dt,varname,filename) : from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure fig = Figure(figsize=(5,4), dpi=100) ax = fig.add_subplot(111) canvas = FigureCanvasAgg(fig) P=ax.pcolor(fld) fig.colorbar(P) ax.set_title("%s at %s"%(varname,str(dt))) canvas.print_figure(filename)
def plot_search_map(datamap, zlim, cvflim, I, direction, fname): fig = Figure() ax = fig.add_subplot(111) extent = cvflim[0], cvflim[1], zlim[0], zlim[1] im = ax.imshow(datamap, cmap=cm.jet, interpolation='nearest', extent=extent, origin='lower') fig.colorbar(im) ax.set_aspect('auto') ax.set_xlabel('Vacancy concentration multiplier') ax.set_ylabel('z* (Effective valence)') ax.set_title(str.format('Least Squares Error for I = {}, {} bias', I, direction)) canvas = FigureCanvas(fig) canvas.print_figure(fname)
class ControlMatplotlib(ControlBase, QtGui.QWidget): def __init__(self, label = ""): QtGui.QWidget.__init__(self) ControlBase.__init__(self, label) def initForm(self): self._fig = Figure((5.0, 4.0), dpi=100) self.canvas = FigureCanvas(self._fig) self.canvas.setParent(self) self.mpl_toolbar = NavigationToolbar(self.canvas, self) vbox = QtGui.QVBoxLayout() vbox.addWidget(self.canvas) vbox.addWidget(self.mpl_toolbar) self.setLayout(vbox) def on_draw(self): """ Redraws the figure """ self.data =[1,2,3,4] x = range(len(self.data)) #self._axes = self._fig.add_subplot(111) #self._axes.bar(left=x, height=self.data) #self.canvas.draw() self._axes = self._fig.add_subplot(111, projection='3d') self._axes.clear(); pts = self._axes.scatter(x, x, x, c=x) self._fig.colorbar(pts) ############################################################################ ############ Properties #################################################### ############################################################################ @property def axes(self): return self._axes @axes.setter def axes(self, value): self._axes = value @property def fig(self): return self._fig @fig.setter def fig(self, value): self._fig = value @property def form(self): return self
def plot_reflectivity(self, data, fname, title='', highres=False, this_run=None): ''' Generate a graph with a combined reflectivity plot for all spin-states. If this_run is given it's raw data is shown on the right side of the same graph, too. ''' logging.info('Saving plot to "%s".'%fname) if highres: fig=Figure(figsize=(10.667, 8.), dpi=150, facecolor='#FFFFFF') fig.subplots_adjust(left=0.1, bottom=0.1, top=0.95, right=0.98) elif this_run: fig=Figure(figsize=(11., 8.), dpi=72, facecolor='#FFFFFF') fig.subplots_adjust(left=0.1, bottom=0.1, top=0.95, right=0.98) gs=GridSpec(2, 2, width_ratios=[3, 1]) else: fig=Figure(figsize=(6., 4.), dpi=72, facecolor='#FFFFFF') fig.subplots_adjust(left=0.12, bottom=0.13, top=0.94, right=0.98) canvas=FigureCanvasAgg(fig) if this_run: ax=fig.add_subplot(gs[:, 0]) xy_ax=fig.add_subplot(gs[0,1]) tof_ax=fig.add_subplot(gs[1, 1]) p1, p2=self.plot_raw(xy_ax, tof_ax, this_run) fig.colorbar(p1, ax=xy_ax, orientation='horizontal') fig.colorbar(p2, ax=tof_ax, orientation='horizontal') else: ax=fig.add_subplot(111) ymin=1e10 ymax=1e-10 xmin=0.1 xmax=0.01 for x, y, label in data: try: ymin=min(y[y>0].min(), ymin) except ValueError: # ignore plots with zero intensity continue else: xmin=min(x.min(), xmin) xmax=max(x.max(), xmax) ymax=max(y.max(), ymax) ax.semilogy(x, y, label=label) ax.set_xlim(xmin-xmin%0.005, xmax-xmax%0.005+0.005) ax.set_ylim(ymin*0.75, ymax*1.25) ax.legend() ax.set_title(title) ax.set_xlabel('Q [$\\AA^{-1}$]') ax.set_ylabel('R') try: canvas.print_png(fname) except IOError: logging.warn('Could not save plot:', exc_info=True)
def createSpectra(self, xHighlight=None, yHighlight=None, contour=False, index=0): """ Creates a spectragram graph. This function is called from the Core class. The spectragram is a three dimensional plot that shows current vs cycle vs time. @param xHighlight: defaults to none @param yHighlight: defaults to none @param contour: defaults to false @return null """ # haven't touched this yet. will likely add new field in gui to cycle through indexes of spectras self.plotInfoStr = self.dataset.getInfo() print("Plotting spectra at index:", index) f = Figure() a = f.add_subplot(111) x = np.array(list(self.dataset.getXUnits())) y = np.array(range(len(self.dataset.getYUnits()))) print("---\nsize of x: %i\nsize of y: %i" % (len(x), len(y))) X, Y = np.meshgrid(x, y) Z = np.array(self.dataset.getPlane()).transpose() if self.dataset.logifyY: Z = Z + np.abs(Z.min()) a.pcolormesh(X, Y, Z, norm=matplotlib.colors.LogNorm(vmin=Z.min(), vmax=Z.max())) else: a.pcolormesh(X, Y, Z) bar = matplotlib.cm.ScalarMappable() bar.set_array(Z) if contour: a.contour(X, Y, Z) f.colorbar(bar, ax=a, label="Current (Im)") f.suptitle(str(self.dataset)) if xHighlight != None: a.axvline(x=xHighlight) print("Trying to put bar at " + str(xHighlight)) if yHighlight != None: a.axhline(y=yHighlight) print("Trying to put hLine at " + str(yHighlight)) a.axis([X.min(), X.max(), Y.min(), Y.max()]) return f
def plot_scurves(occupancy_hist, scan_parameters, title='S-Curves', ylabel='Occupancy', max_occ=None, scan_parameter_name=None, min_x=None, max_x=None, x_scale=1.0, y_scale=1., filename=None): # tornado plot occ_mask = np.all(occupancy_hist == 0, axis=2) if max_occ is None: max_occ = 2 * np.median(np.amax(occupancy_hist, axis=2)) if np.allclose(max_occ, 0.0): max_occ = np.amax(occupancy_hist) if np.allclose(max_occ, 0.0): max_occ = 1 if len(occupancy_hist.shape) < 3: raise ValueError('Found array with shape %s' % str(occupancy_hist.shape)) n_pixel = occupancy_hist.shape[0] * occupancy_hist.shape[1] cmap = cm.get_cmap('jet', 200) for index, scan_parameter in enumerate(scan_parameters): compressed_data = np.ma.masked_array(occupancy_hist[:, :, index], mask=occ_mask, copy=True).compressed() heatmap, xedges, yedges = np.histogram2d(compressed_data, [scan_parameter] * compressed_data.shape[0], range=[[0, max_occ], [scan_parameters[0], scan_parameters[-1]]], bins=(max_occ + 1, len(scan_parameters))) if index == 0: hist = heatmap else: hist += heatmap fig = Figure() FigureCanvas(fig) ax = fig.add_subplot(111) fig.patch.set_facecolor('white') if len(scan_parameters) > 1: scan_parameter_dist = (np.amax(scan_parameters) - np.amin(scan_parameters)) / (len(scan_parameters) - 1) else: scan_parameter_dist = 0 extent = [yedges[0] - scan_parameter_dist / 2, yedges[-1] * x_scale + scan_parameter_dist / 2, xedges[-1] * y_scale + 0.5, xedges[0] - 0.5] norm = colors.LogNorm() im = ax.imshow(hist, interpolation='nearest', aspect="auto", cmap=cmap, extent=extent, norm=norm) ax.invert_yaxis() if min_x is not None or max_x is not None: ax.set_xlim((min_x if min_x is not None else np.amin(scan_parameters), max_x if max_x is not None else np.amax(scan_parameters))) fig.colorbar(im) ax.set_title(title + ' for %d pixel(s)' % (n_pixel - np.count_nonzero(occ_mask))) if scan_parameter_name is None: ax.set_xlabel('Scan parameter') else: ax.set_xlabel(scan_parameter_name) ax.set_ylabel(ylabel) if not filename: fig.show() elif isinstance(filename, PdfPages): filename.savefig(fig) else: fig.savefig(filename)
def plot_tdc_event(points, filename=None): fig = Figure() FigureCanvas(fig) ax = fig.add_subplot(111, projection='3d') xs = points[:, 0] ys = points[:, 1] zs = points[:, 2] cs = points[:, 3] p = ax.scatter(xs, ys, zs, c=cs, s=points[:, 3] ** (2) / 5., marker='o') ax.set_xlabel('x [250 um]') ax.set_ylabel('y [50 um]') ax.set_zlabel('t [25 ns]') ax.title('Track of one TPC event') ax.set_xlim(0, 80) ax.set_ylim(0, 336) c_bar = fig.colorbar(p) c_bar.set_label('charge [TOT]') if not filename: fig.show() elif isinstance(filename, PdfPages): filename.savefig(fig) elif filename: fig.savefig(filename) return fig
def heatmap(self): [dates,watts] = self.building.data clipMax = scipy.stats.scoreatpercentile(watts,per=95)/1000 clipMin = scipy.stats.scoreatpercentile(watts,per=0)/1000 #watts[watts > clipMax] = clipMax [datesA,wattsA] = self.building.dailyData (m,n) = wattsA.shape fig = Figure(figsize=(10,6),facecolor='white',edgecolor='none') ax = fig.add_subplot(111) #print 'shapes:',m,n #print cm.coolwarm p = ax.imshow(wattsA/1000, interpolation='nearest', aspect='auto', cmap=cm.coolwarm, extent=[0,n*20*2,0,m*2]) p.cmap.set_over('grey') cbar = fig.colorbar(p,ax=ax,shrink=0.8) cbar.set_label('kW') p.set_clim(clipMin, clipMax) ax.set_xticks(range(0,n*40+1,n*40/24*2)) ax.set_xticklabels(['%iam' % x for x in [12]+range(2,12,2)] + ['%ipm' % x for x in [12] + range(2,12,2)] + ['12am']) # rotate lables for l in ax.xaxis.get_majorticklabels(): l.set_rotation(70) ax.set_yticks(range(1,m*2+1,30*2)) ax.format_ydata = mpld.DateFormatter('%m/%d') ax.set_yticklabels([x.strftime('%m/%d/%y') for x in datesA[-1:1:-30,0]]) #fig.autofmt_ydate() ax.tick_params(axis='both', which='major', labelsize=8) ax.set_title('Heat map of %s data for %s' % ('electricity','uploaded data')) ax.set_xlabel('Hour of day') ax.set_ylabel('Date') ax.grid(True) fig.subplots_adjust(top=1.0, left=0.20) return fig
def plot_cluster_tot_size(hist, median=False, z_max=None, filename=None): H = hist[0:50, 0:20] if z_max is None: z_max = np.ma.max(H) if z_max < 1 or H.all() is np.ma.masked: z_max = 1 fig = Figure() FigureCanvas(fig) ax = fig.add_subplot(111) extent = [-0.5, 20.5, 49.5, -0.5] bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True) cmap = cm.get_cmap('jet') cmap.set_bad('w') norm = colors.BoundaryNorm(bounds, cmap.N) im = ax.imshow(H, aspect="auto", interpolation='nearest', cmap=cmap, norm=norm, extent=extent) # for monitoring ax.set_title('Cluster size and cluster ToT (' + str(np.sum(H) / 2) + ' entries)') ax.set_xlabel('cluster size') ax.set_ylabel('cluster ToT') ax.invert_yaxis() divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.1) cb = fig.colorbar(im, cax=cax, ticks=np.linspace(start=0, stop=z_max, num=9, endpoint=True)) cb.set_label("#") fig.patch.set_facecolor('white') if not filename: fig.show() elif isinstance(filename, PdfPages): filename.savefig(fig) else: fig.savefig(filename)
def generate_scatterplot(datafname, imgfname): """Creates a 2D scatter plot of the specified Gocator XYZ data and saves it in the specified image filename.""" matplotlib.rcParams['axes.formatter.limits'] = -4, 4 matplotlib.rcParams['font.size'] = 14 matplotlib.rcParams['axes.titlesize'] = 12 matplotlib.rcParams['axes.labelsize'] = 12 matplotlib.rcParams['xtick.labelsize'] = 11 matplotlib.rcParams['ytick.labelsize'] = 11 figure = Figure() canvas = FigureCanvas(figure) axes = figure.gca() x,y,z = np.genfromtxt(datafname, delimiter=",", unpack=True) xi = x[z!=-32.768] yi = y[z!=-32.768] zi = z[z!=-32.768] scatter_plt = axes.scatter(xi, yi, c=zi, cmap=cm.get_cmap("Set1"), marker=',') axes.grid(True) axes.axis([np.min(xi), np.max(xi), np.min(yi), np.max(yi)]) axes.set_title(os.path.basename(datafname)) colorbar = figure.colorbar(scatter_plt) colorbar.set_label("Range [mm]") axes.set_xlabel("Horizontal Position [mm]") axes.set_ylabel("Scan Position [mm]") figure.savefig(imgfname)
def plotGridSearch(self, X, Y, S, gamma, C): fig = Figure(facecolor="white", tight_layout=True) ax = fig.add_subplot(111) ax.contour(X, Y, S) pc = ax.pcolormesh(X, Y, S, shading="gouraud", cmap=cm.coolwarm) fig.colorbar(pc) ax.axvline(gamma, linewidth=1, color="yellow") ax.axhline(C, linewidth=1, color="yellow") ax.set_xlabel("gamma") ax.set_ylabel("C") ax.set_title("gamma=%g, C=%g" % (gamma, C)) ax.loglog() self.addFigure("Grid Search", fig)
def plot_raw_only(self, fname, this_run): ''' Generate a graph with only the raw data and no reflectivity plot. ''' fig=Figure(figsize=(11., 5.), dpi=72, facecolor='#FFFFFF') fig.subplots_adjust(left=0.1, bottom=0.1, top=0.95, right=0.98) canvas=FigureCanvasAgg(fig) xy_ax=fig.add_subplot(121) tof_ax=fig.add_subplot(122) p1, p2=self.plot_raw(xy_ax, tof_ax, this_run) fig.colorbar(p1, ax=xy_ax, orientation='vertical') fig.colorbar(p2, ax=tof_ax, orientation='vertical') try: canvas.print_png(fname) except IOError: logging.warn('Could not save raw plot:', exc_info=True)
def test_aea(): from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg # Now make a simple example using the custom projection. import numpy as np fig = Figure(figsize=(6, 6)) # ra = np.random.uniform(size=100, low=0, high=360) # dec = np.random.uniform(size=100, low=-90, high=90) ra = np.linspace(0, 360, 100) dec = np.linspace(-90, 90, 100) ax = fig.add_subplot(111, projection="ast.aea") ax.set_xlim(359, 0) ax.set_ylim(-70, 70) ax.set_parallels(-20, 60) ax.set_center(180, 0) ax.plot(ra, dec, '*') ax.axhline(-20) ax.axvline(140) # ax.plot(*pix2tri(8, [104, 105, 106]).reshape(-1, 2).T, color='k') ra = np.random.uniform(size=1000, low=30, high=60) dec = np.random.uniform(size=1000, low=-50, high=50) ax.histmap(ra, dec, nside=32, weights=ra * dec, mean=True) ra = np.random.uniform(size=1000, low=120, high=160) dec = np.random.uniform(size=1000, low=-50, high=50) ax.histcontour(ra, dec, weights=ra * dec, nside=32, mean=True) ax.tick_params(labelright=True, labeltop=True) ax.tripcolor(ra, dec, ra*dec) fig.colorbar(ax._gci()) ra = np.random.uniform(size=1000, low=180, high=200) dec = np.random.uniform(size=1000, low=-50, high=50) ax.set_meridian_grid(30) ax.set_parallel_grid(30) ax.grid() canvas = FigureCanvasAgg(fig) fig.savefig('xxx-aea.png')
def print_plot(self, array_to_be_plotted, plot_title, colormap): a = array_to_be_plotted self.rmmpl() fig = Figure() self.addmpl(fig) ax = fig.add_subplot(111) cax = ax.imshow(a, cmap=colormap) fig.colorbar(cax, shrink=0.6, aspect=5) fig.tight_layout() ax.set_title(plot_title, fontsize=20, y=1.01) ax.axes.get_xaxis().set_ticks([]) ax.axes.get_yaxis().set_ticks([]) ax.format_coord = lambda x, y: '' ax.set_xlabel('300 mm', fontsize=20, rotation=0) ax.set_ylabel('200 mm', fontsize=20, rotation=90) ax.autoscale(False) plt.show()
class SpectrogramCanvas(FigureCanvas): def __init__(self, window): """Initialize spectrogram canvas graphs.""" # Initialize variables to default values. self.window = window self.samples = 100 # Number of samples to store self.fftSize = 256 # Initial FFT size just to render something in the charts self.sampleRate = 0 self.binFreq = 0 self.binCount = self.fftSize/2 self.graphUpdateHz = 10 # Update rate of the animation self.coloredBin = None self.magnitudes = np.zeros((self.samples, self.binCount)) # Tell numpy to ignore errors like taking the log of 0 np.seterr(all='ignore') # Set up figure to hold plots self.figure = Figure(figsize=(1024,768), dpi=72, facecolor=(1,1,1), edgecolor=(0,0,0)) # Set up 4x4 grid to hold 2 plots and colorbar gs = GridSpec(2, 2, height_ratios=[1,2], width_ratios=[9.5, 0.5]) gs.update(left=0.075, right=0.925, bottom=0.05, top=0.95, wspace=0.05) # Set up frequency histogram bar plot self.histAx = self.figure.add_subplot(gs[0]) self.histAx.set_title('Frequency Histogram') self.histAx.set_ylabel('Intensity (decibels)') self.histAx.set_xlabel('Frequency Bin (hz)') self.histAx.set_xticks([]) self.histPlot = self.histAx.bar(np.arange(self.binCount), np.zeros(self.binCount), width=1.0, linewidth=0.0, facecolor='blue') # Set up spectrogram waterfall plot self.spectAx = self.figure.add_subplot(gs[2]) self.spectAx.set_title('Spectrogram') self.spectAx.set_ylabel('Sample Age (seconds)') self.spectAx.set_xlabel('Frequency Bin (hz)') self.spectAx.set_xticks([]) self.spectPlot = self.spectAx.imshow(self.magnitudes, aspect='auto', cmap=get_cmap('jet')) # Add formatter to translate position to age in seconds self.spectAx.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: '%d' % (x*(1.0/self.graphUpdateHz)))) # Set up spectrogram color bar cbAx = self.figure.add_subplot(gs[3]) self.figure.colorbar(self.spectPlot, cax=cbAx, use_gridspec=True, format=FuncFormatter(lambda x, pos: '%d' % (x*100.0))) cbAx.set_ylabel('Intensity (decibels)') # Initialize canvas super(SpectrogramCanvas, self).__init__(self.figure) # Hook up mouse and animation events self.mpl_connect('motion_notify_event', self._mouseMove) self.ani = FuncAnimation(self.figure, self._update, interval=1000.0/self.graphUpdateHz, blit=False)
def create_plot(data, title, width, height): """Generates a matplotlib Figure instance of the specified data""" mainmodel.init_matplotlib_defaults() figure = Figure(figsize=(width, height)) canvas = FigureCanvas(figure) axes = figure.gca() if 2 in data.shape: axes.plot(data[0], data[1]) elif data.ndim == 1: axes.plot(data) else: img = axes.imshow(data, cmap=cm.get_cmap('Spectral')) figure.colorbar(img) if len(title) > 20: title = ''.join([title[:10], "...", title[-10:]]) axes.set_title(title) axes.grid(True) return figure
class MatplotlibPatchWidget(FigureCanvas): def __init__(self, parent, grid, bounding_box=None, vmin=None, vmax=None, codim=2, dpi=100): assert grid.reference_element in (triangle, square) assert grid.dim == 2 assert codim in (0, 2) self.figure = Figure(dpi=dpi) super().__init__(self.figure) subentities, coordinates, entity_map = flatten_grid(grid) self.subentities = subentities if grid.reference_element is triangle \ else np.vstack((subentities[:, 0:3], subentities[:, [2, 3, 0]])) self.coordinates = coordinates self.entity_map = entity_map self.reference_element = grid.reference_element self.vmin = vmin self.vmax = vmax self.codim = codim self.setParent(parent) self.setMinimumSize(300, 300) self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) def set(self, U, vmin=None, vmax=None): self.vmin = self.vmin if vmin is None else vmin self.vmax = self.vmax if vmax is None else vmax U = np.array(U) f = self.figure f.clear() a = f.gca() if self.codim == 2: p = a.tripcolor(self.coordinates[:, 0], self.coordinates[:, 1], self.subentities, U, vmin=self.vmin, vmax=self.vmax, shading='flat') elif self.reference_element is triangle: p = a.tripcolor(self.coordinates[:, 0], self.coordinates[:, 1], self.subentities, facecolors=U, vmin=self.vmin, vmax=self.vmax, shading='flat') else: p = a.tripcolor(self.coordinates[:, 0], self.coordinates[:, 1], self.subentities, facecolors=np.tile(U, 2), vmin=self.vmin, vmax=self.vmax, shading='flat') self.figure.colorbar(p) self.draw()
class Plotter(FigureCanvas): def __init__(self, canvas, beschriftung, width=5, height=5, dpi=75): """ :type canvas: [Module.Canvas.Canvas | QtGui.QWidget] :type beschriftung: Module.Sonstige.Achsenbeschriftung :type width: int :type height: int :type dpi: int """ self.canvas = canvas self.beschriftung = beschriftung self.figure = Figure(figsize=(width, height), dpi=dpi) self.axes = self.figure.add_subplot(111, xlabel=beschriftung.x, ylabel=beschriftung.y) """ :type: matplotlib.axes.Axes """ self.axes.hold(False) self.colorbar = None FigureCanvas.__init__(self, self.figure) self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.updateGeometry() try: # QWidget ohne Statusleiste self.statusbar = canvas.statusbar self.mpl_connect("motion_notify_event", self.maus_bewegt) except AttributeError: pass def maus_bewegt(self, event): """ :type event: matplotlib.backend_bases.MouseEvent """ if event.inaxes is not None: canvas = self.canvas # Das ist nur sinnvoll für ein Canvas """ :type: Module.Canvas.Canvas """ self.statusbar.showMessage(canvas.str_status(event.xdata, event.ydata)) else: self.statusbar.clearMessage() def mit_skala(self, plot): """ :type plot: matplotlib.image.AxesImage """ if self.colorbar is None: self.colorbar = self.figure.colorbar(plot) self.colorbar.set_label(self.beschriftung.farbe) else: self.colorbar.update_normal(plot) self.draw() def draw(self): self.axes.set_xlabel(self.beschriftung.x) self.axes.set_ylabel(self.beschriftung.y) super(Plotter, self).draw()
class PlotSpectrogram(FigureCanvas): """docstring for PlotSpectrogram""" def __init__(self, *args): self.figure = Figure() FigureCanvas.__init__(self, self.figure) self.axes = self.figure.add_subplot(111) self.log = logging.getLogger("measurement.PlotSpectrogram") # __init__() dBmMin = float("Inf") dBmMax = -float("Inf") image = None def updatePlot(self, fReader): if fReader.sweepCurrent is None: self.log.warning("Missing data to plot") return if fReader.frequencyList is None: self.log.warning("Missing frequency list") freqList = range(fReader.sweepCurrent.shape[0]) else: freqList = fReader.frequencyList t0 = time.time() - (fReader.timeStart + fReader.timeStamp[-1]) t1 = time.time() - (fReader.timeStart + fReader.timeStamp[0]) if self.image is None: self.image = self.axes.matshow(fReader.sweepAll, cmap=viridis.cm, animated=True, aspect="auto", extent=[freqList[0], freqList[-1], t0, t1]) self.figure.colorbar(self.image) else: self.image.set_extent([freqList[0], freqList[-1], t0, t1]) self.image.set_data(fReader.sweepAll) self.image.autoscale() self.figure.canvas.draw() # def updatePlot def initUI(self): self.setMinimumSize(QtCore.QSize(610, 250))
def plot_pixel_matrix(hist, title="Hit correlation", filename=None): logging.info("Plotting pixel matrix: %s", title) fig = Figure() FigureCanvas(fig) ax = fig.add_subplot(111) ax.set_title(title) ax.set_xlabel('Col') ax.set_ylabel('Row') cmap = cm.get_cmap('jet') ax.imshow(hist.T, aspect='auto', cmap=cmap, interpolation='nearest') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) z_max = np.max(hist) bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True) norm = colors.BoundaryNorm(bounds, cmap.N) fig.colorbar(boundaries=bounds, cmap=cmap, norm=norm, ticks=np.linspace(start=0, stop=z_max, num=9, endpoint=True), cax=cax) if not filename: fig.show() elif isinstance(filename, PdfPages): filename.savefig(fig) else: fig.savefig(filename)
def _fetch(self): if self.checkBox.isChecked() == True: self.__fet() else: self.dn = sfn(ds=self.dcube_path,name='foo',od=2.,bn=1., pol=self.poldt_path,du=1.5e-5) self.ds = sf(ds=self.dcube_path,name='foo',od=2.,bn=1., pol=self.poldt_path,du=1.5e-5) m0 = self.dn.m0 m1 = self.dn.m1 i = 0 for n in [m0,m1]: fig_ = Figure() axf_ = fig_.add_subplot(111) cax = axf_.imshow(n,origin='lower') fig_.colorbar(cax) name = 'moment %s' %i self.fig_dict[name] = fig_ self.fg_dict[name] = n self.mplfigs.addItem(name) i += 1
class PlotFigure(Frame): def __init__(self): Frame.__init__(self, None, -1, "Test embedded wxFigure") self.fig = Figure((5,4), 75) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = NavigationToolbar2Wx(self.canvas) self.toolbar.Realize() tw, th = self.toolbar.GetSizeTuple() fw, fh = self.canvas.GetSizeTuple() self.toolbar.SetSize(Size(fw, th)) sizer = BoxSizer(VERTICAL) sizer.Add(self.canvas, 1, LEFT|TOP|GROW) sizer.Add(self.toolbar, 0, GROW) self.SetSizer(sizer) self.Fit() EVT_TIMER(self, TIMER_ID, self.onTimer) def init_plot_data(self): a = self.fig.add_axes([0.075,0.1,0.75,0.85]) cax = self.fig.add_axes([0.85,0.1,0.075,0.85]) self.x = npy.empty((120,120)) self.x.flat = npy.arange(120.0)*2*npy.pi/120.0 self.y = npy.empty((120,120)) self.y.flat = npy.arange(120.0)*2*npy.pi/100.0 self.y = npy.transpose(self.y) z = npy.sin(self.x) + npy.cos(self.y) self.im = a.imshow( z, cmap=cm.jet)#, interpolation='nearest') self.fig.colorbar(self.im,cax=cax,orientation='vertical') def GetToolBar(self): return self.toolbar def onTimer(self, evt): self.x += npy.pi/15 self.y += npy.pi/20 z = npy.sin(self.x) + npy.cos(self.y) self.im.set_array(z) self.canvas.draw() def onEraseBackground(self, evt): pass
class expression_heat(): def __init__(self,height=19): matplotlib.rc('axes',edgecolor='white') self.fig=Figure(figsize=(13,((6.0/19)*height)+1)) self.fig.set_facecolor('white') self.ax=self.fig.add_subplot(111) self.ax.set_axis_bgcolor('#EEEEEE') self.ax.tick_params(axis='both', direction='out') self.ax.get_xaxis().tick_bottom() # remove unneeded ticks self.ax.get_yaxis().tick_left() self.x_labels = [] box = self.ax.get_position() self.ax.set_position([box.x0, box.y0, box.width * 0.7, box.height]) self.data = {} def add_gene(self,gene): gene_data = gene.genedata_set.all() self.data[gene.gene_short_name+' | '+gene.pk] = (map(lambda g:g.fpkm,gene_data)) self.x_labels = map(lambda f: f.sample_name.sample_name,gene_data) def response(self,errors=False): genes = sorted(self.data.keys(),key=lambda n:numpy.mean(self.data[n]),reverse=True) data_array = [] for g in genes: data_array.append(self.data[g]) data_array = numpy.array(data_array) hm = self.ax.imshow(data_array,interpolation='nearest') cbar = self.fig.colorbar(hm) cbar.ax.set_ylabel('FPKM') self.ax.set_yticks(range(len(genes))) self.ax.set_yticklabels(genes) self.ax.set_xticks(range(len(self.x_labels))) self.ax.set_xticklabels(self.x_labels,rotation='vertical') canvas=FigureCanvas(self.fig) response=django.http.HttpResponse(content_type='image/png') canvas.print_png(response) return response
def heatmap(df, term, outdir, axis=0, figsize=(5,5), format='png'): """Visualize the dataframe. :param df: DataFrame from expression table. :param term: gene set name. :param outdir: path to save heatmap. :param axis: z_score axis. :param figsize: heatmap figsize. :param format: Matplotlib supported figure formats. """ df = z_score(df, axis=axis) # Get the positions and used label for the ticks nx, ny = df.T.shape xticks = np.arange(0, nx, 1) + .5 yticks = np.arange(0, ny, 1) + .5 #If working on commandline, don't show figure fig = Figure(figsize=figsize) canvas = FigureCanvas(fig) ax = fig.add_subplot(111) vmin = np.percentile(df.min(), 2) vmax = np.percentile(df.max(), 98) matrix = ax.pcolormesh(df.values, cmap=plt.cm.RdBu_r, vmin=vmin, vmax=vmax) ax.set_ylim([0,len(df)]) ax.set(xticks=xticks, yticks=yticks) ax.set_xticklabels(df.columns.values, fontsize=18, rotation=90) ax.set_yticklabels(df.index.values, fontsize=18) ax.set_title("%s\nHeatmap of the Analyzed GeneSet"%term, fontsize=24) ax.tick_params(axis='both', which='both', bottom='off', top='off', right='off', left='off') #fig.colorbar(matrix, ax=ax) cax=fig.add_axes([0.93,0.25,0.05,0.20]) cbar = fig.colorbar(matrix, cax=cax) cbar.ax.tick_params(axis='both', which='both', bottom='off', top='off', right='off', left='off') for side in ["top", "right", "left", "bottom"]: ax.spines[side].set_visible(False) cbar.ax.spines[side].set_visible(False) #cbar.ax.set_title('',loc='left') canvas.print_figure("{a}/{b}.heatmap.{c}".format(a=outdir, b=term, c=format), bbox_inches='tight')
class HeatMapPanel(MyPanel): def __init__(self, *args, **kwargs): MyPanel.__init__(self, *args, **kwargs) self.vbox = wx.BoxSizer(wx.VERTICAL) self.fig = Figure(facecolor=self.face_col) self.ax1 = self.fig.add_subplot(211) self.ax2 = self.fig.add_subplot(212) self.cbar = None self.canvas = FigureCanvas(self, -1, self.fig) self.vbox.Add(self.canvas) self.SetSizerAndFit(self.vbox) pub.subscribe(self.redraw, "assignments_calced") def redraw(self, message): """Create both heatmaps and colorbar. Listner for the assignments_calced event""" cax1 = self.createHeatMap(self.ax1, "H1") cax2 = self.createHeatMap(self.ax2, "H2") if self.cbar is None: self.cbar = self.fig.colorbar(cax2, orientation="horizontal") self.canvas.draw() def createHeatMap(self, ax, half): resultsH1, xlabels, ylabels = self.model.genHeatMap(half) ax.clear() cax = ax.imshow(resultsH1, interpolation="none", picker=True, vmin=0, vmax=20) ax.set_title(half) ax.set_yticklabels([""] + ylabels) ax.set_xticks(range(0, len(xlabels), 3)) ax.set_xticklabels(xlabels[::3]) return cax
class TopographicMapCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100): self.fig = Figure(figsize=(width, height), dpi=dpi) self.axes = self.fig.add_subplot(111) self.colorbar = None FigureCanvas.__init__(self, self.fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def update_figure(self, data, pos=None, names=None, show_names=None, show_colorbar=True, central_text=None, right_bottom_text=None, show_not_found_symbol=False, montage=None): if montage is None: if pos is None: pos = ch_names_to_2d_pos(names) else: pos = montage.get_pos('EEG') names = montage.get_names('EEG') data = np.array(data) self.axes.clear() if self.colorbar: self.colorbar.remove() if show_names is None: show_names = [ 'O1', 'O2', 'CZ', 'T3', 'T4', 'T7', 'T8', 'FP1', 'FP2' ] show_names = [name.upper() for name in show_names] mask = np.array([name.upper() in show_names for name in names]) if names else None v_min, v_max = None, None if (data == data[0]).all(): data[0] += 0.1 data[1] -= 0.1 v_min, v_max = -1, 1 a, b = plot_topomap(data, pos, axes=self.axes, show=False, contours=0, names=names, show_names=True, mask=mask, mask_params=dict(marker='o', markerfacecolor='w', markeredgecolor='w', linewidth=0, markersize=3), vmin=v_min, vmax=v_max) if central_text is not None: self.axes.text(0, 0, central_text, horizontalalignment='center', verticalalignment='center') if right_bottom_text is not None: self.axes.text(-0.65, 0.65, right_bottom_text, horizontalalignment='left', verticalalignment='top') if show_not_found_symbol: self.axes.text(0, 0, '/', horizontalalignment='center', verticalalignment='center') self.axes.text(0, 0, 'O', size=10, horizontalalignment='center', verticalalignment='center') if show_colorbar: self.colorbar = self.fig.colorbar(a, orientation='horizontal', ax=self.axes) self.colorbar.ax.tick_params(labelsize=6) self.colorbar.ax.set_xticklabels( self.colorbar.ax.get_xticklabels(), rotation=90) self.draw() def draw_central_text(self, text='', right_bottom_text='', show_not_found_symbol=False): data = np.random.randn(3) * 0 pos = np.array([(0, 0), (1, -1), (-1, -1)]) self.update_figure(data, pos, central_text=text, names=[], show_colorbar=False, right_bottom_text=right_bottom_text, show_not_found_symbol=show_not_found_symbol) def test_update_figure(self): from vendor.nfb.pynfb.inlets.montage import Montage montage = Montage(names=['Fp1', 'Fp2', 'Cz', 'AUX', 'MEG 2632']) print(montage) data = np.random.randn(3) pos = np.array([(0, 0), (1, -1), (-1, -1)]) self.update_figure(data=data, pos=pos, names=['c1', 'c2', 'oz'], montage=montage)
class PyMcaMatplotlibSaveImage: def __init__(self, imageData=None, fileName=None, dpi=300, size=(5, 5), xaxis='off', yaxis='off', xlabel='', ylabel='', nxlabels=0, nylabels=0, colorbar=None, title='', interpolation='nearest', colormap=None, linlogcolormap='linear', origin='lower', contour='off', contourlabels='on', contourlabelformat='%.3f', contourlevels=10, contourlinewidth=10, xorigin=0.0, yorigin=0.0, xpixelsize=1.0, ypixelsize=1.0, xlimits=None, ylimits=None, vlimits=None, extent=None): self.figure = Figure(figsize=size) #in inches self.canvas = FigureCanvas(self.figure) self.imageData = imageData self.pixmapImage = None self.config = { 'xaxis': xaxis, 'yaxis': yaxis, 'title': title, 'xlabel': xlabel, 'ylabel': ylabel, 'nxlabels': nxlabels, 'nylabels': nylabels, 'colorbar': colorbar, 'colormap': colormap, 'linlogcolormap': linlogcolormap, 'interpolation': interpolation, 'origin': origin, 'contour': contour, 'contourlabels': contourlabels, 'contourlabelformat': contourlabelformat, 'contourlevels': contourlevels, 'contourlinewidth': contourlinewidth, 'xpixelsize': xpixelsize, 'ypixelsize': ypixelsize, 'xorigin': xorigin, 'yorigin': yorigin, 'zoomxmin': None, 'zoomxmax': None, 'zoomymin': None, 'zoomymax': None, 'valuemin': None, 'valuemax': None, 'xlimits': xlimits, 'ylimits': ylimits, 'vlimits': vlimits, 'extent': extent } #generate own colormaps cdict = { 'red': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)) } self.__redCmap = LinearSegmentedColormap('red', cdict, 256) cdict = { 'red': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), 'blue': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)) } self.__greenCmap = LinearSegmentedColormap('green', cdict, 256) cdict = { 'red': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)) } self.__blueCmap = LinearSegmentedColormap('blue', cdict, 256) # Temperature as defined in spslut cdict = { 'red': ((0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0, 0.0), (0.25, 1.0, 1.0), (0.75, 1.0, 1.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 1.0, 1.0), (0.25, 1.0, 1.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0)) } #Do I really need as many colors? self.__temperatureCmap = LinearSegmentedColormap( 'temperature', cdict, 65536) #reversed gray cdict = { 'red': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0)) } self.__reversedGrayCmap = LinearSegmentedColormap('yerg', cdict, 256) if fileName is not None: self.saveImage(fileName) def setImage(self, image=None): self.imageData = image def setParameters(self, ddict): self.config.update(ddict) def saveImage(self, filename): self.figure.clear() if (self.imageData is None) and\ (self.pixmapImage is None): return # The axes self.axes = self.figure.add_axes([.15, .15, .75, .8]) if self.config['xaxis'] == 'off': self.axes.xaxis.set_visible(False) else: self.axes.xaxis.set_visible(True) nLabels = self.config['nxlabels'] if nLabels not in ['Auto', 'auto', '0', 0]: self.axes.xaxis.set_major_locator(MaxNLocator(nLabels)) else: self.axes.xaxis.set_major_locator(AutoLocator()) if self.config['yaxis'] == 'off': self.axes.yaxis.set_visible(False) else: self.axes.yaxis.set_visible(True) if nLabels not in ['Auto', 'auto', '0', 0]: self.axes.yaxis.set_major_locator(MaxNLocator(nLabels)) else: self.axes.yaxis.set_major_locator(AutoLocator()) if self.pixmapImage is not None: self._savePixmapFigure(filename) return interpolation = self.config['interpolation'] origin = self.config['origin'] cmap = self.__temperatureCmap ccmap = cm.gray if self.config['colormap'] in ['grey', 'gray']: cmap = cm.gray ccmap = self.__temperatureCmap elif self.config['colormap'] in ['yarg', 'yerg']: cmap = self.__reversedGrayCmap ccmap = self.__temperatureCmap elif self.config['colormap'] == 'jet': cmap = cm.jet elif self.config['colormap'] == 'hot': cmap = cm.hot elif self.config['colormap'] == 'cool': cmap = cm.cool elif self.config['colormap'] == 'copper': cmap = cm.copper elif self.config['colormap'] == 'spectral': cmap = cm.spectral elif self.config['colormap'] == 'hsv': cmap = cm.hsv elif self.config['colormap'] == 'rainbow': cmap = cm.gist_rainbow elif self.config['colormap'] == 'red': cmap = self.__redCmap elif self.config['colormap'] == 'green': cmap = self.__greenCmap elif self.config['colormap'] == 'blue': cmap = self.__blueCmap elif self.config['colormap'] == 'temperature': cmap = self.__temperatureCmap elif self.config['colormap'] == 'paired': cmap = cm.Paired elif self.config['colormap'] == 'paired_r': cmap = cm.Paired_r elif self.config['colormap'] == 'pubu': cmap = cm.PuBu elif self.config['colormap'] == 'pubu_r': cmap = cm.PuBu_r elif self.config['colormap'] == 'rdbu': cmap = cm.RdBu elif self.config['colormap'] == 'rdbu_r': cmap = cm.RdBu_r elif self.config['colormap'] == 'gist_earth': cmap = cm.gist_earth elif self.config['colormap'] == 'gist_earth_r': cmap = cm.gist_earth_r elif self.config['colormap'] == 'blues': cmap = cm.Blues elif self.config['colormap'] == 'blues_r': cmap = cm.Blues_r elif self.config['colormap'] == 'ylgnbu': cmap = cm.YlGnBu elif self.config['colormap'] == 'ylgnbu_r': cmap = cm.YlGnBu_r else: print("Unsupported colormap %s" % self.config['colormap']) if self.config['extent'] is None: h, w = self.imageData.shape x0 = self.config['xorigin'] y0 = self.config['yorigin'] w = w * self.config['xpixelsize'] h = h * self.config['ypixelsize'] if origin == 'upper': extent = (x0, w + x0, h + y0, y0) else: extent = (x0, w + x0, y0, h + y0) else: extent = self.config['extent'] vlimits = self.__getValueLimits() if vlimits is None: imageData = self.imageData vmin = self.imageData.min() vmax = self.imageData.max() else: vmin = min(vlimits[0], vlimits[1]) vmax = max(vlimits[0], vlimits[1]) imageData = self.imageData.clip(vmin, vmax) if self.config['linlogcolormap'] != 'linear': if vmin <= 0: if vmax > 0: vmin = min(imageData[imageData > 0]) else: vmin = 0.0 vmax = 1.0 self._image = self.axes.imshow(imageData.clip(vmin, vmax), interpolation=interpolation, origin=origin, cmap=cmap, extent=extent, norm=LogNorm(vmin, vmax)) else: self._image = self.axes.imshow(imageData, interpolation=interpolation, origin=origin, cmap=cmap, extent=extent, norm=Normalize(vmin, vmax)) ylim = self.axes.get_ylim() if self.config['colorbar'] is not None: barorientation = self.config['colorbar'] self._colorbar = self.figure.colorbar(self._image, orientation=barorientation) #contour plot if self.config['contour'] != 'off': dataMin = imageData.min() dataMax = imageData.max() ncontours = int(self.config['contourlevels']) contourlinewidth = int(self.config['contourlinewidth']) / 10. levels = (numpy.arange(ncontours)) *\ (dataMax - dataMin)/float(ncontours) if self.config['contour'] == 'filled': self._contour = self.axes.contourf(imageData, levels, origin=origin, cmap=ccmap, extent=extent) else: self._contour = self.axes.contour(imageData, levels, origin=origin, cmap=ccmap, linewidths=contourlinewidth, extent=extent) if self.config['contourlabels'] != 'off': self.axes.clabel(self._contour, fontsize=9, inline=1, fmt=self.config['contourlabelformat']) if 0 and self.config['colorbar'] is not None: if barorientation == 'horizontal': barorientation = 'vertical' else: barorientation = 'horizontal' self._ccolorbar = self.figure.colorbar( self._contour, orientation=barorientation, extend='both') self.__postImage(ylim, filename) def setPixmapImage(self, image=None, bgr=False): if bgr: self.pixmapImage = image * 1 self.pixmapImage[:, :, 0] = image[:, :, 2] self.pixmapImage[:, :, 2] = image[:, :, 0] else: self.pixmapImage = image def _savePixmapFigure(self, filename): interpolation = self.config['interpolation'] origin = self.config['origin'] if self.config['extent'] is None: h = self.pixmapImage.shape[0] w = self.pixmapImage.shape[1] x0 = self.config['xorigin'] y0 = self.config['yorigin'] w = w * self.config['xpixelsize'] h = h * self.config['ypixelsize'] if origin == 'upper': extent = (x0, w + x0, h + y0, y0) else: extent = (x0, w + x0, y0, h + y0) else: extent = self.config['extent'] self._image = self.axes.imshow(self.pixmapImage, interpolation=interpolation, origin=origin, extent=extent) ylim = self.axes.get_ylim() self.__postImage(ylim, filename) def __getValueLimits(self): if (self.config['valuemin'] is not None) and\ (self.config['valuemax'] is not None) and\ (self.config['valuemin'] != self.config['valuemax']): vlimits = (self.config['valuemin'], self.config['valuemax']) elif self.config['vlimits'] is not None: vlimits = self.config['vlimits'] else: vlimits = None return vlimits def __postImage(self, ylim, filename): self.axes.set_title(self.config['title']) self.axes.set_xlabel(self.config['xlabel']) self.axes.set_ylabel(self.config['ylabel']) origin = self.config['origin'] if (self.config['zoomxmin'] is not None) and\ (self.config['zoomxmax'] is not None)and\ (self.config['zoomxmax'] != self.config['zoomxmin']): xlimits = (self.config['zoomxmin'], self.config['zoomxmax']) elif self.config['xlimits'] is not None: xlimits = self.config['xlimits'] else: xlimits = None if (self.config['zoomymin'] is not None) and\ (self.config['zoomymax'] is not None) and\ (self.config['zoomymax'] != self.config['zoomymin']): ylimits = (self.config['zoomymin'], self.config['zoomymax']) elif self.config['ylimits'] is not None: ylimits = self.config['ylimits'] else: ylimits = None if ylimits is None: self.axes.set_ylim(ylim[0], ylim[1]) else: ymin = min(ylimits) ymax = max(ylimits) if origin == "lower": self.axes.set_ylim(ymin, ymax) else: self.axes.set_ylim(ymax, ymin) if xlimits is not None: xmin = min(xlimits) xmax = max(xlimits) self.axes.set_xlim(xmin, xmax) self.canvas.print_figure(filename)
class DensityPanel(FigureCanvasWxAgg): def __init__(self, parent, **kwargs): self.figure = Figure() FigureCanvasWxAgg.__init__(self, parent, -1, self.figure, **kwargs) self.canvas = self.figure.canvas self.SetMinSize((100, 100)) self.figure.set_facecolor((1, 1, 1)) self.figure.set_edgecolor((1, 1, 1)) self.canvas.SetBackgroundColour('white') self.subplot = self.figure.add_subplot(111) self.gate_helper = GatingHelper(self.subplot, self) self.navtoolbar = None self.point_list = [] self.gridsize = 50 self.cb = None self.x_scale = LINEAR_SCALE self.y_scale = LINEAR_SCALE self.color_scale = None self.x_label = '' self.y_label = '' self.cmap = 'jet' self.canvas.mpl_connect('button_release_event', self.on_release) def setpointslists(self, points): self.subplot.clear() self.point_list = points plot_pts = np.array(points).astype(float) if self.x_scale == LOG_SCALE: plot_pts = plot_pts[(plot_pts[:, 0] > 0)] if self.y_scale == LOG_SCALE: plot_pts = plot_pts[(plot_pts[:, 1] > 0)] hb = self.subplot.hexbin(plot_pts[:, 0], plot_pts[:, 1], gridsize=self.gridsize, xscale=self.x_scale, yscale=self.y_scale, bins=self.color_scale, cmap=matplotlib.cm.get_cmap(self.cmap)) if self.cb: # Remove the existing colorbar and reclaim the space so when we add # a colorbar to the new hexbin subplot, it doesn't get indented. #self.figure.delaxes(self.figure.axes[1]) self.cb.remove() self.figure.subplots_adjust(right=0.90) self.cb = self.figure.colorbar(hb, fraction=0.046, pad=0.04) if self.color_scale == LOG_SCALE: self.cb.set_label('log10(N)') self.subplot.set_xlabel(self.x_label) self.subplot.set_ylabel(self.y_label) xmin = np.nanmin(plot_pts[:, 0]) xmax = np.nanmax(plot_pts[:, 0]) ymin = np.nanmin(plot_pts[:, 1]) ymax = np.nanmax(plot_pts[:, 1]) # Pad all sides if self.x_scale == LOG_SCALE: xmin = xmin / 1.5 xmax = xmax * 1.5 else: xmin = xmin - (xmax - xmin) / 20. xmax = xmax + (xmax - xmin) / 20. if self.y_scale == LOG_SCALE: ymin = ymin / 1.5 ymax = ymax * 1.5 else: ymin = ymin - (ymax - ymin) / 20. ymax = ymax + (ymax - ymin) / 20. self.subplot.axis([xmin, xmax, ymin, ymax]) self.reset_toolbar() def getpointslists(self): return self.point_list def setgridsize(self, gridsize): self.gridsize = gridsize def set_x_scale(self, scale): self.x_scale = scale def set_y_scale(self, scale): self.y_scale = scale def set_color_scale(self, scale): if scale == LINEAR_SCALE: scale = None self.color_scale = scale def set_x_label(self, label): self.x_label = label def set_y_label(self, label): self.y_label = label def set_colormap(self, cmap): self.cmap = cmap self.draw() def get_toolbar(self): if not self.navtoolbar: self.navtoolbar = NavigationToolbar(self.canvas) return self.navtoolbar def reset_toolbar(self): # Cheat since there is no way reset if self.navtoolbar: self.navtoolbar._views.clear() self.navtoolbar._positions.clear() self.navtoolbar.push_current() def set_configpanel(self, configpanel): '''Allow access of the control panel from the plotting panel''' self.configpanel = configpanel def on_release(self, evt): if evt.button == 3: # right click self.show_popup_menu((evt.x, self.canvas.GetSize()[1] - evt.y), None) def show_popup_menu(self, (x, y), data): self.popup_menu_filters = {} popup = wx.Menu() loadimages_table_item = popup.Append( -1, 'Create gated table for CellProfiler LoadImages') selected_gate = self.configpanel.gate_choice.get_gatename_or_none() selected_gates = [] if selected_gate: selected_gates = [selected_gate] self.Bind( wx.EVT_MENU, lambda (e): ui.prompt_user_to_create_loadimages_table( self, selected_gates), loadimages_table_item) show_images_in_gate_item = popup.Append(-1, 'Show images in gate') show_images_in_gate_item.Enable(selected_gate is not None) self.Bind(wx.EVT_MENU, self.show_images_from_gate, show_images_in_gate_item) if p.object_table: show_objects_in_gate_item = popup.Append( -1, 'Show %s in gate' % (p.object_name[1])) show_objects_in_gate_item.Enable(selected_gate is not None) self.Bind(wx.EVT_MENU, self.show_objects_from_gate, show_objects_in_gate_item) self.PopupMenu(popup, (x, y))
def visualize_image_attr( attr: ndarray, original_image: Union[None, ndarray] = None, method: str = "heat_map", sign: str = "absolute_value", plt_fig_axis: Union[None, Tuple[figure, axis]] = None, outlier_perc: Union[int, float] = 2, cmap: Union[None, str] = None, alpha_overlay: float = 0.5, show_colorbar: bool = False, title: Union[None, str] = None, fig_size: Tuple[int, int] = (6, 6), use_pyplot: bool = True, ): r""" Visualizes attribution for a given image by normalizing attribution values of the desired sign (positive, negative, absolute value, or all) and displaying them using the desired mode in a matplotlib figure. Parameters ---------- attr Numpy array corresponding to attributions to be visualized. Shape must be in the form (H, W, C), with channels as last dimension. Shape must also match that of the original image if provided. original_image Numpy array corresponding to original image. Shape must be in the form (H, W, C), with channels as the last dimension. Image can be provided either with float values in range 0-1 or int values between 0-255. This is a necessary argument for any visualization method which utilizes the original image. method Chosen method for visualizing attribution. Supported options are: 1. `heat_map` - Display heat map of chosen attributions 2. `blended_heat_map` - Overlay heat map over greyscale version of original image. Parameter alpha_overlay corresponds to alpha of heat map. 3. `original_image` - Only display original image. 4. `masked_image` - Mask image (pixel-wise multiply) by normalized attribution values. 5. `alpha_scaling` - Sets alpha channel of each pixel to be equal to normalized attribution value. Default: `heat_map` sign Chosen sign of attributions to visualize. Supported options are: 1. `positive` - Displays only positive pixel attributions. 2. `absolute_value` - Displays absolute value of attributions. 3. `negative` - Displays only negative pixel attributions. 4. `all` - Displays both positive and negative attribution values. This is not supported for `masked_image` or `alpha_scaling` modes, since signed information cannot be represented in these modes. plt_fig_axis Tuple of matplotlib.pyplot.figure and axis on which to visualize. If None is provided, then a new figure and axis are created. outlier_perc Top attribution values which correspond to a total of outlier_perc percentage of the total attribution are set to 1 and scaling is performed using the minimum of these values. For sign=`all`, outliers a nd scale value are computed using absolute value of attributions. cmap String corresponding to desired colormap for heatmap visualization. This defaults to "Reds" for negative sign, "Blues" for absolute value, "Greens" for positive sign, and a spectrum from red to green for all. Note that this argument is only used for visualizations displaying heatmaps. alpha_overlay Alpha to set for heatmap when using `blended_heat_map` visualization mode, which overlays the heat map over the greyscaled original image. show_colorbar Displays colorbar for heatmap below the visualization. If given method does not use a heatmap, then a colormap axis is created and hidden. This is necessary for appropriate alignment when visualizing multiple plots, some with colorbars and some without. title Title string for plot. If None, no title is set. fig_size Size of figure created. use_pyplot If true, uses pyplot to create and show figure and displays the figure after creating. If False, uses Matplotlib object oriented API and simply returns a figure object without showing. Returns ------- 2-element tuple of **figure**, **axis**: - **figure** (*matplotlib.pyplot.figure*): Figure object on which visualization is created. If plt_fig_axis argument is given, this is the same figure provided. - **axis** (*matplotlib.pyplot.axis*): Axis object on which visualization is created. If plt_fig_axis argument is given, this is the same axis provided. """ # Create plot if figure, axis not provided if plt_fig_axis is not None: plt_fig, plt_axis = plt_fig_axis else: if use_pyplot: plt_fig, plt_axis = plt.subplots(figsize=fig_size) else: plt_fig = Figure(figsize=fig_size) plt_axis = plt_fig.subplots() if original_image is not None: if np.max(original_image) <= 1.0: original_image = _prepare_image(original_image * 255) else: assert ( ImageVisualizationMethod[method] == ImageVisualizationMethod.heat_map ), "Original Image must be provided for any visualization other than heatmap." # Remove ticks and tick labels from plot. plt_axis.xaxis.set_ticks_position("none") plt_axis.yaxis.set_ticks_position("none") plt_axis.set_yticklabels([]) plt_axis.set_xticklabels([]) heat_map = None # Show original image if ImageVisualizationMethod[ method] == ImageVisualizationMethod.original_image: plt_axis.imshow(original_image) else: # Choose appropriate signed attributions and normalize. norm_attr = _normalize_image_attr(attr, sign, outlier_perc) # Set default colormap and bounds based on sign. if VisualizeSign[sign] == VisualizeSign.all: default_cmap = LinearSegmentedColormap.from_list( "RdWhGn", ["red", "white", "green"]) vmin, vmax = -1, 1 elif VisualizeSign[sign] == VisualizeSign.positive: default_cmap = "Greens" vmin, vmax = 0, 1 elif VisualizeSign[sign] == VisualizeSign.negative: default_cmap = "Reds" vmin, vmax = 0, 1 elif VisualizeSign[sign] == VisualizeSign.absolute_value: default_cmap = "Blues" vmin, vmax = 0, 1 else: raise AssertionError("Visualize Sign type is not valid.") cmap = cmap if cmap is not None else default_cmap # Show appropriate image visualization. if ImageVisualizationMethod[ method] == ImageVisualizationMethod.heat_map: heat_map = plt_axis.imshow(norm_attr, cmap=cmap, vmin=vmin, vmax=vmax) elif (ImageVisualizationMethod[method] == ImageVisualizationMethod.blended_heat_map): plt_axis.imshow(np.mean(original_image, axis=2), cmap="gray") heat_map = plt_axis.imshow(norm_attr, cmap=cmap, vmin=vmin, vmax=vmax, alpha=alpha_overlay) elif ImageVisualizationMethod[ method] == ImageVisualizationMethod.masked_image: assert VisualizeSign[sign] != VisualizeSign.all, ( "Cannot display masked image with both positive and negative " "attributions, choose a different sign option.") plt_axis.imshow( _prepare_image(original_image * np.expand_dims(norm_attr, 2))) elif ImageVisualizationMethod[ method] == ImageVisualizationMethod.alpha_scaling: assert VisualizeSign[sign] != VisualizeSign.all, ( "Cannot display alpha scaling with both positive and negative " "attributions, choose a different sign option.") plt_axis.imshow( np.concatenate( [ original_image, _prepare_image(np.expand_dims(norm_attr, 2) * 255), ], axis=2, )) else: raise AssertionError("Visualize Method type is not valid.") # Add colorbar. If given method is not a heatmap and no colormap is relevant, # then a colormap axis is created and hidden. This is necessary for appropriate # alignment when visualizing multiple plots, some with heatmaps and some # without. if show_colorbar: axis_separator = make_axes_locatable(plt_axis) colorbar_axis = axis_separator.append_axes("bottom", size="5%", pad=0.1) if heat_map: plt_fig.colorbar(heat_map, orientation="horizontal", cax=colorbar_axis) else: colorbar_axis.axis("off") if title: plt_axis.set_title(title) if use_pyplot: plt.show() return plt_fig, plt_axis
class Qt4Mpl2dCanvas(FigureCanvas): """ A customized Qt widget for matplotlib 2D image. It can be used to replace GraphicsView """ def __init__(self, parent): """ Initialization """ # Instantiating matplotlib Figure self.fig = Figure() self.fig.patch.set_facecolor('white') self.axes = self.fig.add_subplot( 111) # return: matplotlib.axes.AxesSubplot # Initialize parent class and set parent FigureCanvas.__init__(self, self.fig) self.setParent(parent) # Set size policy to be able to expanding and resizable with frame FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) # legend and color bar self._colorBar = None # Buffer of data self._currentArray2D = None # image management data structure self._currIndex = 0 self._imagePlotDict = dict() # image size self._xLimit = [0., 1.] self._yLimit = [0., 1.] return @property def array2d(self): """ get the matrix plot now :return: """ return self._currentArray2D def add_2d_plot(self, array2d, x_min, x_max, y_min, y_max, hold_prev, yticklabels=None): """ Add a 2D plot Requirements: (1) a valid 2-dimensional numpy.ndarray (2) x_min, x_max, y_min, y_max are of right order Guarantees: a 2D fill-plot is made :param array2d: :param x_min: :param x_max: :param y_min: :param y_max: :param hold_prev: hold previous image. If False, all 2D image and polygon patches will be removed :param yticklabels: list of string for y ticks :return: """ # Check assert isinstance( array2d, np.ndarray ), 'Input array2d must be a numpy array but not %s.' % str( type(array2d)) assert isinstance(x_min, int) and isinstance(x_max, int) and x_min < x_max, \ 'x_min = %s (of type %s) should be less than x_max = %s (of type %s).' \ '' % (str(x_min), str(type(x_min)), str(x_max), str(type(x_max))) assert isinstance(y_min, int) and isinstance(y_max, int) and y_min < y_max # Release the current image self.axes.hold(hold_prev) # show image img_plot = self.axes.imshow(array2d, extent=[x_min, x_max, y_min, y_max], interpolation='none') self._currentArray2D = array2d # set y ticks as an option: if yticklabels is not None: # it will always label the first N ticks even image is zoomed in # FUTURE-VZ : The way to set up the Y-axis ticks is wrong!" # self.axes.set_yticklabels(yticklabels) print( '[Warning] The method to set up the Y-axis ticks to 2D image is wrong!' ) # explicitly set aspect ratio of the image self.axes.set_aspect('auto') # Set color bar. plt.colorbar() does not work! if self._colorBar is None: # set color map type img_plot.set_cmap('spectral') self._colorBar = self.fig.colorbar(img_plot) else: self._colorBar.update_bruteforce(img_plot) # Flush... self._flush() # Add the image management self._currIndex += 1 self._imagePlotDict[self._currIndex] = img_plot return self._currIndex def add_patch(self, patch): """ add an artist patch such as polygon :param patch: :return: """ self.axes.add_artist(patch) # Flush... self._flush() return def addImage(self, imagefilename): """ Add an image by file """ # set aspect to auto mode self.axes.set_aspect('auto') img = matplotlib.image.imread(str(imagefilename)) # lum_img = img[:,:,0] # FUTURE : refactor for image size, interpolation and origin imgplot = self.axes.imshow(img, extent=[0, 1000, 800, 0], interpolation='none', origin='lower') # Set color bar. plt.colorbar() does not work! if self._colorBar is None: # set color map type imgplot.set_cmap('spectral') self._colorBar = self.fig.colorbar(imgplot) else: self._colorBar.update_bruteforce(imgplot) self._flush() return def clear_canvas(self): """ Clear data including lines and image from canvas """ # clear the image for next operation self.axes.hold(False) # clear 2D image self.axes.cla() # Try to clear the color bar if len(self.fig.axes) > 1: self.fig.delaxes(self.fig.axes[1]) self._colorBar = None # This clears the space claimed by color bar but destroys sub_plot too. self.fig.clear() # Re-create subplot self.axes = self.fig.add_subplot(111) # END-FOR # flush/commit self._flush() return def plot_polygon(self, vertex_array, fill=False, color='w'): """ Plot a new polygon :param vertex_array: :param fill: :param color: :return: """ # check requirements assert isinstance(vertex_array, np.ndarray) assert isinstance(fill, bool) assert isinstance(color, str) # plot polygon p = plt.Polygon(vertex_array, fill=fill, color=color) self.axes.add_artist(p) # Flush... self._flush() return p @property def x_min(self): """ x minimum :return: """ return self._xLimit[0] @property def x_max(self): """ maximum x :return: """ return self._xLimit[1] @property def y_min(self): """ minimum y :return: """ return self._yLimit[0] @property def y_max(self): """ maximum y :return: """ return self._yLimit[1] def _flush(self): """ A dirty hack to flush the image """ w, h = self.get_width_height() self.resize(w + 1, h) self.resize(w, h) return
def __create3dGraphWithPlanes(self, Xs, Ys, Zs): """ Arguments: Xs ([float]) -- Ys ([float]) -- Zs ([float]) -- """ fig = Figure() ax = Axes3D(fig) Ms = ['o', '^'] Ls = [ 'Human Rights Journal Article', 'Intellectual Property Journal Article' ] for i in range(len(Xs)): ax.scatter(Xs[i], Ys[i], Zs[i], s=40, marker=Ms[i], c=[[0, 0.733, 0.839]], label=Ls[i]) fig.legend() allXs = Xs[0] + Xs[1] smallX = min(allXs) bigX = max(allXs) allYs = Ys[0] + Ys[1] smallY = min(allYs) bigY = max(allYs) allZs = Zs[0] + Zs[1] smallZ = min(allZs) bigZ = max(allZs) averageX = int((smallX + bigX) / 2) ax.text(smallX, smallY, 0, 'User', color=[0, 0.733, 0.839], fontsize=14, weight='bold') ax.text(smallX, bigY, 0, 'Creator', color=[0, 0.733, 0.839], fontsize=14, weight='bold') Xplane = np.arange(smallX, bigX, 200) Yplane = np.arange(smallY, bigY, 0.01) Zplane = np.arange(smallZ, bigZ, 0.05) Xzmesh, Zxmesh = np.meshgrid(Xplane, Zplane) Yzmesh, Zymesh = np.meshgrid(Yplane, Zplane) Xymesh, Yxmesh = np.meshgrid(Xplane, Yplane) Xzero = np.full(Yzmesh.shape, averageX) Zzero = np.zeros(Xymesh.shape) Yzero = np.zeros(Xzmesh.shape) YZsurface = ax.plot_surface(Xzmesh, Yzero, Zxmesh, \ cmap=plt.get_cmap('seismic_r'), alpha=0.2, linewidth=0, \ antialiased=True) XYsurface = ax.plot_surface(Xymesh, Yxmesh, Zzero, alpha=0.2, \ linewidth=0, antialiased=True) cbaxes = fig.add_axes([0.05, 0.1, 0.03, 0.8]) YZcolbar = fig.colorbar(YZsurface, cax=cbaxes, ticks=[-0.7, 0.7], shrink=0.2, aspect=5, orientation='vertical') YZcolbar.ax.set_yticklabels(['HR', 'IP'], fontdict={ 'fontsize': 'large', 'fontweight': 'bold', 'color': [0, 0.733, 0.839] }) ax.set_xlabel("Date of Publication", fontsize='large', fontweight='bold') ax.set_ylabel("User-Creator Scale", fontsize='large', fontweight='bold') ax.set_zlabel("HR-IP Scale", fontsize='large', fontweight='bold') years = mdates.YearLocator() months = mdates.MonthLocator() yearsFmt = mdates.DateFormatter('%Y') ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(yearsFmt) ax.xaxis.set_minor_locator(months) ax.tick_params(axis='x', labelrotation=90, which='major', pad=0) ax.tick_params(axis='y', labelrotation=45, which='major', pad=0) ax.tick_params(axis='z', labelrotation=0, which='major', pad=0) ax.xaxis.labelpad = 25 ax.yaxis.labelpad = 18 ax.zaxis.labelpad = 4 ax.xaxis.label.set_color([0, 0.733, 0.839]) ax.yaxis.label.set_color([0, 0.733, 0.839]) ax.zaxis.label.set_color([0, 0.733, 0.839]) self._ax = ax self._fig = fig
def save_recon_images(img_file_name, imgs, recons, errs, fig_size): from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure imgs, recons, errs = np.squeeze(imgs), np.squeeze(recons), np.squeeze(errs) test_size = imgs.shape[0] indx = np.random.randint(0, int(test_size / 2)) f, f_MP = imgs[indx, :, :], imgs[int(test_size / 2) + indx, :, :] f_recon, f_MP_recon = recons[indx, :, :], recons[int(test_size / 2) + indx, :, :] f_recon_err, f_MP_recon_err = errs[indx, :, :], errs[int(test_size / 2) + indx, :, :] # fig_size = (8,6) fig_size = fig_size fig = Figure(figsize=fig_size) rows, cols = 2, 3 ax = fig.add_subplot(rows, cols, 1) cax = ax.imshow(f, cmap='gray') fig.colorbar(cax) ax.set_title('Image') ax.set_ylabel('f') ax = fig.add_subplot(rows, cols, 2) cax = ax.imshow(f_recon, cmap='gray') fig.colorbar(cax) ax.set_title('Recon') ax = fig.add_subplot(rows, cols, 3) cax = ax.imshow(f_recon_err, cmap='gray') fig.colorbar(cax) ax.set_title('Error') ax = fig.add_subplot(rows, cols, 4) cax = ax.imshow(f_MP, cmap='gray') fig.colorbar(cax) ax.set_ylabel('f_MP') ax = fig.add_subplot(rows, cols, 5) cax = ax.imshow(f_MP_recon, cmap='gray') fig.colorbar(cax) ax = fig.add_subplot(rows, cols, 6) cax = ax.imshow(f_MP_recon_err, cmap='gray') fig.colorbar(cax) canvas = FigureCanvasAgg(fig) canvas.print_figure(img_file_name, dpi=100)
def plot_fancy_occupancy(self, hist, z_max=None): if z_max == 'median': z_max = 2 * np.ma.median(hist) elif z_max == 'maximum' or z_max is None: z_max = np.ma.max(hist) if z_max < 1 or hist.all() is np.ma.masked: z_max = 1.0 fig = Figure() FigureCanvas(fig) ax = fig.add_subplot(111) extent = [0.5, 400.5, 192.5, 0.5] bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True) if z_max == 'median': cmap = cm.get_cmap('coolwarm') else: cmap = cm.get_cmap('cool') cmap.set_bad('w', 1.0) norm = colors.BoundaryNorm(bounds, cmap.N) im = ax.imshow(hist, interpolation='none', aspect='auto', cmap=cmap, norm=norm, extent=extent) # TODO: use pcolor or pcolormesh ax.set_ylim((192.5, 0.5)) ax.set_xlim((0.5, 400.5)) ax.set_xlabel('Column') ax.set_ylabel('Row') # create new axes on the right and on the top of the current axes # The first argument of the new_vertical(new_horizontal) method is # the height (width) of the axes to be created in inches. divider = make_axes_locatable(ax) axHistx = divider.append_axes("top", 1.2, pad=0.2, sharex=ax) axHisty = divider.append_axes("right", 1.2, pad=0.2, sharey=ax) cax = divider.append_axes("right", size="5%", pad=0.1) cb = fig.colorbar(im, cax=cax, ticks=np.linspace(start=0, stop=z_max, num=9, endpoint=True)) cb.set_label("#") # make some labels invisible setp(axHistx.get_xticklabels() + axHisty.get_yticklabels(), visible=False) hight = np.ma.sum(hist, axis=0) axHistx.bar(x=range(1, 401), height=hight, align='center', linewidth=0) axHistx.set_xlim((0.5, 400.5)) if hist.all() is np.ma.masked: axHistx.set_ylim((0, 1)) axHistx.locator_params(axis='y', nbins=3) axHistx.ticklabel_format(style='sci', scilimits=(0, 4), axis='y') axHistx.set_ylabel('#') width = np.ma.sum(hist, axis=1) axHisty.barh(y=range(1, 193), width=width, align='center', linewidth=0) axHisty.set_ylim((192.5, 0.5)) if hist.all() is np.ma.masked: axHisty.set_xlim((0, 1)) axHisty.locator_params(axis='x', nbins=3) axHisty.ticklabel_format(style='sci', scilimits=(0, 4), axis='x') axHisty.set_xlabel('#') self._save_plots(fig, suffix='fancy_occupancy')
def plot_scurves(self, scurves, scan_parameters, electron_axis=False, scan_parameter_name=None, title='S-curves', ylabel='Occupancy', max_occ=None): if max_occ is None: max_occ = np.max(scurves) + 5 x_bins = scan_parameters # np.arange(-0.5, max(scan_parameters) + 1.5) y_bins = np.arange(-0.5, max_occ + 0.5) n_pixel = 256 * 256 param_count = scurves.shape[0] hist = np.empty([param_count, max_occ], dtype=np.uint32) scurves[scurves >= max_occ] = max_occ - 1 for param in range(param_count): hist[param] = np.bincount(scurves[param, :], minlength=max_occ) fig = Figure() FigureCanvas(fig) ax = fig.add_subplot(111) self._add_text(fig) fig.patch.set_facecolor('white') cmap = cm.get_cmap('cool') if np.allclose(hist, 0.0) or hist.max() <= 1: z_max = 1.0 else: z_max = hist.max() # for small z use linear scale, otherwise log scale if z_max <= 10.0: bounds = np.linspace(start=0.0, stop=z_max, num=255, endpoint=True) norm = colors.BoundaryNorm(bounds, cmap.N) else: bounds = np.linspace(start=1.0, stop=z_max, num=255, endpoint=True) norm = colors.LogNorm() im = ax.pcolormesh(x_bins, y_bins, hist.T, norm=norm, rasterized=True) if z_max <= 10.0: cb = fig.colorbar(im, ticks=np.linspace(start=0.0, stop=z_max, num=min( 11, math.ceil(z_max) + 1), endpoint=True), fraction=0.04, pad=0.05) else: cb = fig.colorbar(im, fraction=0.04, pad=0.05) cb.set_label("# of pixels") ax.set_title(title + ' for %d pixel(s)' % (n_pixel), color=TITLE_COLOR) if scan_parameter_name is None: ax.set_xlabel('Scan parameter') else: ax.set_xlabel(scan_parameter_name) ax.set_ylabel(ylabel) if electron_axis: self._add_electron_axis(fig, ax) if self.qualitative: ax.xaxis.set_major_formatter(plt.NullFormatter()) ax.xaxis.set_minor_formatter(plt.NullFormatter()) ax.yaxis.set_major_formatter(plt.NullFormatter()) ax.yaxis.set_minor_formatter(plt.NullFormatter()) cb.formatter = plt.NullFormatter() cb.update_ticks() self._save_plots(fig, suffix='scurves')
def plot_occupancy(self, hist, electron_axis=False, use_electron_offset=True, title='Occupancy', z_label='# of hits', z_min=None, z_max=None, show_sum=True, suffix=None): if z_max == 'median': z_max = 2 * np.ma.median(hist) elif z_max == 'maximum' or z_max is None: z_max = np.ma.max(hist) if z_max < 1 or hist.all() is np.ma.masked: z_max = 1.0 if z_min is None: z_min = np.ma.min(hist) if z_min == z_max or hist.all() is np.ma.masked: z_min = 0 fig = Figure() FigureCanvas(fig) ax = fig.add_subplot(111) self._add_text(fig) ax.set_adjustable('box') extent = [0.5, 256.5, 256.5, 0.5] bounds = np.linspace(start=z_min, stop=z_max, num=255, endpoint=True) cmap = cm.get_cmap('plasma') cmap.set_bad('w', 1.0) norm = colors.BoundaryNorm(bounds, cmap.N) im = ax.imshow(hist, interpolation='none', aspect='equal', cmap=cmap, norm=norm, extent=extent) # TODO: use pcolor or pcolormesh ax.set_ylim((256.5, 0.5)) ax.set_xlim((0.5, 256.5)) if self.qualitative or not show_sum: ax.set_title(title, color=TITLE_COLOR) else: ax.set_title(title + r' ($\Sigma$ = {0})'.format( (0 if hist.all() is np.ma.masked else np.ma.sum(hist))), color=TITLE_COLOR) ax.set_xlabel('Column') ax.set_ylabel('Row') divider = make_axes_locatable(ax) if electron_axis: pad = 1.0 else: pad = 0.6 cax = divider.append_axes("bottom", size="5%", pad=pad) cb = fig.colorbar(im, cax=cax, ticks=np.linspace(start=z_min, stop=z_max, num=10, endpoint=True), orientation='horizontal') cax.set_xticklabels([ int(round(float(x.get_text()))) for x in cax.xaxis.get_majorticklabels() ]) cb.set_label(z_label) if electron_axis: fig.canvas.draw() ax2 = cb.ax.twiny() pos = ax2.get_position() pos.y1 = 0.14 ax2.set_position(pos) for spine in ax2.spines.values(): spine.set_visible(False) xticks = [ int( round( self._convert_to_e(float(x.get_text()), use_offset=use_electron_offset))) for x in cax.xaxis.get_majorticklabels() ] ax2.set_xticklabels(xticks) # l = cax.get_xlim() l2 = ax2.get_xlim() def f(x): return l2[0] + (x - l[0]) / \ (l[1] - l[0]) * (l2[1] - l2[0]) ticks = f(cax.get_xticks()) ax2.xaxis.set_major_locator(matplotlib.ticker.FixedLocator(ticks)) # ax2.set_xlabel(r'%s [Electrons ($x \cdot %1.2f \; \frac{e^-}{\Delta VCAL} + %1.2f \; e^-$)]' % (z_label, ELECTRON_CONVERSION['slope'], ELECTRON_CONVERSION['offset']), labelpad=7) ax2.set_xlabel('%s [Electrons]' % (z_label), labelpad=7) cb.set_label(r'%s [$\Delta$ VCAL]' % z_label) if self.qualitative: ax.xaxis.set_major_formatter(plt.NullFormatter()) ax.xaxis.set_minor_formatter(plt.NullFormatter()) ax.yaxis.set_major_formatter(plt.NullFormatter()) ax.yaxis.set_minor_formatter(plt.NullFormatter()) cb.formatter = plt.NullFormatter() cb.update_ticks() self._save_plots(fig, suffix=suffix)
def plot_stacked_threshold(self, data, tdac_mask, plot_range=None, electron_axis=False, x_axis_title=None, y_axis_title=None, title=None, suffix=None, min_tdac=0, max_tdac=15, range_tdac=16): start_column = self.run_config['start_column'] stop_column = self.run_config['stop_column'] data = data[:, start_column:stop_column] if plot_range is None: diff = np.amax(data) - np.amin(data) if (np.amax(data)) > np.median(data) * 5: plot_range = np.arange(np.amin(data), np.median(data) * 5, diff / 100.) else: plot_range = np.arange(np.amin(data), np.amax(data) + diff / 100., diff / 100.) tick_size = plot_range[1] - plot_range[0] hist, bins = np.histogram(np.ravel(data), bins=plot_range) bin_centres = (bins[:-1] + bins[1:]) / 2 p0 = (np.amax(hist), np.mean(bins), (max(plot_range) - min(plot_range)) / 3) try: coeff, _ = curve_fit(self._gauss, bin_centres, hist, p0=p0) except: coeff = None self.logger.warning('Gauss fit failed!') if coeff is not None: points = np.linspace(min(plot_range), max(plot_range), 500) gau = self._gauss(points, *coeff) fig = Figure() FigureCanvas(fig) ax = fig.add_subplot(111) self._add_text(fig) cmap = cm.get_cmap('viridis', (range_tdac - 1)) # create dicts for tdac data data_thres_tdac = {} hist_tdac = {} tdac_bar = {} tdac_map = tdac_mask[:, start_column:stop_column] # select threshold data for different tdac values according to tdac map for tdac in range(range_tdac): data_thres_tdac[tdac] = data[tdac_map == tdac - abs(min_tdac)] # histogram threshold data for each tdac hist_tdac[tdac], _ = np.histogram(np.ravel(data_thres_tdac[tdac]), bins=bins) if tdac == 0: tdac_bar[tdac] = ax.bar(bins[:-1], hist_tdac[tdac], width=tick_size, align='edge', color=cmap(.9 / range_tdac * tdac), edgecolor='white') elif tdac == 1: tdac_bar[tdac] = ax.bar(bins[:-1], hist_tdac[tdac], bottom=hist_tdac[0], width=tick_size, align='edge', color=cmap(1. / range_tdac * tdac), edgecolor='white') else: tdac_bar[tdac] = ax.bar( bins[:-1], hist_tdac[tdac], bottom=np.sum([hist_tdac[i] for i in range(tdac)], axis=0), width=tick_size, align='edge', color=cmap(1. / range_tdac * tdac), edgecolor='white') fig.subplots_adjust(right=0.85) cax = fig.add_axes([0.89, 0.11, 0.02, 0.645]) sm = plt.cm.ScalarMappable(cmap=cmap, norm=colors.Normalize(vmin=min_tdac, vmax=max_tdac)) sm.set_array([]) cb = fig.colorbar(sm, cax=cax, ticks=np.linspace(start=min_tdac, stop=max_tdac, num=range_tdac, endpoint=True)) cb.set_label('TDAC') if coeff is not None: ax.plot(points, gau, "r-", label='Normal distribution') ax.set_xlim((min(plot_range), max(plot_range))) ax.set_title(title, color=TITLE_COLOR) if x_axis_title is not None: ax.set_xlabel(x_axis_title) if y_axis_title is not None: ax.set_ylabel(y_axis_title) ax.grid(True) if coeff is not None and not self.qualitative: if electron_axis: textright = '$\mu=%.0f\;\Delta$VCAL\n$\;\,\,=%.0f \; e^-$\n\n$\sigma=%.0f\;\Delta$VCAL\n$\;\,\,=%.0f \; e^-$' % ( abs(coeff[1]), self._convert_to_e(abs( coeff[1])), abs(coeff[2]), self._convert_to_e(abs(coeff[2]), use_offset=False)) else: textright = '$\mu=%.0f$\n$\sigma=%.0f$' % (abs( coeff[1]), abs(coeff[2])) props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) ax.text(0.05, 0.9, textright, transform=ax.transAxes, fontsize=8, verticalalignment='top', bbox=props) if electron_axis: self._add_electron_axis(fig, ax) if self.qualitative: ax.xaxis.set_major_formatter(plt.NullFormatter()) ax.xaxis.set_minor_formatter(plt.NullFormatter()) ax.yaxis.set_major_formatter(plt.NullFormatter()) ax.yaxis.set_minor_formatter(plt.NullFormatter()) self._save_plots(fig, suffix=suffix)
class MyTableWidget(QWidget): def __init__(self, parent): super(QWidget, self).__init__(parent) self.layout = QVBoxLayout(self) # Initialize tabs ---------------------------------- self.tabs = QTabWidget() self.Load_data = QWidget() # create tab 1 self.SettRzPlot_tab = QWidget() # create tab 2 self.Rz_tab = QWidget() # create tab 3 self.tabs.resize(300, 200) # Add tabs to the Main WIndow self.tabs.addTab(self.Load_data, "Load data") # tab 1 self.tabs.addTab(self.SettRzPlot_tab, "Rz plot Settings") # tab 2 self.tabs.addTab(self.Rz_tab, "Rz plot") # tab 3 # Add tabs to widget self.layout.addWidget(self.tabs) self.setLayout(self.layout) self.show() # ---------------------------------------------------------------------------------- # Load_data tab - content self.data_loaded = False layout_load = QtWidgets.QVBoxLayout(self.Load_data) # main layout sublayout_load = QtWidgets.QGridLayout() # layout for inputs layout_load.addLayout(sublayout_load) # Input widgets # Shot self.Shot_lbl_load = QLabel(self.Load_data) self.Shot_lbl_load.setText('Shot # ') self.Shot_ed_load = QLineEdit(self.Load_data) self.Shot_ed_load.setText('25781') # Diag self.Diag_lbl_load = QLabel(self.Load_data) self.Diag_lbl_load.setText('Diag: ') self.Diag_load = QComboBox(self.Load_data) self.Diag_load.addItems(['ECI', 'TDI']) self.Diag_lbl_EQ_load = QLabel(self.Load_data) self.Diag_lbl_EQ_load.setText('Equilibrium: ') self.Diag_EQ_load = QComboBox(self.Load_data) self.Diag_EQ_load.addItems(['EQH']) # Load button self.Butt_load = QPushButton("Load ECEI and equilibrium data", self.Load_data) self.Butt_load.clicked.connect(self.Load_ECEI_data) # Monitor self.Monitor_load = QtWidgets.QTextBrowser(self.Load_data) self.Monitor_load.setText("Status:\nECEI data is not loaded") # Add widgets to layout sublayout_load.setSpacing(5) sublayout_load.addWidget(self.Shot_lbl_load, 0, 0) sublayout_load.addWidget(self.Diag_lbl_load, 1, 0) sublayout_load.addWidget(self.Diag_lbl_EQ_load, 2, 0) sublayout_load.addWidget(self.Shot_ed_load, 0, 1) sublayout_load.addWidget(self.Diag_load, 1, 1) sublayout_load.addWidget(self.Diag_EQ_load, 2, 1) sublayout_load.addWidget(self.Butt_load, 3, 1) sublayout_2_load = QtWidgets.QGridLayout() # layout for inputs layout_load.addLayout(sublayout_2_load) sublayout_2_load.addWidget(self.Monitor_load, 1, 0) # stretch free space (compress widgets at the top) layout_load.addStretch() # ---------------------------------------------------------------------------------- # Rz plot tab - content # Create layouts layout_RzPl = QtWidgets.QVBoxLayout(self.Rz_tab) # main layout sublayout_RzPl = QtWidgets.QGridLayout() # layout for inputs layout_RzPl.addLayout(sublayout_RzPl) # Input widgets # labels self.tB_lbl_RzPl = QLabel(self.Rz_tab) self.tB_lbl_RzPl.setText('tB [s]:') self.tE_lbl_RzPl = QLabel(self.Rz_tab) self.tE_lbl_RzPl.setText('tE [s]:') self.tCnt_lbl_RzPl = QLabel(self.Rz_tab) self.tCnt_lbl_RzPl.setText('tCenter [s] (optional):') self.dt_lbl_RzPl = QLabel(self.Rz_tab) self.dt_lbl_RzPl.setText('dt [s](optional) :') # filter labels self.Fourier_lbl0_RzPl = QLabel(self.Rz_tab) self.Fourier_lbl0_RzPl.setText('Fourier lowpass f [kHz]:') self.Fourier2_lbl0_RzPl = QLabel(self.Rz_tab) self.Fourier2_lbl0_RzPl.setText('Fourier highpass f [kHz]:') self.SavGol_lbl0_RzPl = QLabel(self.Rz_tab) self.SavGol_lbl0_RzPl.setText('SavGol win_len:') self.SavGol_lbl1_RzPl = QLabel(self.Rz_tab) self.SavGol_lbl1_RzPl.setText('SavGol pol_ord:') self.Binning_lbl_RzPl = QLabel(self.Rz_tab) self.Binning_lbl_RzPl.setText('Binning [kHz]:') self.Contour_lbl_RzPl = QLabel(self.Rz_tab) self.Contour_lbl_RzPl.setText('Contour [1 or 0]') self.NNcont_lbl_RzPl = QLabel(self.Rz_tab) self.NNcont_lbl_RzPl.setText('NNcont:') self.tplot_lbl_RzPl = QLabel(self.Rz_tab) self.tplot_lbl_RzPl.setText('t_plot [s](within tB and tE):') self.dtplot_lbl_RzPl = QLabel(self.Rz_tab) self.dtplot_lbl_RzPl.setText('dt_plot [s]:') self.FourMult_lbl_RzPl = QLabel(self.Rz_tab) self.FourMult_lbl_RzPl.setText('Fourier multiple f [kHz]:') # plot params labels self.vmin_lbl_RzPl = QLabel(self.Rz_tab) self.vmin_lbl_RzPl.setText('vmin:') self.vmax_lbl_RzPl = QLabel(self.Rz_tab) self.vmax_lbl_RzPl.setText('vmax:') self.chzz_lbl_RzPl = QLabel(self.Rz_tab) self.chzz_lbl_RzPl.setText('Remove LOS:') self.chRR_lbl_RzPl = QLabel(self.Rz_tab) self.chRR_lbl_RzPl.setText('Remove R chs:') # velocimetry specific labels self.rhop_lbl_RzPl = QLabel(self.Rz_tab) self.rhop_lbl_RzPl.setText('rho_pol:') # line edits # time edits self.tB_ed_RzPl = QLineEdit(self.Rz_tab) self.tB_ed_RzPl.setText('4.488525') self.tB_ed_RzPl.setMinimumSize(QtCore.QSize(55, 0)) self.tE_ed_RzPl = QLineEdit(self.Rz_tab) self.tE_ed_RzPl.setText('4.489525') self.tE_ed_RzPl.setMinimumSize(QtCore.QSize(55, 0)) self.tCnt_ed_RzPl = QLineEdit(self.Rz_tab) self.tCnt_ed_RzPl.setMinimumSize(QtCore.QSize(50, 0)) self.dt_ed_RzPl = QLineEdit(self.Rz_tab) self.dt_ed_RzPl.setText('0.001') self.dt_ed_RzPl.setMinimumSize(QtCore.QSize(100, 0)) self.Butt_dt_RzPl = QPushButton("Calc t", self.Rz_tab) self.Butt_dt_RzPl.clicked.connect(lambda: self.tBE_from_tCnt(9)) # plot params edits self.vmin_ed_RzPl = QLineEdit(self.Rz_tab) self.vmin_ed_RzPl.setText('None') self.vmin_ed_RzPl.setMinimumSize(QtCore.QSize(40, 0)) self.vmax_ed_RzPl = QLineEdit(self.Rz_tab) self.vmax_ed_RzPl.setText('None') self.vmax_ed_RzPl.setMinimumSize(QtCore.QSize(40, 0)) self.chzz_ed_RzPl = QLineEdit(self.Rz_tab) self.chzz_ed_RzPl.setMinimumSize(QtCore.QSize(100, 0)) self.chRR_ed_RzPl = QLineEdit(self.Rz_tab) self.chRR_ed_RzPl.setMinimumSize(QtCore.QSize(100, 0)) # Filters edits self.Fourier_cut_RzPl = QLineEdit(self.Rz_tab) self.Fourier_cut_RzPl.setText('30.0') self.Fourier2_cut_RzPl = QLineEdit(self.Rz_tab) self.Fourier2_cut_RzPl.setText('2.0') self.SavGol_ed0_RzPl = QLineEdit(self.Rz_tab) self.SavGol_ed0_RzPl.setText('11') self.SavGol_ed0_RzPl.setMinimumSize(QtCore.QSize(20, 0)) self.SavGol_ed1_RzPl = QLineEdit(self.Rz_tab) self.SavGol_ed1_RzPl.setText('3') self.Binning_ed_RzPl = QLineEdit(self.Rz_tab) self.Binning_ed_RzPl.setText('60.0') self.Binning_ed_RzPl.setMinimumSize(QtCore.QSize(40, 0)) self.Contour_ed_RzPl = QLineEdit(self.Rz_tab) self.Contour_ed_RzPl.setText('0') self.NNcont_ed_RzPl = QLineEdit(self.Rz_tab) self.NNcont_ed_RzPl.setText('60') self.tplot_ed_RzPl = QLineEdit(self.Rz_tab) self.tplot_ed_RzPl.setText('4.488550') self.tplot_ed_RzPl.setMinimumSize(QtCore.QSize(50, 0)) self.dtplot_ed_RzPl = QLineEdit(self.Rz_tab) self.dtplot_ed_RzPl.setText('5.0e-6') self.dtplot_ed_RzPl.setMinimumSize(QtCore.QSize(50, 0)) self.FourMult_ed_RzPl = QLineEdit(self.Rz_tab) self.FourMult_ed_RzPl.setText('13.0,15.0;26,30') self.FourMult_ed_RzPl.setMinimumSize(QtCore.QSize(100, 0)) # velocimetry specific line edits self.rhop_ed_RzPl = QLineEdit(self.Rz_tab) self.rhop_ed_RzPl.setText('0.3') self.sendpoints_butt_RzPl = QPushButton("Send t,R,z,r", self.Rz_tab) self.sendpoints_butt_RzPl.clicked.connect(self.send_points) self.clearpoints_butt_RzPl = QPushButton("Clear table", self.Rz_tab) self.clearpoints_butt_RzPl.clicked.connect(self.clear_table) # what to plot (type of filter) self.ImgType_plot_RzPl = QComboBox(self.Rz_tab) self.ImgType_plot_RzPl.addItems([ 'no Image filter', 'Gaussian', 'Median', 'Bilateral', 'Conservative_smoothing' ]) self.type_plot_RzPl = QComboBox(self.Rz_tab) self.type_plot_RzPl.addItems([ 'no 1D filter', 'Fourier highpass', 'Fourier lowpass', 'Fourier both', 'Fourier multiple', 'SavGol', 'Binning' ]) self.Interp_plot_RzPl = QComboBox(self.Rz_tab) self.Interp_plot_RzPl.addItems( ['no interpolation', 'with interpolation', 'set to zero']) # self.Interp_plot_RzPl.setMaximumSize(QtCore.QSize(90, 0)) self.Save_plot_RzPl = QComboBox(self.Rz_tab) self.Save_plot_RzPl.addItems( ['do not save', 'save as pdf', 'save as png']) # plot buttom self.MinusTplot_butt_RzPl = QPushButton("< -dt", self.Rz_tab) self.PlusTplot_butt_RzPl = QPushButton("+dt >", self.Rz_tab) self.tplot_butt_RzPl = QPushButton("plot time", self.Rz_tab) self.MinusTplot_butt_RzPl.clicked.connect(lambda: self.f_Rz_plot(1)) self.PlusTplot_butt_RzPl.clicked.connect(lambda: self.f_Rz_plot(2)) self.tplot_butt_RzPl.clicked.connect(lambda: self.f_Rz_plot(3)) # Add widgets to layout # First row sublayout_RzPl.setSpacing(2) sublayout_RzPl.addWidget(self.tB_lbl_RzPl, 0, 0) sublayout_RzPl.addWidget(self.tB_ed_RzPl, 0, 1) sublayout_RzPl.addWidget(self.tE_lbl_RzPl, 0, 2) sublayout_RzPl.addWidget(self.tE_ed_RzPl, 0, 3) sublayout_RzPl.addWidget(self.tCnt_lbl_RzPl, 0, 4) sublayout_RzPl.addWidget(self.tCnt_ed_RzPl, 0, 5) sublayout_RzPl.addWidget(self.dt_lbl_RzPl, 0, 6) sublayout_RzPl.addWidget(self.dt_ed_RzPl, 0, 7) sublayout_RzPl.addWidget(self.Butt_dt_RzPl, 0, 8) # Second row sublayout_RzPl.addWidget(self.Fourier2_lbl0_RzPl, 1, 0) sublayout_RzPl.addWidget(self.Fourier2_cut_RzPl, 1, 1) sublayout_RzPl.addWidget(self.Fourier_lbl0_RzPl, 1, 2) sublayout_RzPl.addWidget(self.Fourier_cut_RzPl, 1, 3) sublayout_RzPl.addWidget(self.FourMult_lbl_RzPl, 1, 4) sublayout_RzPl.addWidget(self.FourMult_ed_RzPl, 1, 5) ###### sublayout_RzPl.addWidget(self.SavGol_lbl0_RzPl, 1, 6) sublayout_RzPl.addWidget(self.SavGol_ed0_RzPl, 1, 7) sublayout_RzPl.addWidget(self.SavGol_lbl1_RzPl, 1, 8) sublayout_RzPl.addWidget(self.SavGol_ed1_RzPl, 1, 9) sublayout_RzPl.addWidget(self.Binning_lbl_RzPl, 1, 10) sublayout_RzPl.addWidget(self.Binning_ed_RzPl, 1, 11) ###### sublayout_RzPl.addWidget(self.chzz_lbl_RzPl, 2, 0) sublayout_RzPl.addWidget(self.chzz_ed_RzPl, 2, 1) sublayout_RzPl.addWidget(self.chRR_lbl_RzPl, 2, 2) sublayout_RzPl.addWidget(self.chRR_ed_RzPl, 2, 3) ###### sublayout_RzPl.addWidget(self.vmin_lbl_RzPl, 2, 4) sublayout_RzPl.addWidget(self.vmin_ed_RzPl, 2, 5) sublayout_RzPl.addWidget(self.vmax_lbl_RzPl, 2, 6) sublayout_RzPl.addWidget(self.vmax_ed_RzPl, 2, 7) sublayout_RzPl.addWidget(self.Contour_lbl_RzPl, 2, 8) sublayout_RzPl.addWidget(self.Contour_ed_RzPl, 2, 9) sublayout_RzPl.addWidget(self.NNcont_lbl_RzPl, 2, 10) sublayout_RzPl.addWidget(self.NNcont_ed_RzPl, 2, 11) ##### ###### # Third row sublayout_RzPl.addWidget(self.tplot_lbl_RzPl, 3, 0) sublayout_RzPl.addWidget(self.tplot_ed_RzPl, 3, 1) sublayout_RzPl.addWidget(self.dtplot_lbl_RzPl, 3, 2) sublayout_RzPl.addWidget(self.dtplot_ed_RzPl, 3, 3) # Fourth row sublayout_RzPl.addWidget(self.rhop_lbl_RzPl, 4, 0) sublayout_RzPl.addWidget(self.rhop_ed_RzPl, 4, 1) sublayout_RzPl.addWidget(self.sendpoints_butt_RzPl, 4, 2) sublayout_RzPl.addWidget(self.clearpoints_butt_RzPl, 4, 3) # Plot control sublayout_RzPl.addWidget(self.ImgType_plot_RzPl, 1, 12) sublayout_RzPl.addWidget(self.type_plot_RzPl, 2, 12) sublayout_RzPl.addWidget(self.Save_plot_RzPl, 3, 7) sublayout_RzPl.addWidget(self.Interp_plot_RzPl, 3, 8) sublayout_RzPl.addWidget(self.MinusTplot_butt_RzPl, 3, 10) sublayout_RzPl.addWidget(self.PlusTplot_butt_RzPl, 3, 11) sublayout_RzPl.addWidget(self.tplot_butt_RzPl, 3, 12) # Add matplotlib plot self.figure_RzPl = Figure(figsize=(5, 3), constrained_layout=False) self.static_canvas_RzPl = FigureCanvas(self.figure_RzPl) layout_RzPl.addWidget(self.static_canvas_RzPl, QtCore.Qt.AlignTop) # align the plot up layout_RzPl.addStretch() # stretch plot in all free space self.toolbar = NavigationToolbar( self.static_canvas_RzPl, self.Rz_tab, coordinates=True) # add toolbar below the plot layout_RzPl.addWidget(self.toolbar) self._static_ax = self.static_canvas_RzPl.figure.subplots() # add axes # velcimetry data self.Monitor_RzPl = QtWidgets.QTextBrowser(self.Rz_tab) self.Monitor_RzPl.setText("NN\tt\tR\tz\tr\n") self.counter = 1 self.Monitor_RzPl.setMaximumSize(QtCore.QSize(1920, 50)) sublayout2_RzPl = QtWidgets.QVBoxLayout() # layout for monitor layout_RzPl.addLayout(sublayout2_RzPl) sublayout2_RzPl.addWidget(self.Monitor_RzPl, 0) # ---------------------------------------------------------------------------------- # SettRz tab - content # Create layouts layout_RzSet = QtWidgets.QVBoxLayout( self.SettRzPlot_tab) # main layout sublayout_RzSet = QtWidgets.QGridLayout() # layout for inputs layout_RzSet.addLayout(sublayout_RzSet) # Input widgets # labels self.one_lbl_RzSet = QLabel(self.SettRzPlot_tab) self.one_lbl_RzSet.setText('Gaussian filter:') self.two_lbl_RzSet = QLabel(self.SettRzPlot_tab) self.two_lbl_RzSet.setText('Median filter:') self.three_lbl_RzSet = QLabel(self.SettRzPlot_tab) self.three_lbl_RzSet.setText('Bilateral filter:') self.four_lbl_RzSet = QLabel(self.SettRzPlot_tab) self.four_lbl_RzSet.setText('Conservative smoothing filter:') # filters parameters self.BilKernSize_lbl_RzSet = QLabel(self.SettRzPlot_tab) self.BilKernSize_lbl_RzSet.setText('Kernel size:') self.BilS0_lbl_RzSet = QLabel(self.SettRzPlot_tab) self.BilS0_lbl_RzSet.setText('s0:') self.BilS1_lbl_RzSet = QLabel(self.SettRzPlot_tab) self.BilS1_lbl_RzSet.setText('s1:') self.MedKernSize_lbl_RzSet = QLabel(self.SettRzPlot_tab) self.MedKernSize_lbl_RzSet.setText('Kernel size:') self.ConsSize_lbl_RzSet = QLabel(self.SettRzPlot_tab) self.ConsSize_lbl_RzSet.setText('Neighborhood size:') self.GausSigma_lbl_RzSet = QLabel(self.SettRzPlot_tab) self.GausSigma_lbl_RzSet.setText('sigma:') # Line edits (inputs) self.GausSigma_ed_RzSet = QLineEdit(self.SettRzPlot_tab) self.GausSigma_ed_RzSet.setText('1.0') self.BilKern_type_RzSet = QComboBox(self.SettRzPlot_tab) self.BilKern_type_RzSet.addItems(['disk', 'square']) self.BilKernSize_ed_RzSet = QLineEdit(self.SettRzPlot_tab) self.BilKernSize_ed_RzSet.setText('1') self.BilS0_ed_RzSet = QLineEdit(self.SettRzPlot_tab) self.BilS0_ed_RzSet.setText('100') self.BilS1_ed_RzSet = QLineEdit(self.SettRzPlot_tab) self.BilS1_ed_RzSet.setText('100') self.MedKern_type_RzSet = QComboBox(self.SettRzPlot_tab) self.MedKern_type_RzSet.addItems(['disk', 'square']) self.MedKernSize_ed_RzSet = QLineEdit(self.SettRzPlot_tab) self.MedKernSize_ed_RzSet.setText('1') self.ConsSize_ed_RzSet = QLineEdit(self.SettRzPlot_tab) self.ConsSize_ed_RzSet.setText('2') sublayout_RzSet.setSpacing(2) # First row sublayout_RzSet.addWidget(self.one_lbl_RzSet, 0, 0) sublayout_RzSet.addWidget(self.GausSigma_lbl_RzSet, 0, 2) sublayout_RzSet.addWidget(self.GausSigma_ed_RzSet, 0, 3) # Second row sublayout_RzSet.addWidget(self.two_lbl_RzSet, 1, 0) sublayout_RzSet.addWidget(self.MedKern_type_RzSet, 1, 1) sublayout_RzSet.addWidget(self.MedKernSize_lbl_RzSet, 1, 2) sublayout_RzSet.addWidget(self.MedKernSize_ed_RzSet, 1, 3) # Third row sublayout_RzSet.addWidget(self.three_lbl_RzSet, 2, 0) sublayout_RzSet.addWidget(self.BilKern_type_RzSet, 2, 1) sublayout_RzSet.addWidget(self.BilKernSize_lbl_RzSet, 2, 2) sublayout_RzSet.addWidget(self.BilKernSize_ed_RzSet, 2, 3) sublayout_RzSet.addWidget(self.BilS0_lbl_RzSet, 2, 4) sublayout_RzSet.addWidget(self.BilS0_ed_RzSet, 2, 5) sublayout_RzSet.addWidget(self.BilS1_lbl_RzSet, 2, 6) sublayout_RzSet.addWidget(self.BilS1_ed_RzSet, 2, 7) # Fourth row sublayout_RzSet.addWidget(self.four_lbl_RzSet, 3, 0) sublayout_RzSet.addWidget(self.ConsSize_lbl_RzSet, 3, 2) sublayout_RzSet.addWidget(self.ConsSize_ed_RzSet, 3, 3) sublayout1_RzSet = QtWidgets.QVBoxLayout() # one more layout for title layout_RzSet.addLayout(sublayout1_RzSet) self.Info1_lbl_RzSet = QLabel(self.SettRzPlot_tab) self.Info1_lbl_RzSet.setText( '====== Matrix for interpolation (scipy.interpolate.interp2d, type = cubic) or "set to zero" options ======' ) sublayout1_RzSet.addWidget(self.Info1_lbl_RzSet) sublayout2_RzSet = QtWidgets.QGridLayout( ) # one more layout for interpolation layout_RzSet.addLayout(sublayout2_RzSet) LOSlabels = {} self.LOSlabels = {} for i_L in range(20): LOSlabels['%d' % (i_L)] = (i_L, 0) for sText, pos in LOSlabels.items(): # QLabels self.LOSlabels[sText] = QLabel("LOS: %d" % (int(sText) + 1)) sublayout2_RzSet.addWidget(self.LOSlabels[sText], pos[0] + 1, pos[1]) checks = {} self.checks = {} for i_L in range(20): for i_R in range(8): checks['%d,%d' % (i_L, i_R)] = (i_L, i_R) for sText, pos in checks.items(): # QCheckBoxes self.checks[sText] = QCheckBox("%d,%d" % (pos[0] + 1, pos[1] + 1)) sublayout2_RzSet.addWidget(self.checks[sText], pos[0] + 1, pos[1] + 1) sublayout2_RzSet.setSpacing(2) sublayout3_RzSet = QtWidgets.QHBoxLayout() # one more layout for path layout_RzSet.addLayout(sublayout3_RzSet) self.path_lbl_RzSet = QLabel(self.SettRzPlot_tab) self.path_lbl_RzSet.setText( 'Path to save Rz plots (path should end with "/" symbol):') self.path_ed_RzSet = QLineEdit(self.SettRzPlot_tab) self.path_ed_RzSet.setText('/afs/ipp/home/o/osam/Documents/output/') sublayout3_RzSet.addWidget(self.path_lbl_RzSet) sublayout3_RzSet.addWidget(self.path_ed_RzSet) layout_RzSet.addStretch( ) # stretch free space (compress widgets at the top) # ---------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------- # ---------------METHODS------------- def tBE_from_tCnt(self, number): try: if (number == 9): t = float(self.tCnt_ed_RzPl.text()) dt = float(self.dt_ed_RzPl.text()) tB = t - dt / 2.0 tE = t + dt / 2.0 self.tB_ed_RzPl.setText('%0.7g' % (tB)) self.tE_ed_RzPl.setText('%0.7g' % (tE)) self.tplot_ed_RzPl.setText('%0.7g' % (np.mean([tB, tE]))) self.f_Rz_plot(3) except Exception as exc: print("!!! Incorrect input. ERROR: %s" % (exc)) pass def Load_ECEI_data(self): try: self.Shot = int(self.Shot_ed_load.text()) self.Diag = self.Diag_load.currentText() self.Diag_EQ = self.Diag_EQ_load.currentText() self.Monitor_load.setText("Status:\nLoading %s: #%d ... " % (self.Diag, self.Shot)) allow_to_load = True except Exception as exc: print("!!! Incorrect input. ERROR: %s" % (exc)) self.Monitor_load.setText("Status:\nPlease enter shot number.") allow_to_load = False if (self.Diag_EQ == 'EQH') & (allow_to_load): try: # load EQH self.Monitor_load.setText("") EQ = EQH.EQH() EQ.Load(self.Shot) self.EQ_rhopM = EQ.rhopM self.EQ_time = EQ.time self.EQ_R = EQ.R self.EQ_z = EQ.z self.EQ_Rmag = EQ.Rmag self.EQ_zmag = EQ.zmag self.Monitor_load.insertPlainText( "EQH data has been loaded succesfully.\n") except Exception as exc: traceback.print_exc() print("!!! Coudn't load EQH. ERROR: %s" % (exc)) self.Monitor_load.setText( "Status:\nError in loading ECI data.") self.Monitor_load.insertPlainText("!!! EQH data NOT loaded.") print("+++ EQH has been loaded +++") if (self.Diag == 'TDI') & (allow_to_load): try: TD = TDI.TDI() TD.Load(self.Shot) TD.Load_FakeRz() self.ECEId = TD.ECEId.copy() self.ECEId_time = TD.time.copy() self.ECEId_RR = TD.RR_fake.copy() self.ECEId_zz = TD.zz_fake.copy() self.ECEId_R = TD.R_fake.copy() self.ECEId_z = TD.z_fake.copy() self.Monitor_load.insertPlainText( "Status:\nTDI #%d\ntB = %g, tE = %g s\nLoaded succesfully." % (self.Shot, TD.time[0], TD.time[-1])) self.data_loaded = True print("+++ The data has been loaded succesfully. +++") except Exception as exc: print("!!! Coudn't load TDI. ERROR: %s" % (exc)) self.Monitor_load.insertPlainText( "Status:\nError in loading ECI data.") if (self.Diag == 'ECI') & (allow_to_load): try: EI = ECI.ECI() EI.Load(self.Shot) EI.Load_FakeRz() self.ECEId = EI.ECEId.copy() self.ECEId_time = EI.time.copy() self.ECEId_RR = EI.RR_fake.copy() self.ECEId_zz = EI.zz_fake.copy() self.ECEId_R = EI.R_fake.copy() self.ECEId_z = EI.z_fake.copy() self.Monitor_load.insertPlainText( "Status:\nECI #%d\ntB = %g, tE = %g s\nLoaded succesfully." % (self.Shot, EI.time[0], EI.time[-1])) self.data_loaded = True print("+++ The data has been loaded succesfully. +++") except Exception as exc: print("!!! Coudn't load ECI. ERROR: %s" % (exc)) self.Monitor_load.insertPlainText( "Status:\nError in loading ECI data.") def f_Rz_plot(self, which_plot): if (self.data_loaded): # check whether ECEI data is loaded try: import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 10}) # data preparation self.tB_ed_RzPl tB = float(self.tB_ed_RzPl.text()) tE = float(self.tE_ed_RzPl.text()) if (which_plot == 1): tplot_old = float(self.tplot_ed_RzPl.text()) dtplot = float(self.dtplot_ed_RzPl.text()) tplot = tplot_old - dtplot self.tplot_ed_RzPl.setText("%0.7g" % tplot) if (which_plot == 2): tplot_old = float(self.tplot_ed_RzPl.text()) dtplot = float(self.dtplot_ed_RzPl.text()) tplot = tplot_old + dtplot self.tplot_ed_RzPl.setText("%0.7g" % tplot) if (which_plot == 3): tplot = float(self.tplot_ed_RzPl.text()) self.counter_save = 0 self.tplot = tplot dtplot = float(self.dtplot_ed_RzPl.text()) contour_check = self.Contour_ed_RzPl.text() mf = my_funcs.my_funcs() mf.CutDataECEI(self.ECEId_time, self.ECEId, tBegin=tB, tEnd=tE) mf.relECEI(mf.ECEId_C) mf.cutDataEQH(self.EQ_time, self.EQ_rhopM, self.EQ_R, self.EQ_z, self.EQ_Rmag, self.EQ_zmag, tplot) time_plot, data_plot = mf.time_C, mf.ECEId_rel filter_status = "None" if (self.type_plot_RzPl.currentText() == 'Fourier lowpass'): f_cut = float(self.Fourier_cut_RzPl.text()) * 1.0e3 noise_ampl = 1.0 mf.Fourier_analysis_ECEI_lowpass(time_plot, data_plot, noise_ampl, f_cut) data_plot = mf.ECEId_fft_f_ifft filter_status = "Fourier lowpass, freq_cut = %g kHz" % ( f_cut * 1.0e-3) if (self.type_plot_RzPl.currentText() == 'Fourier highpass'): f_cut = float(self.Fourier2_cut_RzPl.text()) * 1.0e3 noise_ampl = 1.0 mf.Fourier_analysis_ECEI_highpass(time_plot, data_plot, noise_ampl, f_cut) data_plot = mf.ECEId_fft_f_ifft filter_status = "Fourier highpass, freq_cut = %g kHz" % ( f_cut * 1.0e-3) if (self.type_plot_RzPl.currentText() == 'Fourier both'): f_cut_lp = float(self.Fourier_cut_RzPl.text()) * 1.0e3 noise_ampl_lp = 1.0 f_cut_hp = float(self.Fourier2_cut_RzPl.text()) * 1.0e3 noise_ampl_hp = 1.0 mf.Fourier_analysis_ECEI_lowpass(time_plot, data_plot, noise_ampl_lp, f_cut_lp) data_plot = mf.ECEId_fft_f_ifft.copy() mf.Fourier_analysis_ECEI_highpass(time_plot, data_plot, noise_ampl_hp, f_cut_hp) data_plot = mf.ECEId_fft_f_ifft.copy() filter_status = "Fourier high and low pass, freq_cut_hp = %g kHz, freq_cut_lp = %g kHz" % ( f_cut_hp * 1.0e-3, f_cut_lp * 1.0e-3) if (self.type_plot_RzPl.currentText() == 'Fourier multiple'): string = self.FourMult_ed_RzPl.text() freq_num = len(string.split(";")) f_hp = np.zeros(freq_num) f_lp = np.zeros(freq_num) for i in range(freq_num): f_hp[i] = string.split(";")[i].split(",")[0] f_hp[i] *= 1.0e3 f_lp[i] = string.split(";")[i].split(",")[1] f_lp[i] *= 1.0e3 mf.Fourier_analysis_ECEI_multiple(time_plot, data_plot, f_hp, f_lp) data_plot = mf.ECEId_fft_f_ifft filter_status = "Fourier multiple, freqs: %s kHz" % ( string) if (self.type_plot_RzPl.currentText() == 'SavGol'): win_len = int(self.SavGol_ed0_RzPl.text()) pol_ord = int(self.SavGol_ed1_RzPl.text()) mf.SavGol_filter_ECEI(data_plot, win_len, pol_ord) data_plot = mf.ECEId_savgol filter_status = "Savgol, win_len = %g, pol_ord = %g" % ( win_len, pol_ord) if (self.type_plot_RzPl.currentText() == 'Binning'): binning_freq = float(self.Binning_ed_RzPl.text()) time_plot, data_plot = mf.dataBinningECEI( time_plot, data_plot, binning_freq) filter_status = "Binning, freq = %g kHz" % (binning_freq) RR_plot, zz_plot = self.ECEId_RR, self.ECEId_zz removeLOS_ch = self.chzz_ed_RzPl.text() if removeLOS_ch: removeLOS_ch = np.array( self.chzz_ed_RzPl.text().split(',')) removeLOS_ch = removeLOS_ch.astype(int) - 1 else: removeLOS_ch = [] removeRR_ch = self.chRR_ed_RzPl.text() if removeRR_ch: removeRR_ch = np.array(self.chRR_ed_RzPl.text().split(',')) removeRR_ch = removeRR_ch.astype(int) - 1 else: removeRR_ch = [] NN_LOS, NN_R = data_plot.shape[1], data_plot.shape[2] ch_zz = np.arange(NN_LOS) ch_zz = np.delete(ch_zz, removeLOS_ch) ch_RR = np.arange(NN_R) ch_RR = np.delete(ch_RR, removeRR_ch) trace_1D = data_plot[:, 6, 3] # remove channels RR_plot = np.delete(RR_plot, removeLOS_ch, axis=0) RR_plot = np.delete(RR_plot, removeRR_ch, axis=1) zz_plot = np.delete(zz_plot, removeLOS_ch, axis=0) zz_plot = np.delete(zz_plot, removeRR_ch, axis=1) data_plot = np.delete(data_plot, removeLOS_ch, axis=1) data_plot = np.delete(data_plot, removeRR_ch, axis=2) check_vmin_vmax = 0 if (self.vmin_ed_RzPl.text().replace('-', '', 1).replace('.', '', 1).isdigit()): vmin = float(self.vmin_ed_RzPl.text()) check_vmin_vmax = 1 else: vmin = None if (self.vmax_ed_RzPl.text().replace('.', '', 1).isdigit()): vmax = float(self.vmax_ed_RzPl.text()) check_vmin_vmax = 1 else: vmax = None if (self.NNcont_ed_RzPl.text().replace('.', '', 1).isdigit()): NN_cont = int(self.NNcont_ed_RzPl.text()) else: NN_cont = 20 # find time index of plot idx_tplot = mf.find_nearest_idx(time_plot, tplot) time_plot_t, data_plot_t = time_plot[idx_tplot], data_plot[ idx_tplot, :, :] if (self.Interp_plot_RzPl.currentText() == 'with interpolation' ): interp_mask = np.full((NN_LOS, NN_R), False) for i_L in range(NN_LOS): for i_R in range(NN_R): interp_mask[i_L, i_R] = self.checks['%d,%d' % (i_L, i_R)].isChecked() interp_mask = np.delete(interp_mask, removeLOS_ch, axis=0) interp_mask = np.delete(interp_mask, removeRR_ch, axis=1) data_to_interp = data_plot_t.copy() data_to_interp[interp_mask] = np.NaN data_plot_t = mf.nan_interp_2d(data_to_interp) if (self.Interp_plot_RzPl.currentText() == 'set to zero'): interp_mask = np.full((NN_LOS, NN_R), False) for i_L in range(NN_LOS): for i_R in range(NN_R): interp_mask[i_L, i_R] = self.checks['%d,%d' % (i_L, i_R)].isChecked() interp_mask = np.delete(interp_mask, removeLOS_ch, axis=0) interp_mask = np.delete(interp_mask, removeRR_ch, axis=1) data_plot_t[interp_mask] = 0.0 if (self.ImgType_plot_RzPl.currentText() == 'Gaussian'): sigma = float(self.GausSigma_ed_RzSet.text()) data_plot_t = mf.gaussian_filter(data_plot_t, sigma) filter_status += "; Img filt: Gaussian, sigma=%g" % (sigma) if (self.ImgType_plot_RzPl.currentText() == 'Bilateral'): kernel = self.BilKern_type_RzSet.currentText() kern_size = int(self.BilKernSize_ed_RzSet.text()) s0 = int(self.BilS0_ed_RzSet.text()) s1 = int(self.BilS1_ed_RzSet.text()) data_plot_t = mf.bilateral_filter(data_plot_t, kernel, kern_size, s0, s1) filter_status += "; Img filt: Bilateral, %s, kern_size=%g, s0=%g, s1=%g" % ( kernel, kern_size, s0, s1) if (self.ImgType_plot_RzPl.currentText() == 'Median'): kernel = self.MedKern_type_RzSet.currentText() kern_size = int(self.MedKernSize_ed_RzSet.text()) data_plot_t = mf.median_filter(data_plot_t, kernel, kern_size) filter_status += "; Img filt: Median, %s, kern_size=%g" % ( kernel, kern_size) if (self.ImgType_plot_RzPl.currentText() == 'Conservative_smoothing'): size_filt = int(self.ConsSize_ed_RzSet.text()) data_plot_t = mf.conservative_smoothing_filter( data_plot_t, size_filt) filter_status += "; Img filt: Conservative smoothing, filt_size=%g" % ( size_filt) # plotting # initiate plot self.figure_RzPl.clf() # clear previous figure and axes self._static_ax = self.static_canvas_RzPl.figure.subplots( 1, 2, sharex=False, sharey=False) # add axes if (check_vmin_vmax == 1): levels_to_plot = np.linspace(vmin, vmax, NN_cont) if (check_vmin_vmax == 0): levels_to_plot = NN_cont contours = self._static_ax[0].contourf(RR_plot, zz_plot, data_plot_t, vmin=vmin, vmax=vmax, levels=levels_to_plot, cmap='jet') cbar = self.figure_RzPl.colorbar(contours, ax=self._static_ax[0], pad=0.07) cbar.ax.set_ylabel('deltaTrad/<Trad>', rotation=90) if contour_check == '1': self._static_ax[0].contour(RR_plot, zz_plot, data_plot_t, vmin=vmin, vmax=vmax, levels=levels_to_plot, cmap='binary') # cbar.ax.tick_params(labelsize=8, rotation=90) self._static_ax[0].plot(RR_plot, zz_plot, "ko", ms=2) if (self.Interp_plot_RzPl.currentText() == 'set to zero') | ( self.Interp_plot_RzPl.currentText() == 'with interpolation'): self._static_ax[0].plot(RR_plot[interp_mask], zz_plot[interp_mask], "wo", ms=6) self._static_ax[0].set_xlabel("R [m]") self._static_ax[0].set_ylabel("z [m]") for i, txt in enumerate(ch_zz): self._static_ax[0].annotate(txt + 1, (RR_plot[i, 0], zz_plot[i, 0]), fontsize=8) for i, txt in enumerate(ch_RR): self._static_ax[0].annotate(txt + 1, (RR_plot[0, i], zz_plot[0, i]), fontsize=8) # EQ contours contours_rhop = self._static_ax[0].contour( mf.RR_t, mf.zz_t, mf.rhopM_t, 50) self._static_ax[0].clabel(contours_rhop, inline=True, fontsize=10) self._static_ax[0].plot(mf.Rmag_t, mf.zmag_t, 'bo') self._static_ax[0].set_xlim([mf.Rmag_t, RR_plot[0, -1]]) self._static_ax[0].set_ylim([zz_plot[0, 0], zz_plot[-1, 0]]) rhop_to_plot = float(self.rhop_ed_RzPl.text()) equ_data = equ.equ_map(self.Shot, 'EQH', 'AUGD') data_rz = equ_data.rho2rz(rhop_to_plot, tplot, 'rho_pol') R_from_rhop = data_rz[0][0][0] z_from_rhop = data_rz[1][0][0] self.Rmag_t = mf.Rmag_t self.zmag_t = mf.zmag_t r_rhop = np.sqrt((self.Rmag_t - R_from_rhop[0])**2 + (self.zmag_t - z_from_rhop[0])**2) self._static_ax[0].plot(R_from_rhop, z_from_rhop, 'g-', linewidth=4.0) self.my_line, = self._static_ax[0].plot( [self.Rmag_t, R_from_rhop[0]], [self.zmag_t, z_from_rhop[0]], marker='o', color='b') self._static_ax[0].set_title( "t = %0.7g s, rhop(green) = %0.2g, r_rhop = %0.4g m" % (time_plot_t, rhop_to_plot, r_rhop)) # 1D plot self._static_ax[1].plot(time_plot, trace_1D) self._static_ax[1].set_xlabel("t [s]") self._static_ax[1].set_ylabel("deltaTrad/<Trad>") self._static_ax[1].set_title( "LOS = 7, R_ch = 4, dt resolut = %g s" % (time_plot[1] - time_plot[0])) self._static_ax[1].axvline(x=time_plot_t, color="k") self.figure_RzPl.suptitle("ECEI, Shot #%d, Filter: %s" % (self.Shot, filter_status), fontsize=10) if (self.Save_plot_RzPl.currentText() == 'save as pdf') | ( (self.Save_plot_RzPl.currentText() == 'save as pdf') & (self.counter_save == 0)): path_to_save = self.path_ed_RzSet.text() self.figure_RzPl.savefig(path_to_save + 'p_%03d.pdf' % (self.counter_save), bbox_inches='tight') self.counter_save += 1 if (self.Save_plot_RzPl.currentText() == 'save as png') | ( (self.Save_plot_RzPl.currentText() == 'save as pdf') & (self.counter_save == 0)): path_to_save = self.path_ed_RzSet.text() self.figure_RzPl.savefig(path_to_save + 'p_%03d.png' % (self.counter_save), bbox_inches='tight') self.counter_save += 1 click_coord = self.static_canvas_RzPl.mpl_connect( 'button_press_event', self.mouse_click_Rz) self.static_canvas_RzPl.draw() # self.sync_tabs(9) print("+++ The data has been plotted succesfully. +++") except Exception as exc: traceback.print_exc() print("!!! Cannot plot. ERROR: %s" % (exc)) else: print("Please load the ECEI data (first tab)") def mouse_click_Rz(self, event): if (event.dblclick == True) & (event.button == 1): ix, iy = event.xdata, event.ydata self.tplot_ed_RzPl.setText("%0.7g" % (ix)) self.f_Rz_plot(3) if (event.dblclick == True) & (event.button == 3): ix, iy = event.xdata, event.ydata self.r_rhop_blue = np.sqrt((self.Rmag_t - ix)**2 + (self.zmag_t - iy)**2) self.R_blue = ix self.z_blue = iy self.my_line.remove() self.my_line, = self._static_ax[0].plot([self.Rmag_t, ix], [self.zmag_t, iy], marker='o', color='b') self._static_ax[0].set_xlabel( "R [m]; blue: R = %0.4g m, z = %0.4g m, r_rhop = %0.4g m" % (self.R_blue, self.z_blue, self.r_rhop_blue)) def sync_tabs(self, number): try: if (number == 9): tB_ed = self.tB_ed_RzPl.text() tE_ed = self.tE_ed_RzPl.text() tCnt_ed = self.tCnt_ed_RzPl.text() dt_ed = self.dt_ed_RzPl.text() Fourier_cut = self.Fourier_cut_RzPl.text() Fourier2_cut = self.Fourier2_cut_RzPl.text() Savgol_ed0 = self.SavGol_ed0_RzPl.text() Savgol_ed1 = self.SavGol_ed1_RzPl.text() Binning_ed = self.Binning_ed_RzPl.text() # 9 self.tB_ed_RzPl.setText(tB_ed) self.tE_ed_RzPl.setText(tE_ed) self.tCnt_ed_RzPl.setText(tCnt_ed) self.dt_ed_RzPl.setText(dt_ed) self.Fourier_cut_RzPl.setText(Fourier_cut) self.Fourier2_cut_RzPl.setText(Fourier2_cut) self.SavGol_ed0_RzPl.setText(Savgol_ed0) self.SavGol_ed1_RzPl.setText(Savgol_ed1) self.Binning_ed_RzPl.setText(Binning_ed) except Exception as exc: print("!!! Couldn't synchronize tabs. ERROR: %s" % (exc)) def send_points(self): try: self.Monitor_RzPl.moveCursor(QTextCursor.End) self.Monitor_RzPl.insertPlainText( "%d\t%0.7g\t%0.4g\t%0.4g\t%0.4g\n" % (self.counter, self.tplot, self.R_blue, self.z_blue, self.r_rhop_blue)) self.counter += 1 except Exception as exc: traceback.print_exc() print("!!! Cannot plot. ERROR: %s" % (exc)) def clear_table(self): try: self.Monitor_RzPl.setText("NN\tt\tR\tz\tr\n") self.counter = 1 except Exception as exc: traceback.print_exc() print("!!! Cannot plot. ERROR: %s" % (exc))
def plot(self, logger=None, **kwargs): r"""Make the plots. :param logger: A logger object for logging debug info. [default: None] :params \**kwargs: Any additional kwargs go into the matplotlib plot() function. [ignored in this function] :returns: fig, ax """ from matplotlib.figure import Figure logger = galsim.config.LoggerWrapper(logger) fig = Figure(figsize=(12, 9)) # In matplotlib 2.0, this will be # axs = fig.subplots(ncols=3, nrows=3) axs = [[ fig.add_subplot(3, 3, 1), fig.add_subplot(3, 3, 2), fig.add_subplot(3, 3, 3) ], [ fig.add_subplot(3, 3, 4), fig.add_subplot(3, 3, 5), fig.add_subplot(3, 3, 6) ], [ fig.add_subplot(3, 3, 7), fig.add_subplot(3, 3, 8), fig.add_subplot(3, 3, 9) ]] axs = np.array(axs, dtype=object) # left column gets the Y coordinate label axs[0, 0].set_ylabel('v') axs[1, 0].set_ylabel('v') axs[2, 0].set_ylabel('v') # bottom row gets the X coordinate label axs[2, 0].set_xlabel('u') axs[2, 1].set_xlabel('u') axs[2, 2].set_xlabel('u') # make the colormaps logger.info("Creating TwoDHist colormaps") # T and T_model share colorbar vmin__T = np.min([self.twodhists['T'], self.twodhists['T_model']]) vmax__T = np.max([self.twodhists['T'], self.twodhists['T_model']]) vcent__T = np.median([self.twodhists['T'], self.twodhists['T_model']]) cmap__T = self._shift_cmap(vmin__T, vmax__T, center=vcent__T) # g1, g2, g1_model, g2_model share colorbar vmin__g = np.min([ self.twodhists['g1'], self.twodhists['g1_model'], self.twodhists['g2'], self.twodhists['g2_model'] ]) vmax__g = np.max([ self.twodhists['g1'], self.twodhists['g1_model'], self.twodhists['g2'], self.twodhists['g2_model'] ]) cmap__g = self._shift_cmap(vmin__g, vmax__g) # dT gets own colorbar vmin__dT = np.min(self.twodhists['dT']) vmax__dT = np.max(self.twodhists['dT']) cmap__dT = self._shift_cmap(vmin__dT, vmax__dT) # dg1 and dg2 share a colorbar vmin__dg = np.min([self.twodhists['dg1'], self.twodhists['dg2']]) vmax__dg = np.max([self.twodhists['dg1'], self.twodhists['dg2']]) cmap__dg = self._shift_cmap(vmin__dg, vmax__dg) # make the plots logger.info("Creating TwoDHist plots") ax = axs[0, 0] ax.set_title('T') IM = ax.pcolor(self.bins_u, self.bins_v, self.twodhists['T'], cmap=cmap__T, vmin=vmin__T, vmax=vmax__T) ax.set_xlim(min(self.bins_u), max(self.bins_u)) ax.set_ylim(min(self.bins_v), max(self.bins_v)) fig.colorbar(IM, ax=ax) ax = axs[1, 0] ax.set_title('T Model') IM = ax.pcolor(self.bins_u, self.bins_v, self.twodhists['T_model'], cmap=cmap__T, vmin=vmin__T, vmax=vmax__T) ax.set_xlim(min(self.bins_u), max(self.bins_u)) ax.set_ylim(min(self.bins_v), max(self.bins_v)) fig.colorbar(IM, ax=ax) ax = axs[2, 0] ax.set_title('dT') IM = ax.pcolor(self.bins_u, self.bins_v, self.twodhists['dT'], cmap=cmap__dT, vmin=vmin__dT, vmax=vmax__dT) ax.set_xlim(min(self.bins_u), max(self.bins_u)) ax.set_ylim(min(self.bins_v), max(self.bins_v)) fig.colorbar(IM, ax=ax) ax = axs[0, 1] ax.set_title('g1') IM = ax.pcolor(self.bins_u, self.bins_v, self.twodhists['g1'], cmap=cmap__g, vmin=vmin__g, vmax=vmax__g) ax.set_xlim(min(self.bins_u), max(self.bins_u)) ax.set_ylim(min(self.bins_v), max(self.bins_v)) fig.colorbar(IM, ax=ax) ax = axs[1, 1] ax.set_title('g1 Model') IM = ax.pcolor(self.bins_u, self.bins_v, self.twodhists['g1_model'], cmap=cmap__g, vmin=vmin__g, vmax=vmax__g) ax.set_xlim(min(self.bins_u), max(self.bins_u)) ax.set_ylim(min(self.bins_v), max(self.bins_v)) fig.colorbar(IM, ax=ax) ax = axs[2, 1] ax.set_title('dg1') IM = ax.pcolor(self.bins_u, self.bins_v, self.twodhists['dg1'], cmap=cmap__dg, vmin=vmin__dg, vmax=vmax__dg) ax.set_xlim(min(self.bins_u), max(self.bins_u)) ax.set_ylim(min(self.bins_v), max(self.bins_v)) fig.colorbar(IM, ax=ax) ax = axs[0, 2] ax.set_title('g2') IM = ax.pcolor(self.bins_u, self.bins_v, self.twodhists['g2'], cmap=cmap__g, vmin=vmin__g, vmax=vmax__g) ax.set_xlim(min(self.bins_u), max(self.bins_u)) ax.set_ylim(min(self.bins_v), max(self.bins_v)) fig.colorbar(IM, ax=ax) ax = axs[1, 2] ax.set_title('g2 Model') IM = ax.pcolor(self.bins_u, self.bins_v, self.twodhists['g2_model'], cmap=cmap__g, vmin=vmin__g, vmax=vmax__g) ax.set_xlim(min(self.bins_u), max(self.bins_u)) ax.set_ylim(min(self.bins_v), max(self.bins_v)) fig.colorbar(IM, ax=ax) ax = axs[2, 2] ax.set_title('dg2') IM = ax.pcolor(self.bins_u, self.bins_v, self.twodhists['dg2'], cmap=cmap__dg, vmin=vmin__dg, vmax=vmax__dg) ax.set_xlim(min(self.bins_u), max(self.bins_u)) ax.set_ylim(min(self.bins_v), max(self.bins_v)) fig.colorbar(IM, ax=ax) return fig, axs
def heatmap(x, y, z, **kwargs): """Plot a heatmap using pcolormesh and do typical configuration. plt, fig, canvas, ax, im, cb = heatmap(x, y, z, **kwargs) x and y are bin centers, edges, or ranges; x is associated with the columns of z and y is associated with the rows of z. If len(x) == z.shape[1], x is assumed to correspond to the center of the rectangle and the labels are placed at the center of the bin. The bin widths are x[i+1]-x[i]. If the spacing of x values is not uniform, the bin width of x[-1] is assumed to be equal to that of x[-2]. The same logic is applied to y if len(y) == z.shape[0]. If len(x) == z.shape[1] + 1, x is assumed to correspond to edges of the rectangle and the labels are placed at x[i] and the bin widths are x[i+1]-x[i]. The same logic is applied to y if len(y) == z.shape[0] + 1. If x.shape = (z.shape[1], 2), each row gives the range of the rectangle associated with the columns of z and a "No data" color is used for ranges that do not have data. The same logic is applied to y if y.shape = (z.shape[0], 2). kwargs: Axes ---- * xlabel * ylabel * title * logx * logy Colorbar ------ * zlabel * ztitle * logz * clim - Ignore if ... * cmap * cmap.name (ignored if cmap given) * cmap.numcolors (ignored if cmap given) * cmap.clim Logarithm --------- * logx - All x values must be either >= 0 or <= 0. * logy - All y values must be either >= 0 or <= 0. * logz - All z values must be either >= 0 or <= 0. The zero values rectangles are colored using logz0color. * logz0.legend * log.auto Tile edges, gaps, and NaN ------------------------- * edgecolor - Edge color of tile border * logz0.color * logz0.alpha * logz0.hatch * logz0.legend - Show legend entry for logz0 * gap.color * gap.alpha * gap.hatch * gap.hatch.color * gap.legend - Show legend entry for gaps (True by default and if gaps) * nan.color * nan.alpha * nan.hatch * nan.hatch.color * nan.legend - Show legend entry for nans (True by default and if NaNs) """ ########################################################################### def warning(message): print("\x1b[31mheatmap() warning: \x1b[0m" + message) def calcEdges(y, coord): """Caclulate bin ranges given bin centers.""" # TODO: Set bin width to 1 if y is not datetime. # TODO: If datetime, guess cadence by inspecting and warn? if len(y) == 1: # Put tick at center of bin; make bin have width = 1. y = np.array([y[0] - 0.5, y[0] + 0.5]) else: # y are bin centers dy = np.diff(y) dyu = np.unique(dy) if len(dyu) > 1: if coord == 'y': warning('Only bin centers given for y and bin separation distance is not constant. ' + \ 'Bin width assumed based on separation distance and data pickers will not work properly.') else: warning('Only bin centers given for x and bin separation distance is not constant. ' + \ 'Bin width assumed based on separation distance and data pickers will not work properly.') y = np.append(y, y[-1] + dy[-1]) else: y = np.append(y, y[-1] + dy[0]) y = y - dyu[0] / 2 return y def calcGaps(y, z, coord): if coord == 'x': z = np.transpose(z) havegaps = False Igaps = [] ynew = [] for k in range(0, len(y) - 1): ynew.append(y[k][0]) if y[k][1] != y[k + 1][0]: havegaps = True break if len(y) == 1: ynew.append(y[0][0]) ynew.append(y[0][1]) y = ynew elif not havegaps: # Set top-most two bin edges. ynew.append(y[k + 1][0]) ynew.append(y[k + 1][1]) y = ynew else: # Insert NaN rows where gaps znew = z[0, :] nanrow = np.nan * z[0, :] ynew = [] ynew.append(y[0][0]) if y[0][1] != y[1][0]: # Gap between bins ynew.append(y[0][1]) znew = np.vstack((znew, nanrow)) Igaps.append(1) for k in range(1, len(y) - 1): ynew.append(y[k][0]) znew = np.vstack((znew, z[k, :])) if y[k][1] != y[k + 1][0]: # Gap between bins ynew.append(y[k][1]) #print('inserting nan row or column') znew = np.vstack((znew, nanrow)) Igaps.append(znew.shape[0] - 1) # Set top-most two bin edges ynew.append(y[k + 1][0]) ynew.append(y[k + 1][1]) znew = np.vstack((znew, z[k + 1, :])) z = znew Igaps = np.asarray(Igaps, dtype=np.int32) y = np.array(ynew) if coord == 'x': z = np.transpose(z) return y, z, Igaps def adjustCenters(y, yc): # Adjusts centers and their labels if nonuniform diff(y) dy = np.diff(y) dyu = np.unique(dy) if len(dyu) > 1: # If centers not uniform, they were used as lower edges. # Need to adjust center location for ticks and labels. ycl = np.copy(y) # y center labels yc = np.copy(y[0:-1]) for i in range(0, y.shape[0] - 1): yc[i] = y[i] + (y[i + 1] - y[i]) / 2 else: # No adjustment needed. Indicate this with empty ycl. ycl = np.array([]) return yc, ycl def iscategorical(x): return isinstance(x[0], np.character) def categoryinfo(x): if len(x.shape) > 1: raise ValueError( 'If x contains characters, it must have one column or one row.' ) if not len(x) == Nx: raise ValueError( 'If x contains characters, number of elements must match number of rows in z.' ) xcategories = x x = np.linspace(0, x.shape[0] - 1, x.shape[0], dtype='int32') return xcategories, x def allint(x): Ig = ~np.isnan(x) if np.all(np.equal(x[Ig], np.int32(x[Ig]))): return True else: return False ########################################################################### opts = { 'logging': False, 'title': '', 'xlabel': '', 'ylabel': '', 'logx': False, 'logy': False, 'backend': 'default', 'returnimage': False, 'transparent': False, 'ztitle': '', 'zlabel': '', 'logz': False, 'edgecolor': None, 'cmap': None, 'cmap.numcolors': 32, 'cmap.name': 'viridis', 'cmap.clim': None, 'nan.color': [0.95, 0.95, 0.95], 'nan.alpha': 1, 'nan.hatch': '', 'nan.hatch.color': [0.1, 0.1, 0.1], 'nan.legend': True, 'gap.color': [0, 0, 0], 'gap.alpha': 1, 'gap.hatch': '', 'gap.hatch.color': [0.95, 0.95, 0.95], 'gap.legend': True, 'logz0.color': [1, 1, 1], 'logz0.alpha': 1, 'logz0.hatch': '', 'logz0.hatch.color': [0.95, 0.95, 0.95], 'logz0.legend': True } for key, value in kwargs.items(): if key in opts: opts[key] = value else: warnings.warn( 'Warning: Ignoring invalid keyword option "%s".' % key, SyntaxWarning) if opts['returnimage']: # When returnimage=True, the Matplotlib OO API is used b/c it is thread safe. # Otherwise, the pyplot API is used. Ideally would always use the OO API, # but this has problems with notebooks and showing figure when executing # a script from the command line. # TODO: Document issues. # # API differences description: # https://www.saltycrane.com/blog/2007/01/how-to-use-pylab-api-vs-matplotlib-api_3134/ from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas else: from matplotlib import pyplot as plt if opts['logging']: print("heatmap(): Using Matplotlib back-end " + matplotlib.get_backend()) from matplotlib.ticker import MaxNLocator if not opts['cmap.name'] in matplotlib.pyplot.colormaps(): warning('colormap name "' + opts['cmap.name'] + '" is not in list of known names: ' + str(matplotlib.pyplot.colormaps()) + ". Using 'viridis'.") opts['cmap.name'] = 'viridis' if not opts['cmap']: opts['cmap'] = matplotlib.pyplot.get_cmap(opts['cmap.name'], opts['cmap.numcolors']) if opts['returnimage']: fig = Figure() FigureCanvas( fig ) # Not used directly, but calling attaches canvas to fig which is used later. ax = fig.add_subplot(111) else: fig, ax = plt.subplots() if opts['logging']: print("timeseries(): Using Matplotlib back-end " + matplotlib.get_backend()) if type(x) == list: x = np.array(x) if type(y) == list: y = np.array(y) if type(z) == list: z = np.array(z) # Number of x values (columns) Nx = z.shape[1] if len(z.shape) == 2 else 1 # Number of y values (rows) Ny = z.shape[0] if len(z.shape) == 2 else 1 # If y is a matrix, assume it has two columns. # First column is lower edge, second is upper edge. # If given a two-row matrix, transpose. if len(y.shape) > 1: # Bin edges given if y.shape[1] != 2 and y.shape[0] == 2: warning( 'If y is a matrix, it should have two columns. Two rows found. Transposing.' ) y = np.transpose(y) if y.shape[0] != 2 and y.shape[1] != 2: raise ValueError( 'If y is a matrix, it must have two columns or two rows.') if len(x.shape) > 1: # Bin edges given if x.shape[1] != 2 and x.shape[0] == 2: warning( 'If x is a matrix, it should have two columns. Two rows found. Transposing.' ) x = np.transpose(x) if x.shape[0] != 2 and x.shape[1] != 2: raise ValueError( 'If x is a matrix, it must have two columns or two rows.') if x.ndim == 1 and not (len(x) == Nx or len(x) == Nx + 1): raise ValueError( 'Required: len(x) == z.shape[1] or len(x) == z.shape[1] + 1.') if y.ndim == 1 and not (len(y) == Ny or len(y) == Ny + 1): raise ValueError( 'Required: len(y) == z.shape[0] or len(y) == z.shape[0] + 1.') categoricalx = iscategorical(x) if len(x.shape) == 1 and len(x) == Nx: # Centers given. Calculate edges. if categoricalx: xlabels = x x = np.linspace(0, y.shape[0] - 1, y.shape[0], dtype='int32') xedges = False xc = x x = calcEdges(x, 'x') xc, xcl = adjustCenters(x, xc) else: xc = np.array([]) xedges = True categoricaly = iscategorical(y) if len(y.shape) == 1 and len(y) == Ny: # Centers given. Calculate edges. if categoricaly: ylabels = y y = np.linspace(0, y.shape[0] - 1, y.shape[0], dtype='int32') yedges = False yc = y y = calcEdges(y, 'y') yc, ycl = adjustCenters(y, yc) else: yc = np.array([]) yedges = True inan = np.where(np.isnan(z)) havenans = False allnan = False if np.any(inan) > 0: havenans = True if np.all(np.isnan(z)): allnan = True xgaps = np.array([], dtype=np.int32) ygaps = np.array([], dtype=np.int32) if len(x.shape) == 2: # x is an matrix x, z, xgaps = calcGaps(x, z, 'x') if len(y.shape) == 2: # y is an matrix y, z, ygaps = calcGaps(y, z, 'y') legendh = [] havegaps = False if len(xgaps) > 0 or len(ygaps) > 0: havegaps = True cmapg = colors.LinearSegmentedColormap.from_list( 'gap', [opts['gap.color'], opts['gap.color']], 2) zg = np.nan * np.copy(z) if len(xgaps) > 0: zg[:, xgaps] = 1 if len(ygaps) > 0: zg[ygaps, :] = 1 if opts['gap.hatch'] == '': ax.pcolormesh(x, y, zg, cmap=cmapg) else: # pcolormesh does not support hatch # TODO: Must set hatch.color through rc params and context manager. # opts['nan.hatch.color'] # https://stackoverflow.com/a/42672782/1491619 with rc_context(rc={'hatch.color': opts['gap.hatch.color']}): ax.pcolor(x, y, zg, cmap=cmapg, hatch=opts['gap.hatch']) if opts['gap.legend']: with rc_context(rc={'hatch.color': opts['gap.hatch.color']}): legendh.append( Patch(facecolor=opts['gap.color'], hatch=opts['gap.hatch'] + opts['gap.hatch'], edgecolor=opts['edgecolor'], label='No data')) if havenans: edgecolor = opts['edgecolor'] if allnan and edgecolor is None: edgecolor = 'k' cmapn = colors.LinearSegmentedColormap.from_list( 'nan', [opts['nan.color'], opts['nan.color']], 2) zn = np.nan * np.copy(z) if havegaps: inan = np.where(np.logical_and(np.isnan(z), zg != 1)) zn[inan] = 1 if opts['nan.hatch'] == '': ax.pcolormesh(x, y, zn, edgecolor=edgecolor, cmap=cmapn) else: # Must set hatch.color through rc params and context manager. with rc_context(rc={'hatch.color': opts['nan.hatch.color']}): ax.pcolor(x, y, zn, cmap=cmapn, edgecolor=edgecolor, hatch=opts['nan.hatch']) if opts['nan.legend']: with rc_context(rc={'hatch.color': opts['nan.hatch.color']}): legendh.append( Patch(facecolor=opts['nan.color'], hatch=opts['nan.hatch'] + opts['nan.hatch'], edgecolor=edgecolor, label='NaN')) # TODO: Handle case where > 10. # Label every Nth, etc. as needed if xedges and x.size <= 10: ax.set_xticks(x) if xc.size > 0 and xc.size <= 10: ax.set_xticks(xc) if len(xcl) > 0: # Relabel x-ticks b/c nonuniform center spacing. ax.set_xticklabels(xcl) #for spine in ax.spines.values(): spine.set_edgecolor(None) if yedges and y.size <= 10: ax.set_yticks(y) if yc.size > 0 and yc.size <= 10: ax.set_yticks(yc) if len(ycl) > 0: # Relabel y-ticks b/c nonuniform center spacing. ax.set_yticklabels(ycl) # Note: categoricalx and categoricaly are very similar. if categoricalx: xcategories, x = categoryinfo(xlabels) # TODO: This will create too many ticks if # of categories is large ax.set_xticklabels(xcategories) ax.set_xticks( list(ax.get_xticks()) + [-0.5] + list(ax.get_xticks() + 0.5)) k = 0 l = ax.get_xticklines() for l in ax.get_xticklines(): if k < 2 * len(xcategories): l.set_markeredgewidth(0) k = k + 1 if categoricaly: ycategories, y = categoryinfo(ylabels) ax.set_yticklabels(ycategories) ax.set_yticks( list(ax.get_yticks()) + [-0.5] + list(ax.get_yticks() + 0.5)) k = 0 l = ax.get_yticklines() for l in ax.get_yticklines(): if k < 2 * len(ycategories): l.set_markeredgewidth(0) k = k + 1 # TODO: categoricalz not implemented. categoricalz = iscategorical(z) if categoricalz: zcategories, z = categoryinfo(z) #ax.set_ylim(y[0], y[-1]) if opts['xlabel']: ax.set_xlabel(opts['xlabel']) if opts['logx']: # TODO: Flip sign if needed. ax.set_xscale('log') if opts['ylabel']: ax.set_ylabel(opts['ylabel']) if opts['logy']: # TODO: Flip sign if needed. ax.set_yscale('log') if opts['title']: ax.set_title(opts['title'], fontsize=10) if False and allint(x): xa = ax.get_yaxis() xa.set_major_locator(MaxNLocator(integer=True, steps=[1, 2, 4, 5, 10])) if False and allint(y): ya = ax.get_yaxis() ya.set_major_locator(MaxNLocator(integer=True, steps=[1, 2, 4, 5, 10])) # NaN, logz0, and gap legend if len(legendh) > 0: fig.legend(frameon=False, borderaxespad=0.25, borderpad=0.15, handles=legendh, loc='upper right', fontsize='x-small', ncol=len(legendh)) if allnan: cb = None else: # Colorbar zc = np.array([]) allintz = allint(z) if not 'cmap' in kwargs and allintz: Ig = ~np.isnan(z) zc = np.unique(z[Ig]) if len(zc) == 1: nc = len(zc) else: nc = np.int(zc[-1] - zc[0] + 1) nc = np.min([1024, nc]) if 'cmap.numcolors' in kwargs: if opts['cmap.numcolors'] != nc: warning( 'Overriding requested number of colors. Using number of colors = ' + str(nc)) cmap_name = opts['cmap.name'] if len(Ig) == 2 and not 'cmap.name' in kwargs: # Binary. Plot black and white. cmap_name = 'gray' opts['cmap'] = matplotlib.pyplot.get_cmap(cmap_name, nc) zmin = np.nanmin(z) zmax = np.nanmax(z) if zmin < 0 and zmax > 0: warning( 'Colorbar cannot have log scale when all values do not have the same sign.' ) havelogz0 = False if not opts['logz']: im = ax.pcolormesh(x, y, z, cmap=opts['cmap'], edgecolor=opts['edgecolor']) else: # Log scale emits warning if data have NaNs. warnings.filterwarnings( action='ignore', message='invalid value encountered in less_equal') flipsign = False if zmin < 0 and zmax <= 0 and opts['logz']: z = -z flipsign = True if zmin == 0: #warning('Log scale for z requested but min(z) = 0.') havelogz0 = True logz0idx = np.where(z == 0) z[z == 0] = np.nan havelogz0 = True zmin = np.nanmin(z) norm = LogNorm(vmin=zmin, vmax=zmax) im = ax.pcolormesh(x, y, z, cmap=opts['cmap'], norm=norm, edgecolor=opts['edgecolor']) if havelogz0: cmapz = colors.LinearSegmentedColormap.from_list( 'logz0', [opts['logz0.color'], opts['logz0.color']], 2) z = np.nan * z z[logz0idx] = 1 ax.pcolormesh(x, y, z, cmap=cmapz) if opts['logz0.legend']: legendh.append( Patch(facecolor=opts['logz0.color'], edgecolor='k', label='0.0')) cb = fig.colorbar(im, ax=ax, pad=0.01) if allintz: # Put tick label at center of color patch. if not opts['cmap.clim']: im.set_clim(zc[0] - 0.5, zc[-1] + 0.5) za = cb.ax.get_yaxis() za.set_major_locator( MaxNLocator(integer=True, min_n_ticks=1, steps=[1, 2, 4, 5, 10])) if opts['cmap.clim']: im.set_clim(opts['cmap.clim']) zt = cb.get_ticks() # How to label zmin and zmax without overlap of default labels? # Extend clim to next interval? But then one may think actual values in # extended range. For now, just warn. if zt[0] != zmin: #warnings.warn('Lower z limit not labeled.') zt = np.concatenate(([zmin], zt)) #cb.set_ticks(zt) if zt[-1] != zmax: #warnings.warn('Upper z limit not labeled.') zt = np.concatenate((zt, [zmax])) #cb.set_ticks(zt) cb.set_label(opts['zlabel'], fontsize=10) # On side cb.ax.set_title(opts['ztitle'], fontsize=10) # On top if opts['logz'] and flipsign: # Put negative sign in front of numbers on colorbar zlabels = cb.ax.get_yticklabels() for i in range(0, len(zlabels)): text = zlabels[i].get_text() if text != '': zlabels[i].set_text('-' + text) cb.ax.set_yticklabels(zlabels) if isinstance(x[0], datetime.datetime): datetick('x', axes=ax) if isinstance(y[0], datetime.datetime): datetick('y', axes=ax) # The following two conditions will be replaced by more general # code that calculates ax and cb position and dimensions based on # computed text box sizes. Note that plt.tight_subplot() and # bbox_inches='tight' have many issues that indicate they probably will # require significant work-arounds to be developed: # https://github.com/matplotlib/matplotlib/issues/12355/ # https://stackoverflow.com/questions/48128546/why-is-the-legend-not-present-in-the-generated-image-if-i-use-tight-for-bbox-i # https://stackoverflow.com/questions/10101700/moving-matplotlib-legend-outside-of-the-axis-makes-it-cutoff-by-the-figure-box ax_w = 0.8 if opts['zlabel'].count('\n') > 0: ax_w = 0.75 ax_h = 0.73 if opts['title'].count('\n') > 0: ax_h = 0.73 # Set positions of axes and colorbar ax_x = 0.1 # Offset from left ax_y = 0.14 # Offset from bottom cb_x = ax_x + ax_w + 0.005 # Offset from left cb_y = ax_y # Offset from bottom cb_w = 0.1 # Width cb_h = ax_h # Height ax.set_position([ax_x, ax_y, ax_w, ax_h]) if not allnan: cb.ax.set_position([cb_x, cb_y, cb_w, cb_h]) if opts['transparent']: fig.patch.set_alpha(0) ax.patch.set_alpha(0) if not opts['returnimage']: plt.show() return fig, cb
class Canvas_sourceImage: def __init__(self, ui, parent, parentOptions, gridOptions, W_matrix, N): # SI = Source Image self.ui = ui self.parentOptions = parentOptions self.gridOptions = gridOptions self.frame_sourceImage = parent # Create the mpl Figure and FigCanvas objects. # 5x4 inches, 100 dots-per-inch self.dpi = 100 self.fig = Figure((5.0, 4.0), dpi=self.dpi) self.canvas = FigureCanvas(self.fig) # #self.canvas.updateGeometry() #ui.gridLayout_sourceImage.addWidget(self.canvas) #self.frame_sourceImage.setWidget(self.canvas) #self.frame_sourceImage.setMaximumHeight(self.canvas.height()+10) #self.frame_sourceImage.setMaximumWidth(self.canvas.width()+10) #ui.gridLayout_sourceImage.addWidget(self.canvas, 1, 0, 1, 5) # Since we have only one plot, we can use add_axes # instead of add_subplot, but then the subplot # configuration tool in the navigation toolbar wouldn't # work. # self.axes = self.fig.add_subplot(111) # creating image source image_source = zeros((N, N)) for i in range(0, N): for j in range(0, N): image_source[i, j] = W_matrix[i, j, i, j].real # PLOT self.im = self.axes.pcolormesh(image_source) self.cbar = self.fig.colorbar(self.im) # font size self.fsize = 12 # x,y Labels self.axes.set_xlabel("x (m)", fontsize=self.fsize) self.axes.set_ylabel("y (m)", fontsize=self.fsize) # Bind the 'pick' event for clicking on one of the bars self.canvas.mpl_connect('pick_event', ui.on_pick) #self.canvas.mpl_connect("scroll_event", ui.scrolling) #ui.scrollArea_sourceImage.setWidget(self.canvas) # Create the navigation toolbar, tied to the canvas self.mpl_toolbar = NavigationToolbar(self.canvas, self.frame_sourceImage) ui.gridLayout_TabSourceImage.addWidget(self.mpl_toolbar, 2, 0, 1, 3) """ # Other GUI controls # self.textbox = QLineEdit() self.textbox.setMinimumWidth(200) self.textbox.editingFinished.connect(ui.draw_sourceImage) self.draw_button = QPushButton("&Draw") self.draw_button.clicked.connect(ui.draw_sourceImage) self.grid_cb = QCheckBox("Show &Grid") self.grid_cb.setChecked(False) self.grid_cb.stateChanged.connect(ui.draw_sourceImage) slider_label = QLabel('Bar width (%):') self.slider = QSlider(Qt.Horizontal) self.slider.setRange(1, 100) self.slider.setValue(20) self.slider.setTracking(True) self.slider.setTickPosition(QSlider.TicksBothSides) self.slider.valueChanged.connect(ui.draw_sourceImage) # # Layout with box sizers # hbox = QHBoxLayout() for w in [ self.textbox, self.draw_button, self.grid_cb, slider_label, self.slider]: hbox.addWidget(w) hbox.setAlignment(w, Qt.AlignVCenter) """ #self.canvas.setSizePolicy(QtWidgets.QSizePolicy.Minimum,QtWidgets.QSizePolicy.Minimum) self.containerGraph = QWidget(parent) #self.containerGraph.setSizePolicy(QtWidgets.QSizePolicy.Minimum,QtWidgets.QSizePolicy.Minimum) self.vbox = QVBoxLayout(self.containerGraph) self.vbox.addWidget(self.canvas) #self.canvas.setParent(self.containerGraph) # #vbox.addWidget(self.mpl_toolbar) #vbox.addLayout(hbox) #parent.setLayout(vbox) #vbox.setSizePolicy(QtWidgets.QSizePolicy.Minimum,QtWidgets.QSizePolicy.Minimum) #ui.scrollArea_sourceImage.setLayout(vbox) #ui.gridLayout_sourceImage.addWidget(self.containerGraph) #ui.setCentralWidget(self.frame_sourceImage) #======================================================================= # Figure Options #======================================================================= # Options self.label_opt = QtWidgets.QLabel(self.parentOptions) self.label_opt.setObjectName("label_pot") self.label_opt.setText("Plot Options:") self.gridOptions.addWidget(self.label_opt, 3, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # label title self.label_title = QtWidgets.QLabel(self.parentOptions) self.label_title.setObjectName("label_title") self.label_title.setText("Title") self.gridOptions.addWidget(self.label_title, 4, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit title label self.lineEdit_title = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_title.setObjectName("lineEdit_title") self.lineEdit_title.textChanged.connect(self.change_title) self.gridOptions.addWidget(self.lineEdit_title, 4, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.change_title() self.lineEdit_title.setText("Source Image") # label x self.label_x = QtWidgets.QLabel(self.parentOptions) self.label_x.setObjectName("label_x") self.label_x.setText("Label x-axis") self.gridOptions.addWidget(self.label_x, 6, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit x label self.lineEdit_xLabel = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_xLabel.setObjectName("lineEdit_xlabel") self.lineEdit_xLabel.textChanged.connect(self.change_labelx) self.gridOptions.addWidget(self.lineEdit_xLabel, 6, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.change_labelx() self.lineEdit_xLabel.setText("x") # label y self.label_y = QtWidgets.QLabel(self.parentOptions) self.label_y.setObjectName("label_y") self.label_y.setText("Label y-axis") self.gridOptions.addWidget(self.label_y, 8, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit y label self.lineEdit_yLabel = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_yLabel.setObjectName("lineEdit_ylabel") self.lineEdit_yLabel.textChanged.connect(self.change_labely) self.gridOptions.addWidget(self.lineEdit_yLabel, 8, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.change_labely() self.lineEdit_yLabel.setText("y") # label xlim self.label_xlim = QtWidgets.QLabel(self.parentOptions) self.label_xlim.setObjectName("label_xlim") self.label_xlim.setText("xlim") self.gridOptions.addWidget(self.label_xlim, 10, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit xlim self.lineEdit_xlim = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_xlim.setObjectName("lineEdit_ylabel") self.lineEdit_xlim.textChanged.connect(self.change_xlim) self.gridOptions.addWidget(self.lineEdit_xlim, 10, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_xlim.setText("(_,_)") self.change_xlim() # label ylim self.label_ylim = QtWidgets.QLabel(self.parentOptions) self.label_ylim.setObjectName("label_ylim") self.label_ylim.setText("ylim") self.gridOptions.addWidget(self.label_ylim, 12, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit ylim self.lineEdit_ylim = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_ylim.setObjectName("lineEdit_ylabel") self.lineEdit_ylim.textChanged.connect(self.change_ylim) self.gridOptions.addWidget(self.lineEdit_ylim, 12, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_ylim.setText("(_,_)") self.change_ylim() # label cmap self.label_cmap = QtWidgets.QLabel(self.parentOptions) self.label_cmap.setObjectName("label_cmap") self.label_cmap.setText("Color Map") self.gridOptions.addWidget(self.label_cmap, 18, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit cmap self.lineEdit_cmap = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_cmap.setObjectName("lineEdit_cmap") self.lineEdit_cmap.textChanged.connect(self.change_cmap) self.gridOptions.addWidget(self.lineEdit_cmap, 18, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_cmap.setText("hot") self.change_cmap() # label Font Size self.label_fsize = QtWidgets.QLabel(self.parentOptions) self.label_fsize.setObjectName("label_fsize") self.label_fsize.setText("Font Size") self.gridOptions.addWidget(self.label_fsize, 20, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit font size self.lineEdit_fsize = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_fsize.setObjectName("label_fsize") self.lineEdit_fsize.textChanged.connect(self.change_fsize) self.gridOptions.addWidget(self.lineEdit_fsize, 20, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_fsize.setText(str(self.fsize)) self.change_fsize() #self.ui.gridLayout_sourceImage.setRowMinimumHeight(1, int(2*self.canvas.height())) # update size #ui.scrollAreaWidgetContents_sourceImageOpt.setMaximumHeight(int(self.canvas.height()/2)) #ui.scrollArea_sourceImage.setMinimumHeight(self.canvas.height()+500) #ui.gridLayout_TabSourceImage.setRowMinimumHeight(1, self.canvas.height()+10) self.canvas.updateGeometry() def update_gridSize(self): self.canvas.draw() self.ui.update_outputText(self.canvas.height()) def change_fsize(self): try: self.fsize = int(self.lineEdit_fsize.text()) self.change_title() self.change_labelx() self.change_labely() self.update_gridSize() print(self.fsize) except Exception as error: self.ui.update_outputText(error) def change_cmap(self): try: self.im.set_cmap(self.lineEdit_cmap.text()) self.canvas.draw() except Exception as error: pass #self.ui.update_outputText(error) def change_xlim(self): try: temp_txt = self.lineEdit_xlim.text() Ntxt = len(temp_txt) numList = [] if temp_txt[0] == "(" and temp_txt[-1] == ")": actual = "" for i in range(1, Ntxt - 1): if temp_txt[i] == ",": numList.append(float(actual)) actual = "" elif i == Ntxt - 2: actual += temp_txt[i] numList.append(float(actual)) else: actual += temp_txt[i] self.axes.set_xlim(numList[0], numList[1]) except Exception as error: self.ui.update_outputText(error) def change_ylim(self): try: temp_txt = self.lineEdit_ylim.text() Ntxt = len(temp_txt) numList = [] if temp_txt[0] == "(" and temp_txt[-1] == ")": actual = "" for i in range(1, Ntxt - 1): if temp_txt[i] == ",": numList.append(float(actual)) actual = "" elif i == Ntxt - 2: actual += temp_txt[i] numList.append(float(actual)) else: actual += temp_txt[i] self.axes.set_ylim(numList[0], numList[1]) self.canvas.draw() except Exception as error: self.ui.update_outputText(error) def change_title(self): self.axes.set_title(self.lineEdit_title.text(), fontsize=self.fsize) self.canvas.draw() def change_labelx(self): if self.lineEdit_xLabel.text() == "": self.axes.set_xlabel("") else: try: self.axes.set_xlabel(self.lineEdit_xLabel.text(), fontsize=self.fsize) self.canvas.draw() except: pass #self.ui.update_outputText("Unable to update x-label.") def change_labely(self): if self.lineEdit_yLabel.text() == "": self.axes.set_ylabel("") else: try: self.axes.set_ylabel(self.lineEdit_yLabel.text(), fontsize=self.fsize) self.canvas.draw() except: pass
class h5plot(object): """ h5plot class plots and saves all dataset in the h5 file. We recursively walk through the entry tree of datasets, check for their ds_type and plot the data in a default setting with matplotlib. The plots are then saved in an 'image' folder beside the h5 file. """ y_data = None # type: ndarray def __init__(self, h5_filepath, comment='', save_pdf=False): """Inits h5plot with a h5_filepath (string, absolute path), optional comment string, and optional save_pdf boolean. """ if not plot_enable or not qkit.module_available("matplotlib"): logging.warning( "matplotlib not installed. I can not save your measurement files as png. I will disable this function." ) qkit.cfg['save_png'] = False if not qkit.cfg.get('save_png', True): return self.comment = comment self.save_pdf = save_pdf self.path = h5_filepath filepath = os.path.abspath( self.path) #put filepath to platform standards self.filedir = os.path.dirname( filepath ) #return directory component of the given pathname, here filepath self.image_dir = os.path.join(self.filedir, 'images') try: os.mkdir(self.image_dir) except OSError: logging.warning('Error creating image directory.') pass # open the h5 file and get the hdf_lib object self.hf = store.Data(self.path) # check for datasets for i, pentry in enumerate(self.hf['/entry'].keys()): key = '/entry/' + pentry for j, centry in enumerate(self.hf[key].keys()): try: self.key = '/entry/' + pentry + "/" + centry self.ds = self.hf[self.key] if self.ds.attrs.get('save_plot', True): self.plt() # this is the plot function except Exception as e: print("Exception in qkit/gui/plot/plot.py while plotting") print(self.key) print(e) #close hf file self.hf.close() print('Plots saved in ' + self.image_dir) def plt(self): """ Creates the matplotlib figure, checks for some metadata and calls the plotting with respect to the ds_type of the dataset. Args: self: Object of the h5plot class. Returns: No return variable. The function operates on the given object. """ logging.info(" -> plotting dataset: " + str(self.ds.attrs.get('name'))) self.ds_type = self.ds.attrs.get('ds_type', '') self.x_ds_url = self.ds.attrs.get('x_ds_url', '') self.y_ds_url = self.ds.attrs.get('y_ds_url', '') self.z_ds_url = self.ds.attrs.get('z_ds_url', '') self.fig = Figure(figsize=(20, 10), tight_layout=True) self.ax = self.fig.gca() self.canvas = FigureCanvas(self.fig) self._unit_prefixes = { 24: 'Y', 21: 'Z', 18: 'E', 15: 'P', 12: 'T', 9: 'G', 6: 'M', 3: 'k', 0: '', -3: 'm', -6: u'µ', -9: 'n', -12: 'p', -15: 'f', -18: 'a', -21: 'z', -24: 'y' } self.plot_styles = {0: '-', 1: '.-', 2: '.'} if self.ds_type == ds_types['coordinate']: #self.plt_coord() return elif self.ds_type == ds_types['vector']: self.plt_vector() elif self.ds_type == ds_types['matrix']: self.plt_matrix() elif self.ds_type == ds_types['box']: self.plt_box() elif self.ds_type == ds_types['txt']: #self.plt_txt() return elif self.ds_type == ds_types['view']: self.plt_view() else: return ## Some labeling depending on the ds_type. The label variables are set ## in the respective plt_xxx() fcts. self.ax.set_xlabel(self.x_label) self.ax.set_ylabel(self.y_label) self.ax.xaxis.label.set_fontsize(20) self.ax.yaxis.label.set_fontsize(20) self.ax.ticklabel_format(useOffset=False) for i in self.ax.get_xticklabels(): i.set_fontsize(16) for i in self.ax.get_yticklabels(): i.set_fontsize(16) save_name = str( os.path.basename(self.filedir))[0:6] + '_' + self.key.replace( '/entry/', '').replace('/', '_') if self.comment: save_name = save_name + '_' + self.comment image_path = str(os.path.join(self.image_dir, save_name)) if self.save_pdf: self.canvas.print_figure(image_path + '.pdf') self.canvas.print_figure(image_path + '.png') """ except Exception as e: print "Exception in qkit/gui/plot/plot.py" print e """ def plt_vector(self): """ Plot one-dimensional dataset. Print data vs. x-coordinate. Args: self: Object of the h5plot class. Returns: No return variable. The function operates on the self- matplotlib objects. """ self.ax.set_title(self.hf._filename[:-3] + " " + self.ds.attrs.get('name', '_name_').decode()) self.y_data = np.array(self.ds) self.y_exp = self._get_exp(self.y_data) self.y_label = self.ds.attrs.get('name', '_name_').decode( ) + ' (' + self._unit_prefixes[self.y_exp] + self.ds.attrs.get( 'unit', '_unit_').decode() + ')' try: self.x_data = self.hf[self.x_ds_url] self.x_exp = self._get_exp(np.array(self.x_data)) self.x_label = self.x_data.attrs.get('name', '_xname_').decode( ) + ' (' + self._unit_prefixes[self.x_exp] + self.x_data.attrs.get( 'unit', '_xunit_').decode() + ')' except Exception: self.x_data = np.arange(len(self.y_data)) self.x_label = '_none_ / _none_' plot_style = self.plot_styles[ int(not (len(self.y_data) - 1)) * 2] # default is 'x' for one point and '-' for lines #if len(self.y_data) == 1: #only one entry, print as cross # plot_style = 'x' #else: # plot_style = '-' try: self.ax.plot( np.array(self.x_data) * 10**int(-self.x_exp), self.y_data[0:len(self.x_data)] * 10**int(-self.y_exp), plot_style ) #JB: avoid crash after pressing the stop button when arrays are of different lengths except TypeError: self.ax.plot(0, self.y_data, plot_style) def plt_matrix(self): """ Plot two-dimensional dataset. print data color-coded y-coordinate vs. x-coordinate. Args: self: Object of the h5plot class. Returns: No return variable. The function operates on the self- matplotlib objects. """ self.x_ds = self.hf[self.x_ds_url] self.x_exp = self._get_exp(np.array(self.x_ds)) self.x_label = self.x_ds.attrs.get('name', '_xname_').decode( ) + ' (' + self._unit_prefixes[self.x_exp] + self.x_ds.attrs.get( 'unit', '_xunit_').decode() + ')' self.y_ds = self.hf[self.y_ds_url] self.y_exp = self._get_exp(np.array(self.y_ds)) self.y_label = self.y_ds.attrs.get('name', '_yname_').decode( ) + ' (' + self._unit_prefixes[self.y_exp] + self.y_ds.attrs.get( 'unit', '_yunit_').decode() + ')' self.ds_data = np.array( self.ds).T #transpose matrix to get x/y axis correct self.ds_exp = self._get_exp(self.ds_data) self.ds_data *= 10.**-self.ds_exp self.ds_label = self.ds.attrs.get('name', '_name_').decode( ) + ' (' + self._unit_prefixes[self.ds_exp] + self.ds.attrs.get( 'unit', '_unit_').decode() + ')' x_data = np.array(self.x_ds) * 10.**-self.x_exp x_min, x_max = np.amin(x_data), np.amax(x_data) dx = self.x_ds.attrs.get('dx', (x_data[-1] - x_data[0]) / (len(x_data) - 1)) y_data = np.array(self.y_ds) * 10.**-self.y_exp y_min, y_max = np.amin(y_data), np.amax(y_data) dy = self.y_ds.attrs.get('dy', (y_data[-1] - y_data[0]) / (len(y_data) - 1)) # downsweeps in any direction have to be corrected # this is triggered by dx/dy values < 0 # data-matrix and min/max-values have to be swapped if dx < 0: self.ds_data = np.fliplr(self.ds_data) if dy < 0: self.ds_data = np.flipud(self.ds_data) # plot self.ax.set_title(self.hf._filename[:-3] + " " + self.ds.attrs.get('name', '_name_').decode()) self.cax = self.ax.imshow(self.ds_data, extent=(x_min, x_max, y_min, y_max), aspect='auto', origin='lower', vmin=self._get_vrange(self.ds_data, 2)[0], vmax=self._get_vrange(self.ds_data, 2)[1], interpolation='none') #self.cax = self.ax.pcolormesh(x_data, y_data, self.ds_data) self.cax.set_rasterized(True) self.cbar = self.fig.colorbar(self.cax) self.cbar.ax.set_ylabel(self.ds_label) self.cbar.ax.yaxis.label.set_fontsize(20) for i in self.cbar.ax.get_yticklabels(): i.set_fontsize(16) def plt_box(self): """ Plot two-dimensional dataset. Print data color-coded y-coordinate vs. x-coordinate. Args: self: Object of the h5plot class. Returns: No return variable. The function operates on the self- matplotlib objects. """ self.x_ds = self.hf[self.x_ds_url] self.x_exp = self._get_exp(np.array(self.x_ds)) self.x_label = self.x_ds.attrs.get('name', '_xname_').decode( ) + ' (' + self._unit_prefixes[self.x_exp] + self.x_ds.attrs.get( 'unit', '_xunit_').decode() + ')' self.y_ds = self.hf[self.y_ds_url] self.y_exp = self._get_exp(np.array(self.y_ds)) self.y_label = self.y_ds.attrs.get('name', '_yname_').decode( ) + ' (' + self._unit_prefixes[self.y_exp] + self.y_ds.attrs.get( 'unit', '_yunit_').decode() + ')' self.z_ds = self.hf[self.z_ds_url] self.z_exp = self._get_exp(np.array(self.z_ds)) self.z_label = self.z_ds.attrs.get('name', '_zname_').decode( ) + ' (' + self._unit_prefixes[self.z_exp] + self.z_ds.attrs.get( 'unit', '_zunit_').decode() + ')' self.ds_data = np.array( self.ds)[:, :, self.ds.shape[2] // 2].T # transpose matrix to get x/y axis correct self.ds_exp = self._get_exp(self.ds_data) self.ds_data *= 10.**-self.ds_exp self.ds_label = self.ds.attrs.get('name', '_name_').decode( ) + ' (' + self._unit_prefixes[self.ds_exp] + self.ds.attrs.get( 'unit', '_unit_').decode() + ')' x_data = np.array(self.x_ds) * 10.**-self.x_exp x_min, x_max = np.amin(x_data), np.amax(x_data) dx = self.x_ds.attrs.get('dx', (x_data[-1] - x_data[0]) / (len(x_data) - 1)) y_data = np.array(self.y_ds) * 10.**-self.y_exp y_min, y_max = np.amin(y_data), np.amax(y_data) dy = self.y_ds.attrs.get('dy', (y_data[-1] - y_data[0]) / (len(y_data) - 1)) # downsweeps in any direction have to be corrected # this is triggered by dx/dy values < 0 # data-matrix and min/max-values have to be swapped if dx < 0: self.ds_data = np.fliplr(self.ds_data) if dy < 0: self.ds_data = np.flipud(self.ds_data) # plot self.ax.set_title(self.hf._filename[:-3] + " " + self.ds.attrs.get('name', '_name_').decode()) self.cax = self.ax.imshow(self.ds_data, extent=(x_min, x_max, y_min, y_max), aspect='auto', origin='lower', vmin=self._get_vrange(self.ds_data, 2)[0], vmax=self._get_vrange(self.ds_data, 2)[1], interpolation='none') #self.cax = self.ax.pcolormesh(x_data, y_data, self.ds_data) self.cax.set_rasterized(True) self.cbar = self.fig.colorbar(self.cax) self.cbar.ax.set_ylabel(self.ds_label) self.cbar.ax.yaxis.label.set_fontsize(20) for i in self.cbar.ax.get_yticklabels(): i.set_fontsize(16) def plt_coord(self): # not (yet?) implemented. we'll see ... pass def plt_txt(self): # not (yet?) implemented. we'll see ... pass def plt_view(self): """ Plot views with possible multi-level overlays. First shot at (automatically) plotting views. Since this structure is rather flexible, there is no universal approach for meaningful plots. First demand was IV curves from the transport measurements. The code is a recycled version of the _display_1D_view() fct of qkit.gui.qviewkit.PlotWindow_lib Args: self: Object of the h5plot class. Returns: No return variable. The function operates on the self- matplotlib objects. """ # views are organized in overlays, the number of x vs y plot in one figure (i.e. data and fit) overlay_num = self.ds.attrs.get("overlays", 0) overlay_urls = [] err_urls = [] self.ax.set_title(self.hf._filename[:-3] + " " + self.ds.attrs.get('name', '_name_').decode()) # the overlay_urls (urls of the x and y datasets that ar plotted) are extracted from the metadata for i in range(overlay_num + 1): ov = self.ds.attrs.get("xy_" + str(i), "").decode() if ov: overlay_urls.append(ov.split(":")) err_urls.append(self.ds.attrs.get("xy_" + str(i) + "_error", "")) self.ds_xs = [] self.ds_ys = [] self.ds_errs = [] for xy in overlay_urls: self.ds_xs.append(self.hf[xy[0]]) self.ds_ys.append(self.hf[xy[1]]) for err_url in err_urls: try: self.ds_errs.append(self.hf[err_url]) except: self.ds_errs.append(0) """ the ds_type are detected. this determines which dataset is displayed as a 1D plot. since the initial demand for the plotting comes from IV measurements and for easy handling, the default display in qviewkit is saved. """ self.ds_label = self.ds.attrs.get('name', '_name_').decode() view_params = json.loads(self.ds.attrs.get("view_params", {}).decode()) #if 'aspect' in view_params: # self.ax.set_aspect = view_params.get('aspect', 'auto') markersize = view_params.get('markersize', 5) # iteratring over all x- (and y-)datasets and checking for dimensions gives the data to be plotted for i, x_ds in enumerate(self.ds_xs): y_ds = self.ds_ys[i] err_ds = self.ds_errs[i] #1D data is easy, for matrix and box the very last recorded 1D data is plotted if x_ds.attrs.get('ds_type', 0) == ds_types['coordinate'] or x_ds.attrs.get( 'ds_type', 0) == ds_types['vector']: if y_ds.attrs.get('ds_type', 0) == ds_types['vector'] or y_ds.attrs.get( 'ds_type', 0) == ds_types['coordinate']: x_data = np.array(x_ds) y_data = np.array(y_ds) if err_ds: err_data = np.array(err_ds) elif y_ds.attrs.get('ds_type', 0) == ds_types['matrix']: x_data = np.array(x_ds) if "default_trace" in view_params: y_data = np.array( y_ds[:, view_params.get("default_trace", -1)]) else: y_data = np.array( y_ds[-1] ) # The code was like this, but I believe the axis is wrong if err_ds: err_data = np.array(err_ds[-1]) elif y_ds.attrs.get('ds_type', 0) == ds_types['box']: x_data = np.array(x_ds) y_data = np.array(y_ds[-1, -1, :]) if err_ds: err_data = np.array(err_ds[-1, -1, :]) ## This is in our case used so far only for IQ plots. The functionality derives from this application. elif x_ds.attrs.get('ds_type', 0) == ds_types['matrix']: x_data = np.array(x_ds[-1]) y_data = np.array(y_ds[-1]) elif x_ds.attrs.get('ds_type', 0) == ds_types['box']: x_data = np.array(x_ds[-1, -1, :]) y_data = np.array(y_ds[-1, -1, :]) plot_style = self.plot_styles[view_params.get( 'plot_style', int(not (len(y_data) - 1)) * 2)] # default is 'x' for one point and '-' for lines if err_ds: self.ax.errorbar(x_data, y_data[0:len(x_data)], yerr=err_data[0:len(x_data)], label=y_ds.name.split('/')[-1]) else: try: x_exp = self._get_exp( x_data) # caculate order of magnitude for unit-prefix y_exp = self._get_exp(y_data[0:len(x_data)]) self.ax.plot(x_data * 10**-x_exp, y_data[0:len(x_data)] * 10**-y_exp, plot_style, label=y_ds.name.split('/')[-1]) except TypeError: self.ax.plot(0, y_data, plot_style) # x- and y-labels come from view_params['labels'] or if not provided from the last added entry in the overlay if view_params.get("labels", False): self.x_label = view_params['labels'][0] self.y_label = view_params['labels'][1] else: self.x_label = x_ds.attrs.get("name", "_none_").decode() self.y_label = y_ds.attrs.get("name", "_none_").decode() self.x_unit = x_ds.attrs.get("unit", "_none_") self.y_unit = y_ds.attrs.get("unit", "_none_") self.x_label += ' (' + self._unit_prefixes[ x_exp] + self.x_unit.decode() + ')' self.y_label += ' (' + self._unit_prefixes[ y_exp] + self.y_unit.decode() + ')' self.ax.legend() def _get_exp(self, data): """ This function calculates the order of magnitude (exponent in steps of 3) to use for unit-prefix. """ try: return np.nanmax(np.log10(np.abs(data[data != 0]))) // 3 * 3 except: return 0 def _get_vrange(self, data, percent): ''' This function calculates ranges for the colorbar to get rid of spikes in the data. If the data is evenly distributed, this should not change anything in your colorbar. ''' _min = np.nanpercentile(data, percent) _max = np.nanpercentile(data, 100 - percent) _min -= (_max - _min) * percent / (100. - 2 * percent) _max += (_max - _min) * percent / (100. - 2 * percent) return [_min, _max]
def save_recon_images_1(img_file_name, imgs, recons, fig_size): from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure imgs, recons = np.squeeze(imgs), np.squeeze(recons) test_size = imgs.shape[0] indxs = np.random.randint(0, int(test_size), 3) # fig_size = (8,6) fig_size = fig_size fig = Figure(figsize=fig_size) rows, cols = 2, 3 ax = fig.add_subplot(rows, cols, 1) cax = ax.imshow(imgs[indxs[0], :], cmap='gray') fig.colorbar(cax) ax.set_title('Image-{}'.format(indxs[0])) ax.set_ylabel('f') ax = fig.add_subplot(rows, cols, 2) cax = ax.imshow(imgs[indxs[1], :], cmap='gray') fig.colorbar(cax) ax.set_title('Image-{}'.format(indxs[1])) ax = fig.add_subplot(rows, cols, 3) cax = ax.imshow(imgs[indxs[2], :], cmap='gray') fig.colorbar(cax) ax.set_title('Image-{}'.format(indxs[2])) ax = fig.add_subplot(rows, cols, 4) cax = ax.imshow(recons[indxs[0], :], cmap='gray') fig.colorbar(cax) ax.set_ylabel('f_MP') ax = fig.add_subplot(rows, cols, 5) cax = ax.imshow(recons[indxs[1], :], cmap='gray') fig.colorbar(cax) ax = fig.add_subplot(rows, cols, 6) cax = ax.imshow(recons[indxs[2], :], cmap='gray') fig.colorbar(cax) canvas = FigureCanvasAgg(fig) canvas.print_figure(img_file_name, dpi=100)
class GraphSet(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.first_time = True def show_tracks(self): if not (self.controller.loaded): tk.messagebox.showerror('Error', 'No data was loaded') else: trackwindow = tk.Toplevel() thetaNS = self.controller.tools.thetaNS sigNS = self.controller.tools.sigNS size = thetaNS.shape figure = Figure(figsize=(8, 3), dpi=150) axis = figure.add_subplot(111) im = axis.imshow(sigNS, extent=[0, size[1], 0, size[0]], aspect='auto', cmap='jet') divider = make_axes_locatable(axis) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(im, cax=cax, orientation='vertical') cbar.ax.set_title('$\sigma^0,dB$') canvas = FigureCanvasTkAgg(figure, trackwindow) canvas.draw() canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) def update_map(self): LaNS = self.controller.tools.LaNS LoNS = self.controller.tools.LoNS thetaNS = self.controller.tools.thetaNS sigNS = self.controller.tools.sigNS #Boundries=[64, 168, 44, 132]; if self.first_time: self.figure = Figure() self.figure = Figure(figsize=(6, 5), dpi=150) self.axis = self.figure.add_subplot(111) self.main_map = Basemap(llcrnrlon=132, llcrnrlat=44, urcrnrlon=168, urcrnrlat=64, projection='merc', ax=self.axis, resolution='c') self.main_map.fillcontinents(zorder=0) self.main_map.drawcoastlines(linewidth=0.2, color='grey', zorder=3) self.main_map.drawmapboundary(linewidth=0.1, zorder=-1) x, y = self.main_map(LoNS, LaNS) self.scat = self.main_map.scatter(x, y, 2, sigNS, marker='.', alpha=0.7, cmap='jet', zorder=3) self.cbar = self.figure.colorbar(self.scat) self.cbar.ax.set_title('$\sigma^0,dB$') self.canvas = FigureCanvasTkAgg(self.figure, self) # self.canvas.get_tk_widget().pack(pady = 10, expand = True) self.canvas.draw() canvas_toolbar = NavigationToolbar2Tk(self.canvas, self) canvas_toolbar.update() # self.canvas._tkcanvas.pack(side = tk.BOTTOM,fill = tk.BOTH, expand = True) self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) # self.canvas._tkcanvas.pack(side = tk.BOTTOM,fill = tk.BOTH, expand = True) self.first_time = False else: self.scat.remove() x, y = self.main_map(LoNS, LaNS) self.scat = self.main_map.scatter(x, y, 1, sigNS, marker='.', alpha=0.7, cmap='jet') # divider = make_axes_locatable(ax) # cax = divider.append_axes("right", size="5%", pad=0.05) # cbar = plt.colorbar(im, cax=cax, orientation='vertical') # cbar.ax.set_title('$\sigma^0,dB$') self.canvas.draw()
class Scene: """A virtual landscape for a volume rendering. The Scene class is meant to be the primary container for the new volume rendering framework. A single scene may contain several Camera and RenderSource instances, and is the primary driver behind creating a volume rendering. This sets up the basics needed to add sources and cameras. This does very little setup, and requires additional input to do anything useful. Parameters ---------- None Examples -------- This example shows how to create an empty scene and add a VolumeSource and a Camera. >>> import yt >>> from yt.visualization.volume_rendering.api import ( ... Camera, Scene, create_volume_source) >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> sc = Scene() >>> source = create_volume_source(ds.all_data(), "density") >>> sc.add_source(source) >>> cam = sc.add_camera() >>> im = sc.render() Alternatively, you can use the create_scene function to set up defaults and then modify the Scene later: >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> sc = yt.create_scene(ds) >>> # Modify camera, sources, etc... >>> im = sc.render() """ _current = None _camera = None _unit_registry = None def __init__(self): r"""Create a new Scene instance""" super().__init__() self.sources = OrderedDict() self._last_render = None # A non-public attribute used to get around the fact that we can't # pass kwargs into _repr_png_() self._sigma_clip = None def get_source(self, source_num=0): """Returns the volume rendering source indexed by ``source_num``""" return list(self.sources.values())[source_num] def __getitem__(self, item): if item in self.sources: return self.sources[item] return self.get_source(item) @property def opaque_sources(self): """ Iterate over opaque RenderSource objects, returning a tuple of (key, source) """ for k, source in self.sources.items(): if isinstance(source, OpaqueSource) or issubclass( OpaqueSource, type(source)): yield k, source @property def transparent_sources(self): """ Iterate over transparent RenderSource objects, returning a tuple of (key, source) """ for k, source in self.sources.items(): if not isinstance(source, OpaqueSource): yield k, source def add_source(self, render_source, keyname=None): """Add a render source to the scene. This will autodetect the type of source. Parameters ---------- render_source: :class:`yt.visualization.volume_rendering.render_source.RenderSource` A source to contribute to the volume rendering scene. keyname: string (optional) The dictionary key used to reference the source in the sources dictionary. """ if keyname is None: keyname = "source_%02i" % len(self.sources) data_sources = (VolumeSource, MeshSource, GridSource) if isinstance(render_source, data_sources): self._set_new_unit_registry( render_source.data_source.ds.unit_registry) line_annotation_sources = (GridSource, BoxSource, CoordinateVectorSource) if isinstance(render_source, line_annotation_sources): lens_str = str(self.camera.lens) if "fisheye" in lens_str or "spherical" in lens_str: raise NotImplementedError( "Line annotation sources are not supported for %s." % (type(self.camera.lens).__name__), ) if isinstance(render_source, (LineSource, PointSource)): if isinstance(render_source.positions, YTArray): render_source.positions = (self.arr( render_source.positions).in_units("code_length").d) self.sources[keyname] = render_source return self def __setitem__(self, key, value): return self.add_source(value, key) def _set_new_unit_registry(self, input_registry): self.unit_registry = UnitRegistry(add_default_symbols=False, lut=input_registry.lut) # Validate that the new unit registry makes sense current_scaling = self.unit_registry["unitary"][0] if current_scaling != input_registry["unitary"][0]: for source in self.sources.items(): data_source = getattr(source, "data_source", None) if data_source is None: continue scaling = data_source.ds.unit_registry["unitary"][0] if scaling != current_scaling: raise NotImplementedError( "Simultaneously rendering data from datasets with " "different units is not supported") def render(self, camera=None): r"""Render all sources in the Scene. Use the current state of the Scene object to render all sources currently in the scene. Returns the image array. If you want to save the output to a file, call the save() function. Parameters ---------- camera: :class:`Camera`, optional If specified, use a different :class:`Camera` to render the scene. Returns ------- A :class:`yt.data_objects.image_array.ImageArray` instance containing the current rendering image. Examples -------- >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> sc = yt.create_scene(ds) >>> # Modify camera, sources, etc... >>> im = sc.render() >>> sc.save(sigma_clip=4.0, render=False) Altneratively, if you do not need the image array, you can just call ``save`` as follows. >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> sc = yt.create_scene(ds) >>> # Modify camera, sources, etc... >>> sc.save(sigma_clip=4.0) """ mylog.info("Rendering scene (Can take a while).") if camera is None: camera = self.camera assert camera is not None self._validate() bmp = self.composite(camera=camera) self._last_render = bmp return bmp def _render_on_demand(self, render): # checks for existing render before rendering, in most cases we want to # render every time, but in some cases pulling the previous render is # desirable (e.g., if only changing sigma_clip or # saving after a call to sc.show()). if self._last_render is not None and not render: mylog.info("Found previously rendered image to save.") return if self._last_render is None: mylog.warning("No previously rendered image found, rendering now.") elif render: mylog.warning( "Previously rendered image exists, but rendering anyway. " "Supply 'render=False' to save previously rendered image directly." ) self.render() def _get_render_sources(self): return [ s for s in self.sources.values() if isinstance(s, RenderSource) ] def _setup_save(self, fname, render): self._render_on_demand(render) rensources = self._get_render_sources() if fname is None: # if a volume source present, use its affiliated ds for fname if len(rensources) > 0: rs = rensources[0] basename = rs.data_source.ds.basename if isinstance(rs.field, str): field = rs.field else: field = rs.field[-1] fname = f"{basename}_Render_{field}" # if no volume source present, use a default filename else: fname = "Render_opaque" fname = validate_image_name(fname) mylog.info("Saving rendered image to %s", fname) return fname def save(self, fname=None, sigma_clip=None, render=True): r"""Saves a rendered image of the Scene to disk. Once you have created a scene, this saves an image array to disk with an optional filename. This function calls render() to generate an image array, unless the render parameter is set to False, in which case the most recently rendered scene is used if it exists. Parameters ---------- fname: string, optional If specified, save the rendering as to the file "fname". If unspecified, it creates a default based on the dataset filename. The file format is inferred from the filename's suffix. Supported fomats are png, pdf, eps, and ps. Default: None sigma_clip: float, optional Image values greater than this number times the standard deviation plus the mean of the image will be clipped before saving. Useful for enhancing images as it gets rid of rare high pixel values. Default: None floor(vals > std_dev*sigma_clip + mean) render: boolean, optional If True, will always render the scene before saving. If False, will use results of previous render if it exists. Default: True Returns ------- Nothing Examples -------- >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> sc = yt.create_scene(ds) >>> # Modify camera, sources, etc... >>> sc.save("test.png", sigma_clip=4) When saving multiple images without modifying the scene (camera, sources,etc.), render=False can be used to avoid re-rendering. This is useful for generating images at a range of sigma_clip values: >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> sc = yt.create_scene(ds) >>> # save with different sigma clipping values >>> sc.save("raw.png") # The initial render call happens here >>> sc.save("clipped_2.png", sigma_clip=2, render=False) >>> sc.save("clipped_4.png", sigma_clip=4, render=False) """ fname = self._setup_save(fname, render) # We can render pngs natively but for other formats we defer to # matplotlib. if fname.endswith(".png"): self._last_render.write_png(fname, sigma_clip=sigma_clip) else: from matplotlib.figure import Figure shape = self._last_render.shape fig = Figure((shape[0] / 100.0, shape[1] / 100.0)) canvas = get_canvas(fig, fname) ax = fig.add_axes([0, 0, 1, 1]) ax.set_axis_off() out = self._last_render nz = out[:, :, :3][out[:, :, :3].nonzero()] max_val = nz.mean() + sigma_clip * nz.std() alpha = 255 * out[:, :, 3].astype("uint8") out = np.clip(out[:, :, :3] / max_val, 0.0, 1.0) * 255 out = np.concatenate([out.astype("uint8"), alpha[..., None]], axis=-1) # not sure why we need rot90, but this makes the orientation # match the png writer ax.imshow(np.rot90(out), origin="lower") canvas.print_figure(fname, dpi=100) def save_annotated( self, fname=None, label_fmt=None, text_annotate=None, dpi=100, sigma_clip=None, render=True, ): r"""Saves the most recently rendered image of the Scene to disk, including an image of the transfer function and and user-defined text. Once you have created a scene and rendered that scene to an image array, this saves that image array to disk with an optional filename. If an image has not yet been rendered for the current scene object, it forces one and writes it out. Parameters ---------- fname: string, optional If specified, save the rendering as a bitmap to the file "fname". If unspecified, it creates a default based on the dataset filename. Default: None sigma_clip: float, optional Image values greater than this number times the standard deviation plus the mean of the image will be clipped before saving. Useful for enhancing images as it gets rid of rare high pixel values. Default: None floor(vals > std_dev*sigma_clip + mean) dpi: integer, optional By default, the resulting image will be the same size as the camera parameters. If you supply a dpi, then the image will be scaled accordingly (from the default 100 dpi) label_fmt : str, optional A format specifier (e.g., label_fmt="%.2g") to use in formatting the data values that label the transfer function colorbar. text_annotate : list of iterables Any text that you wish to display on the image. This should be an list containing a tuple of coordinates (in normalized figure coordinates), the text to display, and, optionally, a dictionary of keyword/value pairs to pass through to the matplotlib text() function. Each item in the main list is a separate string to write. render: boolean, optional If True, will render the scene before saving. If False, will use results of previous render if it exists. Default: True Returns ------- Nothing Examples -------- >>> sc.save_annotated( ... "fig.png", ... text_annotate=[ ... [ ... (0.05, 0.05), ... f"t = {ds.current_time.d}", ... dict(horizontalalignment="left"), ... ], ... [ ... (0.5, 0.95), ... "simulation title", ... dict(color="y", fontsize="24", horizontalalignment="center"), ... ], ... ], ... ) """ fname = self._setup_save(fname, render) # which transfer function? rs = self._get_render_sources()[0] tf = rs.transfer_function label = rs.data_source.ds._get_field_info(rs.field).get_label() ax = self._show_mpl(self._last_render.swapaxes(0, 1), sigma_clip=sigma_clip, dpi=dpi) self._annotate(ax.axes, tf, rs, label=label, label_fmt=label_fmt) # any text? if text_annotate is not None: f = self._render_figure for t in text_annotate: xy = t[0] string = t[1] if len(t) == 3: opt = t[2] else: opt = dict() # sane default if "color" not in opt: opt["color"] = "w" ax.axes.text(xy[0], xy[1], string, transform=f.transFigure, **opt) self._render_figure.canvas = get_canvas(self._render_figure, fname) self._render_figure.tight_layout() self._render_figure.savefig(fname, facecolor="black", pad_inches=0) def _show_mpl(self, im, sigma_clip=None, dpi=100): from matplotlib.figure import Figure s = im.shape self._render_figure = Figure(figsize=(s[1] / float(dpi), s[0] / float(dpi))) self._render_figure.clf() ax = self._render_figure.add_subplot(111) ax.set_position([0, 0, 1, 1]) if sigma_clip is not None: nz = im[im > 0.0] nim = im / (nz.mean() + sigma_clip * np.std(nz)) nim[nim > 1.0] = 1.0 nim[nim < 0.0] = 0.0 del nz else: nim = im axim = ax.imshow(nim[:, :, :3] / nim[:, :, :3].max(), interpolation="bilinear") return axim def _annotate(self, ax, tf, source, label="", label_fmt=None): ax.get_xaxis().set_visible(False) ax.get_xaxis().set_ticks([]) ax.get_yaxis().set_visible(False) ax.get_yaxis().set_ticks([]) cb = self._render_figure.colorbar(ax.images[0], pad=0.0, fraction=0.05, drawedges=True) tf.vert_cbar( ax=cb.ax, label=label, label_fmt=label_fmt, resolution=self.camera.resolution[0], log_scale=source.log_field, ) def _validate(self): r"""Validate the current state of the scene.""" for source in self.sources.values(): source._validate() return def composite(self, camera=None): r"""Create a composite image of the current scene. First iterate over the opaque sources and set the ZBuffer. Then iterate over the transparent sources, rendering from the value of the zbuffer to the front of the box. Typically this function is accessed through the .render() command. Parameters ---------- camera: :class:`Camera`, optional If specified, use a specific :class:`Camera` to render the scene. Returns ------- im: :class:`ImageArray` ImageArray instance of the current rendering image. Examples -------- >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> sc = yt.create_scene(ds) >>> # Modify camera, sources, etc... >>> im = sc.composite() """ if camera is None: camera = self.camera empty = camera.lens.new_image(camera) opaque = ZBuffer(empty, np.full(empty.shape[:2], np.inf)) for _, source in self.opaque_sources: source.render(camera, zbuffer=opaque) im = source.zbuffer.rgba for _, source in self.transparent_sources: im = source.render(camera, zbuffer=opaque) opaque.rgba = im # rotate image 180 degrees so orientation agrees with e.g. # a PlotWindow plot return np.rot90(im, k=2) def add_camera(self, data_source=None, lens_type="plane-parallel", auto=False): r"""Add a new camera to the Scene. The camera is defined by a position (the location of the camera in the simulation domain,), a focus (the point at which the camera is pointed), a width (the width of the snapshot that will be taken, a resolution (the number of pixels in the image), and a north_vector (the "up" direction in the resulting image). A camera can use a variety of different Lens objects. If the scene already has a camera associated with it, this function will create a new camera and discard the old one. Parameters ---------- data_source: :class:`AMR3DData` or :class:`Dataset`, optional This is the source to be rendered, which can be any arbitrary yt data object or dataset. lens_type: string, optional This specifies the type of lens to use for rendering. Current options are 'plane-parallel', 'perspective', and 'fisheye'. See :class:`yt.visualization.volume_rendering.lens.Lens` for details. Default: 'plane-parallel' auto: boolean If True, build smart defaults using the data source extent. This can be time-consuming to iterate over the entire dataset to find the positional bounds. Default: False Examples -------- In this example, the camera is set using defaults that are chosen to be reasonable for the argument Dataset. >>> import yt >>> from yt.visualization.volume_rendering.api import Camera, Scene >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> sc = Scene() >>> sc.add_camera() Here, we set the camera properties manually: >>> import yt >>> from yt.visualization.volume_rendering.api import Camera, Scene >>> sc = Scene() >>> cam = sc.add_camera() >>> cam.position = np.array([0.5, 0.5, -1.0]) >>> cam.focus = np.array([0.5, 0.5, 0.0]) >>> cam.north_vector = np.array([1.0, 0.0, 0.0]) Finally, we create a camera with a non-default lens: >>> import yt >>> from yt.visualization.volume_rendering.api import Camera >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> sc = Scene() >>> sc.add_camera(ds, lens_type="perspective") """ self._camera = Camera(self, data_source, lens_type, auto) return self.camera def camera(): doc = r"""The camera property. This is the default camera that will be used when rendering. Can be set manually, but Camera type will be checked for validity. """ def fget(self): return self._camera def fset(self, value): value.width = self.arr(value.width) value.focus = self.arr(value.focus) value.position = self.arr(value.position) self._camera = value def fdel(self): del self._camera self._camera = None return locals() camera = property(**camera()) def unit_registry(): def fget(self): ur = self._unit_registry if ur is None: ur = UnitRegistry() # This will be updated when we add a volume source ur.add("unitary", 1.0, length) self._unit_registry = ur return self._unit_registry def fset(self, value): self._unit_registry = value if self.camera is not None: self.camera.width = YTArray( self.camera.width.in_units("unitary"), registry=value) self.camera.focus = YTArray( self.camera.focus.in_units("unitary"), registry=value) self.camera.position = YTArray( self.camera.position.in_units("unitary"), registry=value) def fdel(self): del self._unit_registry self._unit_registry = None return locals() unit_registry = property(**unit_registry()) def set_camera(self, camera): r""" Set the camera to be used by this scene. """ self.camera = camera def get_camera(self): r""" Get the camera currently used by this scene. """ return self.camera def annotate_domain(self, ds, color=None): r""" Modifies this scene by drawing the edges of the computational domain. This adds a new BoxSource to the scene corresponding to the domain boundaries and returns the modified scene object. Parameters ---------- ds : :class:`yt.data_objects.static_output.Dataset` This is the dataset object corresponding to the simulation being rendered. Used to get the domain bounds. color : array_like of shape (4,), optional The RGBA value to use to draw the domain boundaries. Default is black with an alpha of 1.0. Examples -------- >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> sc = yt.create_scene(ds) >>> sc.annotate_domain(ds) >>> im = sc.render() """ box_source = BoxSource(ds.domain_left_edge, ds.domain_right_edge, color=color) self.add_source(box_source) return self def annotate_grids(self, data_source, alpha=0.3, cmap=None, min_level=None, max_level=None): r""" Modifies this scene by drawing the edges of the AMR grids. This adds a new GridSource to the scene that represents the AMR grid and returns the resulting Scene object. Parameters ---------- data_source: :class:`~yt.data_objects.api.DataContainer` The data container that will be used to identify grids to draw. alpha : float The opacity of the grids to draw. cmap : color map name The color map to use to map resolution levels to color. min_level : int, optional Minimum level to draw max_level : int, optional Maximum level to draw Examples -------- >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> sc = yt.create_scene(ds) >>> sc.annotate_grids(ds.all_data()) >>> im = sc.render() """ if cmap is None: cmap = ytcfg.get("yt", "default_colormap") grids = GridSource( data_source, alpha=alpha, cmap=cmap, min_level=min_level, max_level=max_level, ) self.add_source(grids) return self def annotate_mesh_lines(self, color=None, alpha=1.0): """ Modifies this Scene by drawing the mesh line boundaries on all MeshSources. Parameters ---------- color : array_like of shape (4,), optional The RGBA value to use to draw the mesh lines. Default is black with an alpha of 1.0. alpha : float, optional The opacity of the mesh lines. Default is 255 (solid). """ for _, source in self.opaque_sources: if isinstance(source, MeshSource): source.annotate_mesh_lines(color=color, alpha=alpha) return self def annotate_axes(self, colors=None, alpha=1.0): r""" Modifies this scene by drawing the coordinate axes. This adds a new CoordinateVectorSource to the scene and returns the modified scene object. Parameters ---------- colors: array-like of shape (3,4), optional The RGBA values to use to draw the x, y, and z vectors. The default is [[1, 0, 0, alpha], [0, 1, 0, alpha], [0, 0, 1, alpha]] where ``alpha`` is set by the parameter below. If ``colors`` is set then ``alpha`` is ignored. alpha : float, optional The opacity of the vectors. Examples -------- >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> sc = yt.create_scene(ds) >>> sc.annotate_axes(alpha=0.5) >>> im = sc.render() """ coords = CoordinateVectorSource(colors, alpha) self.add_source(coords) return self def show(self, sigma_clip=None): r"""This will send the most recently rendered image to the IPython notebook. If yt is being run from within an IPython session, and it is able to determine this, this function will send the current image of this Scene to the notebook for display. If there is no current image, it will run the render() method on this Scene before sending the result to the notebook. If yt can't determine if it's inside an IPython session, this will raise YTNotInsideNotebook. Examples -------- >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> sc = yt.create_scene(ds) >>> sc.show() """ if "__IPYTHON__" in dir(builtins): from IPython.display import display self._sigma_clip = sigma_clip display(self) else: raise YTNotInsideNotebook _arr = None @property def arr(self): """Converts an array into a :class:`yt.units.yt_array.YTArray` The returned YTArray will be dimensionless by default, but can be cast to arbitrary units using the ``units`` keyword argument. Parameters ---------- input_array : Iterable A tuple, list, or array to attach units to units: String unit specification, unit symbol object, or astropy units object input_units : deprecated in favor of 'units' The units of the array. Powers must be specified using python syntax (cm**3, not cm^3). dtype : string or NumPy dtype object The dtype of the returned array data Examples -------- >>> a = sc.arr([1, 2, 3], "cm") >>> b = sc.arr([4, 5, 6], "m") >>> a + b YTArray([ 401., 502., 603.]) cm >>> b + a YTArray([ 4.01, 5.02, 6.03]) m Arrays returned by this function know about the scene's unit system >>> a = sc.arr(np.ones(5), "unitary") >>> a.in_units("Mpc") YTArray([ 1.00010449, 1.00010449, 1.00010449, 1.00010449, 1.00010449]) Mpc """ if self._arr is not None: return self._arr self._arr = functools.partial(YTArray, registry=self.unit_registry) return self._arr _quan = None @property def quan(self): """Converts an scalar into a :class:`yt.units.yt_array.YTQuantity` The returned YTQuantity will be dimensionless by default, but can be cast to arbitrary units using the ``units`` keyword argument. Parameters ---------- input_scalar : an integer or floating point scalar The scalar to attach units to units : String unit specification, unit symbol object, or astropy units input_units : deprecated in favor of 'units' The units of the quantity. Powers must be specified using python syntax (cm**3, not cm^3). dtype : string or NumPy dtype object The dtype of the array data. Examples -------- >>> a = sc.quan(1, "cm") >>> b = sc.quan(2, "m") >>> a + b 201.0 cm >>> b + a 2.01 m Quantities created this way automatically know about the unit system of the scene >>> a = ds.quan(5, "unitary") >>> a.in_cgs() 1.543e+25 cm """ if self._quan is not None: return self._quan self._quan = functools.partial(YTQuantity, registry=self.unit_registry) return self._quan def _repr_png_(self): if self._last_render is None: self.render() png = self._last_render.write_png(filename=None, sigma_clip=self._sigma_clip, background="black") self._sigma_clip = None return png def __repr__(self): disp = "<Scene Object>:" disp += "\nSources: \n" for k, v in self.sources.items(): disp += f" {k}: {v}\n" disp += "Camera: \n" disp += f" {self.camera}" return disp
class GUI(QMainWindow): def __init__(self, database: Database): super(GUI, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # self.ui.actionGuardar.triggered.connect(self.save_figure) self.ui.actionSalir.triggered.connect(self.close) self.ui.actionReiniciar.triggered.connect(self.restart_figure) # self.ui.actionMapa # self.ui.actionPredicci_n_GP # self.ui.actionIncertidumbre_GP # self.ui.actionFuncion_de_Adquisici_n self.ui.action3D.triggered.connect(self.send_request) self.db = database initial_map = obtain_map_data("E:/ETSI/Proyecto/data/Map/" + self.db.properties_df['map'].values[0] + "/map.yaml") sensors = {} for data in self.db.properties_df.values: if data[1] not in sensors.keys(): sensors[data[1]] = initial_map self.fig = Figure(figsize=(640, 480), dpi=72, facecolor=(1, 1, 1), edgecolor=(0, 0, 0)) self.canvas = FigureCanvas(self.fig) self.setCentralWidget(self.canvas) row = np.ceil(np.sqrt(len(sensors))) col = np.round(np.sqrt(len(sensors))) * 3 self.image = [] self.data = [] self.titles = [] self.nans = [] self.shape = None i = 1 for key in sensors: ax = self.fig.add_subplot(int(row * 100 + col * 10 + i)) # plt.subplot(row, col, i) self.image.append(ax.imshow(sensors[key], origin='lower')) self.titles.append("{} real".format(key)) ax.set_title("Map for sensor {}".format(key)) self.data.append(sensors[key]) for k in range(np.shape(self.data[0])[0]): for j in range(np.shape(self.data[0])[1]): if self.data[0][k, j] == 1.0: self.nans.append([k, j]) ax = self.fig.add_subplot(int(row * 100 + col * 10 + i + 1)) # plt.subplot(row, col, i + 1) self.image.append(ax.imshow(sensors[key], origin='lower')) self.titles.append("{} gp".format(key)) ax.set_title("Sensor {} Gaussian Process Regression".format(key)) self.data.append(sensors[key]) self.fig.colorbar(self.image[i], ax=ax, orientation='horizontal') current_cmap = cm.get_cmap() current_cmap.set_bad(color='white') ax = self.fig.add_subplot(int(row * 100 + col * 10 + i + 2)) # plt.subplot(row, col, i + 2) self.image.append(ax.imshow(sensors[key], origin='lower')) self.titles.append("{} gp un".format(key)) ax.set_title("Sensor {} GP Uncertainty".format(key)) self.data.append(sensors[key]) self.fig.colorbar(self.image[i + 1], ax=ax, orientation='horizontal') current_cmap = cm.get_cmap() current_cmap.set_bad(color='white') i += 3 if self.shape is None: self.shape = np.shape(sensors[key]) self.row = None self.col = None self.vmin = 0 self.vmax = 0 self.sm = None self.coordinator = Coordinator(None, self.data[0], 't') self.update_thread = QTimer() self.update_thread.setInterval(500) self.update_thread.timeout.connect(self.update_request) self.update_thread.start() self.signalManager = SignalManager() self.signalManager.sensor_sig.connect(self.request_sensors_update) self.signalManager.drones_sig.connect(self.request_drones_update) # self.signalManager.proper_sig.connect(self.request_proper_update) self.signalManager.images_ready.connect(self.update_images) @Slot() def update_request(self): for updatable_data in self.db.needs_update(): if "sensors" in updatable_data: self.signalManager.sensor_sig.emit('') elif "drones" in updatable_data: self.signalManager.drones_sig.emit('') elif "properties" in updatable_data: self.signalManager.proper_sig.emit('') @Slot() def request_sensors_update(self): # print('updating sensors') threading.Thread(target=self.generate_sensor_image, ).start() @Slot() def request_drones_update(self): # print('updating drones') threading.Thread(target=self.update_drone_position).start() @Slot() def request_proper_update(self): print('updating proper') def update_drone_position(self): self.db.updating_drones = True self.db.drones_c_index += 1 self.db.updating_drones = False def generate_sensor_image(self): self.db.updating_sensors = True raw_data = self.db.sensors_df.loc[self.db.sensors_df['type'] == 't'].to_numpy() last_index = len(raw_data) raw_data = raw_data[self.db.sensors_c_index:, 1:4] new_data = [[row[:2], row[2]] for row in raw_data] if self.db.sensors_c_index == 0: self.coordinator.initialize_data_gpr(new_data) else: self.coordinator.add_data(new_data[0]) self.coordinator.fit_data() self.db.sensors_c_index = last_index mu, std, sensor_name = self.coordinator.surrogate(return_std=True, return_sensor=True) observe_maps = dict() if self.ui.actionPredicci_n_GP.isChecked(): observe_maps["{} gp".format(sensor_name)] = mu if self.ui.actionIncertidumbre_GP.isChecked(): observe_maps["{} gp un".format(sensor_name)] = std if self.ui.actionFuncion_de_Adquisici_n.isChecked(): observe_maps["{} acq f".format(sensor_name)] = std self.observe_maps(observe_maps) self.db.updating_sensors = False def observe_maps(self, images: dict): for i in range(len(self.titles)): if self.titles[i] in images.keys(): for key in images.keys(): if self.titles[i] == key: data = images[key].reshape(self.shape[1], self.shape[0]).T for nnan in self.nans: data[nnan[0], nnan[1]] = -1 self.data[i] = np.ma.array(data, mask=(data == -1)) self.image[i].set_data(self.data[i]) self.image[i].set_clim(vmin=np.min(self.data[i]), vmax=np.max(self.data[i])) # a.update_ticks() break self.signalManager.images_ready.emit('') def restart_figure(self): self.coordinator.data = [np.array([[], []]), np.array([])] self.db.sensors_df = self.db.sensors_df.iloc[0:0] self.db.sensors_c_index = 0 for i in range(len(self.titles)): self.image[i].set_data(self.data[0]) self.image[i].set_clim(vmin=np.min(self.data[0]), vmax=np.max(self.data[0])) self.signalManager.images_ready.emit('') # threading.Thread(target=self.observe_maps, args=(,),).start() # self.coordinator = Coordinator(None, self.data[0], 't') @Slot() def update_images(self): self.canvas.draw() def export_maps(self, extension='png'): for my_image, my_title in zip(self.data, self.titles): if self.row is None: self.row, self.col = np.where(np.isnan(my_image)) self.sm = cm.ScalarMappable(cmap='viridis') self.vmin = np.min(my_image) self.vmax = np.max(my_image) if "un" in my_title: self.sm.set_clim(np.min(my_image), np.max(my_image)) my_image[self.row, self.col] = 0 new_image = self.sm.to_rgba(my_image, bytes=True) new_image[self.row, self.col, :] = [0, 0, 0, 0] new_image = np.flipud(new_image) img.imsave( "E:/ETSI/Proyecto/results/Map/{}_{}.{}".format( datetime.now().timestamp(), my_title, extension), new_image) # plt.show(block=True) def send_request(self): self.db.online_db.send_request()
class ScatterView3D(BaseTopologicalView): """ A view widget for visualizing 3D scatterplots of data utilizing matplotlib. """ def __init__(self, parent=None, amsc=None, title="3D Projection"): """ Initialization method that can optionally specify the parent widget, an AMSC object to reference, and a title for this widget. @ In, parent, an optional QWidget that will be the parent of this widget @ In, amsc, an optional AMSC_Object specifying the underlying data object for this widget to use. @ In, title, an optional string specifying the title of this widget. """ super(ScatterView3D, self).__init__(parent, amsc, title) def Reinitialize(self, parent=None, amsc=None, title="3D Projection"): """ Reinitialization method that resets this widget and can optionally specify the parent widget, an AMSC object to reference, and a title for this widget. @ In, parent, an optional QWidget that will be the parent of this widget @ In, amsc, an optional AMSC_Object specifying the underlying data object for this widget to use. @ In, title, an optional string specifying the title of this widget. """ # Try to apply a new layout, if one already exists then make sure to grab # it for updating if self.layout() is None: self.setLayout(qtw.QVBoxLayout()) layout = self.layout() self.clearLayout(layout) mySplitter = qtw.QSplitter() mySplitter.setOrientation(qtc.Qt.Vertical) layout.addWidget(mySplitter) self.fig = Figure(facecolor='white') self.mplCanvas = FigureCanvas(self.fig) self.mplCanvas.axes = self.fig.add_subplot(111, projection='3d') # We want the axes cleared every time plot() is called self.mplCanvas.axes.hold(False) self.colorbar = None mySplitter.addWidget(self.mplCanvas) controls = qtw.QGroupBox() controls.setLayout(qtw.QGridLayout()) subLayout = controls.layout() row = 0 col = 0 self.rightClickMenu = qtw.QMenu() self.axesLabelAction = self.rightClickMenu.addAction( 'Show Axis Labels') self.axesLabelAction.setCheckable(True) self.axesLabelAction.setChecked(True) self.axesLabelAction.triggered.connect(self.updateScene) self.chkExts = qtw.QCheckBox('Show Extrema') self.chkExts.setTristate(True) self.chkExts.setCheckState(qtc.Qt.PartiallyChecked) self.chkExts.stateChanged.connect(self.updateScene) subLayout.addWidget(self.chkExts, row, col) row += 1 col = 0 self.chkEdges = qtw.QCheckBox('Show Edges') self.chkEdges.setChecked(False) self.chkEdges.stateChanged.connect(self.updateScene) subLayout.addWidget(self.chkEdges, row, col) row += 1 col = 0 self.cmbVars = {} for i, name in enumerate(['X', 'Y', 'Z', 'Color']): varLabel = name + ' variable:' self.cmbVars[name] = qtw.QComboBox() dimNames = self.amsc.GetNames() self.cmbVars[name].addItems(dimNames) if name == 'Color': self.cmbVars[name].addItems(['Segment']) self.cmbVars[name].addItems(['Minimum Flow']) self.cmbVars[name].addItems(['Maximum Flow']) self.cmbVars[name].addItem('Predicted from Linear Fit') self.cmbVars[name].addItem('Residual from Linear Fit') if i < len(dimNames): self.cmbVars[name].setCurrentIndex(i) else: self.cmbVars[name].setCurrentIndex(len(dimNames) - 1) self.cmbVars[name].currentIndexChanged.connect(self.updateScene) subLayout.addWidget(qtw.QLabel(varLabel), row, col) col += 1 subLayout.addWidget(self.cmbVars[name], row, col) row += 1 col = 0 self.cmbColorMaps = qtw.QComboBox() self.cmbColorMaps.addItems(matplotlib.pyplot.colormaps()) self.cmbColorMaps.setCurrentIndex( self.cmbColorMaps.findText('coolwarm')) self.cmbColorMaps.currentIndexChanged.connect(self.updateScene) subLayout.addWidget(qtw.QLabel('Colormap'), row, col) col += 1 subLayout.addWidget(self.cmbColorMaps, row, col) mySplitter.addWidget(controls) self.modelsChanged() self.updateScene() def sizeHint(self): """ This property holds the recommended size for the widget. If the value of this property is an invalid size, no size is recommended. The default implementation of PySide.QtGui.QWidget.sizeHint() returns an invalid size if there is no layout for this widget, and returns the layout's preferred size otherwise. (Copied from base class text) """ return qtc.QSize(300, 600) def selectionChanged(self): """ An event handler triggered when the user changes the selection of the data. """ self.updateScene() def persistenceChanged(self): """ An event handler triggered when the user changes the persistence setting of the data. """ self.modelsChanged() def modelsChanged(self): """ An event handler triggered when the user requests a new set of local models. """ enabled = self.amsc.FitsSynced() for cmb in self.cmbVars.values(): for i in range(cmb.count()): if 'Predicted' in cmb.itemText( i) or 'Residual' in cmb.itemText(i): item = cmb.model().item(i, 0) if enabled: item.setFlags(qtc.Qt.ItemIsSelectable | qtc.Qt.ItemIsEnabled) else: item.setFlags(qtc.Qt.NoItemFlags) ## If this cmb is currently displaying fit information, then change it ## to display the output dimension if not enabled and ( 'Predicted' in cmb.currentText() \ or 'Residual' in cmb.currentText()): cmb.setCurrentIndex(self.amsc.GetDimensionality()) self.updateScene() def updateScene(self): """ A method for drawing the scene of this view. """ fontSize = 24 smallFontSize = 20 rows = self.amsc.GetSelectedIndices() names = self.amsc.GetNames() self.mplCanvas.axes.clear() myColormap = colors.cm.get_cmap(self.cmbColorMaps.currentText()) if len(rows) == 0: rows = list(range(self.amsc.GetSampleSize())) allValues = {} values = {} mins = {} maxs = {} minValues = {} maxValues = {} minIdxs = [] maxIdxs = [] minDrawParams = { 'c': colors.minBrushColor.name(), 'marker': 'v', 's': 160, 'zorder': 3, 'edgecolors': colors.minPenColor.name() } maxDrawParams = { 'c': colors.maxBrushColor.name(), 'marker': '^', 's': 160, 'zorder': 3, 'edgecolors': colors.maxPenColor.name() } if self.chkExts.checkState() == qtc.Qt.Checked \ or self.chkExts.checkState() == qtc.Qt.PartiallyChecked: minMaxPairs = self.amsc.GetSelectedSegments() for extPair in minMaxPairs: minIdxs.append(extPair[0]) maxIdxs.append(extPair[1]) extIdxs = self.amsc.GetSelectedExtrema() for extIdx in extIdxs: if self.amsc.GetClassification(extIdx) == 'maximum': maxIdxs.append(extIdx) elif self.amsc.GetClassification(extIdx) == 'minimum': minIdxs.append(extIdx) ## Remove any duplicates minIdxs = list(set(minIdxs)) maxIdxs = list(set(maxIdxs)) if len(minIdxs) == 0 and len(maxIdxs) == 0: minMaxPairs = self.amsc.GetCurrentLabels() for extPair in minMaxPairs: minIdxs.append(extPair[0]) maxIdxs.append(extPair[1]) ## Remove the extrema from the list of regular points that will be ## rendered for extIdx in minIdxs + maxIdxs: if extIdx in rows: rows.remove(extIdx) specialColorKeywords = ['Segment', 'Minimum Flow', 'Maximum Flow'] string_type = '|U7' #If python 2 compatibility is needed, use '|S7' for key, cmb in self.cmbVars.items(): if cmb.currentText() == 'Predicted from Linear Fit': allValues[key] = self.amsc.PredictY(None) mins[key] = min(allValues[key]) maxs[key] = max(allValues[key]) minValues[key] = allValues[key][minIdxs] maxValues[key] = allValues[key][maxIdxs] values[key] = self.amsc.PredictY(rows) elif cmb.currentText() == 'Residual from Linear Fit': allValues[key] = self.amsc.Residuals(None) mins[key] = min(allValues[key]) maxs[key] = max(allValues[key]) minValues[key] = allValues[key][minIdxs] maxValues[key] = allValues[key][maxIdxs] values[key] = self.amsc.Residuals(rows) elif cmb.currentText() == 'Segment': colorMap = self.amsc.GetColors() partitions = self.amsc.Partitions() allValues[key] = np.zeros(self.amsc.GetSampleSize(), dtype=string_type) for extPair, items in partitions.items(): for item in items: allValues[key][item] = colorMap[extPair] values[key] = allValues[key][rows] minValues[key] = [colorMap[minIdx] for minIdx in minIdxs] maxValues[key] = [colorMap[maxIdx] for maxIdx in maxIdxs] elif cmb.currentText() == 'Maximum Flow': colorMap = self.amsc.GetColors() partitions = self.amsc.Partitions() allValues[key] = np.zeros(self.amsc.GetSampleSize(), dtype=string_type) for extPair, items in partitions.items(): for item in items: allValues[key][item] = colorMap[extPair[1]] values[key] = allValues[key][rows] minValues[key] = [colorMap[minIdx] for minIdx in minIdxs] maxValues[key] = [colorMap[maxIdx] for maxIdx in maxIdxs] elif cmb.currentText() == 'Minimum Flow': colorMap = self.amsc.GetColors() partitions = self.amsc.Partitions() allValues[key] = np.zeros(self.amsc.GetSampleSize(), dtype=string_type) for extPair, items in partitions.items(): for item in items: allValues[key][item] = colorMap[extPair[0]] values[key] = allValues[key][rows] minValues[key] = [colorMap[minIdx] for minIdx in minIdxs] maxValues[key] = [colorMap[maxIdx] for maxIdx in maxIdxs] else: col = names.index(cmb.currentText()) if col == len(names) - 1: allValues[key] = self.amsc.GetY(None) mins[key] = min(allValues[key]) maxs[key] = max(allValues[key]) minValues[key] = allValues[key][minIdxs] maxValues[key] = allValues[key][maxIdxs] values[key] = self.amsc.GetY(rows) else: allValues[key] = self.amsc.GetX(None, col) mins[key] = min(allValues[key]) maxs[key] = max(allValues[key]) minValues[key] = allValues[key][minIdxs] maxValues[key] = allValues[key][maxIdxs] values[key] = self.amsc.GetX(rows, col) if self.chkEdges.isChecked(): lines = [] lineColors = [] lines2 = [] lineIdxs = [] for row in rows + minIdxs + maxIdxs: cols = self.amsc.GetNeighbors(int(row)) for col in cols: if col in rows + minIdxs + maxIdxs: if row < col: A = row B = col elif col > row: B = row A = col lineIdxs.append((A, B)) lines.append([ (allValues['X'][row], allValues['Y'][row], allValues['Z'][row]), (allValues['X'][col], allValues['Y'][col], allValues['Z'][col]) ]) if self.cmbVars['Color'].currentText( ) not in specialColorKeywords: lineColors.append( myColormap(((allValues['Color'][row] + allValues['Color'][col]) / 2. - mins['Color']) / (maxs['Color'] - mins['Color']))) elif allValues['Color'][row] == allValues['Color'][ col]: lineColors.append(allValues['Color'][row]) else: lineColors.append('#CCCCCC') lc = mpl_toolkits.mplot3d.art3d.Line3DCollection(lines, colors=lineColors, linewidths=1) self.mplCanvas.axes.add_collection(lc) self.mplCanvas.axes.hold(True) if self.cmbVars['Color'].currentText() not in specialColorKeywords: myPlot = self.mplCanvas.axes.scatter(values['X'], values['Y'], values['Z'], c=values['Color'], cmap=myColormap, vmin=mins['Color'], vmax=maxs['Color'], edgecolors='none') if self.colorbar is None: self.colorbar = self.fig.colorbar(myPlot) else: # This is intended to be a deprecated feature, but how else can we # force matplotlib to rescale the axis on the colorbar? self.colorbar.update_bruteforce(myPlot) ## Here is its replacement, but this guy will not rescale the colorbar #self.colorbar.update_normal(myPlot) self.colorbar.set_label(self.cmbVars['Color'].currentText(), size=fontSize, labelpad=10) self.colorbar.set_ticks( np.linspace(mins['Color'], maxs['Color'], 5)) self.colorbar.ax.tick_params(labelsize=smallFontSize) self.mplCanvas.axes.hold(True) if self.chkExts.checkState() == qtc.Qt.PartiallyChecked: maxValues['Color'] = colors.maxBrushColor.name() minValues['Color'] = colors.minBrushColor.name() self.mplCanvas.axes.scatter(maxValues['X'], maxValues['Y'], maxValues['Z'], c=maxValues['Color'], cmap=myColormap, marker=maxDrawParams['marker'], s=maxDrawParams['s'], zorder=maxDrawParams['zorder'], vmin=mins['Color'], vmax=maxs['Color'], edgecolors=maxDrawParams['edgecolors']) self.mplCanvas.axes.scatter(minValues['X'], minValues['Y'], minValues['Z'], c=minValues['Color'], cmap=myColormap, marker=minDrawParams['marker'], s=minDrawParams['s'], zorder=minDrawParams['zorder'], vmin=mins['Color'], vmax=maxs['Color'], edgecolors=minDrawParams['edgecolors']) else: myPlot = self.mplCanvas.axes.scatter(values['X'], values['Y'], values['Z'], c=values['Color'], edgecolors='none') self.mplCanvas.axes.hold(True) if self.chkExts.checkState() == qtc.Qt.PartiallyChecked: maxValues['Color'] = colors.maxBrushColor.name() minValues['Color'] = colors.minBrushColor.name() self.mplCanvas.axes.scatter(maxValues['X'], maxValues['Y'], maxValues['Z'], c=maxValues['Color'], marker=maxDrawParams['marker'], s=maxDrawParams['s'], zorder=maxDrawParams['zorder'], edgecolors=maxDrawParams['edgecolors']) self.mplCanvas.axes.scatter(minValues['X'], minValues['Y'], minValues['Z'], c=minValues['Color'], marker=minDrawParams['marker'], s=minDrawParams['s'], zorder=minDrawParams['zorder'], edgecolors=minDrawParams['edgecolors']) if self.axesLabelAction.isChecked(): self.mplCanvas.axes.set_xlabel(self.cmbVars['X'].currentText(), size=fontSize, labelpad=20) self.mplCanvas.axes.set_ylabel(self.cmbVars['Y'].currentText(), size=fontSize, labelpad=20) self.mplCanvas.axes.set_zlabel(self.cmbVars['Z'].currentText(), size=fontSize, labelpad=20) #Doesn't do anything self.mplCanvas.axes.set_axisbelow(True) ticks = np.linspace(mins['X'], maxs['X'], 3) self.mplCanvas.axes.set_xticks(ticks) self.mplCanvas.axes.set_xlim([ticks[0], ticks[-1]]) ticks = np.linspace(mins['Y'], maxs['Y'], 3) self.mplCanvas.axes.set_yticks(ticks) self.mplCanvas.axes.set_ylim([ticks[0], ticks[-1]]) ticks = np.linspace(mins['Z'], maxs['Z'], 3) # ticks = np.linspace(0, 2, 5) self.mplCanvas.axes.set_zticks(ticks) self.mplCanvas.axes.set_zlim([ticks[0], ticks[-1]]) self.mplCanvas.axes.xaxis.set_major_formatter( matplotlib.ticker.FormatStrFormatter('%.2g')) self.mplCanvas.axes.yaxis.set_major_formatter( matplotlib.ticker.FormatStrFormatter('%.2g')) self.mplCanvas.axes.zaxis.set_major_formatter( matplotlib.ticker.FormatStrFormatter('%.2g')) for label in (self.mplCanvas.axes.get_xticklabels() + self.mplCanvas.axes.get_yticklabels() + self.mplCanvas.axes.get_zticklabels()): label.set_fontsize(smallFontSize) self.mplCanvas.axes.hold(False) self.mplCanvas.draw() def test(self): """ A test function for performing operations on this class that need to be automatically tested such as simulating mouse and keyboard events, and other internal operations. For this class in particular, we will test: - Toggling the edges on and off and updating the display in both cases. - Toggling all three states of the extrema display. - Changing the color attribute to cycle through each of the labeled variables: Segment, Minimum Flow, Maximum Flow, Local fit value, and local fit error/residual. - Resizing the display - Subselecting the data that is displayed. @ In, None @ Out, None """ self.amsc.ClearSelection() self.axesLabelAction.setChecked(True) self.chkExts.setCheckState(qtc.Qt.Checked) self.chkEdges.setChecked(True) self.cmbVars['Color'].setCurrentIndex(self.cmbVars['Color'].count() - 5) self.updateScene() self.axesLabelAction.setChecked(False) self.chkExts.setCheckState(qtc.Qt.Unchecked) self.chkEdges.setChecked(True) self.cmbVars['Color'].setCurrentIndex(self.cmbVars['Color'].count() - 4) self.updateScene() self.chkExts.setCheckState(qtc.Qt.PartiallyChecked) self.cmbVars['Color'].setCurrentIndex(self.cmbVars['Color'].count() - 3) self.updateScene() self.cmbVars['Color'].setCurrentIndex(self.cmbVars['Color'].count() - 2) self.updateScene() self.cmbVars['Color'].setCurrentIndex(self.cmbVars['Color'].count() - 1) self.updateScene() self.resizeEvent(qtg.QResizeEvent(qtc.QSize(1, 1), qtc.QSize(100, 100))) pair = list(self.amsc.GetCurrentLabels())[0] self.amsc.SetSelection([pair, pair[0], pair[1]]) self.updateScene() super(ScatterView3D, self).test()
class ImageWindow(QtGui.QWidget): data = [] def __init__(self, Parent=None): super(ImageWindow, self).__init__(Parent) self.setFixedSize(layout_params['image'][0], layout_params['image'][1]) self.populate() # Default od and count limits self.odLimits = [[0, 3]] * KRBCAM_N_PLOT_SETTINGS self.countLimits = [[500, 2000]] * KRBCAM_N_PLOT_SETTINGS # [Number of acquisitions, number of kinetics frames per acquisition] self.gAcqLoopLength = 0 self.gFKSeriesLength = 0 self.odFrames = [0] * KRBCAM_N_PLOT_SETTINGS # Frame select state self.frameSelectState = [[(None, None), (None, None), (None, None)]] * KRBCAM_N_PLOT_SETTINGS # Colormaps self.colors = KRbCustomColors() self.cmaps = [ self.colors.whiteJet, self.colors.whiteMagma, self.colors.whitePlasma, plt.cm.jet ] # Set default values self.setDefaultValues() def setFrameSelectState(self, fss): self.frameSelectState = fss a = self.gAcqLoopLength fk = self.gFKSeriesLength for f, w in zip(fss[0], self.frameSelectArray): w.setCurrentIndex(f[0] * fk + f[1]) def getFrameSelectState(self): return self.frameSelectState def imageRotated(self, rotate): if rotate: self.colorbarOrientation = 'vertical' else: self.colorbarOrientation = 'horizontal' def setDefaultValues(self): self.minEdit.setText(str(self.odLimits[0][0])) self.maxEdit.setText(str(self.odLimits[0][1])) def resetComboBoxes(self, numKin, acqLength): for widget in self.frameSelectArray: widget.clear() for i in range(acqLength): for j in range(numKin): widget.addItem("{},{}".format(i, j)) widget.setCurrentIndex(0) def controlComboBoxes(self, numKin, acqLength): if self.gAcqLoopLength != acqLength or self.gFKSeriesLength != numKin: self.gAcqLoopLength = acqLength self.gFKSeriesLength = numKin self.resetComboBoxes(numKin, acqLength) def getComboBoxState(self): arr = [] for widget in self.frameSelectArray: text = widget.currentText() arr.append((int(text.split(',')[0]), int(text.split(',')[1]))) return arr def settingChanged(self): setting = self.settingSelect.currentIndex() config = self.frameSelectState[setting] if config[0][0] == None: self.resetComboBoxes(self.gFKSeriesLength, self.gAcqLoopLength) config = self.getComboBoxState() for i in range(len(config)): (i0, i1) = config[i] widget = self.frameSelectArray[i] index = i0 * self.gFKSeriesLength + i1 widget.setCurrentIndex(index) self.displayData() # Populate GUI # self.displayData is a listener for any state change of the buttons def populate(self): self.figure = Figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) self.settingLabel = QtGui.QLabel("Setting") self.settingSelect = QtGui.QComboBox(self) self.settingSelect.addItem("0") self.settingSelect.addItem("1") self.settingSelect.setToolTip("K: 0; Rb: 1") self.settingSelect.currentIndexChanged.connect(self.settingChanged) self.frameLabel = QtGui.QLabel("Frame") self.frameSelect = QtGui.QComboBox(self) self.frameSelect.addItem("OD") self.frameSelect.addItem("Shadow") self.frameSelect.addItem("Light") self.frameSelect.addItem("Dark") self.frameSelect.currentIndexChanged.connect(self.displayData) self.shadowFrameLabel = QtGui.QLabel("Shadow") self.shadowFrameSelect = QtGui.QComboBox(self) self.shadowFrameSelect.setToolTip("K: (0,0); Rb: (0,1)") self.shadowFrameSelect.currentIndexChanged.connect(self.displayData) self.lightFrameLabel = QtGui.QLabel("Light") self.lightFrameSelect = QtGui.QComboBox(self) self.lightFrameSelect.setToolTip("K: (1,0); Rb: (1,1)") self.lightFrameSelect.currentIndexChanged.connect(self.displayData) self.darkFrameLabel = QtGui.QLabel("Dark") self.darkFrameSelect = QtGui.QComboBox(self) self.darkFrameSelect.setToolTip("K: (2,0); Rb: (2,1)") self.darkFrameSelect.currentIndexChanged.connect(self.displayData) self.frameSelectArray = [ self.shadowFrameSelect, self.lightFrameSelect, self.darkFrameSelect ] self.colorLabel = QtGui.QLabel("Colormap", self) self.colorSelect = QtGui.QComboBox(self) self.colorSelect.addItem("White Jet") self.colorSelect.addItem("White Magma") self.colorSelect.addItem("White Plasma") self.colorSelect.addItem("Jet") self.colorSelect.currentIndexChanged.connect(self.displayData) self.minLabel = QtGui.QLabel("Min", self) self.minEdit = QtGui.QLineEdit(self) self.maxLabel = QtGui.QLabel("Max", self) self.maxEdit = QtGui.QLineEdit(self) self.maxEdit.returnPressed.connect(self.validateLimits) self.minEdit.returnPressed.connect(self.validateLimits) self.autoscaleButton = QtGui.QPushButton("Autoscale", self) self.autoscaleButton.clicked.connect(self.autoscale) self.spacer = QtGui.QSpacerItem(1, 1) self.layout = QtGui.QGridLayout() self.layout.addWidget(self.toolbar, 0, 0, 1, 6) self.layout.addWidget(self.canvas, 1, 0, 6, 6) row = 8 self.layout.addWidget(self.settingLabel, row, 0) self.layout.addWidget(self.settingSelect, row, 1) row += 1 self.layout.addWidget(self.frameLabel, row, 0) self.layout.addWidget(self.frameSelect, row, 1) row += 1 self.layout.addWidget(self.shadowFrameLabel, row, 0) self.layout.addWidget(self.shadowFrameSelect, row, 1) row += 1 self.layout.addWidget(self.lightFrameLabel, row, 0) self.layout.addWidget(self.lightFrameSelect, row, 1) row += 1 self.layout.addWidget(self.darkFrameLabel, row, 0) self.layout.addWidget(self.darkFrameSelect, row, 1) row += 1 row = 8 self.layout.addWidget(self.colorLabel, row, 4) self.layout.addWidget(self.colorSelect, row, 5) row += 1 self.layout.addWidget(self.minLabel, row, 4) self.layout.addWidget(self.minEdit, row, 5) row += 1 self.layout.addWidget(self.maxLabel, row, 4) self.layout.addWidget(self.maxEdit, row, 5) row += 1 self.layout.addWidget(self.autoscaleButton, row, 4, 1, 2) # Try to make the layout look nice for i in range(4): self.layout.setColumnStretch(i, 1) self.setLayout(self.layout) def autoscale(self): (setting, frame) = self.getConfig() if frame == 0: low = np.percentile(self.odFrames[setting], KRBCAM_AUTOSCALE_PERCENTILES[0]) high = np.percentile(self.odFrames[setting], KRBCAM_AUTOSCALE_PERCENTILES[1]) else: (i0, i1) = self.getComboBoxState()[frame - 1] low = np.percentile(self.data[i0][i1], KRBCAM_AUTOSCALE_PERCENTILES[0]) high = np.percentile(self.data[i0][i1], KRBCAM_AUTOSCALE_PERCENTILES[1]) self.minEdit.setText(str(low)) self.maxEdit.setText(str(high)) self.validateLimits() # Display the data! def displayData(self): if self.data: try: # Take the button states and determine what image the user wants to see (setting, frame) = self.getConfig() # If this fails, it's usually because the combo boxes are not setup yet # This is okay, for example it happens when the setting is initially changed # In this case, just return nothing until things are okay except: return # Then try to plot the image try: # Get the correct colorbar limits if frame == 0: lims = self.odLimits[setting] else: lims = self.countLimits[setting] # Update the text boxes self.minEdit.setText(str(lims[0])) self.maxEdit.setText(str(lims[1])) if frame == 0: self.odFrames[setting] = self.calcOD( self.getComboBoxState()) self.plot(self.odFrames[setting], lims[0], lims[1]) else: (i0, i1) = self.getComboBoxState()[frame - 1] self.plot(self.data[i0][i1], lims[0], lims[1]) # AttributeError will occur if no data collected, since # then self.data is undefined except Exception as e: print e def setData(self, data, kinFrames, acqLength): self.controlComboBoxes(kinFrames, acqLength) self.data = self.processData(data) # Validate the entered values in the min and max boxes def validateLimits(self): # Try to cast to int try: max_entry = float(self.maxEdit.text()) min_entry = float(self.minEdit.text()) (setting, frame) = self.getConfig() if max_entry < min_entry: temp = min_entry min_entry = max_entry max_entry = temp if frame != 0: max_entry = int(max_entry) min_entry = int(min_entry) # Update our od limits or count limits if frame == 0: if min_entry == max_entry: max_entry += 0.1 # Avoid an issue with values pointing to each other self.odLimits[setting] = [min_entry, max_entry] else: if min_entry == max_entry: max_entry += 1 # Avoid an issue with values pointing to each other self.countLimits[setting] = [min_entry, max_entry] # Update the image shown on the screen self.displayData() except: msgBox = QtGui.QMessageBox() msgBox.setText("Invalid entry for image display limits.") msgBox.setInformativeText("Please check entry (must be integer).") msgBox.setStandardButtons(QtGui.QMessageBox.Ok) msgBox.exec_() # Determine which image to display def getConfig(self): config = self.getComboBoxState() setting = self.settingSelect.currentIndex() if self.frameSelectState[setting] != config: self.frameSelectState[setting] = config self.odFrames[setting] = self.calcOD(config) frame = self.frameSelect.currentIndex() return (setting, frame) def calcOD(self, config): (s0, s1) = config[0] (l0, l1) = config[1] (d0, d1) = config[2] shadow = self.data[s0][s1] light = self.data[l0][l1] dark = self.data[d0][d1] with np.errstate(divide='ignore', invalid='ignore'): od = np.log( (light - dark).astype(float) / (shadow - dark).astype(float)) od += (light - shadow) / float(KRBCAM_C_SAT) od[np.isnan(od)] = 0 od[np.isinf(od)] = 0 od[od > KRBCAM_OD_MAX] = KRBCAM_OD_MAX return od # Separate images, get OD image def processData(self, data): out = [] # Data comes in as an array sorted by FK index # with acquisition loop frames concatenated # # We want to change the indices for convenience for i in range(self.gAcqLoopLength): arr = [] # Loop through kinetics frames # and pull out the i-th acquisition loop frame for j in range(self.gFKSeriesLength): x = data[j] (length, width) = np.shape(x) length /= self.gAcqLoopLength arr.append(x[i * length:(i + 1) * length]) out.append(arr) # Now out should be a 2d array of data # First index is acquisition loop frame # Second index is FK frame return out # Plot the data def plot(self, data, vmin, vmax): # Clear plot self.figure.clear() # Plot the data ax = self.figure.add_subplot(111) color_index = self.colorSelect.currentIndex() im = ax.imshow(data, vmin=vmin, vmax=vmax, cmap=self.cmaps[color_index]) # Add a horizontal colorbar self.figure.colorbar(im, orientation=self.colorbarOrientation) # Need to do the following to get the z data to show up in the toolbar numrows, numcols = np.shape(data) def format_coord(x, y): col = int(x + 0.5) row = int(y + 0.5) if col >= 0 and col < numcols and row >= 0 and row < numrows: z = data[row, col] return '({:},{:}), z={:.2f}'.format(int(x), int(y), z) else: return 'x=%1.4f, y=%1.4f' % (x, y) ax.format_coord = format_coord # Update the plot self.canvas.draw()
def dotplot(df, column='Adjusted P-value', title='', cutoff=0.05, top_term=10, sizes=None, norm=None, legend=True, figsize=(6, 5.5), cmap='RdBu_r', ofname=None, **kwargs): """Visualize enrichr results. :param df: GSEApy DataFrame results. :param column: which column of DataFrame to show. Default: Adjusted P-value :param title: figure title :param cutoff: p-adjust cut-off. :param top_term: number of enriched terms to show. :param ascending: bool, the order of y axis. :param sizes: tuple, (min, max) scatter size. Not functional for now :param norm: maplotlib.colors.Normalize object. :param legend: bool, whether to show legend. :param figsize: tuple, figure size. :param cmap: matplotlib colormap :param ofname: output file name. If None, don't save figure """ colname = column # sorting the dataframe for better visualization if colname in ['Adjusted P-value', 'P-value']: # check if any values in `df[colname]` can't be coerced to floats can_be_coerced = df[colname].map(isfloat) if np.sum(~can_be_coerced) > 0: raise ValueError( 'some value in %s could not be typecast to `float`' % colname) else: df.loc[:, colname] = df[colname].map(float) df = df[df[colname] <= cutoff] if len(df) < 1: msg = "Warning: No enrich terms when cutoff = %s" % cutoff return msg df = df.assign(logAP=lambda x: -x[colname].apply(np.log10)) colname = 'logAP' df = df.sort_values(by=colname).iloc[-top_term:, :] # temp = df['Overlap'].str.split("/", expand=True).astype(int) df = df.assign(Hits=temp.iloc[:, 0], Background=temp.iloc[:, 1]) df = df.assign(Hits_ratio=lambda x: x.Hits / x.Background) # x axis values x = df.loc[:, colname].values combined_score = df['Combined Score'].round().astype('int') # y axis index and values y = [i for i in range(0, len(df))] ylabels = df['Term'].values # Normalise to [0,1] # b = (df['Count'] - df['Count'].min())/ np.ptp(df['Count']) # area = 100 * b # control the size of scatter and legend marker levels = numbers = np.sort(df.Hits.unique()) if norm is None: norm = Normalize() elif isinstance(norm, tuple): norm = Normalize(*norm) elif not isinstance(norm, Normalize): err = ("``size_norm`` must be None, tuple, " "or Normalize object.") raise ValueError(err) min_width, max_width = np.r_[20, 100] * plt.rcParams["lines.linewidth"] norm.clip = True if not norm.scaled(): norm(np.asarray(numbers)) size_limits = norm.vmin, norm.vmax scl = norm(numbers) widths = np.asarray(min_width + scl * (max_width - min_width)) if scl.mask.any(): widths[scl.mask] = 0 sizes = dict(zip(levels, widths)) df['sizes'] = df.Hits.map(sizes) area = df['sizes'].values # creat scatter plot if hasattr(sys, 'ps1') and (ofname is None): # working inside python console, show figure fig, ax = plt.subplots(figsize=figsize) else: # If working on commandline, don't show figure fig = Figure(figsize=figsize) canvas = FigureCanvas(fig) ax = fig.add_subplot(111) vmin = np.percentile(combined_score.min(), 2) vmax = np.percentile(combined_score.max(), 98) sc = ax.scatter(x=x, y=y, s=area, edgecolors='face', c=combined_score, cmap=cmap, vmin=vmin, vmax=vmax) if column in ['Adjusted P-value', 'P-value']: xlabel = "-log$_{10}$(%s)" % column else: xlabel = column ax.set_xlabel(xlabel, fontsize=14, fontweight='bold') ax.yaxis.set_major_locator(plt.FixedLocator(y)) ax.yaxis.set_major_formatter(plt.FixedFormatter(ylabels)) ax.set_yticklabels(ylabels, fontsize=16) # ax.set_ylim([-1, len(df)]) ax.grid() # colorbar cax = fig.add_axes([0.95, 0.20, 0.03, 0.22]) cbar = fig.colorbar( sc, cax=cax, ) cbar.ax.tick_params(right=True) cbar.ax.set_title('Combined\nScore', loc='left', fontsize=12) # for terms less than 3 if len(df) >= 3: # find the index of the closest value to the median idx = [ area.argmax(), np.abs(area - area.mean()).argmin(), area.argmin() ] idx = unique(idx) else: idx = df.index.values label = df.iloc[idx, df.columns.get_loc('Hits')] if legend: handles, _ = ax.get_legend_handles_labels() legend_markers = [] for ix in idx: legend_markers.append(ax.scatter([], [], s=area[ix], c='b')) # artist = ax.scatter([], [], s=size_levels,) ax.legend(legend_markers, label, title='Hits') ax.set_title(title, fontsize=20, fontweight='bold') if ofname is not None: # canvas.print_figure(ofname, bbox_inches='tight', dpi=300) fig.savefig(ofname, bbox_inches='tight', dpi=300) return return ax
def _plot_stcov_fired(self): t, y = self.curve_manager.interactive_curve.current_data() y *= 1e6 t_stamp = t[0].mean() t = (t - t[0]) * 1e3 dt = t[1] - t[0] # shoot for minimum of 1 ms per frame skip = 1 while dt * skip <= 1: skip += 1 N = int(self.n_lags / (dt * skip)) # print self.n_lags, dt, N, skip y = y - y.mean(axis=1, keepdims=1) N = min(len(t) - 1, N) Ct = np.empty((N, len(y), len(y)), 'd') T = len(t) for n in tqdm(range(0, skip * N, skip), desc='Computing S-T functions', leave=True): Ct_ = np.einsum('ik,jk->ij', y[:, :T - n], y[:, n:]) Ct[n // skip] = Ct_ / (T - n) if self.norm_kernel: nrm = np.sqrt(Ct[0].diagonal()) Ct /= np.outer(nrm, nrm) chan_map = self.chan_map # stcov is a time-lagged sequence of 2D autocovariance (lag-y by lag-x) stcov = list() for Ct_ in tqdm(Ct, desc='Centering S-T kernels'): stcov.append(spatial_autocovariance(Ct_, chan_map, mean=True)) stcov = np.array(stcov) y, x = stcov.shape[-2:] midx = int(x / 2) xx = (np.arange(x) - midx) * chan_map.dx midy = int(y / 2) yy = (np.arange(y) - midy) * chan_map.dy for n in range(N): stcov[n, midy, midx] = np.mean(Ct[n].diagonal()) #fig, ax = subplots(figsize=(6, 5)) fig = Figure(figsize=(6, 8)) ax = subplot2grid(fig, (2, 2), (0, 0), colspan=2) mx = np.nanmax(np.abs(stcov)) im = ax.imshow(stcov[0], cmap='bwr', clim=(-mx, mx), extent=[xx[0], xx[-1], yy[0], yy[-1]]) ax.set_xlabel('Distance X (mm)') ax.set_ylabel('Distance Y (mm)') ax.set_title('Spatiotemporal kernel ~ t={0:.2f} sec'.format(t_stamp)) cb = fig.colorbar(im) if self.norm_kernel: cb.set_label('Autocorrelation map') else: cb.set_label('Autocovariance map') # Marginal over y ax2 = subplot2grid(fig, (2, 2), (1, 0)) st_xt = np.nanmean(stcov, axis=1) mx = np.nanmax(np.abs(st_xt)) im = ax2.imshow(st_xt, extent=[xx[0], xx[-1], t[N * skip], 0], clim=(-mx, mx), cmap='bwr', origin='upper') ax2.axis('auto') fig.colorbar(im, ax=ax2) ax2.set_xlabel('Mean X-transect (mm)') ax2.set_ylabel('Lag (ms)') # Marginal over x ax3 = subplot2grid(fig, (2, 2), (1, 1)) st_yt = np.nanmean(stcov, axis=2) mx = np.nanmax(np.abs(st_yt)) im = ax3.imshow(st_yt, extent=[yy[0], yy[-1], t[N * skip], 0], clim=(-mx, mx), cmap='bwr', origin='upper') ax3.axis('auto') fig.colorbar(im, ax=ax3) ax3.set_xlabel('Mean Y-transect (mm)') ax3.set_ylabel('Lag (ms)') splot = MultiframeSavesFigure(fig, stcov, mode_name='lag (ms)', frame_index=t[0:N * skip:skip]) splot.edit_traits() fig.tight_layout() fig.canvas.draw_idle() if not hasattr(self, '_kernel_plots'): self._kernel_plots = [splot] else: self._kernel_plots.append(splot)
ax.set_ylim(-70, 70) ax.set_parallels(-20, 60) ax.set_center(180, 0) ax.plot(ra, dec, '*') ax.axhline(-20) ax.axvline(140) ax.plot(*pix2tri(8, [104, 105, 106]).reshape(-1, 2).T, color='k') ra = np.random.uniform(size=1000, low=30, high=60) dec = np.random.uniform(size=1000, low=-50, high=50) ax.histmap(ra, dec, nside=32, weights=ra * dec, mean=True) ra = np.random.uniform(size=1000, low=120, high=160) dec = np.random.uniform(size=1000, low=-50, high=50) ax.histcontour(ra, dec, weights=ra * dec, nside=32, mean=True) ax.tick_params(labelright=True, labeltop=True) ax.tripcolor(ra, dec, ra * dec) fig.colorbar(ax._gci()) ra = np.random.uniform(size=1000, low=180, high=200) dec = np.random.uniform(size=1000, low=-50, high=50) ax.set_meridian_grid(30) ax.set_parallel_grid(30) ax.grid() canvas = FigureCanvasAgg(fig) fig.savefig('xxx.png')
class Scan3DHistoWidget(AbstractScanHistoWidget): class PlotType: LINES = 0 SURFACE = 1 def __init__(self, workspace_units_to_cm, image_height=645, image_width=860, type=PlotType.LINES): super(Scan3DHistoWidget, self).__init__(workspace_units_to_cm) self.figure = Figure(figsize=(image_height, image_width)) self.figure.patch.set_facecolor('white') self.axis = self.figure.add_subplot(111, projection='3d') self.axis.set_title("") self.axis.clear() self.colorbar = None self.plot_canvas = FigureCanvasQTAgg(self.figure) layout = QVBoxLayout() layout.addWidget(self.plot_canvas) self.setLayout(layout) self.xx = None self.yy = None self.zz = None self.title = "" self.xlabel = "" self.ylabel = "" self.zlabel = "" self.__type = type self.__cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.5) def clear(self): self.reset_plot() try: self.plot_canvas.draw() except: pass def reset_plot(self): self.xx = None self.yy = None self.zz = None self.axis.set_title("") self.axis.clear() def set_labels(self, title, xlabel, ylabel, zlabel): self.title = title self.xlabel = xlabel self.ylabel = ylabel self.zlabel = zlabel def restore_labels(self): self.axis.set_title(self.title) self.axis.set_xlabel(self.xlabel) self.axis.set_ylabel(self.ylabel) self.axis.set_zlabel(self.zlabel) def set_xrange(self, xrange): self.xx = xrange def plot_histo(self, beam, col, nbins=100, title="", xtitle="", ytitle="", histo_index=0, scan_variable_name="Variable", scan_variable_value=0, offset=0.0, xrange=None, show_reference=True, add_labels=True, has_colormap=True, colormap=cm.rainbow): factor = ShadowPlot.get_factor(col, conv=self.workspace_units_to_cm) if histo_index == 0 and xrange is None: ticket = beam._beam.histo1(col, xrange=None, nbins=nbins, nolost=1, ref=23) fwhm = ticket['fwhm'] xrange = ticket['xrange'] centroid = xrange[0] + (xrange[1] - xrange[0]) * 0.5 if not fwhm is None: xrange = [centroid - 2 * fwhm, centroid + 2 * fwhm] ticket = beam._beam.histo1(col, xrange=xrange, nbins=nbins, nolost=1, ref=23) if not ytitle is None: ytitle = ytitle + ' weighted by ' + ShadowPlot.get_shadow_label(23) histogram = ticket['histogram_path'] bins = ticket['bin_path'] * factor histogram_stats = ticket['histogram'] bins_stats = ticket['bin_center'] fwhm = ticket['fwhm'] sigma = get_sigma(histogram_stats, bins_stats) * factor fwhm = sigma * 2.35 if fwhm is None else fwhm * factor peak_intensity = numpy.average(histogram_stats[numpy.where( histogram_stats >= numpy.max(histogram_stats) * 0.85)]) integral_intensity = numpy.sum(histogram_stats) rcParams['axes.formatter.useoffset'] = 'False' self.set_xrange(bins) self.set_labels(title=title, xlabel=xtitle, ylabel=scan_variable_name, zlabel=ytitle) self.add_histo(scan_variable_value, histogram, has_colormap, colormap, histo_index) return HistogramData(histogram_stats, bins_stats, 0.0, xrange, fwhm, sigma, peak_intensity, integral_intensity) def add_histo(self, scan_value, intensities, has_colormap, colormap, histo_index): if self.xx is None: raise ValueError("Initialize X range first") if self.xx.shape != intensities.shape: raise ValueError("Given Histogram has a different binning") if isinstance(scan_value, str): self.yy = numpy.array([1]) if self.yy is None else numpy.append( self.yy, len(self.yy) + 1) else: self.yy = numpy.array([scan_value ]) if self.yy is None else numpy.append( self.yy, scan_value) if self.zz is None: self.zz = numpy.array([intensities]) else: self.zz = numpy.append(self.zz, intensities) self.axis.clear() self.restore_labels() x_to_plot, y_to_plot = numpy.meshgrid(self.xx, self.yy) zz_to_plot = self.zz.reshape(len(self.yy), len(self.xx)) if self.__type == Scan3DHistoWidget.PlotType.SURFACE: if has_colormap: self.axis.plot_surface(x_to_plot, y_to_plot, zz_to_plot, rstride=1, cstride=1, cmap=colormap, linewidth=0.5, antialiased=True) else: self.axis.plot_surface(x_to_plot, y_to_plot, zz_to_plot, rstride=1, cstride=1, color=self.__cc('black'), linewidth=0.5, antialiased=True) elif self.__type == Scan3DHistoWidget.PlotType.LINES: if has_colormap: self.plot_lines_colormap(x_to_plot, y_to_plot, zz_to_plot, colormap, histo_index) else: self.plot_lines_black(x_to_plot, zz_to_plot) xmin = numpy.min(self.xx) xmax = numpy.max(self.xx) ymin = numpy.min(self.yy) ymax = numpy.max(self.yy) zmin = numpy.min(self.zz) zmax = numpy.max(self.zz) self.axis.set_xlim(xmin, xmax) self.axis.set_ylim(ymin, ymax) self.axis.set_zlim(zmin, zmax) self.axis.mouse_init() try: self.plot_canvas.draw() except: pass def add_empty_curve(self, histo_data): pass def plot_lines_black(self, X, Z): verts = [] for i in range(len(self.yy)): verts.append(list(zip(X[i], Z[i, :]))) self.axis.add_collection3d(LineCollection(verts, colors=[self.__cc('black')]), zs=self.yy, zdir='y') def plot_lines_colormap(self, X, Y, Z, colormap, histo_index): import matplotlib.pyplot as plt # Set normalization to the same values for all plots norm = plt.Normalize(numpy.min(self.zz), numpy.max(self.zz)) # Check sizes to loop always over the smallest dimension n, m = Z.shape if n > m: X = X.T Y = Y.T Z = Z.T m, n = n, m transparent_colormap = colormap(numpy.arange(colormap.N)) transparent_colormap[:, -1] = 0.5 * numpy.ones(colormap.N) transparent_colormap = ListedColormap(transparent_colormap) for j in range(n): # reshape the X,Z into pairs points = numpy.array([X[j, :], Z[j, :]]).T.reshape(-1, 1, 2) segments = numpy.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap=transparent_colormap, norm=norm) # Set the values used for colormapping lc.set_array((Z[j, 1:] + Z[j, :-1]) / 2) lc.set_linewidth( 2 ) # set linewidth a little larger to see properly the colormap variation self.axis.add_collection3d(lc, zs=(Y[j, 1:] + Y[j, :-1]) / 2, zdir='y') # add line to axes if histo_index == 0: self.colorbar = self.figure.colorbar( lc) # add colorbar, as the normalization is the same for all, self.colorbar.update_normal(lc) self.colorbar.draw_all() self.colorbar.update_bruteforce(lc)
class MplPlotCanvas(FigureCanvas): """ Matplot plot canvas. This class implements the updating 2D image canvas. """ matplotlib.rcParams.update({'font.size': 8}) cbar_numticks = 9 def __init__(self, parent=None, dpi=100): """ Initialise the plot canvas object. This method initialises the plot canvas object, creating an empty subplot within it. """ # Create a list of ADC part for plotting self.adc = ('Coarse', 'Fine', 'Gain') # Create the figure canvas self.figure = Figure(dpi=dpi) FigureCanvas.__init__(self, self.figure) self.setParent(parent) FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) # Add the image axes to the figure self.axes = (self.figure.add_subplot(1, 3, 1), self.figure.add_subplot(1, 3, 2), self.figure.add_subplot(1, 3, 3)) self.axes[0].set_xticks([]) self.axes[0].set_yticks([]) self.axes[0].set_title(self.adc[0]) self.axes[1].set_xticks([]) self.axes[1].set_yticks([]) self.axes[1].set_title(self.adc[1]) self.axes[2].set_xticks([]) self.axes[2].set_yticks([]) self.axes[2].set_title(self.adc[2]) # Set up storage variables self.img_range = () self.img_shape = None self.img_obj = { self.adc[0]: None, self.adc[1]: None, self.adc[2]: None } self.colorbar = { self.adc[0]: None, self.adc[1]: None, self.adc[2]: None } self.bar_orient = 'horizontal' # Render an initial empty image frame tmp_img = (np.zeros( (10, 10), dtype=np.uint16), np.zeros( (10, 10), dtype=np.uint16), np.zeros((10, 10), dtype=np.uint16)) self.multi_render_frame(tmp_img, min_val=0, max_val=10) self.figure.tight_layout() def multi_render_frame(self, img_data, min_val=None, max_val=None): """ Redefine the number of plots. """ self.render_frame(img_data[0], self.axes[0], self.adc[0]) self.render_frame(img_data[1], self.axes[1], self.adc[1]) self.render_frame(img_data[2], self.axes[2], self.adc[2]) def render_frame(self, img_data, axe, adc, min_val=None, max_val=None): """ Render an image frame in the plot canvas. This method renders a scaled image and colorbar in the plot canvas. For speed, the image data is just updated if there is no change to the image shape, otherwise the axes and colorbar are redrawn. """ # If the minimum and/or maximum values are not defined, determine from the # incoming image data if min_val is None: min_val = np.amin(img_data) if max_val is None: max_val = np.amax(img_data) # If the shape of the incoming data has changed, delete the image object to force # a redraw if self.img_shape != img_data.shape: self.img_shape = img_data.shape self.img_obj.update({adc: None}) # Set the colorbar orientation dependent on the aspect ratio of the image if self.img_shape[0] < self.img_shape[1]: self.bar_orient = 'horizontal' else: self.bar_orient = 'vertical' # Remove any existing colorbar prior to subequent re-draw if self.colorbar[adc] is not None: self.colorbar[adc].remove() self.colorbar.update({adc: None}) # If no image object exists, draw one and add a colorbar if self.img_obj[adc] is None: self.img_obj[adc] = axe.imshow(img_data, interpolation='nearest', vmin=min_val, vmax=max_val, cmap='jet') axe.invert_xaxis() if self.colorbar[adc] is None: cbar_ticks = np.linspace(min_val, max_val, self.cbar_numticks, dtype=np.uint).tolist() self.colorbar[adc] = self.figure.colorbar( self.img_obj[adc], ax=axe, orientation=self.bar_orient, ticks=cbar_ticks) # Otherwise just update the image data for speed else: self.img_obj[adc].set_data(img_data) axe.draw_artist(self.img_obj[adc]) # If the range of the data changed, update the colorbar accordingly if self.img_range != (min_val, max_val): self.img_range = (min_val, max_val) cbar_ticks = np.linspace(min_val, max_val, self.cbar_numticks, dtype=np.uint).tolist() self.colorbar[adc].set_clim(min_val, max_val) self.colorbar[adc].set_ticks(cbar_ticks) self.colorbar[adc].draw_all() # Draw the frame self.draw()
class MplCanvas(FigureCanvas): _contrastChanged = QtCore.Signal() def __init__(self): # self.figure = Figure(figsize=(5, 5), dpi=100, tight_layout=True, facecolor='r') self.figure = Figure(figsize=(15, 15), tight_layout=True, facecolor="r") self.figure.patch.set_alpha(0) # transparent background self.ax = self.figure.add_subplot(111) super(MplCanvas, self).__init__(self.figure) def setData(self, data): self.data = data # self.data_range = data.max() - data.min() # self.data_min = data.min() self.data._idxChanged.connect(self.updateImage) self.data._dataChanged.connect(self.updateImage) def f_c(x, y): return "x=%.2f y=%.2f " % (x, y) self.ax.format_coord = f_c def setDisplayOptions(self, options): self.displayOptions = options if not ("cmap" in self.displayOptions): self.displayOptions["cmap"] = "cubehelix" self.cmaps = tuple({ self.displayOptions["cmap"], "gray", "afmhot", "cubehelix", "inferno" }) self.currentCmap = 1 @QtCore.Slot(int, int) def setContrast(self, valmin=None, valmax=None): if valmin is not None: self.displayOptions["vmin"] = (self.data.min() + valmin / 1000.0 * self.data.range()) if valmax is not None: self.displayOptions["vmax"] = (self.data.min() + valmax / 1000.0 * self.data.range()) # The following "if" seems required on a Mac to avoid a race condition # that causes a crash when moving the max/min sliders too quickly # beyond the value of the other. if self.displayOptions["vmax"] < self.displayOptions["vmin"]: self.displayOptions["vmax"] = self.displayOptions["vmin"] self._contrastChanged.emit() def cycleCMAP(self): self.currentCmap += 1 newmap = self.cmaps[self.currentCmap % len(self.cmaps)] self.displayOptions["cmap"] = newmap self._contrastChanged.emit() def createImage(self): self.image = self.ax.imshow(self.data.getCurrent(), **self.displayOptions) # , interpolation="none" self.cbar = self.figure.colorbar(self.image, fraction=0.045, pad=0.04) self._contrastChanged.connect(self.updateImage) self.draw() def updateImage(self): self.image.set_data(self.data.getCurrent()) self.image.set_cmap(self.displayOptions["cmap"]) if "norm" in self.displayOptions: self.image.set_norm(self.displayOptions["norm"]) self.image.set_clim(vmin=self.displayOptions["vmin"], vmax=self.displayOptions["vmax"]) self.draw() @QtCore.Slot(int) def setGamma(self, val): if val == 100: self.displayOptions["norm"] = matplotlib.colors.Normalize( vmin=self.displayOptions["vmin"], vmax=self.displayOptions["vmax"]) else: self.displayOptions["norm"] = matplotlib.colors.PowerNorm( val / 100.0, vmin=self.displayOptions["vmin"], vmax=self.displayOptions["vmax"], ) self._contrastChanged.emit()
class SpectrogramCanvas(FigureCanvas): def __init__(self, window): """Initialize spectrogram canvas graphs.""" # Initialize variables to default values. self.window = window self.samples = 100 # Number of samples to store self.fftSize = 256 # Initial FFT size just to render something in the charts self.sampleRate = 0 self.binFreq = 0 self.binCount = self.fftSize / 2 self.graphUpdateHz = 10 # Update rate of the animation self.coloredBin = None self.magnitudes = np.zeros((self.samples, self.binCount)) # Tell numpy to ignore errors like taking the log of 0 np.seterr(all='ignore') # Set up figure to hold plots self.figure = Figure(figsize=(1024, 768), dpi=72, facecolor=(1, 1, 1), edgecolor=(0, 0, 0)) # Set up 4x4 grid to hold 2 plots and colorbar gs = GridSpec(2, 2, height_ratios=[1, 2], width_ratios=[9.5, 0.5]) gs.update(left=0.075, right=0.925, bottom=0.05, top=0.95, wspace=0.05) # Set up frequency histogram bar plot self.histAx = self.figure.add_subplot(gs[0]) self.histAx.set_title('Frequency Histogram') self.histAx.set_ylabel('Intensity (decibels)') self.histAx.set_xlabel('Frequency Bin (hz)') self.histAx.set_xticks([]) self.histPlot = self.histAx.bar(np.arange(self.binCount), np.zeros(self.binCount), width=1.0, linewidth=0.0, facecolor='blue') # Set up spectrogram waterfall plot self.spectAx = self.figure.add_subplot(gs[2]) self.spectAx.set_title('Spectrogram') self.spectAx.set_ylabel('Sample Age (seconds)') self.spectAx.set_xlabel('Frequency Bin (hz)') self.spectAx.set_xticks([]) self.spectPlot = self.spectAx.imshow(self.magnitudes, aspect='auto', cmap=get_cmap('jet')) # Add formatter to translate position to age in seconds self.spectAx.yaxis.set_major_formatter( FuncFormatter(lambda x, pos: '%d' % (x * (1.0 / self.graphUpdateHz)))) # Set up spectrogram color bar cbAx = self.figure.add_subplot(gs[3]) self.figure.colorbar( self.spectPlot, cax=cbAx, use_gridspec=True, format=FuncFormatter(lambda x, pos: '%d' % (x * 100.0))) cbAx.set_ylabel('Intensity (decibels)') # Initialize canvas super(SpectrogramCanvas, self).__init__(self.figure) # Hook up mouse and animation events self.mpl_connect('motion_notify_event', self._mouseMove) self.ani = FuncAnimation(self.figure, self._update, interval=1000.0 / self.graphUpdateHz, blit=False) def updateParameters(self, fftSize, sampleRate): """Update the FFT size and sample rate parameters to redraw the charts appropriately.""" # Update variables to new values. self.fftSize = fftSize self.sampleRate = sampleRate self.binCount = self.fftSize / 2 self.binFreq = self.sampleRate / float(self.fftSize) # Remove old bar plot. for bar in self.histPlot: bar.remove() # Update data for charts. self.histPlot = self.histAx.bar(np.arange(self.binCount), np.zeros(self.binCount), width=1.0, linewidth=0.0, facecolor='blue') self.magnitudes = np.zeros((self.samples, self.binCount)) # Update frequency x axis to have 5 evenly spaced ticks from 0 to sampleRate/2. ticks = np.floor(np.linspace(0, self.binCount, 5)) labels = [ '%d hz' % i for i in np.linspace(0, self.sampleRate / 2.0, 5) ] self.histAx.set_xticks(ticks) self.histAx.set_xticklabels(labels) self.spectAx.set_xticks(ticks) self.spectAx.set_xticklabels(labels) def updateIntensityRange(self, low, high): """Adjust low and high intensity limits for histogram and spectrum axes.""" self.histAx.set_ylim(bottom=low, top=high) self.spectPlot.set_clim(low / 100.0, high / 100.0) def _mouseMove(self, event): # Update the selected frequency bin if the mouse is over a plot. # Check if sampleRate is not 0 so the status bar isn't updated if the spectrogram hasn't ever been started. if self.sampleRate != 0 and (event.inaxes == self.histAx or event.inaxes == self.spectAx): bin = int(event.xdata) self.window.updateStatus('Frequency bin %d: %.0f hz to %.0f hz' % (bin, bin * self.binFreq, (bin + 1) * self.binFreq)) # Highlight selected frequency in red if self.coloredBin != None: self.histPlot[self.coloredBin].set_facecolor('blue') self.histPlot[bin].set_facecolor('red') self.coloredBin = bin else: if self.coloredBin != None: self.histPlot[self.coloredBin].set_facecolor('blue') self.window.updateStatus() def _update(self, *fargs): # Animation function called 10 times a second to update graphs with recent data. # Get a list of recent magnitudes from the open device. mags = self.window.getMagnitudes() if mags != None: # Convert magnitudes to decibels. Also skip the first value because it's # the average power of the signal, and only grab the first half of values # because the second half is for negative frequencies (which don't apply # to an FFT run on real data). mags = 20.0 * np.log10(mags[1:len(mags) / 2 + 1]) # Update histogram bar heights based on magnitudes. for bin, mag in zip(self.histPlot, mags): bin.set_height(mag) # Roll samples forward and save the most recent sample. Note that image # samples are scaled to 0 to 1. self.magnitudes = np.roll(self.magnitudes, 1, axis=0) self.magnitudes[0] = mags / 100.0 # Update spectrogram image data. self.spectPlot.set_array(self.magnitudes) max_f = 0 max = 0 if len(mags) > 0: max = mags[0] for i in range(len(mags)): if mags[i] > max: max = mags[i] max_f = i if max > 60: max_f *= 1000.00 / 128 max_f += (500.00 / 128) if (214 < max_f and max_f < 227): print("A") elif (227 < max_f and max_f < 240): print("Aplus") elif (240 < max_f and max_f < 254): print("B") elif (254 < max_f and max_f < 269): print("C") elif (269 < max_f and max_f < 285): print("Cplus") elif (285 < max_f and max_f < 302): print("D") elif (302 < max_f and max_f < 320): print("Dplus") elif (320 < max_f and max_f < 339): print("E") elif (339 < max_f and max_f < 359): print("F") elif (359 < max_f and max_f < 380): print("Fplus") elif (380 < max_f and max_f < 402): print("G") elif (402 < max_f and max_f < 428): print("Gplus") elif (428 < max_f and max_f < 453): print("HighA") elif (453 < max_f and max_f < 480): print("HighAplus") elif (480 < max_f and max_f < 514): print("HighB") elif (514 < max_f and max_f < 538): print("HighC") elif (538 < max_f and max_f < 571): print("HighCplus") elif (571 < max_f and max_f < 604): print("HighD") elif (604 < max_f and max_f < 641): print("HighDplus") elif (641 < max_f and max_f < 679): print("HighE") elif (679 < max_f and max_f < 719): print("HighF") elif (719 < max_f and max_f < 762): print("HighFplus") elif (762 < max_f and max_f < 807): print("HighG") elif (823 < max_f and max_f < 855): print("HighGplus") return (self.histPlot, self.spectPlot) else: return ()
class Canvas_sourceSDC: def __init__(self, ui, W_matrix, N): # Scroll Area Source Image ui.scrollArea_sourceSDC = QtWidgets.QScrollArea(ui.tab_plotSourceSDC) ui.scrollArea_sourceSDC.setPalette(palette_scrollPlotProp) ui.scrollArea_sourceSDC.setWidgetResizable(True) ui.scrollArea_sourceSDC.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) ui.scrollArea_sourceSDC.setObjectName("scrollArea_sourceSDC") # Scroll Area Options prop ui.scrollArea_sourceSDCOpt = QtWidgets.QScrollArea( ui.tab_plotSourceSDC) ui.scrollArea_sourceSDCOpt.setWidgetResizable(True) ui.scrollArea_sourceSDCOpt.setObjectName("scrollArea_propImageOpt") ui.scrollArea_sourceSDCOpt.setPalette(palette_scrollPlotProp) ui.scrollAreaWidgetContents_sourceSDCOpt = QtWidgets.QWidget() ui.scrollAreaWidgetContents_sourceSDCOpt.setObjectName( "scrollAreaWidgetContents_sourceSDCOpt") ui.scrollArea_sourceSDCOpt.setWidget( ui.scrollAreaWidgetContents_sourceSDCOpt) ui.gridLayout_sourceSDCOpt = QtWidgets.QGridLayout( ui.scrollAreaWidgetContents_sourceSDCOpt) ui.gridLayout_sourceSDCOpt.setObjectName("gridLayout_sourceSDCOpt") ui.gridLayout_TabSourceSDC.addWidget(ui.scrollArea_sourceSDC, 3, 0, 1, 1) ui.gridLayout_TabSourceSDC.addWidget(ui.scrollArea_sourceSDCOpt, 10, 0, 1, 1) # Scroll Area Source SDC Phase ui.scrollArea_sourceSDC_phase = QtWidgets.QScrollArea( ui.tab_plotSourceSDC) ui.scrollArea_sourceSDC_phase.setPalette(palette_scrollPlotProp) ui.scrollArea_sourceSDC_phase.setWidgetResizable(True) ui.scrollArea_sourceSDC_phase.setSizePolicy( QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) ui.scrollArea_sourceSDC_phase.setObjectName( "scrollArea_sourceSDC_phase") # Scroll Area Options Source SDC Phase ui.scrollArea_sourceSDCOpt_phase = QtWidgets.QScrollArea( ui.tab_plotSourceSDC) ui.scrollArea_sourceSDCOpt_phase.setWidgetResizable(True) ui.scrollArea_sourceSDCOpt_phase.setObjectName( "scrollArea_propImageOpt_phase") ui.scrollArea_sourceSDCOpt_phase.setPalette(palette_scrollPlotProp) ui.scrollAreaWidgetContents_sourceSDCOpt_phase = QtWidgets.QWidget() ui.scrollAreaWidgetContents_sourceSDCOpt_phase.setObjectName( "scrollAreaWidgetContents_sourceSDCOpt_phase") ui.scrollArea_sourceSDCOpt_phase.setWidget( ui.scrollAreaWidgetContents_sourceSDCOpt_phase) ui.gridLayout_sourceSDCOpt_phase = QtWidgets.QGridLayout( ui.scrollAreaWidgetContents_sourceSDCOpt_phase) ui.gridLayout_sourceSDCOpt_phase.setObjectName( "gridLayout_sourceSDCOpt_phase") ui.gridLayout_TabSourceSDC.addWidget(ui.scrollArea_sourceSDC_phase, 3, 1, 1, 1) ui.gridLayout_TabSourceSDC.addWidget(ui.scrollArea_sourceSDCOpt_phase, 10, 1, 1, 1) #_______________________________________________________________________ #======================================================================= # Parameters #======================================================================= # N self.N = N # W matrix self.W_matrix = copy.copy(W_matrix) # User interface self.ui = ui # parent self.parent = ui.scrollArea_sourceSDC self.parent_phase = ui.scrollArea_sourceSDC_phase # parent optioncs self.parentOptions = ui.scrollArea_sourceSDCOpt self.parentOptions_phase = ui.scrollArea_sourceSDCOpt_phase # grid parent options self.gridOptions = ui.gridLayout_sourceSDCOpt self.gridOptions_phase = ui.gridLayout_sourceSDCOpt_phase # first plot self.first_plot = False #_______________________________________________________________________ # Initial points (middle) self.P1x = int(N / 2) self.P1y = int(N / 2) self.build_fig() def build_fig(self): #======================================================================= # Create the mpl Figure and FigCanvas objects. #======================================================================= # magnitude self.dpi = 100 self.fig = Figure((5.0, 4.0), dpi=self.dpi) self.canvas = FigureCanvas(self.fig) # phase self.dpi_phase = 100 self.fig_phase = Figure((5.0, 4.0), dpi=self.dpi_phase) self.canvas_phase = FigureCanvas(self.fig_phase) # axes self.axes = self.fig.add_subplot(111) self.axes_phase = self.fig_phase.add_subplot(111) #_______________________________________________________________________ #======================================================================= # Plotting 2D figure and configuring #======================================================================= # creating image prop self.sourceSDC_mag = sqrt(self.W_matrix[self.P1x, self.P1y].real**2 + self.W_matrix[self.P1x, self.P1y].imag**2) self.sourceSDC_phase = angle(self.W_matrix[self.P1y, self.P1y]) # PLOT magnitude self.im = self.axes.imshow(self.sourceSDC_mag) self.cbar = self.fig.colorbar(self.im) # PLOT phase self.im_phase = self.axes_phase.imshow(self.sourceSDC_phase) self.cbar_phase = self.fig_phase.colorbar(self.im_phase) # font size self.fsize = 12 self.fsize_phase = 12 # x,y Labels self.axes.set_xlabel("x (m)", fontsize=self.fsize) self.axes.set_ylabel("y (m)", fontsize=self.fsize) #_______________________________________________________________________ #======================================================================= # Tool bar #======================================================================= # Bind the 'pick' event for clicking on one of the bars self.canvas.mpl_connect( 'pick_event', self.ui.on_pick ) #self.canvas.mpl_connect("scroll_event", ui.scrolling) # Bind the 'pick' event for clicking on one of the bars self.canvas_phase.mpl_connect( 'pick_event', self.ui.on_pick ) #self.canvas.mpl_connect("scroll_event", ui.scrolling) # Create the navigation toolbar, tied to the canvas self.mpl_toolbar = NavigationToolbar(self.canvas, self.parent) self.mpl_toolbar_phase = NavigationToolbar(self.canvas_phase, self.parent_phase) #ui.gridLayout_TabPropImage.addWidget(self.mpl_toolbar, 2, 0, 1, 3) self.ui.gridLayout_TabSourceSDC.addWidget( self.mpl_toolbar, 8, 0, 1, 3, alignment=QtCore.Qt.AlignLeft) self.ui.gridLayout_TabSourceSDC.addWidget( self.mpl_toolbar_phase, 8, 1, 1, 3, alignment=QtCore.Qt.AlignLeft) #_______________________________________________________________________ #======================================================================= # Canvas in Scroll Area - magnitude #======================================================================= #self.canvas.draw() #self.canvas.setParent(parent) self.canvas.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) # Container for VBOX self.containerGraph = QWidget(self.parent) self.containerGraph.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) self.containerGraph.setMinimumWidth(self.canvas.width()) self.containerGraph.setMinimumHeight(self.canvas.height()) self.containerGraph.setMaximumWidth(self.canvas.width() + 5) self.containerGraph.setMaximumHeight(self.canvas.height() + 5) # VBOX for canvas self.vbox = QVBoxLayout(self.containerGraph) #self.vbox.setGeometry(QRect(0, 0, self.canvas.width(), self.canvas.height())) self.vbox.addWidget(self.canvas) self.parent.setWidget(self.containerGraph) #_______________________________________________________________________ #======================================================================= # Canvas in Scroll Area - phase #======================================================================= self.canvas_phase.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) # Container for VBOX self.containerGraph_phase = QWidget(self.parent_phase) self.containerGraph_phase.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) self.containerGraph_phase.setMinimumWidth(self.canvas_phase.width()) self.containerGraph_phase.setMinimumHeight(self.canvas_phase.height()) self.containerGraph_phase.setMaximumWidth(self.canvas_phase.width() + 5) self.containerGraph_phase.setMaximumHeight(self.canvas_phase.height() + 5) # VBOX for canvas self.vbox_phase = QVBoxLayout(self.containerGraph_phase) #self.vbox.setGeometry(QRect(0, 0, self.canvas.width(), self.canvas.height())) self.vbox_phase.addWidget(self.canvas_phase) self.parent_phase.setWidget(self.containerGraph_phase) #_______________________________________________________________________ if not self.first_plot: self.figure_options() self.figure_options_phase() self.first_plot = True def figure_options(self): # label Point P1x self.label_P1x = QtWidgets.QLabel(self.parentOptions) self.label_P1x.setObjectName("label_P1x") self.label_P1x.setText("Point ") self.gridOptions.addWidget(self.label_P1x, 2, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit Point P1x self.lineEdit_P1x = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_P1x.setObjectName("lineEdit_P1x") self.gridOptions.addWidget(self.lineEdit_P1x, 2, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_P1x.setText(str(int(self.N / 2))) self.lineEdit_P1x.textChanged.connect(self.change_P1x) # label Point P1y self.label_P1y = QtWidgets.QLabel(self.parentOptions) self.label_P1y.setObjectName("label_P1y") self.label_P1y.setText('$Point$') self.gridOptions.addWidget(self.label_P1y, 4, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit Point P1x self.lineEdit_P1y = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_P1y.setObjectName("lineEdit_P1y") self.gridOptions.addWidget(self.lineEdit_P1y, 4, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_P1y.setText(str(int(self.N / 2))) self.lineEdit_P1y.textChanged.connect(self.change_P1y) # label title self.label_title = QtWidgets.QLabel(self.parentOptions) self.label_title.setObjectName("label_title") self.label_title.setText("Title") self.gridOptions.addWidget(self.label_title, 6, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit title label self.lineEdit_title = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_title.setObjectName("lineEdit_title") self.lineEdit_title.textChanged.connect(self.change_title) self.gridOptions.addWidget(self.lineEdit_title, 6, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.change_title() self.lineEdit_title.setText("Source SDC") # label x self.label_x = QtWidgets.QLabel(self.parentOptions) self.label_x.setObjectName("label_x") self.label_x.setText("Label x-axis") self.gridOptions.addWidget(self.label_x, 8, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit x label self.lineEdit_xLabel = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_xLabel.setObjectName("lineEdit_xlabel") self.lineEdit_xLabel.textChanged.connect(self.change_labelx) self.gridOptions.addWidget(self.lineEdit_xLabel, 8, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.change_labelx() self.lineEdit_xLabel.setText("x") # label y self.label_y = QtWidgets.QLabel(self.parentOptions) self.label_y.setObjectName("label_y") self.label_y.setText("Label y-axis") self.gridOptions.addWidget(self.label_y, 10, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit y label self.lineEdit_yLabel = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_yLabel.setObjectName("lineEdit_ylabel") self.lineEdit_yLabel.textChanged.connect(self.change_labely) self.gridOptions.addWidget(self.lineEdit_yLabel, 10, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.change_labely() self.lineEdit_yLabel.setText("y") # label xlim self.label_xlim = QtWidgets.QLabel(self.parentOptions) self.label_xlim.setObjectName("label_xlim") self.label_xlim.setText("xlim") self.gridOptions.addWidget(self.label_xlim, 12, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit xlim self.lineEdit_xlim = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_xlim.setObjectName("lineEdit_ylabel") self.lineEdit_xlim.textChanged.connect(self.change_xlim) self.gridOptions.addWidget(self.lineEdit_xlim, 12, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_xlim.setText("(_,_)") self.change_xlim() # label ylim self.label_ylim = QtWidgets.QLabel(self.parentOptions) self.label_ylim.setObjectName("label_ylim") self.label_ylim.setText("ylim") self.gridOptions.addWidget(self.label_ylim, 14, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit ylim self.lineEdit_ylim = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_ylim.setObjectName("lineEdit_ylabel") self.lineEdit_ylim.textChanged.connect(self.change_ylim) self.gridOptions.addWidget(self.lineEdit_ylim, 14, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_ylim.setText("(_,_)") self.change_ylim() # label cmap self.label_cmap = QtWidgets.QLabel(self.parentOptions) self.label_cmap.setObjectName("label_cmap") self.label_cmap.setText("Color Map") self.gridOptions.addWidget(self.label_cmap, 20, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit cmap self.lineEdit_cmap = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_cmap.setObjectName("lineEdit_cmap") self.lineEdit_cmap.textChanged.connect(self.change_cmap) self.gridOptions.addWidget(self.lineEdit_cmap, 20, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_cmap.setText("hot") self.change_cmap() # label Font Size self.label_fsize = QtWidgets.QLabel(self.parentOptions) self.label_fsize.setObjectName("label_fsize") self.label_fsize.setText("Font Size") self.gridOptions.addWidget(self.label_fsize, 22, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit font size self.lineEdit_fsize = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_fsize.setObjectName("label_fsize") self.lineEdit_fsize.textChanged.connect(self.change_fsize) self.gridOptions.addWidget(self.lineEdit_fsize, 22, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_fsize.setText(str(self.fsize)) self.change_fsize() # label DPI self.label_dpi = QtWidgets.QLabel(self.parentOptions) self.label_dpi.setObjectName("label_dpi") self.label_dpi.setText("dpi (100-500)") self.gridOptions.addWidget(self.label_dpi, 24, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit DPI self.lineEdit_dpi = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_dpi.setObjectName("label_dpi") self.lineEdit_dpi.textChanged.connect(self.change_dpi) self.gridOptions.addWidget(self.lineEdit_dpi, 24, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_dpi.setText(str(self.dpi)) self.change_fsize() #_______________________________________________________________________ def figure_options_phase(self): try: # label title_phase self.label_title_phase = QtWidgets.QLabel(self.parentOptions) self.label_title_phase.setObjectName("label_title") self.label_title_phase.setText("Title") self.gridOptions_phase.addWidget(self.label_title_phase, 6, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit title label_phase self.lineEdit_title_phase = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_title_phase.setObjectName("lineEdit_title_phase") self.lineEdit_title_phase.textChanged.connect( self.change_title_phase) self.gridOptions_phase.addWidget(self.lineEdit_title_phase, 6, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_title_phase.setText("Source SDC Phase") self.change_title_phase() # label x_phase self.label_x_phase = QtWidgets.QLabel(self.parentOptions) self.label_x_phase.setObjectName("label_xv") self.label_x_phase.setText("Label x-axis") self.gridOptions_phase.addWidget(self.label_x_phase, 8, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit x label_phase_phase self.lineEdit_xLabel_phase = QtWidgets.QLineEdit( self.parentOptions) self.lineEdit_xLabel_phase.setObjectName("lineEdit_xlabel_phase") self.lineEdit_xLabel_phase.textChanged.connect( self.change_labelx_phase) self.gridOptions_phase.addWidget(self.lineEdit_xLabel_phase, 8, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.change_labelx_phase() self.lineEdit_xLabel_phase.setText("x") # label y_phase self.label_y_phase = QtWidgets.QLabel(self.parentOptions) self.label_y_phase.setObjectName("label_y_phase") self.label_y_phase.setText("Label y-axis") self.gridOptions_phase.addWidget(self.label_y_phase, 10, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit y label_phase self.lineEdit_yLabel_phase = QtWidgets.QLineEdit( self.parentOptions) self.lineEdit_yLabel_phase.setObjectName("lineEdit_ylabel_phase") self.lineEdit_yLabel_phase.textChanged.connect( self.change_labely_phase) self.gridOptions_phase.addWidget(self.lineEdit_yLabel_phase, 10, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.change_labely_phase() self.lineEdit_yLabel_phase.setText("y") # label xlim_phase self.label_xlim_phase = QtWidgets.QLabel(self.parentOptions) self.label_xlim_phase.setObjectName("label_xlim_phase") self.label_xlim_phase.setText("xlim") self.gridOptions_phase.addWidget(self.label_xlim_phase, 12, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit xlim_phase self.lineEdit_xlim_phase = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_xlim_phase.setObjectName("lineEdit_ylabel_phase") self.lineEdit_xlim_phase.textChanged.connect( self.change_xlim_phase) self.gridOptions_phase.addWidget(self.lineEdit_xlim_phase, 12, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_xlim_phase.setText("(_,_)") self.change_xlim_phase() # label ylim_phase self.label_ylim_phase = QtWidgets.QLabel(self.parentOptions) self.label_ylim_phase.setObjectName("label_ylim_phase") self.label_ylim_phase.setText("ylim") self.gridOptions_phase.addWidget(self.label_ylim_phase, 14, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit ylim_phase self.lineEdit_ylim_phase = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_ylim_phase.setObjectName("lineEdit_ylabel_phase") self.lineEdit_ylim_phase.textChanged.connect( self.change_ylim_phase) self.gridOptions_phase.addWidget(self.lineEdit_ylim_phase, 14, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_ylim_phase.setText("(_,_)") self.change_ylim_phase() # label cmap_phase self.label_cmap_phase = QtWidgets.QLabel(self.parentOptions) self.label_cmap_phase.setObjectName("label_cmap_phase") self.label_cmap_phase.setText("Color Map") self.gridOptions_phase.addWidget(self.label_cmap_phase, 20, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit cmap_phase self.lineEdit_cmap_phase = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_cmap_phase.setObjectName("lineEdit_cmap_phase") self.lineEdit_cmap_phase.textChanged.connect( self.change_cmap_phase) self.gridOptions_phase.addWidget(self.lineEdit_cmap_phase, 20, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_cmap_phase.setText("hot") self.change_cmap_phase() # label Font Size_phase self.label_fsize_phase = QtWidgets.QLabel(self.parentOptions) self.label_fsize_phase.setObjectName("label_fsize") self.label_fsize_phase.setText("Font Size") self.gridOptions_phase.addWidget(self.label_fsize_phase, 22, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit font size_phase self.lineEdit_fsize_phase = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_fsize_phase.setObjectName("label_fsize_phase") self.lineEdit_fsize_phase.textChanged.connect(self.change_fsize) self.gridOptions_phase.addWidget(self.lineEdit_fsize_phase, 22, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_fsize_phase.setText(str(self.fsize)) self.change_fsize_phase() # label DPI_phase self.label_dpi_phase = QtWidgets.QLabel(self.parentOptions) self.label_dpi_phase.setObjectName("label_dpi_phase") self.label_dpi_phase.setText("dpi (100-500)") self.gridOptions_phase.addWidget(self.label_dpi_phase, 24, 0, 1, 1, alignment=QtCore.Qt.AlignLeft) # line edit DPI_phase self.lineEdit_dpi_phase = QtWidgets.QLineEdit(self.parentOptions) self.lineEdit_dpi_phase.setObjectName("label_dpi_phase") self.lineEdit_dpi_phase.textChanged.connect(self.change_dpi_phase) self.gridOptions_phase.addWidget(self.lineEdit_dpi_phase, 24, 1, 1, 1, alignment=QtCore.Qt.AlignLeft) self.lineEdit_dpi_phase.setText(str(self.dpi_phase)) self.change_fsize_phase() #_______________________________________________________________________ except Exception as error: self.ui.update_outputText(str(error)) def change_P1x(self): try: temp = self.lineEdit_P1x.text() if temp != "": new = int(temp) if new >= 0 and new < self.N: self.P1x = new self.update_pcolor() self.update_draw() except Except as error: self.ui.update_outputText(str(error)) def change_P1y(self): try: temp = self.lineEdit_P1y.text() if temp != "": new = int(temp) if new >= 0 and new < self.N: self.P1y = new self.update_pcolor() self.update_draw() except Except as error: self.ui.update_outputText(str(error)) def update_pcolor(self): try: # creating image prop self.sourceSDC_mag = sqrt( self.W_matrix[self.P1x, self.P1y].real**2 + self.W_matrix[self.P1x, self.P1y].imag**2) self.sourceSDC_phase = angle(self.W_matrix[self.P1y, self.P1y]) self.im.set_array(self.sourceSDC_mag) self.im_phase.set_array(self.sourceSDC_phase) except Exception as error: self.ui.update_outputText(str(error)) def update_draw(self): self.canvas.draw() self.canvas.updateGeometry() self.canvas_phase.draw() self.canvas_phase.updateGeometry() #=========================================================================== # Magnitude #=========================================================================== def change_dpi(self): try: new = int(self.lineEdit_dpi.text()) if new >= 100 and new <= 500: self.dpi = new self.fig.set_dpi(new) self.update_draw() except: pass def change_fsize(self): try: self.fsize = int(self.lineEdit_fsize.text()) self.change_title() self.change_labelx() self.change_labely() self.update_draw() print(self.fsize) except Exception as error: pass #self.ui.update_outputText(error) def change_cmap(self): try: self.im.set_cmap(self.lineEdit_cmap.text()) self.canvas.draw() except Exception as error: pass #self.ui.update_outputText(error) def change_xlim(self): try: temp_txt = self.lineEdit_xlim.text() Ntxt = len(temp_txt) numList = [] if temp_txt[0] == "(" and temp_txt[-1] == ")": actual = "" for i in range(1, Ntxt - 1): if temp_txt[i] == ",": numList.append(float(actual)) actual = "" elif i == Ntxt - 2: actual += temp_txt[i] numList.append(float(actual)) else: actual += temp_txt[i] self.axes.set_xlim(numList[0], numList[1]) except Exception as error: pass #self.ui.update_outputText(error) def change_ylim(self): try: temp_txt = self.lineEdit_ylim.text() Ntxt = len(temp_txt) numList = [] if temp_txt[0] == "(" and temp_txt[-1] == ")": actual = "" for i in range(1, Ntxt - 1): if temp_txt[i] == ",": numList.append(float(actual)) actual = "" elif i == Ntxt - 2: actual += temp_txt[i] numList.append(float(actual)) else: actual += temp_txt[i] self.axes.set_ylim(numList[0], numList[1]) self.canvas.draw() except Exception as error: pass #self.ui.update_outputText(error) def change_title(self): try: self.axes.set_title(self.lineEdit_title.text(), fontsize=self.fsize) self.canvas.draw() except: pass def change_labelx(self): if self.lineEdit_xLabel.text() == "": self.axes.set_xlabel("") else: try: self.axes.set_xlabel(self.lineEdit_xLabel.text(), fontsize=self.fsize) self.canvas.draw() except Exception as error: self.ui.update_outputText(str(error)) def change_labely(self): if self.lineEdit_yLabel.text() == "": self.axes.set_ylabel("") else: try: self.axes.set_ylabel(self.lineEdit_yLabel.text(), fontsize=self.fsize) self.canvas.draw() except: pass #self.ui.update_outputText("Unable to update y-label.") #___________________________________________________________________________ #=========================================================================== # Phase #=========================================================================== try: def change_dpi_phase(self): try: new = int(self.lineEdit_dpi_phase.text()) if new >= 100 and new <= 500: self.dpi_phase = new self.fig_phase.set_dpi(new) self.update_draw() except: pass def change_fsize_phase(self): try: self.fsize_phase = int(self.lineEdit_fsize.text()) self.change_title_phase() self.change_labelx_phase() self.change_labely_phase() self.update_draw() except Exception as error: pass #self.ui.update_outputText(error) def change_cmap_phase(self): try: self.im_phase.set_cmap(self.lineEdit_cmap_phase.text()) self.canvas_phase.draw() except Exception as error: pass #self.ui.update_outputText(error) def change_xlim_phase(self): try: temp_txt = self.lineEdit_xlim_phase.text() Ntxt = len(temp_txt) numList = [] if temp_txt[0] == "(" and temp_txt[-1] == ")": actual = "" for i in range(1, Ntxt - 1): if temp_txt[i] == ",": numList.append(float(actual)) actual = "" elif i == Ntxt - 2: actual += temp_txt[i] numList.append(float(actual)) else: actual += temp_txt[i] self.axes_phase.set_xlim(numList[0], numList[1]) except Exception as error: pass #self.ui.update_outputText(error) def change_ylim_phase(self): try: temp_txt = self.lineEdit_ylim_phase.text() Ntxt = len(temp_txt) numList = [] if temp_txt[0] == "(" and temp_txt[-1] == ")": actual = "" for i in range(1, Ntxt - 1): if temp_txt[i] == ",": numList.append(float(actual)) actual = "" elif i == Ntxt - 2: actual += temp_txt[i] numList.append(float(actual)) else: actual += temp_txt[i] self.axes_phase.set_ylim(numList[0], numList[1]) self.canvas.draw() except Exception as error: pass #self.ui.update_outputText(error) def change_title_phase(self): try: self.axes_phase.set_title(self.lineEdit_title_phase.text(), fontsize=self.fsize_phase) self.canvas_phase.draw() except: pass def change_labelx_phase(self): if self.lineEdit_xLabel_phase.text() == "": self.axes_phase.set_xlabel("") else: try: self.axes_phase.set_xlabel( self.lineEdit_xLabel_phase.text(), fontsize=self.fsize_phase) self.canvas_phase.draw() except Exception as error: self.ui.update_outputText(str(error)) def change_labely_phase(self): if self.lineEdit_yLabel_phase.text() == "": self.axes_phase.set_ylabel("") else: try: self.axes_phase.set_ylabel( self.lineEdit_yLabel_phase.text(), fontsize=self.fsize_phase) self.canvas_phase.draw() except: pass #self.ui.update_outputText("Unable to update y-label.") except Exception as error: self.ui.update_outputText(error)