def colormap_skewed(exps): vmin_skewed = -1.0 vmid_skewed = 3.0 vmax_skewed = np.max(exps) vstep = 1.0 levels = np.arange(vmin_skewed, vmax_skewed + vstep, vstep) cmap = cm.get_cmap('bwr', len(levels) - 1) deltamax = max(vmax_skewed - vmid_skewed, vmid_skewed - vmin_skewed) vfull = [vmid_skewed - deltamax, vmid_skewed + deltamax] # Full range either side of vmid #levfull = np.arange( vfull[0], vfull[1], vstep ) # Levels over full value range ncols = len(levels) - 1 # number of colours we actually want to use vlo_frac = (vmin_skewed - vfull[0]) / (2.0 * deltamax) # 0 or greater vhi_frac = (vmax_skewed - vfull[0]) / (2.0 * deltamax) # 1 or less cmap_base = cm.get_cmap('bwr') # maps the range 0-1 to colours cols = cmap_base(np.linspace(vlo_frac, vhi_frac, ncols)) cmap_skewed = mpl_col.LinearSegmentedColormap.from_list('skewed', cols, N=ncols) cmap_skewed.set_bad('gray') cmap_skewed.set_under('w') return cmap_skewed
def plot_results(clustered,uncert,expname): # Set some defaults ucolors = ('Blues','Purples','Greys','Blues','Reds','Oranges') proj = ccrs.PlateCarree(central_longitude=180) cmap = cm.get_cmap("jet",nclusters) fig,ax = plt.subplots(1,1,subplot_kw={'projection':proj}) ax = add_coast_grid(ax) gl = ax.gridlines(ccrs.PlateCarree(central_longitude=0),draw_labels=True, linewidth=2, color='gray', alpha=0.5, linestyle="dotted",lw=0.75) gl.xlabels_top = False gl.ylabels_right = False pcm = ax.pcolormesh(lon5,lat5,clustered,cmap=cmap,transform=ccrs.PlateCarree())#,cmap='Accent')#@,cmap='Accent') plt.colorbar(pcm,ax=ax,orientation='horizontal') ax.set_title("Clustering Results \n nclusters=%i %s" % (nclusters,expname)) plt.savefig("%sCluster_results_n%i_%s.png"%(outfigpath,nclusters,expname),dpi=200,transparent=True) # Plot Cluster Uncertainty fig1,ax1 = plt.subplots(1,1,subplot_kw={'projection':proj}) ax1 = add_coast_grid(ax1) for i in range(nclusters): cid = i+1 cuncert = uncert.copy() cuncert[clustered!=cid] *= np.nan ax1.pcolormesh(lon5,lat5,cuncert,vmin=0,vmax=2,cmap=ucolors[i],transform=ccrs.PlateCarree()) #fig.colorbar(pcm,ax=ax) ax1.set_title("Clustering Output (nclusters=%i) %s "% (nclusters,expname)) plt.savefig(outfigpath+"Cluster_with_Shaded_uncertainties_%s.png" % expname,dpi=200) return fig,ax,fig1,ax1
def get_hex_color(depths): """ Returns hex (html) color as a function of depth """ cmap = cm.get_cmap('RdPu') colors = cmap(np.log(depths)/np.max(np.log(depths))) return [rgb2hex(i) for i in colors]
def __init__(self, songfilename, MFCCs, SampleDelays, beatIdx, BeatsPerWin): self.songfilename = songfilename self.title = songfilename.split('.mp3')[0] self.title = self.title.split('/')[-1] self.title = self.title.split('+')[0] self.SampleDelays = SampleDelays self.MFCCs = MFCCs self.BeatsPerWin = BeatsPerWin self.beatIdx = beatIdx #Indexes from the beats into to the SampleDelays array #Do PCA on all windows and assign colormaps to each point cloud N = len(beatIdx) - BeatsPerWin - 1 if N == 0: return self.BeatStartIdx = np.zeros(N) cmConvert = cm.get_cmap('jet') print "Doing PCA on all windows..." self.Y = np.zeros((0, 3)) self.YColors = np.zeros((0, 3)) for i in range(N): P = MFCCs[beatIdx[i]:beatIdx[i+BeatsPerWin]] if P.size == 0: N = i break (Yi, varExplained) = doCenteringAndPCA(P) self.Y = np.concatenate((self.Y, Yi), 0) Colorsi = cmConvert(np.linspace(0, 1, P.shape[0]))[:, 0:3] self.YColors = np.concatenate((self.YColors, Colorsi), 0) self.BeatStartIdx[i+1] = self.BeatStartIdx[i] + Colorsi.shape[0] self.BeatStartIdx = self.BeatStartIdx[0:N] print "Finished PCA on %i windows for %s"%(N, self.title) self.currBeat = 0
def estimateCurvature(self, evt): #Color vertices to be equal to mean curvature curvs = estimateMeanCurvature(self.mesh) curvs = curvs - np.min(curvs) curvs = curvs / np.max(curvs) cmConvert = cm.get_cmap('jet') self.mesh.VColors = cmConvert(curvs)[:, 0:3] self.mesh.needsDisplayUpdate = True
def plot_results(clustered,uncert,expname,lat5,lon5,outfigpath,title=None): # Set some defaults ucolors = ('Blues','Purples','Greys','Blues','Reds','Oranges','Greens') proj = ccrs.PlateCarree(central_longitude=180) cmap = cm.get_cmap("jet",nclusters) fig,ax = plt.subplots(1,1,subplot_kw={'projection':proj}) ax = slutil.add_coast_grid(ax) gl = ax.gridlines(ccrs.PlateCarree(central_longitude=0),draw_labels=True, linewidth=2, color='gray', alpha=0.5, linestyle="dotted",lw=0.75) gl.xlabels_top = False gl.ylabels_right = False pcm = ax.pcolormesh(lon5,lat5,clustered,cmap=cmap,transform=ccrs.PlateCarree())#,cmap='Accent')#@,cmap='Accent') plt.colorbar(pcm,ax=ax,orientation='horizontal') if title is None: ax.set_title("Clustering Results \n nclusters=%i %s" % (nclusters,expname)) else: ax.set_title(title) plt.savefig("%sCluster_results_n%i_%s.png"%(outfigpath,nclusters,expname),dpi=200,transparent=True) # Plot raw uncertainty fig,ax = plt.subplots(1,1,subplot_kw={'projection':proj}) ax = slutil.add_coast_grid(ax) pcm = plt.pcolormesh(lon5,lat5,uncert,cmap='copper',transform=ccrs.PlateCarree()) ax.set_title(r"Uncertainty $(<\sigma^{2}_{out,x}>/<\sigma^{2}_{in,x}>)$") fig.colorbar(pcm,ax=ax,fraction=0.02) plt.savefig(outfigpath+"Uncertainty.png",dpi=200) uncertraw = uncert.copy() # Apply Thompson and Merrifield thresholds uncert[uncert>2] = 2 uncert[uncert<0.5]=0 # Plot Cluster Uncertainty fig1,ax1 = plt.subplots(1,1,subplot_kw={'projection':proj}) ax1 = slutil.add_coast_grid(ax1) for i in range(nclusters): cid = i+1 if (i+1) > len(ucolors): ci=i%len(ucolors) else: ci=i cuncert = uncert.copy() cuncert[clustered!=cid] *= np.nan ax1.pcolormesh(lon5,lat5,cuncert,vmin=0,vmax=2,cmap=ucolors[ci],transform=ccrs.PlateCarree()) #fig.colorbar(pcm,ax=ax) if title is None: ax1.set_title("Clustering Output (nclusters=%i) %s "% (nclusters,expname)) else: ax1.set_title(title) plt.savefig(outfigpath+"Cluster_with_Shaded_uncertainties_%s.png" % expname,dpi=200) return fig,ax,fig1,ax1
def computeMeanCurvatures(self, evt): (L, solver, deltaCoords) = makeLaplacianMatrixSolverIGL(self.mesh.VPos, self.mesh.ITris, anchorsIdx, anchorWeights) #Color vertices to be equal to mean curvature curvs = np.sqrt(np.sum(deltaCoords**2, 1)) curvs = curvs - np.min(curvs) curvs = curvs / np.max(curvs) cmConvert = cm.get_cmap('jet') self.mesh.VColors = cmConvert(curvs)[:, 0:3] self.mesh.needsDisplayUpdate = True
def get_colors(cmap_choice='binary'): too_light = [ 'binary', 'hot', 'copper', 'pink', 'summer', 'bone', 'Pastel1', 'Pastel2', 'gist_ncar', 'nipy_spectral', 'Greens' ] cmap = cm.get_cmap(cmap_choice, len(ks_distributions)) if cmap_choice in too_light: cmap = cm.get_cmap(cmap_choice, len(ks_distributions) * 4) c = [] for i in range(cmap.N): rgb = cmap(i)[:3] # will return rgba, but we need only rgb c.append(matplotlib.colors.rgb2hex(rgb)) if cmap_choice in too_light: if len(ks_distributions) > 1: c = c[2:-2] else: c = [c[-1]] return c
def get_hex(name, number=5): """takes a matplotlib colormap and returns a number (number) of sampled hex colours from the map.""" cmap = cm.get_cmap(name, number) output_list = [] for i in range(cmap.N): rgb = cmap(i)[:3] output_list.append(mplc.rgb2hex(rgb)) return output_list
def data_image_array(self): """Helper function to structure the data into an interpolated CV2 array""" new_kernel = interpolate.RectBivariateSpline(self._rows, self._cols, self.data_shaped) kernel_out = new_kernel(self._yy_rows, self._xx_cols) my_cm = cm.get_cmap(self.cmap) normed_kernel = (kernel_out - min(kernel_out)) / (max(kernel_out) - min(kernel_out)) mapped_kernel = (255 * my_cm(normed_kernel)).astype('uint8') return cvtColor(mapped_kernel, COLOR_BGR2RGB)
def render(self, mode='plot'): pv_points_to_plot = 12 if self._first_render: plt.xkcd() plt.close('all') plt.ion() self._plot_fig, self._plot_axs = plt.subplots(1,3,figsize=(12,4)) self._plot_li0_masks = [] self._plot_li0, = self._plot_axs[0].plot(self._plot_data['V'][:], self._plot_data['P'][:], 'o-', color='white') cs = cm.get_cmap('Blues',11) for i in reversed(range(1,pv_points_to_plot)): self._plot_li0_masks.append( #self._plot_axs[0].plot(self._plot_data['V'][-pv_points_to_plot:-pv_points_to_plot+i], self._plot_data['P'][-pv_points_to_plot:-pv_points_to_plot+i], 'o-', self._plot_axs[0].plot(self._plot_data['V'][-i:-i+2], self._plot_data['P'][-i:-i+2], 'o-', color=cs(i/12.), linewidth=3,zorder=i*100)[0] ) self._plot_li1, = self._plot_axs[1].plot(np.arange(len(self._plot_data["r"])), self._plot_data["r"], 'g-') self._plot_dq_line, = self._plot_axs[2].plot(np.arange(len(self._plot_data["dQ"])), self._plot_data["dQ"], alpha=0.8, label='dQ') self._plot_dw_line, = self._plot_axs[2].plot(np.arange(len(self._plot_data["dW"])), self._plot_data["dW"], alpha=0.8, label='dW') self._plot_axs[2].legend() self._plot_axs[1].axhline(y=self.efficiency, color='red', ls='--') self._plot_axs[0].set_xlabel("Volume [L]") self._plot_axs[0].set_ylabel("Pressure ") vr = abs(self.engine.Vmin-self.engine.Vmax) pr = abs(self.engine.Pmin-self.engine.Pmax) self._plot_axs[0].add_patch(Rectangle((self.engine.Vmin*1000, self.engine.Pmin), vr*1000., pr, color='#DDDDDD')) self._plot_axs[0].set_xlim([(self.engine.Vmin-0.1*vr)*1000, (self.engine.Vmax+0.1*vr)*1000]) self._plot_axs[0].set_ylim([self.engine.Pmin-0.1*pr, self.engine.Pmax+0.1*pr]) self._plot_axs[1].set_xlabel("Step") self._plot_axs[1].set_ylabel("Efficiency") plt.tight_layout() self._plot_fig.canvas.draw() plt.show() self._first_render = False else: self._plot_dq_line.set_xdata(np.arange(len(self._plot_data["dQ"]))) self._plot_dq_line.set_ydata(self._plot_data["dQ"]) self._plot_dw_line.set_xdata(np.arange(len(self._plot_data["dW"]))) self._plot_dw_line.set_ydata(self._plot_data["dW"]) self._plot_li0.set_xdata(self._plot_data['V'][:]) self._plot_li0.set_ydata(self._plot_data['P'][:]) self._plot_li1.set_xdata(np.arange(len(self._plot_data["r"]))) self._plot_li1.set_ydata(self._plot_data["r"]) for i in reversed(range(1,len(self._plot_li0_masks))): self._plot_li0_masks[i].set_xdata(self._plot_data['V'][-i:]) self._plot_li0_masks[i].set_ydata(self._plot_data['P'][-i:]) for ax in [self._plot_axs[1], self._plot_axs[2]]: ax.relim() ax.autoscale_view(True, True, True) self._plot_fig.canvas.draw() plt.pause(0.000001)
def create_cmap(): ### Create a list of RGB tuples colors = [(229, 229, 229), (182, 165, 134), (160, 138, 91), (138, 111, 49), (140, 127, 43), (142, 143, 37), (144, 159, 31), (146, 175, 25), (138, 177, 21), (119, 165, 18), (99, 154, 15), (80, 142, 12), (60, 131, 9), (41, 119, 6), (22, 108, 3), (3, 97, 0), (0, 23, 0)] # This example uses the 8-bit RGB ### Create an array or list of positions from 0 to 1. position = [0, 0.04, 0.08, 0.12, 0.16, 0.20, 0.24, 0.28, 0.32, 0.36, 0.40, 0.44, 0.48, 0.52, 0.56, 0.60, 1] evi_cmap = make_cmap(colors, position=position, bit=True) cm.register_cmap(name='evi', cmap=evi_cmap) EVI = cm.get_cmap('evi') export_colormap('evi_colorbar',evi_cmap) return EVI
def my_colormap(g, property_name, cmap='jet',lognorm=True): prop = g.property(property_name) keys = list(prop.keys()) values = np.array(list(prop.values())) #m, M = int(values.min()), int(values.max()) _cmap = cm.get_cmap(cmap) norm = Normalize() if not lognorm else LogNorm() values = norm(values) #my_colorbar(values, _cmap, norm) colors = (_cmap(values)[:,0:3])*255 colors = np.array(colors,dtype=np.int).tolist() g.properties()['color'] = dict(list(zip(keys,colors)))
def my_colormap(g, property_name, cmap='jet',lognorm=True): prop = g.property(property_name) keys = prop.keys() values = np.array(prop.values()) #m, M = int(values.min()), int(values.max()) _cmap = cm.get_cmap(cmap) norm = Normalize() if not lognorm else LogNorm() values = norm(values) #my_colorbar(values, _cmap, norm) colors = (_cmap(values)[:,0:3])*255 colors = np.array(colors,dtype=np.int).tolist() g.properties()['color'] = dict(zip(keys,colors))
class Settings: COLORMAP = cm.get_cmap('hot') OPACITYGOOD = 1 OPACITYBAD = 0.2 SIZEGOOD = 100 SIZEBAD = 3 XRANGE = (-5, 5) YRANGE = (-10, 10) BIGGESTOBSERVED = 1 LOWESTOBSERVED = -3
def getHeatFlow(self, evt): dlg = wx.TextEntryDialog(None,'Time Parameter','Choose Time Parameter', '1') if dlg.ShowModal() == wx.ID_OK: indices = [a for a in self.laplacianConstraints] t = float(dlg.GetValue()) k = min(100, len(self.mesh.vertices)-1) cmConvert = cm.get_cmap("jet") (x, self.eigvalues, self.eigvectors) = self.mesh.getHeatFlowFromPoints(indices, k, t, self.eigvalues, self.eigvectors) #x = x/np.max(x) #Should already be in the range [0, 1] for i in range(len(self.mesh.vertices)): self.mesh.vertices[i].color = cmConvert(x[i]) self.mesh.needsDisplayUpdate = True self.Refresh() dlg.Destroy()
def create_cm(mini, maxi, step, cm_type): output = [] # https://matplotlib.org/examples/color/colormaps_reference.html #print((mini, maxi)) #print(int((maxi-mini)/step)) maxi += abs(mini) if mini < 0 else 0 # shift colorbar if negative values mini = 0 if mini < 0 else mini cmap = cm.get_cmap(cm_type, int((maxi - mini) / step)) # PiYG for i in range(int(mini / step)): output.append('0') for i in range(cmap.N): rgb = cmap( i)[:3] # will return rgba, we take only first 3 so we get rgb output.append(matplotlib.colors.rgb2hex(rgb)) return output
def createColorListofList(noAnimals, cMapSize): colorListofList = [] cmaps = [ 'spring', 'summer', 'autumn', 'cool', 'Wistia', 'Pastel1', 'Set1', 'winter' ] for colormap in range(noAnimals): currColorMap = cm.get_cmap(cmaps[colormap], cMapSize) currColorList = [] for i in range(currColorMap.N): rgb = list((currColorMap(i)[:3])) rgb = [i * 255 for i in rgb] rgb.reverse() currColorList.append(rgb) colorListofList.append(currColorList) return colorListofList
def ComputeGeodesicDistances(self, evt): if not self.faceMesh: print "ERROR: Haven't loaded mesh yet" return D = getGeodesicDistancesFMM(self.faceMesh) D = D[0, :] minD = min(D) maxD = max(D) print "Finished computing geodesic distances" print "minD = %g, maxD = %g"%(minD, maxD) N = D.shape[0] cmConvert = cm.get_cmap('jet') self.vertexColors = np.zeros((N, 3)) for i in range(0, N): self.vertexColors[i, :] = cmConvert((D[i] - minD)/(maxD - minD))[0:3] self.Refresh()
def plot_clusters(self, input_data, labels, show_axes, title, sub_title, fixed_coord=None, show_legend=False): # generate colors for labels cluster_no = len(set(labels)) color_map = cm.get_cmap("rainbow", cluster_no) #rainbow, jet colors = np.array([color_map(int(x)) for x in labels]) # apply dimension reduction if needed input_data = self.dim_reduction(input_data) # resolve axis if fixed_coord is not None: min_x = fixed_coord[0] max_x = fixed_coord[1] min_y = fixed_coord[2] max_y = fixed_coord[3] plt.axis([min_x, max_x, min_y, max_y]) else: min_x = input_data[:, 0].min() max_x = input_data[:, 0].max() min_y = input_data[:, 1].min() max_y = input_data[:, 1].max() plt.axis([min_x - max_x/5, max_x + max_x/5, min_y - max_y/5, max_y + max_y/5]) # get reference to current plot and hide axis plot_ref = plt.gca() if not show_axes: plot_ref.get_xaxis().set_visible(False) plot_ref.axes.get_yaxis().set_visible(False) # plot text, top and bottom plt.text(0, 1, title, horizontalalignment='left', verticalalignment='bottom', transform=plot_ref.axes.transAxes) plt.text(0, 0, '\n' + sub_title, horizontalalignment='left', verticalalignment='top', transform=plot_ref.axes.transAxes) else: # plot text, top and bottom plt.text(0, 1, title, horizontalalignment='left', verticalalignment='bottom', transform=plot_ref.axes.transAxes) plt.text(0, 0, '\n\n' + sub_title, horizontalalignment='left', verticalalignment='top', transform=plot_ref.axes.transAxes) new_lines = sub_title.count("\n") + 1 plt.gcf().subplots_adjust(bottom=new_lines * 0.06) # plot data, one scatter cmd for each cluster designating also the label labels = np.array(labels) for label_no in range(cluster_no): idxs = np.where(labels == label_no) plt.scatter(input_data[idxs][:, 0], input_data[idxs][:, 1], c=colors[idxs], s=50, label="C" + str(label_no)) if show_legend is True: plt.legend(loc='lower left', bbox_to_anchor=(1.1, 0), ncol=5)
def getHeatFlow(self, evt): dlg = wx.TextEntryDialog(None, 'Time Parameter', 'Choose Time Parameter', '1') if dlg.ShowModal() == wx.ID_OK: indices = [a for a in self.laplacianConstraints] t = float(dlg.GetValue()) k = min(100, len(self.mesh.vertices) - 1) cmConvert = cm.get_cmap("jet") (x, self.eigvalues, self.eigvectors) = self.mesh.getHeatFlowFromPoints( indices, k, t, self.eigvalues, self.eigvectors) #x = x/np.max(x) #Should already be in the range [0, 1] for i in range(len(self.mesh.vertices)): self.mesh.vertices[i].color = cmConvert(x[i]) self.mesh.needsDisplayUpdate = True self.Refresh() dlg.Destroy()
def ComputeGeodesicDistances(self, evt): if not self.mesh: print "ERROR: Haven't loaded mesh yet" return D = getGeodesicDistancesFMM(self.mesh) D = D[0, :] minD = min(D) maxD = max(D) print "Finished computing geodesic distances" print "minD = %g, maxD = %g" % (minD, maxD) N = D.shape[0] cmConvert = cm.get_cmap('jet') self.vertexColors = np.zeros((N, 3)) for i in range(0, N): self.vertexColors[i, :] = cmConvert( (D[i] - minD) / (maxD - minD))[0:3] self.Refresh()
def create_cmap(): ### Create a list of RGB tuples colors = [(229, 229, 229), (182, 165, 134), (160, 138, 91), (138, 111, 49), (140, 127, 43), (142, 143, 37), (144, 159, 31), (146, 175, 25), (138, 177, 21), (119, 165, 18), (99, 154, 15), (80, 142, 12), (60, 131, 9), (41, 119, 6), (22, 108, 3), (3, 97, 0), (0, 23, 0)] # This example uses the 8-bit RGB ### Create an array or list of positions from 0 to 1. position = [ 0, 0.04, 0.08, 0.12, 0.16, 0.20, 0.24, 0.28, 0.32, 0.36, 0.40, 0.44, 0.48, 0.52, 0.56, 0.60, 1 ] evi_cmap = make_cmap(colors, position=position, bit=True) cm.register_cmap(name='evi', cmap=evi_cmap) EVI = cm.get_cmap('evi') export_colormap('evi_colorbar', evi_cmap) return EVI
def plot_LHCNoiseFB_FWHM_bbb(time_step, LHC_noise_FB_bl_bbb, output_freq=1, dirname='fig'): """ Plot of bunch-by-bunch FWHM bunch length used in LHCNoiseFB as a function of time. For large amount of data, monitor with larger 'output_freq'. """ # Time step of plotting # time_step = RFSectionParameters.counter[0] # Load/create data if output_freq < 1: output_freq = 1 ndata = int(time_step / output_freq) t = output_freq * np.arange(ndata) x = np.array(LHC_noise_FB_bl_bbb[0:ndata, :], ndmin=2) x[time_step:, :] = np.nan nbunches = x.shape[1] # Plot fig = plt.figure(1) fig.set_size_inches(8, 6) ax = plt.axes([0.15, 0.1, 0.8, 0.8]) for i in range(nbunches): ax.plot(t, x[:, i], '.', color=cm.get_cmap('jet')(i / nbunches), label="Bunch %d" % i) ax.set_xlabel(r"No. turns [T$_0$]") ax.set_ylabel(r"4-sigma FWHM bunch length [s]") if time_step > 100000: ax.ticklabel_format(style='sci', axis='x', scilimits=(0, 0)) ax.legend() # Save figure if not os.path.exists(dirname): os.makedirs(dirname) fign = dirname + '/LHC_noise_FB_bl_bbb.png' plt.savefig(fign) plt.clf()
def colormap_skewed(exps): """Short descrtiption of this function. Parameters ---------- exps : Unknown Unknown Returns --------- cmap_skewed : matplotlib colorma Skewed colormap """ vmin_skewed = -1.0 vmid_skewed = 3.0 vmax_skewed = np.max(exps) vstep = 1.0 levels = np.arange(vmin_skewed, vmax_skewed + vstep, vstep) # cmap = cm.get_cmap('bwr', len(levels)-1) deltamax = max(vmax_skewed - vmid_skewed, vmid_skewed - vmin_skewed) # Full range either side of vmid vfull = [vmid_skewed - deltamax, vmid_skewed + deltamax] # Levels over full value range # levfull = np.arange( vfull[0], vfull[1], vstep ) ncols = len(levels) - 1 # number of colours we actually want to use vlo_frac = (vmin_skewed - vfull[0]) / (2.0 * deltamax) # 0 or greater vhi_frac = (vmax_skewed - vfull[0]) / (2.0 * deltamax) # 1 or less cmap_base = cm.get_cmap('bwr') # maps the range 0-1 to colours cols = cmap_base(np.linspace(vlo_frac, vhi_frac, ncols)) cmap_skewed = mpl_col.LinearSegmentedColormap.from_list('skewed', cols, N=ncols) cmap_skewed.set_bad('gray') cmap_skewed.set_under('w') return cmap_skewed
def getHeatKernelSignature(self, evt): dlg = wx.TextEntryDialog(None,'Time Parameter','Choose Time Parameter', '1') if dlg.ShowModal() == wx.ID_OK: t = float(dlg.GetValue()) k = min(100, len(self.mesh.vertices)-1) cmConvert = cm.get_cmap("jet") (x, self.eigvalues, self.eigvectors) = self.mesh.getHKS(k, t, self.eigvalues, self.eigvectors) plt.subplot(1, 2, 1) plt.plot(self.eigvalues) plt.title('Laplace Beltrami Eigenvalues') plt.subplot(1, 2, 2) plt.plot(np.exp(-t*self.eigvalues)) plt.title('Exponential Factors') plt.show() #x = x/np.max(x) #Should already be in the range [0, 1] for i in range(len(self.mesh.vertices)): self.mesh.vertices[i].color = cmConvert(x[i]) self.mesh.needsDisplayUpdate = True self.Refresh() dlg.Destroy()
def setupColorVBOMask(self, mask): cmConvert = cm.get_cmap('jet') if self.colorType == LoopDittyFrame.COLORTYPE_TIME: self.glcanvas.XColors = cmConvert(np.linspace(0, 1, self.DelaySeries.shape[0] ))[:, 0:3] elif self.colorType == LoopDittyFrame.COLORTYPE_DENSITY: self.getDSorted() density = np.mean(self.DSorted[1:self.densityNeighbors+1, :], 0).flatten() density = density/np.max(density) density = 1 - density #Close near neighbors implies high density density = density #Stretch out color range self.glcanvas.XColors = cmConvert(density)[:, 0:3] elif self.colorType == LoopDittyFrame.COLORTYPE_HKS: self.getHKSEig() hks = np.array(np.exp(-self.hksEigVals*self.hksTime)*self.hksEigVecs) hks = hks*hks hks = np.sqrt(hks.sum(1)) hks = hks/np.max(hks) self.glcanvas.XColors = cmConvert(hks)[:, 0:3] self.glcanvas.XColors = self.glcanvas.XColors[mask, :] self.glcanvas.XColorsVBO = vbo.VBO(np.array(self.glcanvas.XColors, dtype='float32'))
def plot_LHCNoiseFB_FWHM_bbb(time_step, LHC_noise_FB_bl_bbb, output_freq=1, dirname='fig'): """ Plot of bunch-by-bunch FWHM bunch length used in LHCNoiseFB as a function of time. For large amount of data, monitor with larger 'output_freq'. """ # Time step of plotting # time_step = RFSectionParameters.counter[0] # Load/create data if output_freq < 1: output_freq = 1 ndata = int(time_step/output_freq) t = output_freq*np.arange(ndata) x = np.array(LHC_noise_FB_bl_bbb[0:ndata, :], ndmin=2) x[time_step:, :] = np.nan nbunches = x.shape[1] # Plot fig = plt.figure(1) fig.set_size_inches(8, 6) ax = plt.axes([0.15, 0.1, 0.8, 0.8]) for i in range(nbunches): ax.plot(t, x[:, i], '.', color=cm.get_cmap( 'jet')(i/nbunches), label="Bunch %d" % i) ax.set_xlabel(r"No. turns [T$_0$]") ax.set_ylabel(r"4-sigma FWHM bunch length [s]") if time_step > 100000: ax.ticklabel_format(style='sci', axis='x', scilimits=(0, 0)) ax.legend() # Save figure if not os.path.exists(dirname): os.makedirs(dirname) fign = dirname + '/LHC_noise_FB_bl_bbb.png' plt.savefig(fign) plt.clf()
def getHeatKernelSignature(self, evt): dlg = wx.TextEntryDialog(None, 'Time Parameter', 'Choose Time Parameter', '1') if dlg.ShowModal() == wx.ID_OK: t = float(dlg.GetValue()) k = min(100, len(self.mesh.vertices) - 1) cmConvert = cm.get_cmap("jet") (x, self.eigvalues, self.eigvectors) = self.mesh.getHKS(k, t, self.eigvalues, self.eigvectors) plt.subplot(1, 2, 1) plt.plot(self.eigvalues) plt.title('Laplace Beltrami Eigenvalues') plt.subplot(1, 2, 2) plt.plot(np.exp(-t * self.eigvalues)) plt.title('Exponential Factors') plt.show() #x = x/np.max(x) #Should already be in the range [0, 1] for i in range(len(self.mesh.vertices)): self.mesh.vertices[i].color = cmConvert(x[i]) self.mesh.needsDisplayUpdate = True self.Refresh() dlg.Destroy()
class Settings: """ This class represents settings of the graph that will be plotted and bees algorithm parameters. The graph is in 2d despite that fact that it represents a 3d function (color of the point represents a z coordinate of the corresponding point) GRAPH SETTINGS: - XRANGE (tuple(float or int)): tuple of 2 numbers that specifies that minimal and maximal x limits respectively - YRANGE (tuple(float or int)): tuple of 2 numbers that specifies that minimal and maximal y limits respectively - COLORMAP (matplotlib colormap object): it is used to determine the color of the point according to its z coordinate - LOCALSKIPNUM (int) - number of points that will be plotted in 1 frame while exploring the neighbourhood of the point - BIGGESTOBSERVED (float) - benchmark - biggest function value z that was observed in xrange and yrange (it is needed to determine the color of the point plotted) - LOWESTOBSERVED (float) - benchmark - smallest function value z that was observed in xrange and yrange (it is needed to determine the color of the point plotted) POINTS SETTINGS: there are 4 types of points that can be plotted on the graph 1) BEST - the best fit of all considered points (global minimum) this point has ther biggest size 2) LOCALBEST - the best point in the neighbourhood it is smaller than GLOBALBEST 3) BAD - point that is neither GLOBALBEST nor LOCALBEST it is smaller than LOCALBEST 4) TOR - a transparent point with solid border that represents borders of the neighbourhood (it is the biggest one) there are settings for each of the 4 types they include - width of the border (for tor) - color of the border (for all) - color (fr tor) - size (for all) - opacity (for all) List of all point settings: - SIZEBEST (int or float) - SIZELOCALBEST (int or float) - SIZEBAD (int or float) - SIZETOR (int or float) - BORDERCOLORBEST - RGBA color (see features documentation for more details) - BORDERCOLORLOCALBEST - RGBA color - BORDERCOLORBAD - RGBA color - BORDERCOLOROR - RGBA color - OPACITYBEST - float in range [0; 1] - OPACITYLOCALBEST - float in range [0; 1] - OPACITYBAD - float in range [0; 1] - FILLCOLORTOR - GRBA color - BORDERWIDTH - int BEES ALGORITHM SETTINGS: - FUNC (func(float, float) -> float) - function researched. It should return you z coordinate be providing x and y - BEESNUM (int) - number of neighbourhoods to consider (scoutbees) - ELITE (int) - number of elite neighbourhoods - NONELITE (int) - number of nonelite neighbourhood - RECRUITEDELITE (int) - number of points to explore in elite neighbourhoods - RECRUITEDNONELITE (int) - number of points to explore in nonelite neighbourhoods - NGH (int) - size of the neighourhood """ XRANGE = (-10, 10) YRANGE = (-10, 10) COLORMAP = cm.get_cmap('hot') SIZEBEST = 300 SIZELOCALBEST = 100 SIZEBAD = 10 SIZETOR = 100000 / 2.54 BORDERCOLORBEST = (0, 0, 0, 0) BORDERCOLORLOCALBEST = (0, 0, 0, 0) BORDERCOLORBAD = (0, 0, 0, 0) BORDERCOLORTOR = (0, 0, 0, 1) OPACITYBEST = 1 OPACITYLOCALBEST = 1 OPACITYBAD = 1 FILLCOLORTOR = (0, 0, 0, 0) BORDERWIDTH = 3 BIGGESTOBSERVED = 1 LOWESTOBSERVED = -3 BEESNUM = 100 ELITE = 10 NONELITE = 5 RECRUITEDELITE = 100 RECRUITEDNONELITE = 20 NGH = 2 LOCALSKIPNUM = 10 FUNC = cross_in_tray @classmethod def getrgbcolor(cls, z): """ :param z (float): function value in some point :return (list(float)): returns RGB representation of the color that corresponds to function value z and colormap given in settings (see Features documentation to get more about RGB color) """ percent = (z - cls.LOWESTOBSERVED) / (cls.BIGGESTOBSERVED - cls.LOWESTOBSERVED) percent = min(percent, 1 - (1e-9)) percent = max(percent, 1e-9) color = cls.COLORMAP(percent) return list(color)[:3] @classmethod def getbest(cls, coordinate): """ :param coordinate (Coorindate): coordinate of the point in Cartesian space :return (Point): BEST point that corresponds to coordinate provided (see more in settings documentation) """ color = cls.getrgbcolor(coordinate.z) color.append(cls.OPACITYBEST) features = Features(cls.SIZEBEST, color, cls.BORDERCOLORBEST) res = Point(coordinate, features) return res @classmethod def getlocalbest(cls, coordinate): """ :param coordinate (Coorindate): coordinate of the point in Cartesian space :return (Point): LOCALBEST point that corresponds to coordinate provided (see more in settings documentation) """ color = cls.getrgbcolor(coordinate.z) color.append(cls.OPACITYLOCALBEST) features = Features(cls.SIZELOCALBEST, color, cls.BORDERCOLORLOCALBEST) res = Point(coordinate, features) return res @classmethod def getbad(cls, coordinate): """ :param coordinate (Coorindate): coordinate of the point in Cartesian space :return (Point): LOCALBEST point that corresponds to coordinate provided (see more in settings documentation) """ color = cls.getrgbcolor(coordinate.z) color.append(cls.OPACITYBAD) features = Features(cls.SIZEBAD, color, cls.BORDERCOLORBAD) res = Point(coordinate, features) return res @classmethod def gettor(cls, coordinate): """ :param coordinate (Coorindate): coordinate of the point in Cartesian space :return (Point): TOR point that corresponds to coordinate provided (see more in settings documentation) """ color = cls.FILLCOLORTOR features = Features(cls.SIZETOR, color, cls.BORDERCOLORTOR) res = Point(coordinate, features) return res
def phase_noise_diffusion(Ring, RFStation, spectrum, distribution, distributionBins, Ngrids = 200, M = 1, iterations = 100000, figdir = None): ''' Calculate diffusion in action space according to a given double-sided phase noise spectrum, on a uniform grid in oscillation amplitude. The spectrum is defined on the grid points (Ngrids + 1 points) for all M. The particle distribution in action is defined on the grids (Ngrids points). Returns the diffused action distribution. Optional: define number of side-bands (M) to be taken into account, default is M = 1; N.B. this will only give impair modes for phase noise. Optional: number of iterations to track. Optional: save figures into directory 'figdir'. ''' # Input check N = Ngrids if spectrum.shape != (M, N+1): #NoiseDiffusionError raise RuntimeError("In phase_noise_diffusion(): spectrum has to have shape (M, Ngrids+1)!") if len(distribution) != N: #NoiseDiffusionError raise RuntimeError("In phase_noise_diffusion(): distribution has to be an array of Ngrids elements!") # Some constants T0 = Ring.t_rev[0] omega_s0 = RFStation.omega_s0[0] h = RFStation.harmonic[0,0] Jsep = 8.*omega_s0/(np.pi*h**2) # Action at the separatrix # Settings for plots plt.rc('axes', labelsize=16, labelweight='normal') plt.rc('lines', linewidth=1.5, markersize=6) plt.rc('font', family='sans-serif') plt.rc('legend', fontsize=12) # Construct action grid phimax = np.linspace(0., np.pi, N+1, endpoint=True) xx = x2(phimax) J = action_from_phase_amplitude(xx) dJ = J[1:] - J[:-1] # Differential on grid Jav = 0.5*(J[1:] + J[:-1]) # Average on grid # Interpolate distribution distributionInterp = np.interp(Jav, distributionBins, distribution) # Normalise distribution distributionInterp /= int.simps(distributionInterp, Jav) # Construct weighting function Wm = np.zeros((M, N+1)) for k in range(0,M): m = 2*k+1 Wm[k][:] = (np.pi*m/ellipk(xx))**4 / \ (4.*np.cosh(0.5*np.pi*m*ellipk(1-xx)/ellipk(xx))**2) # Diffusion coefficient for stationary bucket, according to Ivanov # Twice the sum over positive frequencies for double-sided spectrum D = (omega_s0/h)**4*np.sum(Wm*spectrum,axis=0) Dav = 0.5*(D[1:] + D[:-1]) # Average on grid ax = plt.axes([0.15, 0.1, 0.8, 0.8]) ax.plot(J,D) ax.set_xlabel(r"Relative action (J/J$_{\mathrm{sep}}$)") ax.set_ylabel(r"Diffusion coefficient [rad$^2$/s$^3$]") if figdir: plt.savefig(figdir+"D_vs_J.png") plt.clf() else: plt.show() ax = plt.axes([0.15, 0.1, 0.8, 0.8]) for k in range(0,M): ax.plot(J,Wm[k],color=cm.get_cmap('jet')(k/M), label="m=%d mode"%(2*k+1)) ax.set_xlabel(r"Relative action (J/J$_{\mathrm{sep}}$)") ax.set_ylabel(r"Weight function W$_m$ [1]") plt.legend(loc=0) if figdir: plt.savefig(figdir+"Wm_vs_J.png") plt.clf() else: plt.show() # Discretised diffusion equation ------------------------------------------ A = np.zeros((N,N),float) for i in range(1,N-1): A[i,i-1] = dJ[i-1] A[i,i] = 2.*(dJ[i-1]+dJ[i]) A[i,i+1] = dJ[i] A[0,0] = 2.*dJ[0] A[0,1] = dJ[0] A[N-1,N-2] = dJ[N-2] A[N-1,N-1] = 2.*(dJ[N-2]+dJ[N-1]) A *= Jsep/6. B = np.zeros((N,N),float) for i in range(1,N-1): B[i,i-1] = -Dav[i-1]/dJ[i-1] B[i,i] = Dav[i-1]/dJ[i-1] + Dav[i]/dJ[i] B[i,i+1] = -Dav[i]/dJ[i] B[0,0] = Dav[0]/dJ[0] B[0,1] = -Dav[0]/dJ[0] B[N-1,N-2] = -Dav[N-2]/dJ[N-2] B[N-1,N-1] = Dav[N-2]/dJ[N-2]+Dav[N-1]/dJ[N-1] B /= Jsep # Time evolution ---------------------------------------------------------- M1 = A - T0 * B / 2. M2 = A + T0 * B / 2. M1 = np.matrix(M1) M2 = np.matrix(M2) F = np.matrix(distributionInterp) Mtot = np.dot(M2.I,M1) Fold = F.T for i in range(0,iterations): Fnew = np.dot(Mtot,Fold) Fold = Fnew # Back to array for post-processing Fnew = Fnew.T F = np.array(F,order=0) Fnew = np.array(Fnew,order=0) # Plot -------------------------------------------------------------------- # Distributions along action J norm_J_i = int.simps(F[0], Jav) norm_J_f = int.simps(Fnew[0], Jav) J_av_i = int.simps(F[0]*Jav, Jav)/norm_J_i J_av_f = int.simps(Fnew[0]*Jav, Jav)/norm_J_f # Conversion in SHORT-BUNCH APPROXIMATION!!! sigma_phi_i = np.sqrt(8./np.pi*J_av_i) sigma_phi_f = np.sqrt(8./np.pi*J_av_f) tau_i = sigma_phi_i*2*T0/h/np.pi*1.e9 tau_f = sigma_phi_f*2*T0/h/np.pi*1.e9 ax = plt.axes([0.12, 0.1, 0.78, 0.8]) ax.plot(Jav,F[0],"b",label="Initial distribution") ax.plot(Jav,Fnew[0],"r",label="Final distribution") ax.set_xlabel(r"Relative action (J/J$_{\mathrm{sep}}$)") ax.set_ylabel("Particle distribution [1]") plt.legend(loc=1) ax2 = plt.twinx(ax) for k in range(0,M): ax2.plot(J,spectrum[k],color=cm.get_cmap('jet')(k/M), alpha=0.5) ax2.fill_between(J,0,spectrum[k],color=cm.get_cmap('jet')(k/M), alpha=0.2) ax2.set_ylabel(r"Double-sided spectral density [rad$^2$/Hz]") ax2.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.figtext(0.6,0.7,r'$\int_0^{J_{sep}}{F_i(J)}dJ=$ %.3f'%norm_J_i, fontsize=14, ha='left', va='center') plt.figtext(0.6,0.625,r'$\int_0^{J_{sep}}{F_f(J)}dJ=$ %.3f'%norm_J_f, fontsize=14, ha='left', va='center') plt.figtext(0.6,0.55,r'$<J>_i=$ %.4e s'%J_av_i, fontsize=14, ha='left', va='center') plt.figtext(0.6,0.5,r'$<J>_f=$ %.4e s'%J_av_f, fontsize=14, ha='left', va='center') plt.figtext(0.4,0.4,"Converting in short-bunch approximation...", fontsize=12, ha='left', va='center') plt.figtext(0.6,0.35,r'$\sigma_{\varphi}^{(i)}=$ %.4f rad'%sigma_phi_i, fontsize=12, ha='left', va='center') plt.figtext(0.6,0.3,r'$\sigma_{\varphi}^{(f)}=$ %.4f rad'%sigma_phi_f, fontsize=12, ha='left', va='center') plt.figtext(0.6,0.25,r'$\tau_{4\sigma}^{(i)}=$ %.4f ns'%tau_i, fontsize=12, ha='left', va='center') plt.figtext(0.6,0.2,r'$\tau_{4\sigma}^{(f)}=$ %.4f ns'%tau_f, fontsize=12, ha='left', va='center') if figdir: plt.savefig(figdir+"F_vs_J.png") plt.clf() else: plt.show() return Jav, distributionInterp, Fnew[0]
#cutoff = 0.99*max(I(:, 2)); #TODO: Figure out threshold automatically cutoff = 0.8 #http://www.mrzv.org/software/dionysus/examples/cohomology.html fout = open('points.txt', 'w') for i in range(Y.shape[0]): for j in range(Y.shape[1]): fout.write("%g "%Y[i, j]) fout.write("\n") fout.close() subprocess.call(['./rips-pairwise-cohomology', 'points.txt', '-m', "%g"%cutoff, '-b', 'points.bdry', '-c', 'points', '-v', 'points.vrt', '-d', 'points.dgm']) theta = extractCocycle('points.bdry', 'points-0.ccl', 'points.vrt') circorder = np.argsort(theta) #Step 4: Make plots cmConvert = cm.get_cmap('jet') Colors = cmConvert(np.linspace(0, 1, len(y) ))[:, 0:3] plt.subplot(2, 2, 1) plt.plot(t, y) plt.hold(True) #plt.scatter(t, y, 20, Colors) plt.title('Original (%i sines %i samples per period)'%(NSines, SamplesPerPeriod)) plt.subplot(2, 2, 2) Y, varExplained = doPCA(Y) plt.scatter(Y[:, 0], Y[:, 1], 20, Colors[0:Y.shape[0], :]) plt.title('PCA Delay Embedding %.3g Percent Var Explained'%(100*varExplained)) plt.subplot(2, 2, 3) plt.plot(y[circorder]) plt.title('Resorted by Delay Coordinate Angles')
from pylab import cm maps=[m for m in cm.datad] maps.sort() print '#include "ColorMaps.hh"' print '' print 'using namespace Ami::Qt;' print '' print '// This file was automatically generated by Generate_ColorMaps_cc.py' print '' # Create a colormap_xxx array for each colormap. # Encode rgb bytes [0..255] into a single unsigned int. for j, name in enumerate(maps): cmap = cm.get_cmap(name) print 'static unsigned int colormap_%s[] = {' % name, for i in range(0, 256): rgb = cmap(i) r = min(int(256 * rgb[0]), 255) g = min(int(256 * rgb[1]), 255) b = min(int(256 * rgb[2]), 255) hex = 256*256*r + 256*g + b print '0x%x,' % (hex), print '};' print '' # Create the constructor, which inserts every # colormap_xxx array into a map with xxx as the key. print 'ColorMaps::ColorMaps() {' for j, name in enumerate(maps):
# Setup ASET map (floor of 30 m x 10 m) # define floor elements' extension in meters delta = 0.6 # define floor elements' centers x = np.arange(delta / 2, 30, delta) y = np.arange(delta / 2, 10, delta) # create an empty map with a maximal ASET of 120 seconds aset_map = np.zeros((len(y), len(x))) aset_map[:] = 120 aset_map_glob = np.zeros_like(aset_map) aset_map_glob[:] = 120 cmap = cm.get_cmap('RdYlGn', 12) cmap_g = cm.get_cmap('Greys') for q in quantities: slices = glob.glob('HRR_60kW/ascii_slices/{}/*.txt'.format(q)) slices = sorted(slices, key=lambda slice: int(slice[slice.rfind('_') + 1:-4])) for i, slice in enumerate(slices[:]): slice_nr = int(slice[slice.rfind('_') + 1:-4]) print("\t --> ", slice_nr) # load ascii slice file sf = np.loadtxt(slice, delimiter=' ')
def create_location_measurement(self, signal): self._calculate_log_odds(signal) #Create Scaled Version of probabilityData, no interpolation - scaling allows for edge detection to work nicely if self.cv_scale > 1: self.object_tracking_matrix = ndimage.zoom(self.odds_cells_occupied.prob_cells_occupied_shaped, self.cv_scale, order=0) else: self.object_tracking_matrix = self.odds_cells_occupied.prob_cells_occupied_shaped #create a colour map to map numbers between 0,1 to a BGR colour map mycm = cm.get_cmap(self._my_cmap) # Don't need to normalise as already between 0 and 1 and we want # to threshold based on our belief that an object is present # noinspection PyUnresolvedReferences self.object_tracking_matrix = (255 * mycm(self.object_tracking_matrix)).astype('uint8') # Convert image to gray scale self.object_tracking_matrix = cv2.cvtColor(self.object_tracking_matrix, cv2.COLOR_BGR2GRAY) # blur image to highlight contours (small kernel used here) self.object_tracking_matrix = cv2.blur(self.object_tracking_matrix, (2, 2)) # Invert the image and drop all content that is below threshold # which is now a % of 255 & invert the image to show # Body up as white & background as black. ret, self.object_tracking_matrix = cv2.threshold(self.object_tracking_matrix, int((1 - self.object_prob_threshold) * 255), 255, cv2.THRESH_BINARY_INV) # find contours in the image; Only want external ones RETR_EXTERNAL, & just polygon data CHAIN_APPROX_SIMPLE contours, hierarchy = cv2.findContours(self.object_tracking_matrix, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) #Recast tracking matrix with just outlines of objects cv2.drawContours(self.object_tracking_matrix, contours, -1, 128, 1) #Compute the bounding circles for returned contours bounding_circles = np.array([(cv2.minEnclosingCircle(cnt)) for cnt in contours]) #look for overlapping circles and merge optimising the size of the new bounding circle checked_circles = [] for bnd_circle in bounding_circles: #Add original tracking circles to Tracking Matrix cv2.circle(self.object_tracking_matrix, (int(bnd_circle[0][0]), int(bnd_circle[0][1])), int(bnd_circle[1]),64,1) cv2.circle(self.object_tracking_matrix, (int(bnd_circle[0][0]), int(bnd_circle[0][1])), int((10 / 40.) * self.cv_scale), 64, -1) if len([checked_circle for checked_circle in checked_circles if self._is_overlap(checked_circle, bnd_circle)]) == 0: checked_circles.append(bnd_circle) else: #Take Larger of Two Circles for check in [checked_circle for checked_circle in enumerate(checked_circles) if self._is_overlap(checked_circle[1], bnd_circle)]: if bnd_circle[1] > check[1][1]: #bnd_circle[1] = max(g(checked_circle[1],bnd_circle),bnd_circle[1]) checked_circles[check[0]] = self._circle_from_2_circles(check[1], bnd_circle) #Object Present if len(checked_circles) > 0: #Simple case - assume only tracking single object we keep only the largest circle checked_circles = np.array(checked_circles) self.tracking_circle = checked_circles[checked_circles[:, 1].argmax()] #Add Tracking Circles to Matrix cv2.circle(self.object_tracking_matrix, (int(self.tracking_circle[0][0]), int(self.tracking_circle[0][1])), int(self.tracking_circle[1]), 255, 1) cv2.circle(self.object_tracking_matrix, (int(self.tracking_circle[0][0]), int(self.tracking_circle[0][1])), int((10 / 40.) * self.cv_scale), 255, -1) # the angle of arrival for a pixel is based on the FOV for the sensor and the number of pixels # in the image we can then simply work out the local aoa based on the number of # using the center of the tracking circle fov = self.sensor_properties.fov theta = lambda x: fov/2. - x*(fov / (self.sensor_properties.sensing_array_columns * float(self.cv_scale))) self._aoa = theta(self.tracking_circle[0][0]) self._number_of_objects = 1 else: self._number_of_objects = 0 self.tracking_circle = None self._aoa = np.nan # noinspection PyUnresolvedReferences self.time_stamp = self.last_sensor_reading.time_stamp self.location_measurement = AngularLocationMeasurement(self._aoa, self._number_of_objects, self.time_stamp, self.sensor_properties,self.name) #Added Observer Pattern to Class to Allow Fusion Model to Subscribe to Measurement Changes self._publish_location_measurement() return self.location_measurement
def main(): # Parse command line arguments parser = OptionParser() parser.usage = "%prog [options] map_file" parser.add_option('-l','--logscale',dest='logscale', action='store_true', help='use log color scaling', default=False) parser.add_option("-o","--output", dest="outfile", metavar="FILE", help='output image file [default: <map_file>.png]', default=None) parser.add_option("-m","--min", dest="min", metavar="VALUE", help='min value', default=None) parser.add_option("-M","--max", dest="max", metavar="VALUE", help='max value', default=None) parser.add_option('-a','--autorange',dest='autorange', action='store_true', help='use automatic dynamic range (no min/max)', default=False) parser.add_option('--big-endian',dest='big_endian', action='store_true', help='input binary data is stored as big endian', default=False) parser.add_option('-c','--colormap',dest='cmap_str', metavar='CMAP', help='matplotlib color map to use', default="jet") (opts,args)=parser.parse_args() # Parse input and output try: infile = args[0] except: print(parser.print_help()) return 1 if(opts.outfile==None): outfile=infile+'.tif' else: outfile=opts.outfile # Endianness if(opts.big_endian): endianness = ">" else: endianness = "=" # Read image data #print("Reading raw Fortran data...") f = fortranfile.FortranFile(infile) [nx,ny] = f.read_fortran_record('i4', endian=endianness) dat = f.read_fortran_record('f4', endian=endianness) f.close() if(opts.logscale): dat = np.array(dat)+1e-12 rawmin = np.amin(dat) rawmax = np.amax(dat) #print(' Image map size : ',(nx, ny)) #print(' Data bounds : ',(rawmin,rawmax)) #print("Scaling data and processing colormap...") # Bounds if opts.min==None: plotmin = rawmin else: plotmin = float(opts.min) if opts.max==None: plotmax = rawmax else: plotmax = float(opts.max) # Log scale? if(opts.logscale): dat = np.log10(dat) rawmin = np.log10(rawmin) rawmax = np.log10(rawmax) plotmin = np.log10(plotmin) plotmax = np.log10(plotmax) # Auto-adjust dynamic range? if(opts.autorange): #print("Computing dynamic range...") # Overrides any provided bounds NBINS = 200 # Compute histogram (hist,bins) = np.histogram(dat, NBINS, (rawmin,rawmax), normed=True) chist = np.cumsum(hist); chist = chist / np.amax(chist) # Compute black and white point clip_k = chist.searchsorted(0.05) plotmin = bins[clip_k] plotmax = rawmax if(plotmax-plotmin>0): dat = np.clip((dat-plotmin)/(plotmax-plotmin), 0.0, 1.0) else: dat = 0.5*dat/plotmax # if(opts.logscale): #print(' Color bounds : ',(10**plotmin,10**plotmax)) # else: #print(' Color bounds : ',(plotmin,plotmax)) # Apply chosen color map color_map = cm.get_cmap(opts.cmap_str) dat = color_map(dat)*255 # Convert to int dat = np.array(dat, dtype='i') # Output to file #print("Saving image to file...") R_band = Image.new("L",(nx,ny)) R_band.putdata(dat[:,0]) G_band = Image.new("L",(nx,ny)) G_band.putdata(dat[:,1]) B_band = Image.new("L",(nx,ny)) B_band.putdata(dat[:,2]) out_img = Image.merge("RGB", (R_band, G_band, B_band)).transpose(Image.FLIP_TOP_BOTTOM) out_img.save(outfile) print("map2img.py completed")
def plotting(fit_solution): dist, measure, simulation_adjust = fitnessCfl(fit_solution, models="true") from pylab import cm import matplotlib as mpl import matplotlib.pyplot as plt colors = cm.get_cmap('tab10', 10) f, (ax1, ax2) = plt.subplots(2, 1) ax1.plot(simulation_adjust.t, simulation_adjust.i, linewidth=3, color=colors(0), label=' i-simulada') ax1.plot(measure.t, measure.i, linewidth=3, color=colors(1), label='i- medida') ax1.set_title('Resultados') ax1.set_xlim(0, measure.t[-1]) ax1.set_ylim(min(measure.i) - 0.1, max(measure.i) + 0.1) # ax1.set_xlabel('Iteracion(i)') ax1.set_ylabel(r'Corriente(A)', labelpad=10) # ax1.spines['right'].set_visible(False) # ax1.spines['top'].set_visible(False) ax1.xaxis.set_tick_params(which='major', size=10, width=2, direction='in') ax1.xaxis.set_tick_params(which='minor', size=7, width=2, direction='in') ax1.yaxis.set_tick_params(which='major', size=10, width=2, direction='in') ax1.yaxis.set_tick_params(which='minor', size=7, width=2, direction='in') ax1.grid(True) ax1.xaxis.set_major_locator(mpl.ticker.MultipleLocator(1 / 120)) ax1.xaxis.set_minor_locator(mpl.ticker.MultipleLocator(1 / 240)) ax1.yaxis.set_major_locator(mpl.ticker.MultipleLocator(max(measure.i) / 4)) ax1.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(max(measure.i) / 2)) ax1.legend(bbox_to_anchor=(0.78, 0.8), loc=10, frameon=True, fontsize=14) ax2.plot(simulation_adjust.t, simulation_adjust.v, linewidth=3, color=colors(0), label='v-simulada') ax2.plot(measure.t, measure.v, linewidth=3, color=colors(1), label='v-medida') ax2.set_xlim(0, measure.t[-1]) ax2.set_ylim(min(measure.v) - 10, max(measure.v) + 10) ax2.set_ylabel(r'Tension(V)', labelpad=10) ax2.xaxis.set_tick_params(which='major', size=10, width=2, direction='in') ax2.xaxis.set_tick_params(which='minor', size=7, width=2, direction='in') ax2.yaxis.set_tick_params(which='major', size=10, width=2, direction='in') ax2.yaxis.set_tick_params(which='minor', size=7, width=2, direction='in') ax2.grid(True) ax2.xaxis.set_major_locator(mpl.ticker.MultipleLocator(1 / 120)) ax2.xaxis.set_minor_locator(mpl.ticker.MultipleLocator(1 / 240)) ax2.yaxis.set_major_locator(mpl.ticker.MultipleLocator(50)) ax2.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(25)) ax2.legend(bbox_to_anchor=(0.78, 0.8), loc=10, frameon=True, fontsize=14) plt.figure() plt.subplot(211) plt.plot(simulation_adjust.t, simulation_adjust.i) plt.plot(measure.t, measure.i) plt.subplot(212) plt.plot(simulation_adjust.t, simulation_adjust.v) plt.plot(measure.t, measure.v) from sklearn.metrics import mean_squared_error mse = mean_squared_error(measure.i, simulation_adjust.i) rmse = np.sqrt(mse) rms_v = np.sqrt(np.mean(measure.v**2)) rms_imeas = np.sqrt(np.mean(measure.i**2)) rms_isim = np.sqrt(np.mean(simulation_adjust.i**2)) square_relative_error_fromIrms = rmse / rms_imeas relative_root_mean_square_error = rmse / sum(measure.i) metrics = [ dist, mse, rmse, square_relative_error_fromIrms, relative_root_mean_square_error ] return metrics
def set_color(self, color): cpy = copy.copy(self) cpy.color = color return cpy import matplotlib.font_manager as fm # Rebuild the matplotlib font cache # Collect all the font names available to matplotlib font_names = [f.name for f in fm.fontManager.ttflist] # print(font_names) fm._rebuild() colors = cm.get_cmap('tab10', 2) mpl.rcParams['font.family'] = 'Helvetica' plt.rcParams['font.size'] = 6 plt.rcParams['axes.linewidth'] = 1 x_size = 100*2 y_size = 50 a = np.linspace(0,120, 100) b = np.random.random([100]) c = np.sin(a/10) n_plots_x = 2 n_plots_y = 1
plt.close() fig = plt.figure(figsize=(8 , 4.5)) # inch -> cm /2.54 ax1 = fig.add_subplot(111) ax1.set_title('Difference map') # plot the room ax1.plot([0,0], [0,10.2], c='grey', lw=15) ax1.plot([0,30], [10.2,10.2], c='grey', lw=15) ax1.plot([0,30], [0,0], c='grey', lw=15) ax1.plot([30,30], [0,7.5], c='grey', lw=15) ax1.plot([30,30], [9.5,10], c='grey', lw=15) # colorbar with contrastive limiting state ASET-RSET = 0 top = cm.get_cmap('cool_r', 120) bottom = cm.get_cmap('autumn', 120) newcolors = np.vstack((top(np.arange(0, 120, 20)), bottom(np.arange(0, 120, 20)))) newcmp = matplotlib.colors.ListedColormap(newcolors, name='ASETvsRSET', N=12) dd = ax1.pcolorfast(x, y, diff_map, vmin=-60, vmax=60, cmap=newcmp) cb = plt.colorbar(dd, label='ASET-RSET in s', orientation='horizontal') cb.set_ticks( np.arange(-120, 121, 20) ) cbar_ticks = cb.ax.get_xticklabels() cbar_ticks[-1]='> 60' cb.ax.set_yticklabels( cbar_ticks ) ax1.set_xlabel('x in m')
# model_timebnds = data.variables['time_bounds'][:] # # netcdfExtend = get_extend(x, y) # # print(data.variables['air_temp'].units) # if data.variables['air_temp_snapshot'].units == 'Kelvin': # modeltemp = modeltemp - 273 data.close() #### original ice thickness # data = Dataset(args.reference, mode='r') # thk_reference = data.variables['thk'][:] # data.close() cmap = cm.get_cmap('GnBu', 21) # 11 discrete colors cmap = cm.get_cmap('RdYlBu_r', 21) # 11 discrete colors cmap.set_under(color='white') cmap_diff = cm.get_cmap('RdBu_r', 21) # 11 discrete colors # title = args.modelfile.split('/')[-1] thk_last = thk[-1, :, :] thk_first = thk[0, :, :] # thk_first = thk_reference print("resultfile:") print(thk_last.shape) print("reference file:")
def get_cmap(cmap): _cmap = cmap if isinstance(cmap, str): _cmap = cm.get_cmap(cmap) return _cmap
####################################### # Last 30 days ####################################### print " ... Last 30 days" ax = fig.add_subplot(6, 1, 1) axs = [ax] # use masked array to hide NaN's on plot # wtm = numpy.ma.masked_where(numpy.isnan(wtemp), wtemp) # range for pcolor plots cmin = numpy.floor(wtm.min()) cmax = cmin + 8.0 # print "%s : %g %g \n" % ('Temp', cmin, cmax) # cmin, cmax = (15., 35.) # plot pcolor pc = ax.pcolor(dn, z, wtm.T, cmap=cm.get_cmap("jet"), vmin=cmin, vmax=cmax) # setup colorbar axes instance. l, b, w, h = ax.get_position() cax = fig.add_axes([l + 0.04, b + 0.02, 0.25 * w, 0.03]) cb = colorbar(pc, cax=cax, orientation="horizontal") # draw colorbar cb.set_label("Water Temperature (deg C)") cb.ax.xaxis.set_label_position("top") cb.ax.set_xticks([0.1, 0.3, 0.5, 0.7, 0.9]) # make tick labels for 10 posns set and round to one decimal place xtl = numpy.round(numpy.linspace(cmin, cmax, 10), decimals=1) # but only select one at set_xticks cb.ax.set_xticklabels([xtl[1], xtl[3], xtl[5], xtl[7], xtl[9]]) # ax.plot returns a list of lines, so unpack tuple
def cmap_colors(): from pylab import cm cmap = cm.get_cmap('cividis', 9) for i in range(cmap.N): rgb = cmap(i)[:3] print(matplotlib.colors.rgb2hex(rgb))
def __init__(self, matfilename, soundfilename, num): self.num = num #Whether it's the original (0) or the cover (1) self.matfilename = matfilename self.soundfilename = soundfilename #Step 1: Load in precomputed beat information self.title = matfilename.split('.mat')[0] self.title = self.title.split('/')[-1] X = sio.loadmat(matfilename) self.Fs = float(X['Fs'].flatten()[0]) self.TimeLoopHists = X['TimeLoopHists'].flatten() #Cell Array self.bts = X['bts'].flatten() #1D Matrix self.LEigs = X['LEigs'].flatten() #Cell Array self.LEigs = X['LEigs'].flatten() #2D Matrix self.SampleDelays = X['SampleDelays'].flatten()/self.Fs #Cell array self.IsRips = X['IsRips'].flatten() #Cell Array self.IsMorse = X['IsMorse'].flatten() #Cell Array self.MFCCs = X['MFCCs'] #2D Matrix self.PointClouds = X['PointClouds'].flatten() self.Dists = X['Dists'] self.SampleStartTimes = np.zeros(self.SampleDelays.shape[0]) self.BeatStartIdx = np.zeros(self.SampleDelays.shape[0], dtype='int32') self.VarsExplained = np.zeros(self.SampleDelays.shape[0], dtype='int32') for i in range(self.SampleDelays.shape[0]): self.SampleDelays[i] = self.SampleDelays[i].flatten() self.SampleStartTimes[i] = self.SampleDelays[i][0] #Sort the DGMs0 by persistence since the birth time doesn't #really matter IsMorse = [] for i in range(self.IsMorse.shape[0]): if self.IsMorse[i].shape[0] > 0 and self.IsMorse[i].shape[1] > 0: P = self.IsMorse[i][:, 1] - self.IsMorse[i][:, 0] P = np.sort(P) P = P[::-1] IsMorse.append(P) else: IsMorse.append(np.array([0])) self.IsMorse = IsMorse #Step 2: Setup a vertex buffer for this song N = self.PointClouds.shape[0] if N == 0: return cmConvert = cm.get_cmap('jet') print "Doing PCA on all windows..." (self.Y, varExplained) = doCenteringAndPCA(self.PointClouds[0]) self.VarsExplained self.YColors = cmConvert(np.linspace(0, 1, self.Y.shape[0]))[:, 0:3] for i in range(1, self.PointClouds.shape[0]): (Yi, varExplained) = doCenteringAndPCA(self.PointClouds[i]) self.Y = np.concatenate((self.Y, Yi), 0) Colorsi = cmConvert(np.linspace(0, 1, self.PointClouds[i].shape[0]))[:, 0:3] self.YColors = np.concatenate((self.YColors, Colorsi), 0) self.BeatStartIdx[i] = self.BeatStartIdx[i-1] + Colorsi.shape[0] print "Finished PCA" self.YVBO = vbo.VBO(np.array(self.Y, dtype='float32')) self.YColorsVBO = vbo.VBO(np.array(self.YColors, dtype='float32')) #TODO: Free vertex buffers when this is no longer used? #Step 3: Load in the song waveform name, ext = os.path.splitext(soundfilename) #TODO: Replace this ugly subprocess call with some Python #library that understand other files if ext.upper() != ".WAV": if "temp.wav" in set(os.listdir('.')): os.remove("temp.wav") subprocess.call(["avconv", "-i", soundfilename, "temp.wav"]) self.Fs, self.waveform = wavfile.read("temp.wav") else: self.Fs, self.waveform = wavfile.read(soundfilename) if len(self.waveform.shape) > 1 and self.waveform.shape[1] > 1: self.waveform = self.waveform[:, 0] self.currBeat = 0
allclusters, alluncert, allcount, rempts = elim_points(sla_lp, lat5, lon5, nclusters, minpts, maxiter, expdir) np.savez("%s%s_Results.npz" % (datpath, expname), **{ 'lon': lon5, 'lat': lat5, 'sla': sla_lp, 'clusters': allclusters, 'uncert': alluncert, 'count': allcount, 'rempts': rempts }, allow_pickle=True) cmap2 = cm.get_cmap("jet", len(allcount) + 1) fig, ax = plt.subplots( 1, 1, subplot_kw={'projection': ccrs.PlateCarree(central_longitude=180)}) ax = slutil.add_coast_grid(ax) pcm = ax.pcolormesh(lon5, lat5, rempts, cmap=cmap2, transform=ccrs.PlateCarree()) fig.colorbar(pcm, ax=ax) ax.set_title("Removed Points") plt.savefig("%sRemovedPoints_by_Iteration.png" % (expdir), dpi=200) plt.pcolormesh(lon5, lat5, rempts)