def plot_rocs(X, Y, params=None, autoflip=False, outfile=None): """Plot multiple ROCs.""" if params is None: params = [str(i) for i in range(len(X))] assert len(X) == len(Y) == len(params) n_rows, n_cols = len(params), 1 pl.figure(figsize=(n_cols * 6, n_rows * 6)) for x, y, param, row in zip(X, Y, params, range(n_rows)): x = dwi.stats.scale_standard(x) fpr, tpr, auc = dwi.stats.calculate_roc_auc(y, x, autoflip=autoflip) pl.subplot2grid((n_rows, n_cols), (row, 0)) pl.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % auc) pl.plot([0, 1], [0, 1], 'k--') pl.xlim([0.0, 1.0]) pl.ylim([0.0, 1.0]) pl.xlabel('False Positive rate') pl.ylabel('True Positive rate') pl.title('%s' % param) pl.legend(loc='lower right') pl.tight_layout() if outfile is not None: log.info('Plotting to %s', outfile) pl.savefig(str(outfile), bbox_inches='tight') else: pl.show() pl.close()
def plot_simulation_results_initial_controls(time_points, y_sim): pl.rc("text", usetex = True) pl.rc("font", family="serif") pl.subplot2grid((4, 2), (0, 0)) pl.plot(time_points, y_sim[:,0]) pl.title("Simulation results for initial controls") pl.xlabel("t") pl.ylabel("X", rotation = 0, labelpad = 20) pl.subplot2grid((4, 2), (1, 0)) pl.plot(time_points, y_sim[:,1]) pl.xlabel("t") pl.ylabel("Y", rotation = 0, labelpad = 15) pl.subplot2grid((4, 2), (2, 0)) pl.plot(time_points, y_sim[:,2]) pl.xlabel("t") pl.ylabel(r"\phi", rotation = 0, labelpad = 15) pl.subplot2grid((4, 2), (3, 0)) pl.plot(time_points, y_sim[:,3]) pl.xlabel("t") pl.ylabel("v", rotation = 0, labelpad = 20) pl.subplot2grid((4, 2), (0, 1), rowspan = 4) pl.plot(y_sim[:,0], y_sim[:, 1]) pl.title("Simulated race car path for initial controls") pl.xlabel("X") pl.ylabel("Y", rotation = 0, labelpad = 20) pl.show()
def add_bin_gene(self, pheno, pval, samples, attributes, Yi, Yr, bMock=1): opts = list(set(attributes)) groups = { opts[j]: [i for i in range(len(attributes)) if attributes[i] == opts[j]] for j in range(len(opts)) } groups = { g: k for (g, k) in groups.items() if len(k) > 15 and g not in ['boo'] } gY = {opt: [Yi[j] for j in K] for opt, K in groups.items()} gR = {opt: [Yr[j] for j in K] for opt, K in groups.items()} ax = plt.subplot2grid((self.xLen, self.yLen), (self.xLoc, 2), rowspan=bMock, colspan=1) ax2 = plt.subplot2grid((self.xLen, self.yLen), (self.xLoc, 3), rowspan=bMock, colspan=1) self.add_data(gY, ax) self.add_data(gR, ax2) ax.set_title(pheno) ax2.set_title(str(pval)) self.xLoc += bMock
def test2_filtersb_test_real(self): """Test if filter_sideband() on real data for inspection""" # NB: jpgs are required for correct [0,1] data range. PNG data range # [0, 255] gives weird results? files = ['fringe_130622_154235Z_000082_img.jpg', 'fringe_130622_154235Z_000139_img.jpg', 'fringe_130622_154235Z_000220_img.jpg', 'fringe_130622_154235Z_000330_img.jpg', 'fringe_130622_154235Z_000412_img.jpg', 'fringe_130622_154235Z_000505_img.jpg'] fringes = [tim.file.read_file(pjoin(TESTDATAPATH,f)) for f in files] cfreq = fringe_cal(fringes, store_pow=False, do_embed=True) apt_mask = tim.im.mk_rad_mask(*fringes[0].shape) < 1 self.fcache = {} phasepow_l = [filter_sideband(i, cfreq, 0.5, method='spectral', apt_mask=apt_mask, unwrap=True, wsize=-0.5, wfunc='cosine', do_embed=True, cache=self.fcache, ret_pow=True, get_complex=False, verb=0) for i in fringes] for im, phase in zip(fringes, phasepow_l): plt.figure(400, figsize=(4,4)); plt.clf() ax0 = plt.subplot2grid((2,2),(0, 0)) ax0.set_title("fringes") ax0.imshow(im) ax1 = plt.subplot2grid((2,2),(0, 1)) ax1.set_title("log side band power") ax1.imshow(np.log(phase[2])) ax2 = plt.subplot2grid((2,2),(1, 0)) ax2.set_title("phase") ax2.imshow(phase[0]) ax3 = plt.subplot2grid((2,2),(1, 1)) ax3.set_title("amplitude") ax3.imshow(phase[1]) if (raw_input("Continue [b=break]...") == 'b'): break plt.close()
def plot_9(): fig = plt.figure(figsize=(8, 6)) ax = plt.subplot2grid((2, 2), (0, 0)) ax.plot(f, H) ax.set_xlabel("frequency (Hz)") ax.set_ylabel("Frequency filter") ax.set_ylim(0, 1.5) ax = plt.subplot2grid((2, 2), (0, 1)) ax.plot(t - 50, h.real) ax.set_xlabel("time (s)") ax.set_ylabel("convolution kernel") ax = plt.subplot2grid((2, 2), (1, 0)) # , colspan=2) ax.plot(t, f_t, label='original', alpha=0.25) ax.plot(t, f_t_filtered.real, "r", lw=2, label='filtered in frequency domain') ax.plot(t, f_t_filtered_conv.real, 'b--', lw=2, label='filtered with convolution') ax.set_xlim(0, 10) ax.set_xlabel("time (s)") ax.set_ylabel("signal") ax.legend(loc=2) ax = plt.subplot2grid((2, 2), (1, 1)) # , colspan=2) ax.plot(f[mask], np.log(abs(F[mask])), lw=2) ax.set_xlabel("frequency (Hz)") ax.set_ylabel("log(|F|)") fig.tight_layout() fig.savefig("data/ch17-convolution-filter.png")
def weightedAffineInvCompWarpCost(targetIMG, templateIMG, templateWeight, curParameters, displayStuff, targetIMGMask = None): #function [ImageWarpedToTemplate, TX, TY, ErrorIMG, CostValue] = lk_weighted_run_affine_inv_comp_warpcost(targetIMG, templateIMG, TemplateW, CurParameters, displayStuff) # [ImageWarpedToTemplate, TX, TY] = lk_warp_image_affine(targetIMG, size(templateIMG), CurParameters); targetIMGToTemplate, TX, TY = warpImageAffine(targetIMG, templateIMG.shape, curParameters) if displayStuff == True: pylab.subplot(4, 3, 5); CCSegUtils.showIMG(targetIMGToTemplate); pylab.title('template coordinates warped to image'); pylab.subplot2grid((4, 3), (1, 2), rowspan = 2, colspan = 1); pylab.cla(); CCSegUtils.showIMG(targetIMG); pylab.plot(TX[:, 0], TY[:, 0], 'b-') pylab.plot(TX[0, :], TY[0, :], 'b-') pylab.plot(TX[:, -1], TY[:, -1], 'b-') pylab.plot(TX[-1, :], TY[-1, :], 'b-') pylab.title('Coordinates on target') #print "oiajfdoijadsf" errorIMG = targetIMGToTemplate - templateIMG LKCost = numpy.sum(errorIMG * templateWeight * errorIMG) # find out if any coordinates are not in the mask if targetIMGMask != None: T = CCSegUtils.interp2q(numpy.arange(1, targetIMG.shape[1] + 1), numpy.arange(1, targetIMG.shape[0] + 1), targetIMGMask, TX, TY, extrapval = 0) if numpy.any(T == 0): LKCost = numpy.inf return (targetIMGToTemplate, TX, TY, errorIMG, LKCost)
def plot_simulation_results_initial_controls(time_points, y_sim): pl.rc("text", usetex=True) pl.rc("font", family="serif") pl.subplot2grid((4, 2), (0, 0)) pl.plot(time_points, y_sim[:, 0]) pl.title("Simulation results for initial controls") pl.xlabel("t") pl.ylabel("X", rotation=0, labelpad=20) pl.subplot2grid((4, 2), (1, 0)) pl.plot(time_points, y_sim[:, 1]) pl.xlabel("t") pl.ylabel("Y", rotation=0, labelpad=15) pl.subplot2grid((4, 2), (2, 0)) pl.plot(time_points, y_sim[:, 2]) pl.xlabel("t") pl.ylabel(r"\phi", rotation=0, labelpad=15) pl.subplot2grid((4, 2), (3, 0)) pl.plot(time_points, y_sim[:, 3]) pl.xlabel("t") pl.ylabel("v", rotation=0, labelpad=20) pl.subplot2grid((4, 2), (0, 1), rowspan=4) pl.plot(y_sim[:, 0], y_sim[:, 1]) pl.title("Simulated race car path for initial controls") pl.xlabel("X") pl.ylabel("Y", rotation=0, labelpad=20) pl.show()
def setup_main_screen(self): self.fig = pylab.figure(figsize=(6, 8)) pylab.subplots_adjust(top=.95, bottom=0.05, left=.05, right=.95, hspace=.15, wspace=.15) pylab.suptitle('Corsi Blocks') rows = 10 cols = 8 self.ax = {} #Main corsi blocks display self.ax['main'] = pylab.subplot2grid((rows, cols), (0, 0), colspan=cols, rowspan=rows - 1) self.clear_main_screen( 'Move the mouse out of this panel to start.\nA sequence of blocks will appear in this panel.\nAt the end of the sequence the panel will change color.\nAfter the color change, click on the blocks in the order they appeared.' ) #The staircase display with span estimate self.ax['staircase'] = pylab.subplot2grid((rows, cols), (9, 1), colspan=cols - 1) pylab.setp(self.ax['staircase'], 'xticks', [], 'yticks', []) self.cid = self.fig.canvas.mpl_connect('button_press_event', self.onclick) self.cid2 = self.fig.canvas.mpl_connect('axes_leave_event', self.onleaveaxes) self.cid3 = self.fig.canvas.mpl_connect('axes_enter_event', self.onenteraxes)
def okeedokee_spectrum(): f = h5py.File( 'C:/Users/Squirel/Desktop/data_abdel/Data/okeedokee_dCA3_period02.mat', 'r') #load the data data = f.get('ts_dCA3') data = pb.array( data ) #transform to numpy array --> now each element of data is an array of one float sf = 1250. # sampling freq (Hz) beg = 40 lgth = 10. #stating time (s) and length (s) of the selected period minfreq = 1. maxfreq = 50. #Hz signal = data[beg * sf:beg * sf + lgth * sf] #troncate spectrum = fft.fftn(signal) #extract spectra spec = pb.arange(minfreq, maxfreq, 1.0) # for i in range(len(spec)): spec[i] = pb.mean( abs(spectrum[(minfreq + i) * lgth:(minfreq + i) * lgth])) #display fig = pb.figure() ax1 = pb.subplot2grid((1, 3), (0, 1), colspan=2) ax2 = pb.subplot2grid((1, 3), (0, 0)) ax1.plot(signal) ax2.plot(pb.arange(minfreq, maxfreq, 1 / lgth), abs(spectrum[minfreq * lgth:maxfreq * lgth]), ".") pb.show()
def plot_representation(Theta, breaks, atoms_order, grid): J, S = Theta.shape pl.subplot2grid(grid, (grid[0] - 6, 0), rowspan=2, colspan=2) # Color boundaries and cmap vmax = 1.0 vmin = -1.0 norm = mlcol.normalize(vmax=vmax, vmin=vmin) cmap = mlcm.RdBu_r im_ref = pl.imshow(Theta[atoms_order], aspect='auto', interpolation='none', norm=norm, cmap=cmap) plot_breaks(np.arange(1, S, 1), orientation='v', ls='--') plot_breaks(np.arange(1, J, 1), orientation='h') pl.xticks(range(S), ['S%d' % t for t in range(1, S + 1)]) pl.yticks(range(J), ['A#%d' % t for t in range(1, J + 1)], weight='bold') ax = pl.gca() for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(FONT_SIZE) tick.tick1On = False tick.tick2On = False for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(FONT_SIZE) tick.tick1On = False tick.tick2On = False
def plot_measurements(time_points, ydata): pl.rc("text", usetex = True) pl.rc("font", family="serif") pl.subplot2grid((4, 2), (0, 0)) pl.plot(time_points, ydata[:,0]) pl.title("Considered measurement data") pl.xlabel("t") pl.ylabel("X", rotation = 0, labelpad = 20) pl.subplot2grid((4, 2), (1, 0)) pl.plot(time_points, ydata[:,1]) pl.xlabel("t") pl.ylabel("Y", rotation = 0, labelpad = 15) pl.subplot2grid((4, 2), (2, 0)) pl.plot(time_points, ydata[:,2]) pl.xlabel("t") pl.ylabel(r"\phi", rotation = 0, labelpad = 15) pl.subplot2grid((4, 2), (3, 0)) pl.plot(time_points, ydata[:,3]) pl.xlabel("t") pl.ylabel("v", rotation = 0, labelpad = 20) pl.subplot2grid((4, 2), (0, 1), rowspan = 4) pl.plot(ydata[:,0], ydata[:, 1]) pl.title("Considered racecar track (measured)") pl.xlabel("X") pl.ylabel("Y", rotation = 0, labelpad = 20) pl.show()
def plot_measurements(time_points, ydata): pl.rc("text", usetex=True) pl.rc("font", family="serif") pl.subplot2grid((4, 2), (0, 0)) pl.plot(time_points, ydata[:, 0]) pl.title("Considered measurement data") pl.xlabel("t") pl.ylabel("X", rotation=0, labelpad=20) pl.subplot2grid((4, 2), (1, 0)) pl.plot(time_points, ydata[:, 1]) pl.xlabel("t") pl.ylabel("Y", rotation=0, labelpad=15) pl.subplot2grid((4, 2), (2, 0)) pl.plot(time_points, ydata[:, 2]) pl.xlabel("t") pl.ylabel(r"\phi", rotation=0, labelpad=15) pl.subplot2grid((4, 2), (3, 0)) pl.plot(time_points, ydata[:, 3]) pl.xlabel("t") pl.ylabel("v", rotation=0, labelpad=20) pl.subplot2grid((4, 2), (0, 1), rowspan=4) pl.plot(ydata[:, 0], ydata[:, 1]) pl.title("Considered racecar track (measured)") pl.xlabel("X") pl.ylabel("Y", rotation=0, labelpad=20) pl.show()
def __init__(self, z, verbatims=None, labels=None): """ Shows a given array in a 2d-viewer. Input: z, an 2d array. x,y coordinters are optional. """ self.z = z self.verbatims = verbatims self.labels = labels self.fig = plt.figure() # Doing some layout with subplots: self.fig.subplots_adjust(0.05, 0.05, 0.98, 0.98, 0.1) self.overview = plt.subplot2grid((8, 4), (0, 0), rowspan=7, colspan=4) self.draw() # Adding widgets, to not be gc'ed, they are put in a list: cursor = Cursor(self.overview, useblit=True, color='black', linewidth=2) but_ax = plt.subplot2grid((8, 4), (7, 0), colspan=1) reset_button = Button(but_ax, 'Reset') self._widgets = [cursor, reset_button] # connect events reset_button.on_clicked(self.clear_xy_subplots) self.fig.canvas.mpl_connect('button_press_event', self.click)
def plot_xin(viking,data,fit,output="plot.png",startrow=1,stoprow=-1,baseline=None): values=odict() #for fit functions values["vl1"] = odict() values["vl2"] = odict() for name in ["viking","data","fit"]: fname = getattr(args,name) try: values["vl1"][name]=read_data(fname, "vl1", args.startrow, args.stoprow) values["vl2"][name]=read_data(fname, "vl2", args.startrow, args.stoprow) except AttributeError as e: pass for v in ["vl1","vl2"]: values[v]["diff"] = dict(values[v]["viking"]) values[v]["diff"]["y"] = values[v]["diff"]["y"] - values[v]["fit"]["y"] pylab.figure(figsize=(6,6)) ylim=None plots = odict() top_plots = [ ["vl1",values["vl1"]["data"], "grey","-",1], [None,values["vl1"]["fit"], "magenta","--",2], [None,values["vl1"]["viking"], "blue","--",2], ["vl2",values["vl2"]["data"], "black","-",1], [None,values["vl2"]["fit"], "green","--",2], [None,values["vl2"]["viking"], "red","--",2]] bottom_plots = [ ["vl1",values["vl1"]["diff"], "blue","-",2], ["vl2",values["vl2"]["diff"], "red","-",2] ] ax = pylab.subplot2grid((9,1),(0, 0),rowspan=6) handles = odict() for n,p,c,l,w in top_plots: ylim,handle=segmented_plot(p["x"],p["y"],ylim=ylim, color=c, ls=l,lw=w, return_handle=True,alpha=1) if n: handles[n] = handle pylab.legend(handles,loc='upper left', framealpha=0.5) pylab.xlabel("Ls") ; pylab.xlim(0,360) ; pylab.xticks([0,60,120,180,240,300,360]) pylab.ylabel("Pressure (Pa)") ; pylab.ylim(ylim) pylab.grid() ax = pylab.subplot2grid((9,1),(7, 0),rowspan=2) ylim=None handles = odict() for n,p,c,l,w in bottom_plots: ylim,handle=segmented_plot(p["x"],p["y"],ylim=ylim, color=c, ls=l,lw=w, return_handle=True,alpha=1) if n: handles[n] = handle pylab.legend(handles, loc="upper left", framealpha=0.5) pylab.xlabel("Ls") ; pylab.xlim(0,360) ; pylab.xticks([0,60,120,180,240,300,360]) pylab.ylabel("P (Pa)") ; pylab.ylim(ylim) pylab.grid() pylab.savefig(filename=args.output, dpi=150)
def main( ): global loc_ nGames = 20 prevRows, prevCells = np.zeros( shape=(10,10) ), np.zeros( shape=(100,100)) cellTransitionProbMean = [ ] rowTransitionProbMean = [ ] for i in range( nGames ): loc_ = 0 while True: r1, c1 = int(loc_ / 10), loc_ loc_ += roll_dice( ) loc_ = check_for_snakes_and_ladders( loc_ ) r2, c2 = int(loc_ / 10), loc_ if loc_ < 100: cells_[c1,c2] += 1.0 rows_[r1,r2] += 1.0 if loc_ > 100: print( "Game %d is over" % i ) loc_ = 0 thisRows = renormalize( rows_ ) thisCells = renormalize( cells_ ) diffRow = thisRows - prevRows diffCell = thisCells - prevCells rowTransitionProbMean.append( diffRow.mean( ) ) cellTransitionProbMean.append( diffCell.mean( ) ) prevRows, prevCells = thisRows, thisCells # drawNow( img ) break pCells = cells_ / cells_.sum( axis = 0 ) pRows = rows_ / rows_.sum( axis = 0 ) with np.errstate(divide='ignore', invalid='ignore'): pCells = np.true_divide(cells_, cells_.sum( axis = 0 ) ) pRows = np.true_divide( rows_, rows_.sum( axis = 0 ) ) pCells = np.nan_to_num( pCells ) pRows = np.nan_to_num( pRows ) pylab.figure( figsize=(10,6) ) gridSize = (2, 2) ax1 = pylab.subplot2grid( gridSize, (0,0), colspan = 1 ) ax2 = pylab.subplot2grid( gridSize, (0,1), colspan = 1 ) ax3 = pylab.subplot2grid( gridSize, (1,0), colspan = 2 ) ax1.set_title( 'Cell to cell transitions' ) img1 = ax1.imshow( pCells, interpolation = 'none' ) pylab.colorbar( img1, ax = ax1 ) #orientation = 'horizontal' ) img2 = ax2.imshow( pRows, interpolation = 'none' ) pylab.colorbar( img2, ax = ax2 ) # orientation = 'horizontal' ) ax2.set_title( 'Row to row transitions' ) ax3.plot( rowTransitionProbMean, '-o', label = 'Row probs' ) ax3.plot( cellTransitionProbMean, '-*', label = 'Cell probs' ) ax3.set_ylabel( 'diff of transition probs' ) ax3.set_xlabel( 'Number of games completed' ) ax3.legend( ) pylab.suptitle( 'Total games %d' % nGames ) # pylab.tight_layout( ) pylab.savefig( '%s.png' % sys.argv[0] )
def _run_interface(self, runtime): from nipype.interfaces.base import isdefined import numpy as np import pylab as plt import os realignment_parameters = np.loadtxt(self.inputs.realignment_parameters) title = self.inputs.title F = plt.figure(figsize=(8.3, 11.7)) F.text(0.5, 0.96, self.inputs.title, horizontalalignment='center') ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2) handles = ax1.plot(realignment_parameters[:, 0:3]) ax1.legend(handles, ["x translation", "y translation", "z translation"], loc=0) ax1.set_xlabel("image #") ax1.set_ylabel("mm") ax1.set_xlim((0, realignment_parameters.shape[0] - 1)) ax1.set_ylim(bottom=realignment_parameters[:, 0:3].min(), top=realignment_parameters[:, 0:3].max()) ax2 = plt.subplot2grid((2, 2), (1, 0), colspan=2) handles = ax2.plot(realignment_parameters[:, 3:6] * 180.0 / np.pi) ax2.legend(handles, ["pitch", "roll", "yaw"], loc=0) ax2.set_xlabel("image #") ax2.set_ylabel("degrees") ax2.set_xlim((0, realignment_parameters.shape[0] - 1)) ax2.set_ylim( bottom=(realignment_parameters[:, 3:6] * 180.0 / np.pi).min(), top=(realignment_parameters[:, 3:6] * 180.0 / np.pi).max()) if isdefined(self.inputs.outlier_files): try: outliers = np.loadtxt(self.inputs.outlier_files) except IOError as e: if e.args[ 0] == "End-of-file reached before encountering data.": pass else: raise else: if outliers.size > 0: ax1.vlines(outliers, ax1.get_ylim()[0], ax1.get_ylim()[1]) ax2.vlines(outliers, ax2.get_ylim()[0], ax2.get_ylim()[1]) if title != "": filename = title.replace(" ", "_") + ".pdf" else: filename = "plot.pdf" F.savefig(filename, papertype="a4", dpi=self.inputs.dpi) plt.clf() plt.close() del F self._plot = filename runtime.returncode = 0 return runtime
def zoomindraw(m_name, mask, rgb, bands): maxm = 1. phi = 1. theta = 1.3 for k in range(11): if k == 0: w_p = np.where(mask) a = np.arange(len(w_p[0])) else: ind = np.random.choice(a) p_x = w_p[0][ind] p_y = w_p[1][ind] cmap = plt.get_cmap('gray') fig = plt.figure(figsize=(10, 10)) ax1 = plt.subplot2grid((2, 2), (0, 0)) ax2 = plt.subplot2grid((2, 2), (0, 1), colspan=2) ax3 = plt.subplot2grid((2, 2), (1, 0), colspan=2, rowspan=2) patch = patches.Rectangle( (max(0, p_y / 10. - 25.), max(0, p_x / 10. - 25.)), 50 + min(0, (p_y / 10. - 25.)), 50 + min(0, (p_x / 10. - 25.)), facecolor='none', linewidth=0.5, edgecolor='r') ax1.add_patch(patch) ax1.imshow(rgb[::10, ::10, :] * 1.7, interpolation=None) #plot1 = (((maxm)/phi)*(rgb[::10,::10,:]/(maxm/theta)))**0.9 #ax1.imshow(plot1, interpolation = None) ax1.set_xlim([0, 1098]) ax1.set_ylim([1098, 0]) ax1.plot(p_y / 10., p_x / 10., 'ro', markersize=2.8) p2 = rgb[max(0, p_x - 50):min(10980, p_x + 50), max(0, p_y - 50):min(10980, p_y + 50), :] plot2 = (p2 - p2.min()) / (p2.max() - p2.min()) ax2.imshow(plot2, interpolation=None) ax2.set_xlim([0, 100]) ax2.set_ylim([100, 0]) ax2.plot(50, 50, 'ro', markersize=5) p_r = [] for m in bands: p_r.append(m[p_x, p_y]) plt.plot(wl, p_r) plt.ylim([0, 1.]) plt.ylabel('TOA reflectance') plt.xlabel('wavelength (nm)') for i in wl: line = ax3.plot([i, i], [0, 1], '--') plt.setp(line, linewidth=0.5, color='gray') plt.tight_layout() plt.savefig('%s%i.pdf' % (m_name, k), format='pdf') plt.close(fig)
def main(): global loc_ nGames = 20 prevRows, prevCells = np.zeros(shape=(10, 10)), np.zeros(shape=(100, 100)) cellTransitionProbMean = [] rowTransitionProbMean = [] for i in range(nGames): loc_ = 0 while True: r1, c1 = int(loc_ / 10), loc_ loc_ += roll_dice() loc_ = check_for_snakes_and_ladders(loc_) r2, c2 = int(loc_ / 10), loc_ if loc_ < 100: cells_[c1, c2] += 1.0 rows_[r1, r2] += 1.0 if loc_ > 100: print("Game %d is over" % i) loc_ = 0 thisRows = renormalize(rows_) thisCells = renormalize(cells_) diffRow = thisRows - prevRows diffCell = thisCells - prevCells rowTransitionProbMean.append(diffRow.mean()) cellTransitionProbMean.append(diffCell.mean()) prevRows, prevCells = thisRows, thisCells # drawNow( img ) break pCells = cells_ / cells_.sum(axis=0) pRows = rows_ / rows_.sum(axis=0) with np.errstate(divide='ignore', invalid='ignore'): pCells = np.true_divide(cells_, cells_.sum(axis=0)) pRows = np.true_divide(rows_, rows_.sum(axis=0)) pCells = np.nan_to_num(pCells) pRows = np.nan_to_num(pRows) pylab.figure(figsize=(10, 6)) gridSize = (2, 2) ax1 = pylab.subplot2grid(gridSize, (0, 0), colspan=1) ax2 = pylab.subplot2grid(gridSize, (0, 1), colspan=1) ax3 = pylab.subplot2grid(gridSize, (1, 0), colspan=2) ax1.set_title('Cell to cell transitions') img1 = ax1.imshow(pCells, interpolation='none') pylab.colorbar(img1, ax=ax1) #orientation = 'horizontal' ) img2 = ax2.imshow(pRows, interpolation='none') pylab.colorbar(img2, ax=ax2) # orientation = 'horizontal' ) ax2.set_title('Row to row transitions') ax3.plot(rowTransitionProbMean, '-o', label='Row probs') ax3.plot(cellTransitionProbMean, '-*', label='Cell probs') ax3.set_ylabel('diff of transition probs') ax3.set_xlabel('Number of games completed') ax3.legend() pylab.suptitle('Total games %d' % nGames) # pylab.tight_layout( ) pylab.savefig('%s.png' % sys.argv[0])
def _run_interface(self, runtime): import matplotlib matplotlib.use("Agg") import pylab as plt realignment_parameters = np.loadtxt(self.inputs.realignment_parameters) title = self.inputs.title F = plt.figure(figsize=(8.3, 11.7)) F.text(0.5, 0.96, self.inputs.title, horizontalalignment="center") ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2) handles = ax1.plot(realignment_parameters[:, 0:3]) ax1.legend(handles, ["x translation", "y translation", "z translation"], loc=0) ax1.set_xlabel("image #") ax1.set_ylabel("mm") ax1.set_xlim((0, realignment_parameters.shape[0] - 1)) ax1.set_ylim(bottom=realignment_parameters[:, 0:3].min(), top=realignment_parameters[:, 0:3].max()) ax2 = plt.subplot2grid((2, 2), (1, 0), colspan=2) handles = ax2.plot(realignment_parameters[:, 3:6] * 180.0 / np.pi) ax2.legend(handles, ["pitch", "roll", "yaw"], loc=0) ax2.set_xlabel("image #") ax2.set_ylabel("degrees") ax2.set_xlim((0, realignment_parameters.shape[0] - 1)) ax2.set_ylim( bottom=(realignment_parameters[:, 3:6] * 180.0 / np.pi).min(), top=(realignment_parameters[:, 3:6] * 180.0 / np.pi).max(), ) if isdefined(self.inputs.outlier_files): try: outliers = np.loadtxt(self.inputs.outlier_files) except IOError as e: if e.args[0] == "End-of-file reached before encountering data.": pass else: raise else: if outliers.size > 0: ax1.vlines(outliers, ax1.get_ylim()[0], ax1.get_ylim()[1]) ax2.vlines(outliers, ax2.get_ylim()[0], ax2.get_ylim()[1]) if title != "": filename = title.replace(" ", "_") + ".pdf" else: filename = "plot.pdf" F.savefig(filename, papertype="a4", dpi=self.inputs.dpi) plt.clf() plt.close() del F self._plot = filename runtime.returncode = 0 return runtime
def SE_spectrum_analysis(sim_exp): #load matlab file where timeserie is stored #f = h5py.File('C:/Users/Squirel/Desktop/data_antoine/status_epilepticus/timeserie_SE_4j_rat8l_sr250Hz.mat', 'r') if sim_exp=='exp': f = h5py.File('C:/Users/Squirel/Desktop/data_antoine/status_epilepticus/EEG_rat8l.mat', 'r') data = f.get('EEG/data') data = pb.array(data) #transform to numpy array --> now each element of data is an array of one float sf = 250. # sampling freq (Hz) beg=120000; lgth = 20.; #stating time (s) and length (s) of the selected period spectrum_ymax = 0.2 #maximum value displayed in plot (to have all the same scale) ts_ylim = (-0.0020, 0.0010) else: #sim_exp=='sim' #radical='_40_HMR_40_ML_CpES1_0_CpES2_0_x0_35_noise3_0_noise2_30_noise1_60_gx1x2_20_gx2x1_20_gx1x1_20_gx2x2_20_r40_20s' #phase I #radical='_40_HMR_40_ML_CpES1_20_CpES2_20_x0_20_noise3_0_noise2_30_noise1_60_gx1x2_20_gx2x1_20_gx1x1_20_gx2x2_20_r40_20s' # phase II #radical='_40_HMR_40_ML_CpES1_80_CpES2_80_x0_20_noise3_0_noise2_30_noise1_60_gx1x2_20_gx2x1_20_gx1x1_20_gx2x2_20_r40_20s' #phase III radical='_40_HMR_40_ML_CpES1_40_CpES2_40_x0_35_noise3_0_noise2_30_noise1_60_gx1x2_20_gx2x1_20_gx1x1_20_gx2x2_20_r40_100s' #phase IV !!! set beg=20 instead of 10s x1_plot = np.load('./traces_dec13/x1plot'+radical+'.npy') x2_plot = np.load('./traces_dec13/x2plot'+radical+'.npy') #downsampling to 1kHz x1_plot = x1_plot[:,0:-1:10] x2_plot = x2_plot[:,0:-1:10] data = -(0.75*x1_plot.mean(axis=0) + 0.25*x2_plot.mean(axis=0)) #transform to numpy array --> now each element of data is an array of one float sf = 1000. # sampling freq (Hz) beg=20.; lgth = 80.; #stating time (s) and length (s) of the selected period spectrum_ymax = 300 #maximum value displayed in plot (to have all the same scale) ts_ylim = (-0.5, 1.75) minfreq=1.; maxfreq=50.; #Hz #pb.plot(range(lgth*sf), data[beg*sf:beg*sf+lgth*sf]); pb.show() #if splot needed signal = data[beg*sf:beg*sf+lgth*sf] #signal = pb.sin(2*pb.pi*pb.arange(0,15,0.004)) #pb.plot(signal); pb.show() spectrum = fft.fftn(signal) delta_f = 1.0 / ((lgth*sf)/2) * lgth #pb.plot(pb.arange(minfreq, maxfreq, delta_f),abs(spectrum[minfreq*delta_f:maxfreq*delta_f]), "."); pb.show() #pb.plot(pb.arange(minfreq, maxfreq, 1/lgth), abs(spectrum[minfreq*lgth:maxfreq*lgth]), "."); pb.show() spec = pb.arange(minfreq,maxfreq,1.0) for i in range(len(spec)): spec[i] = pb.mean(abs(spectrum[(minfreq+i)*lgth:(minfreq+i)*lgth + lgth])) #pb.plot(spec) #pb.show() #plots: fig = pb.figure() ax1 = pb.subplot2grid((2,2),(0,0),colspan=2) ax2 = pb.subplot2grid((2,2),(1,0)) ax3 = pb.subplot2grid((2,2),(1,1)) ax1.plot(signal) ax1.set_ylim(ts_ylim) ax2.plot(pb.arange(minfreq, maxfreq, 1/lgth), abs(spectrum[minfreq*lgth:maxfreq*lgth]), ".") ax2.set_ylim(0,spectrum_ymax) ax3.plot(spec) pb.show()
def plotPendulumWithThetaAndPhi(animate = True, \ title = "PendulumNormalModes.png", t0 = p.t0, p0 = p.p0, nsteps = 120, massRat = rm): global rm old = rm rm = massRat fig = pylab.figure() if animate: ax1 = pylab.subplot2grid((1, 2), (0, 1), aspect = 1.0) # Pendulum ax2 = pylab.subplot2grid((1, 2), (0, 0)) # Theta/Phi plots else: ax1 = fig.gca(aspect = 1.0) fig2 = pylab.figure() ax2 = fig2.gca() pendSetup(ax1, titleHigh = True) ax1.set_axis_on() line1, = ax1.plot([], [], 'k', linestyle = '-', marker = 'o', \ markeredgecolor = 'k', markerfacecolor = (0.5, 0.5, 1.0), markersize = 10) line1.set_markevery((1, 1)) line2, = ax2.plot([], [], 'b-', label = r"$\theta$") line3, = ax2.plot([], [], 'r-', label = r"$\phi$") ax2.set_xlim((0, nsteps * p.dt)) ax2.set_ylim((-30 * np.pi / 180.0, 30 * np.pi / 180)) ax2.set_xlabel(r"simulation time $\tau$", fontsize = 14) ax2.set_ylabel("pendula angles", fontsize = 14) pendAnimator1 = PendulumAnimate(line1) angleAnimator = AngleAnimator(line2, line3) simulation = DopeSimulation([pendAnimator1, angleAnimator], \ x0 = np.array([t0, p0, 0.0, 0.0]), nsteps = nsteps) if animate: anim = animation.FuncAnimation(fig, simulation, \ blit = True, init_func = simulation.reset, \ interval = 10, repeat = True) simulation.reset() for i in range(nsteps): simulation(i) pylab.legend(loc = 'lower right') pylab.tight_layout() if animate: pylab.show() else: fig.savefig("pendulum_" + title) fig2.savefig("angles_" + title) rm = old
def PlotMCMC(params, EPIC, sampler, lc, GP=False, KepName=''): import corner if type(sampler)!=np.ndarray: samples = sampler.chain[:, -10000:, :].reshape((-1, len(params))) else: samples=sampler #Turning b into absolute... samples[:,1]=abs(samples[:,1]) p.figure(1) #Clipping extreme values (top.bottom 0.1 percentiles) toclip=np.array([(np.percentile(samples[:,t],99.9)>samples[:,t]) // (samples[:,t]>np.percentile(samples[:,t],0.1)) for t in range(len(params))]).all(axis=0) samples=samples[toclip] #Earmarking the difference between GP and non labs = ["$T_{c}$","$b$","$v$","$Rp/Rs$","$u1$","$u2$","$\sigma_{white}$","$tau$","$a$"] if GP\ else ["$T_{c}$","$b$","$v$","$Rp/Rs$","$F_0$","$u1$","$u2$"] #This plots the corner: fig = corner.corner(samples, label=labs, quantiles=[0.16, 0.5, 0.84], plot_datapoints=False) #Making sure the lightcuvre plot doesnt overstep the corner ndim=np.shape(samples)[1] rows=(ndim-1)/2 cols=(ndim-1)/2 #Printing Kepler name on plot p.subplot(ndim,ndim,ndim+3).axis('off') if KepName=='': if str(int(EPIC)).zfill(9)[0]=='2': KepName='EPIC'+str(EPIC) else: KepName='KIC'+str(EPIC) p.title(KepName, fontsize=22) #This plots the model on the same plot as the corner ax = p.subplot2grid((ndim,ndim), (0, ndim-cols), rowspan=rows-1, colspan=cols) modelfits=PlotModel(lc, samples, scale=1.0, GP=True) #plotting residuals beneath: ax = p.subplot2grid((ndim,ndim), (rows-1, ndim-cols), rowspan=1, colspan=cols) modelfits=PlotModel(lc, samples, modelfits, residuals=True, GP=True, scale=1.0) #Saving as pdf. Will save up to 3 unique files. if os.path.exists(Namwd+'/Outputs/Corner_'+str(EPIC)+'_1.pdf'): if os.path.exists(Namwd+'/Outputs/Corner_'+str(EPIC)+'_2.pdf'): fname=Namwd+'/Outputs/Corner_'+str(EPIC)+'_3.pdf' else: fname=Namwd+'/Outputs/Corner_'+str(EPIC)+'_2.pdf' else: fname=Namwd+'/Outputs/Corner_'+str(EPIC)+'_1.pdf' p.savefig(fname,Transparent=True,dpi=300) return modelfits
def add_bin_gene(self, pheno, pval, samples, attributes, Yi, Yr, bMock=1, key=None): # opts = list(set(attributes)) # my_groups = {opts[j]: [i for i in range(len(attributes)) if attributes[i] == opts[j]] for j in range(len(opts))} # groups = dd(list) # g_list = sorted([(len(k),k,g) for (g,k) in my_groups.items()],reverse=True) # mixG = [] # for i,(kL,kG,g) in enumerate(g_list): groups = self.setup_groups(attributes) gY = {opt: [Yi[j] for j in K] for opt, K in groups.items()} gR = {opt: [Yr[j] for j in K] for opt, K in groups.items()} ax = plt.subplot2grid((self.xLen, self.yLen), (self.xLoc, 2), rowspan=bMock, colspan=1) ax2 = plt.subplot2grid((self.xLen, self.yLen), (self.xLoc, 3), rowspan=bMock, colspan=1) self.add_data(gY, ax) self.add_data(gR, ax2) # ax.set_yticks([]) # ax2.set_yticks([]) ax.set_title(pheno) ax2.set_title(str(pval)) if key: K = key.keys()[self.xLoc] my_attributes = [key[K][s] for s in samples] my_attributes = ['MEGA' if x == '+' else x for x in my_attributes] my_groups = self.setup_groups(my_attributes) ax3 = plt.subplot2grid((self.xLen, self.yLen), (self.xLoc, 4), rowspan=bMock, colspan=1) gY = {opt: [Yi[j] for j in K] for opt, K in my_groups.items()} self.add_data(gY, ax3) ax3.set_title(K) self.xLoc += bMock
def __init__(self,candidate): self.candidate = candidate self.fig = plt.figure(figsize=[14,12]) self.prof_ax = plt.subplot2grid([5,9],[0,1],colspan=2) self.fold_ax = plt.subplot2grid([5,9],[1,1],colspan=2,rowspan=2,sharex=self.prof_ax) self.subs_ax = plt.subplot2grid([5,9],[1,0],rowspan=2,sharey=self.fold_ax) self.table_ax = plt.subplot2grid([5,9],[0,3],colspan=3,rowspan=3,frameon=False) self.dm_ax = plt.subplot2grid([5,9],[0,6],colspan=2) self.acc_ax = plt.subplot2grid([5,9],[1,8],colspan=1,rowspan=2) self.dm_acc_ax = plt.subplot2grid([5,9],[1,6],colspan=2,rowspan=2,sharex=self.dm_ax,sharey=self.acc_ax) self.all_ax = plt.subplot2grid([6,9],[4,0],colspan=9,rowspan=3) self._plot_all_cands(self.all_ax) self.timers = { "read":Timer(), "prof":Timer(), "fold":Timer(), "stat":Timer(), "table":Timer(), "dm":Timer(), "acc":Timer(), "dmacc":Timer(), "write":Timer(), "clear":Timer() } self.header = self.candidate
def plot_rfs_and_theta(sim, neurons, connections): pre, post = neurons c = connections[0] weights = c.weights num_neurons = len(weights) fig = py.figure(figsize=(16, 4 * num_neurons)) for i, w in enumerate(weights): try: # check for channel neurons = pre.neuron_list except AttributeError: neurons = [pre] num_channels = len(neurons) count = 0 vmin, vmax = w.min(), w.max() for c, ch in enumerate(neurons): try: rf_size = ch.rf_size if rf_size < 0: rf_size = py.sqrt(ch.N) assert rf_size == int(rf_size) rf_size = int(rf_size) except AttributeError: rf_size = py.sqrt(ch.N) assert rf_size == int(rf_size) rf_size = int(rf_size) py.subplot2grid((num_neurons, num_channels + 1), (i, c), aspect='equal') subw = w[count:(count + rf_size * rf_size)] #py.pcolor(subw.reshape((rf_size,rf_size)),cmap=py.cm.gray) py.pcolormesh(subw.reshape((rf_size, rf_size)), cmap=py.cm.gray, vmin=vmin, vmax=vmax) py.xlim([0, rf_size]) py.ylim([0, rf_size]) py.axis('off') count += rf_size * rf_size py.subplot2grid((num_neurons, num_channels + 1), (0, num_channels)) sim.monitors['theta'].plot() return fig
def __init__(self,overview): self.overview = overview self.fig = plt.figure(figsize=[14,12]) self.prof_ax = plt.subplot2grid([5,9],[0,1],colspan=2) self.fold_ax = plt.subplot2grid([5,9],[1,1],colspan=2,rowspan=2,sharex=self.prof_ax) self.subs_ax = plt.subplot2grid([5,9],[1,0],rowspan=2,sharey=self.fold_ax) self.table_ax = plt.subplot2grid([5,9],[0,3],colspan=3,rowspan=3,frameon=False) self.dm_ax = plt.subplot2grid([5,9],[0,6],colspan=2) self.acc_ax = plt.subplot2grid([5,9],[1,8],colspan=1,rowspan=2) self.dm_acc_ax = plt.subplot2grid([5,9],[1,6],colspan=2,rowspan=2,sharex=self.dm_ax,sharey=self.acc_ax) self.all_ax = plt.subplot2grid([6,9],[4,0],colspan=9,rowspan=3) self._plot_all_cands(self.all_ax) self.timers = { "read":Timer(), "prof":Timer(), "fold":Timer(), "stat":Timer(), "table":Timer(), "dm":Timer(), "acc":Timer(), "dmacc":Timer(), "write":Timer(), "clear":Timer() } self.header = self.overview._xml.find("header_parameters") self.fig.suptitle("Source name: %s"%self.header.find("source_name").text,fontsize=16)
def plot_rfs_and_theta(sim,neurons,connections): pre,post=neurons c=connections[0] weights=c.weights num_neurons=len(weights) fig=py.figure(figsize=(16,4*num_neurons)) for i,w in enumerate(weights): try: # check for channel neurons=pre.neuron_list except AttributeError: neurons=[pre] num_channels=len(neurons) count=0 vmin,vmax=w.min(),w.max() for c,ch in enumerate(neurons): try: rf_size=ch.rf_size if rf_size<0: rf_size=py.sqrt(ch.N) assert rf_size==int(rf_size) rf_size=int(rf_size) except AttributeError: rf_size=py.sqrt(ch.N) assert rf_size==int(rf_size) rf_size=int(rf_size) py.subplot2grid((num_neurons,num_channels+1),(i, c),aspect='equal') subw=w[count:(count+rf_size*rf_size)] #py.pcolor(subw.reshape((rf_size,rf_size)),cmap=py.cm.gray) py.pcolormesh(subw.reshape((rf_size,rf_size)),cmap=py.cm.gray, vmin=vmin,vmax=vmax) py.xlim([0,rf_size]); py.ylim([0,rf_size]) py.axis('off') count+=rf_size*rf_size py.subplot2grid((num_neurons,num_channels+1),(0, num_channels)) sim.monitors['theta'].plot() return fig
def summary_plot(filename, Y, Theta, B, J, w, positions, atoms_order=None, fit_error=None): atoms_order = range(J) if atoms_order is None else atoms_order breaks = (np.where(w == 0)[0]) if not w is None else [] def cm2inch(value): return value / 2.54 #if len(positions) == 5: # original data # # larghezza, altezza # #size = (cm2inch(15), cm2inch(20)) # size = (4.25, 5) # grid = (9, 2) #elif len(positions) == 7: #results # # larghezza, altezza # #size = (cm2inch(15), cm2inch(22)) size = (4.25, 7) grid = (10, 2) #else: # raise Exception('wrong positions!') fig = pl.figure(figsize=size) pl.subplot2grid(grid, (0, 0)) plot_atoms(B, breaks, atoms_order, positions, grid) plot_representation(Theta, breaks, atoms_order, grid) ax = plot_reconstruction(Y, fit_error, J, breaks, grid) # no fit error cb = pl.colorbar(extend='both', orientation='horizontal', use_gridspec=True) for t in cb.ax.get_xticklabels(): t.set_fontsize(FONT_SIZE) pl.tight_layout(h_pad=0.0) pl.savefig('%s_atoms_repres_reconstr.png' % filename, dpi=DPI) pl.clf() pl.close() plot_dictionary(B, breaks, atoms_order) pl.savefig('%s_dictionary.png' % filename, dpi=DPI) pl.clf() pl.close()
def compare_classifiers(usps=True, digit=3): ''' Compares 3 different linear classifiers (Nearest-Centroid, Linear Discriminant Analysis, Perceptron) on either USPS data (for usps=True) or on BCI data (for usps = False) ''' if usps: #load usps data set X, Y = load_usps_data('usps.mat', digit) tit = 'USPS(' + str(digit) + ')' else: #load bci data set X, Y = load_bci_data('bcidata.mat') tit = 'BCI' #Use crossvalidation to estimate the training and test accuracies acc_cv = sp.zeros((5, 6)) (acc_cv[:, 0], acc_cv[:, 1]) = crossvalidate(X, Y, trainfun=train_ncc) (acc_cv[:, 2], acc_cv[:, 3]) = crossvalidate(X, Y, trainfun=train_lda) (acc_cv[:, 4], acc_cv[:, 5]) = crossvalidate(X, Y, trainfun=train_perceptron) #Plot the crossvalidation output pl.figure() ax1 = pl.subplot2grid((2, 3), (0, 0), colspan=3) pl.bar(sp.array([1, 2, 3, 4, 5, 6]) - 0.4, acc_cv.mean(0), width=0.8, yerr=acc_cv.std(0), ecolor='k', color='g') pl.xticks([1, 2, 3, 4, 5, 6], [ 'NCC tain', 'NCC test', 'LDA train', 'LDA test', 'PER train', 'PER test' ]) pl.xlim([0, 7]) pl.ylim([0.5, 1]) pl.ylabel('CV Accuracy') pl.title(tit + ' data set') #Train the classifiers and plot the output histograms w_ncc, b_ncc = train_ncc(X, Y) w_lda, b_lda = train_lda(X, Y) w_per, b_per = train_perceptron(X, Y) ax2 = pl.subplot2grid((2, 3), (1, 0)) plot_histogram(X, Y, w_ncc, b_ncc, 'NCC') ax3 = pl.subplot2grid((2, 3), (1, 1)) plot_histogram(X, Y, w_lda, b_lda, 'LDA') ax4 = pl.subplot2grid((2, 3), (1, 2)) plot_histogram(X, Y, w_per, b_per, 'PER')
def setup_main_screen(self): self.fig = pylab.figure(figsize=(8,8)) pylab.subplots_adjust(top=.93, bottom=0.1, left=.15, right=.97, hspace=.01, wspace=.15) pylab.suptitle('Filter explore') self.ax = pylab.subplot2grid((2, 5), (0, 0), colspan=4) #Amplitude response self.ax2 = pylab.subplot2grid((2, 5), (1, 0), colspan=4) #Phase response meax = self.menuax = pylab.subplot2grid((2, 5), (0, 4)) menu_names = ['butterworth', 'chebyshev I', 'chebyshev II', 'elliptic', 'bessel'] self.filter_types = ['butter', 'cheby1', 'cheby2', 'ellip', 'bessel'] self.menu_h = [] for n, item in enumerate(menu_names): self.menu_h.append(meax.text(0.1, n, item, picker=5)) self.menu_h[0].set_weight('bold') pylab.setp(meax, 'xticks', [], 'yticks', [], 'xlim',[0,1], 'ylim', [-.5, len(menu_names)-.5])
def singular(Ytra,Ytes,sdata): m=Ytra.shape[0] mt=Ytes.shape[0] xmean=np.mean(Ytra,axis=0) ytra0=Ytra-np.outer(np.ones(m),xmean) xmean=np.mean(Ytes,axis=0) ytes0=Ytes-np.outer(np.ones(mt),xmean) xnorm=np.sqrt(np.sum(ytra0**2,axis=0)) Ctra=np.dot(ytra0.T,ytra0) xnorm=xnorm+(xnorm==0) Ctra=Ctra/np.outer(xnorm,xnorm) xnorm=np.sqrt(np.sum(ytes0**2,axis=0)) Ctes=np.dot(ytes0.T,ytes0) xnorm=xnorm+(xnorm==0) Ctes=Ctes/np.outer(xnorm,xnorm) stra=np_lin.svd(Ctra)[1] stes=np_lin.svd(Ctes)[1] xlinewidth=3 fig1=lab.figure(figsize=(12,6)) ax1=lab.subplot2grid((10,2),(1,0), rowspan=9) ## ax=fig1.add_subplot(1,2,1) ax1.plot(stra,linewidth=xlinewidth, \ linestyle='-',color='b') ax1.set_xlabel('Label indexes', fontsize=14) ax1.set_ylabel('Eigen values',fontsize=14) ax1.set_title('Training:',fontsize=16) ax1.grid(True) ## ax=fig1.add_subplot(1,2,2) ax2=lab.subplot2grid((10,2),(1,1), rowspan=9) ax2.plot(stes,linewidth=xlinewidth, \ linestyle='-',color='b') ax2.set_xlabel('Label indexes', fontsize=14) ax2.set_ylabel('Eigen values',fontsize=14) ax2.set_title('Test:',fontsize=16) ax2.grid(True) fig1.suptitle('Eigen values of correlation matrixes: '+sdata,fontsize=18 ) lab.show() return
def pyplot(f, table, columns, resonance): import pylab global LINENUM first = LINENUM < 0 LINENUM += 1 if LINENUM >= len(colors): showplot(show=False) LINENUM = 0 if LINENUM == 0: if not first: FIGURES.append(pylab.gcf()) pylab.figure(figsize=(18,3), tight_layout={'pad':0}) pylab.subplot2grid((1,5),(0,0),colspan=4) #pylab.figure(figsize=(8,2.3), tight_layout={'pad':0}) #pylab.subplot2grid((1,3),(0,0),colspan=2) #print "shape",table.shape name = os.path.splitext(os.path.basename(f))[0] if '-' in name: name = "-".join(name.split('-')[1:]) label=name p = abundance(f) if p: label += " %.1f%%"%p #label += " res: %.2fA"%wavelength(resonance) color=colors[LINENUM] for i in (2,): #range(1,table.shape[0]): pylab.loglog(table[0,:].T*1e3, table[i,:], label=label, linestyle=lines[i-1], color=color) label='_nolegend_' # Table of relative total cross section if False: if first: print " "*(8*table.shape[0])+"%7s %7s %7s %7s"%("0.5A","6A","15A","20A") TARGET=V2200 y0 = [np.interp(TARGET,table[0,:],table[i,:]) for i in range(1,table.shape[0])] b_c = np.sqrt(y0[0]/(0.01*4*np.pi)) b_cL = np.sqrt(np.interp([L0p1,L0p2,L0p5,L6,L15,L20],table[0,:],table[1,:])/(0.01*4*np.pi)) delta = (b_cL-b_c)/b_c*100 #y0[0] = np.sqrt(y0[0]/(4*np.pi)) print "%7s"%name," ".join("%7.3f"%vi for vi in y0)," ".join("%6.1f%%"%vi for vi in delta) else: if first: print "%7s %7s %15s"%("name","%","res. onset Ang/meV") print "%7s %7s %7.2f %9.2f"%( name, ("%.3f"%p if p else "-"), wavelength(resonance), resonance*1e3)
def plot_dataset(x, y, features, name): pl.rcParams['toolbar'] = 'None' pl.figure(figsize=(14, 14)) fig = pl.gcf() fig.canvas.set_window_title(name) user_colors = [lists_format.visual_class_color[ucl] for ucl in y] for i, feature_i in enumerate(features): for j, feature_j in enumerate(features): ax = pl.subplot2grid((len(features), len(features)), (i, j)) ax.xaxis.set_label_position('top') ax.set_xticklabels([]) ax.set_yticklabels([]) if i == 0: pl.xlabel(feature_j) if j == 0: pl.ylabel(feature_i) if i != j: plot_two_features_scatter(x[:, i], x[:, j], user_colors) else: plot_feature_histogram(x[:, i], y) pl.tight_layout() pl.subplots_adjust(hspace=0.03, wspace=0.03) pl.show()
def plot_alt_az(self,grid,contour='',pfact=4): import pylab polar = pylab.subplot2grid(self.plotgrid,grid[:2],colspan=grid[2],rowspan=grid[3],projection='polar') polar.plot(np.radians(self.aa_az - 90),90 - self.aa_alt,'r.') polar.plot(np.radians(self.ar_az - 90),90 - self.ar_alt,'g.') polar.set_rmax(90) polar.set_xticklabels(['E','SE','S','SW','W','NW','N','NE']) if contour: X = np.radians(self.ar_az - 90) Y = 90 - self.ar_alt if contour == 'model': Z = self.diff_model_angular * 3600 polar.set_title('Model differences') elif contour == 'real': Z = self.diff_angular * 3600 polar.set_title('Real differences') xi = np.linspace(np.radians(-90),np.radians(271),num = 360 * pfact) yi = np.linspace(min(Y),max(Y),num = 90 * pfact) zi = pylab.griddata(X, Y, Z, xi, yi, interp='linear') ctf = polar.contourf(xi,yi,zi,cmap='hot') cbar = pylab.colorbar(ctf, orientation='horizontal', pad=0.05) cbar.set_ticks(range(0,int(max(Z)),60)) cbar.ax.set_xticklabels(map("{0}'".format,range(0,int(max(Z) / 60)))) else: polar.set_title('Alt-Az distribution') return polar
def plot_alt_az(self, grid, contour='', pfact=4): import pylab polar = pylab.subplot2grid(self.plotgrid, grid[:2], colspan=grid[2], rowspan=grid[3], projection='polar') polar.plot(np.radians(self.aa_az - 90), 90 - self.aa_alt, 'r.') polar.plot(np.radians(self.ar_az - 90), 90 - self.ar_alt, 'g.') polar.set_rmax(90) polar.set_xticklabels(['E', 'SE', 'S', 'SW', 'W', 'NW', 'N', 'NE']) if contour: X = np.radians(self.ar_az - 90) Y = 90 - self.ar_alt if contour == 'model': Z = self.diff_model_angular * 3600 polar.set_title('Model differences') elif contour == 'real': Z = self.diff_angular * 3600 polar.set_title('Real differences') xi = np.linspace(np.radians(-90), np.radians(271), num=360 * pfact) yi = np.linspace(min(Y), max(Y), num=90 * pfact) zi = pylab.griddata(X, Y, Z, xi, yi, interp='linear') ctf = polar.contourf(xi, yi, zi, cmap='hot') cbar = pylab.colorbar(ctf, orientation='horizontal', pad=0.05) cbar.set_ticks(range(0, int(max(Z)), 60)) cbar.ax.set_xticklabels( map("{0}'".format, range(0, int(max(Z) / 60)))) else: polar.set_title('Alt-Az distribution') return polar
def plot_one(loc, coord, ylim): ax = pl.subplot2grid(dims, loc) plot_coord(coord, color='blue') pl.ylim(ylim) pl.axhline(0, color='gray', zorder=0) pl.title(coord) common()
def histogram_per_sample(data, args, name='histogram.png', x='x-axis', y='y-axis', x_cutoff=None, title=None): X_SMALL = 6 SMALL_SIZE = 8 MEDIUM_SIZE = 10 BIGGER_SIZE = 16 plt.rc('font', size=BIGGER_SIZE) # controls default text sizes plt.rc('axes', titlesize=BIGGER_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=BIGGER_SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=BIGGER_SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=BIGGER_SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=BIGGER_SIZE) # legend fontsize plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title plt.xscale('log') ax = plt.subplot2grid((1,1),(0, 0)) import numpy as np MIN, MAX = 1.0e-20 , 1.0 #max(data) bins=np.logspace(np.log10(MIN),np.log10(MAX), 20) data1 = [max(1.1e-20, p) for p in data if p >= 0] data2 = [1.0e-20 for p in data if p == -1] ax.hist([data2, data1], bins=bins, label=['Not computed', ''], color=["#e74c3c", "#3498db"]) ax.set_title("Detected in both samples") ax.set_xlabel(x) ax.set_ylabel(y) ax.set_ylim((0,80)) ax.set_xscale("log") ax.legend(loc='upper right') plt.tight_layout() plt.savefig(os.path.join(args.outfolder, "Figure_reviewB.pdf")) plt.clf()
def pca_spec(spec,W_red,mu,plot=False,plotname="spec.png"): spec = spec/(spec.dot(spec))-mu a = (W_red.T).dot(spec.T) model = W_red.dot(a)+mu spec+=mu if plot: from pylab import clf,plot,ylabel,subplot2grid,savefig waves=range(len(model)) subplot2grid((3,3),(0,0),colspan=3,rowspan=2) ylabel('Scaled Flux') plot(waves,spec,'.',waves,model,'-r') subplot2grid((3,3),(2,0),colspan=3) plot(waves, (model-spec)/spec,".") ylabel('Residual (%)') savefig(plotname) clf()
def bstrap_fitting(X, xr, npoly=3, nsampling=1000, plot=True, return_m=True, c='g', ax=None): M = bootf.bstrap(X, xr, nsampling, npoly) M_m = np.mean(M, axis=1) M_s = np.std(M, axis=1) if plot: if ax == None: fig = plt.subplots(2, 2, figsize=(2 * aspect_ratio[0], 2 * aspect_ratio[1]), sharey=False) ax = plt.subplot2grid((2, 2), (0, 0), colspan=1, rowspan=1) ax.plot(X[:, 0], X[:, 1], 'o', ms=8, c=c, alpha=0.8, label='experiment') ax.plot(xr, M_m, lw=2.0, c=c, alpha=1.0) ax.fill_between(xr, M_m - 1.96 * M_s, M_m + 1.96 * M_s, alpha=0.2, facecolor=c) # area with 95% CI
def segmentation_points(d, p, save_fig=None): xs = modelf.xsegment(d, p) ixs = modelf.ixsegment(xs) fig = plt.subplots(1, 1, figsize=(7, 5), sharey=False) ax = plt.subplot2grid((1, 1), (0, 0), colspan=1, rowspan=1) plt.plot(d['t'], d['L_ef'], '-', c=cmap(0.7), lw=1.5, label='Posterior end') plt.plot(xs[:, 0], xs[:, 1], 'o', ms=6, c=cmap(0.15), alpha=0.5, label=r'$du/dx=\theta$') plt.plot(xs[ixs, 0], xs[ixs, 1], 'o', ms=8, c=cmap(0.5), label='Segmentation point') plt.xlabel('time (min)') plt.ylabel('length (um)') plt.legend(frameon=True, loc=2) plt.tight_layout() if save_fig != None: plt.savefig(save_fig, format='pdf')
def vecPlot2(self, row, col, r_m, mWx, mWy, data1, data2, dmr, frmSize, winSize): pl.clf() pl.ion() pWx = [] l = dmr - row - col for f in range(l): pWx.append(mWx[row + f, col + f, :, 0]) pWx = np.array(pWx) sqWx = np.sqrt(pWx * pWx) print sqWx r, c = sqWx.shape x = pl.arange(c + 1) y = pl.arange(r + 1) X, Y = pl.meshgrid(x, y) pl.subplot2grid((1, 2), (0, 0)) pl.pcolor(X, Y, sqWx, vmin=0, vmax=1) pl.xlim(0, c) pl.ylim(0, r) pl.colorbar() pl.title("user_1 (t:" + str(row) + ")") pl.gray() pWy = [] l = dmr - row - col for f in range(l): pWy.append(mWy[row + f, col + f, :, 0]) pWy = np.array(pWy) sqWy = np.sqrt(pWy * pWy) print sqWy r, c = sqWy.shape x = pl.arange(c + 1) y = pl.arange(r + 1) X, Y = pl.meshgrid(x, y) pl.subplot2grid((1, 2), (0, 1)) pl.pcolor(X, Y, sqWy, vmin=0, vmax=1) pl.xlim(0, c) pl.ylim(0, r) pl.colorbar() pl.title("user_2 (t:" + str(col) + ")") pl.gray() pl.tight_layout() pl.draw()
def test1_filtersb_test_zern_sim(self): """Test if filter_sideband() on simulated Zernike wavefront data""" ### Make fake fringes cfreq0 = (18.81111508, 24.76214802) zndata = tim.zern.calc_zern_basis(10, min(self.sz)/2) rad_mask = tim.im.mk_rad_mask(*zndata['mask'].shape) apt_mask = zndata['mask'] apt_mask9 = rad_mask<0.9 np.random.seed(1337) zvecs = [np.random.random(10) for i in range(6)] zphases = [sum(zv*zmode for zv, zmode in zip(zvec, zndata['modes'])) for zvec in zvecs] zfringes = [sim_fringe(zph, cfreq0, noiseamp=0) for zph in zphases] cfreq = fringe_cal(zfringes, store_pow=False, do_embed=True, method='cog') # Should give approximately cfreq, difference should be less # than 2% and pixel difference should be less than 0.3 self.assertLess(np.abs(1-cfreq/np.r_[cfreq0]).mean(), 0.02) self.assertLess(np.abs(cfreq0 - cfreq).mean(), 0.4) self.fcache = {} for zphase, zfringe in zip(zphases, zfringes): phase, amp, ftpow = filter_sideband(zfringe, cfreq0, 0.5, method='spectral', apt_mask=apt_mask, unwrap=True, do_embed=True, wsize=-0.5, wfunc='cosine', ret_pow=True, cache=self.fcache, verb=0) dphase = (zphase*apt_mask-phase) dphase -= dphase[apt_mask].mean() plt.figure(400, figsize=(4,4)); plt.clf() ax0 = plt.subplot2grid((2,2),(0, 0)) ax0.set_title("Input phase") im = ax0.imshow(zphase*apt_mask) ax1 = plt.subplot2grid((2,2),(0, 1)) ax1.set_title("Input fringes") ax1.imshow(zfringe) plt.colorbar(im) ax2 = plt.subplot2grid((2,2),(1, 0)) ax2.set_title("Rec. phase") im = ax2.imshow(phase) plt.colorbar(im) ax3 = plt.subplot2grid((2,2),(1, 1)) ax3.set_title("In-rec. (inner 90%)") im = ax3.imshow(dphase*apt_mask9) plt.colorbar(im) if (raw_input("Continue [b=break]...") == 'b'): break plt.close()
def plot_overlap_withparam(filename, m_log, param): pylab.figure(figsize=(4, 4)) pylab.subplot2grid((3, 1), (0, 0), rowspan=1) pylab.plot(param) pylab.xlim([0, len(param) - 1]) pylab.ylabel("a") pylab.subplot2grid((3, 1), (1, 0), rowspan=2) pylab.imshow(m_log.T, interpolation="none", aspect="auto", cmap="jet") pylab.xlabel("Time") pylab.ylabel("Pattern") #pylab.colorbar() pylab.tight_layout() pylab.savefig(filename) pylab.colorbar() pylab.tight_layout() pylab.savefig("colorbar_" + filename) pylab.close()
def plot_problem_area(array, filename, start_sample, end_sample): """ Plots the area that was found during detection :param start_sample: beginning of the problem area :param end_sample: end of the problem area :return: plot.show() """ # Plot 1 - The time domain waveform view that is instantly recognizable plb.figure('Artifact Overview:', figsize=(8, 6), dpi=100) plb.style.use('ggplot') plb.subplot2grid((3, 1), (0, 0), colspan=1, rowspan=2) # Only plot the slice of audio the dropouts occur in plb.plot(array[start_sample - 1000:end_sample + 1000], label='channel') plb.title('Time domain:\n') plb.ylabel("Threshold of: {0}dbFS".format(convert_to_dbfs(10))) plb.yscale('linear') plb.xlabel("From sample: {0} to sampale: {1} ".format( start_sample, end_sample)) fig1 = plb.gca() fig1.axes.xaxis.set_ticklabels([]) fig1.axes.yaxis.set_ticklabels(range(-100, 100, 20)) plb.legend(loc='lower right') plb.grid(True) # Render this clip to disk for subjective analysis in the output/ directory and label as an artifact wavfile.write('output/{0}_artifact.wav'.format(filename), rate=48000, data=array[start_sample - 48000:end_sample + 48000]) # Plot 2 - the FFT of the waveform decomposed into it's parts plb.subplot2grid((3, 1), (2, 0), colspan=1, rowspan=1) plb.title('Frequency domain:') x = array[start_sample - 1000:end_sample + 1000] fft = abs(np.fft.rfft(x)) plb.plot(fft, label='channel') plb.xscale('symlog') plb.xlabel('frequency [Hz]') plb.yscale('linear') plb.ylabel('amplitude') plb.legend(loc='upper left') plb.tight_layout() # Save an image of the plot alongside the wav file plb.savefig('output/{0}_artifact.png'.format(filename)) # Display the plot. plb.show() return None
def plot_overlap_groupsum_withparam(filename, m_log, group_id, param): pylab.figure(figsize=(4, 4)) pylab.subplot2grid((3, 1), (0, 0), rowspan=1) pylab.plot(param) pylab.xlim([0, len(param) - 1]) pylab.ylabel("a") pylab.subplot2grid((3, 1), (1, 0), rowspan=2) Ngroup = int(numpy.max(group_id) + 1) for i in range(Ngroup): groupsum = numpy.mean(m_log[:, group_id == i], axis=1) pylab.plot(groupsum, label="Group " + str(i + 1)) pylab.xlabel("Time") pylab.ylabel("Mean overlap") pylab.legend() pylab.tight_layout() pylab.savefig(filename) pylab.close()
def plot_initial_and_optimized_controls(time_points, \ udata_init, udata_opt, umin, umax): pl.rc("text", usetex = True) pl.rc("font", family="serif") pl.subplot2grid((2, 1), (0, 0)) pl.step(time_points[:-1], udata_init[:,0], label = "$\delta_{init}$") pl.step(time_points[:-1], udata_init[:,1], label = "$D_{init}$") pl.plot([time_points[0], time_points[-2]], [umin[0], umin[0]], \ color = "b", linestyle = "dashed", label = "$\delta_{min}$") pl.plot([time_points[0], time_points[-2]], [umax[0], umax[0]], \ color = "b", linestyle = "dotted", label = "$\delta_{max}$") pl.plot([time_points[0], time_points[-2]], [umin[1], umin[1]], \ color = "g", linestyle = "dashed", label = "$D_{min}$") pl.plot([time_points[0], time_points[-2]], [umax[1], umax[1]], \ color = "g", linestyle = "dotted", label = "$D_{max}$") pl.ylabel("$\delta,\,D$", rotation = 0) pl.ylim(-0.6, 1.1) pl.title("Initial and optimized controls") pl.legend(loc = "upper right") pl.subplot2grid((2, 1), (1, 0)) pl.step(time_points[:-1], udata_opt[:,0], label = "$\delta_{opt,coll}$") pl.step(time_points[:-1], udata_opt[:,1], label = "$D_{opt,coll}$") pl.plot([time_points[0], time_points[-2]], [umin[0], umin[0]], \ color = "b", linestyle = "dashed", label = "$\delta_{min}$") pl.plot([time_points[0], time_points[-2]], [umax[0], umax[0]], \ color = "b", linestyle = "dotted", label = "$\delta_{max}$") pl.plot([time_points[0], time_points[-2]], [umin[1], umin[1]], \ color = "g", linestyle = "dashed", label = "$D_{min}$") pl.plot([time_points[0], time_points[-2]], [umax[1], umax[1]], \ color = "g", linestyle = "dotted", label = "$D_{max}$") pl.xlabel("$t$") pl.ylabel("$\delta,\,D$", rotation = 0) pl.ylim(-0.6, 1.1) pl.legend(loc = "upper right") pl.show()
def corr_matrix(Ytra,Ytes,sdata): m=Ytra.shape[0] mt=Ytes.shape[0] xmean=np.mean(Ytra,axis=0) ytra0=Ytra-np.outer(np.ones(m),xmean) xmean=np.mean(Ytes,axis=0) ytes0=Ytes-np.outer(np.ones(mt),xmean) xnorm=np.sqrt(np.sum(ytra0**2,axis=0)) Ctra=np.dot(ytra0.T,ytra0) xnorm=xnorm+(xnorm==0) Ctra=Ctra/np.outer(xnorm,xnorm) xnorm=np.sqrt(np.sum(ytes0**2,axis=0)) Ctes=np.dot(ytes0.T,ytes0) xnorm=xnorm+(xnorm==0) Ctes=Ctes/np.outer(xnorm,xnorm) ## Ctra=np.log(np.abs(Ctra)+1)*np.sign(Ctra) ## Ctes=np.log(np.abs(Ctes)+1)*np.sign(Ctes) fig1=lab.figure(figsize=(12,6)) ## ax=fig1.add_subplot(1,2,1) ## ax.imshow(Ctra,interpolation='none') ax1=lab.subplot2grid((10,2),(1,0), rowspan=9) ax1.hist(Ctra.ravel(),200,log=True) ax1.set_xlim(-0.2,1.2) ax1.set_title('Training labels:',fontsize=16) ax1.grid(True) ## ax=fig1.add_subplot(1,2,2) ## ax.imshow(Ctes,interpolation='none') ax2=lab.subplot2grid((10,2),(1,1), rowspan=9) ax2.hist(Ctes.ravel(),200,log=True) ax2.set_xlim(-0.2,1.2) ax2.set_title('Test labels:',fontsize=16) ax2.grid(True) fig1.suptitle('Histograms of label correlation(log scale), data set:'+sdata,fontsize=18 ) ## fig1.tight_layout() lab.show() return
def plot_feature_combinations(data, feature_names=None, figsize=(20, 20)): import numpy as np import pylab as pl import classy.datasets from matplotlib.lines import Line2D from matplotlib.colors import ListedColormap cmap_light = ListedColormap(light_colors[:len(data.target_names)]) cmap_bold = ListedColormap(bold_colors[:len(data.target_names)]) assert len(data.target_names) <= len( bold_colors), "Only %d target colors implemented." % (len( cmap_bold.colors)) if feature_names is None: feature_names = data.feature_names L = len(feature_names) pl.figure(figsize=figsize) for j, f1 in enumerate(feature_names): for i, f2 in enumerate(feature_names): ax = pl.subplot2grid((L, L), (i, j)) if i == 0 and j == 0: if not data.targets is None: lines = [] for ti, t in enumerate(data.target_names): line = Line2D( list(range(2)), list(range(2)), linestyle='-', marker='o', color=cmap_bold.colors[ti]) lines.append(line) pl.legend(lines, data.target_names, loc='center') if f1 == f2: ax.set_axis_off() continue subset = classy.datasets.extract_features(data, [f1, f2]) plot2D(subset, legend_location=None) if j > 0 and i > 1: ax.set_ylabel('') ax.set_yticklabels([]) if j > 1: ax.set_ylabel('') ax.set_yticklabels([]) if i < (L - 1) and j < (L - 1): ax.set_xlabel('') ax.set_xticklabels([]) if i < (L - 2): ax.set_xlabel('') ax.set_xticklabels([])
def plot(imgs, imgs_f, labels, class_set, fname): """ data are 3-d matrix """ n = len(class_set) m = 3 top_idx = getTop(imgs_f, labels, class_set, m) pylab.gray(); for i in range(n): for j in range(m): if j >= len(top_idx[i]): continue # print top_idx[i][j] sig_imgs = tf.sigmoid(imgs[top_idx[i][j]][:, :, 0]).eval() sig_imgs_f = tf.sigmoid(imgs_f[top_idx[i][j]][:, :, 0]).eval() pylab.subplot2grid((n, m*2), (i, 2*j)); pylab.axis('off'); pylab.imshow(sig_imgs) pylab.subplot2grid((n, m*2), (i, 2*j+1)); pylab.axis('off'); pylab.imshow(sig_imgs_f) pylab.savefig(fname)
def __gen_plot(self,plots,band): import pylab plot = [] grid = [] draw = [] i = 0 rows = 1 cols = 1 # process plotting string for mg in plots.split(','): g = [i,0,1,1] if len(mg) == 0: raise Exception('empty plot specifier') plot_s = re.split('([@%])', mg) plot.append(plot_s[0]) i = 1 while i < len(plot_s) - 1: if plot_s[i] == '@': i += 1 if len(draw) < len(plot): draw.append([]) draw[len(plot) - 1].append(plot_s[i]) elif plot_s[i] == '%': if g is None: raise Exception('grid can be specified only once') i += 1 grids = plot_s[i].split(':') grid.append(map(int, grids) + g[len(grids):]) g = None i += 1 if g is not None: grid.append(g) if len(draw) < len(plot): draw.append(None) lg = grid[-1] rows = max(lg[0] + lg[2],rows) cols = max(lg[1] + lg[3],cols) i += 1 self.plotgrid = (rows,cols) for i in range(0,len(plot)): axnam=plot[i].split(':') if len(axnam) < 2: sys.exit('invalid plot name - {0} does not contain at least one :'.format(plot[i])) g = grid[i] p = pylab.subplot2grid(self.plotgrid,g[:2],colspan=g[2],rowspan=g[3]) if axnam[0] == 'paz': ax=axnam[1].split('-') if ax[0] == 'contour': self.plot_alt_az(g,ax[1]) else: self.plot_alt_az(g) else: for j in axnam[1:]: self.plot_data(p,axnam[0],j,band,draw[i])
def plot(self, view=None): import pylab kw = dict((p, getattr(self, p).value) for p in self._pnames) kw.update(self._state) #print "kw_plot",kw if view == 'residual': plot_resid(self.x, self.residuals()) else: plot_ratio = 4 h = pylab.subplot2grid((plot_ratio, 1), (0, 0), rowspan=plot_ratio-1) self._plot(self.x, self.y, self.dy, self.theory(), view=view, **kw) for tick_label in pylab.gca().get_xticklabels(): tick_label.set_visible(False) #pylab.gca().xaxis.set_visible(False) #pylab.gca().spines['bottom'].set_visible(False) #pylab.gca().set_xticks([]) pylab.subplot2grid((plot_ratio, 1), (plot_ratio-1, 0), sharex=h) plot_resid(self.x, self.residuals())
def plotPendulumOnTorus(animate = True, nsteps = p.n): # Plot the pendulum and torus side by side. fig = pylab.figure() if animate: ax1 = pylab.subplot2grid((2, 4), (0, 0), rowspan = 2, colspan = 2) ax2 = pylab.subplot2grid((2, 4), (0, 2), rowspan = 2, colspan = 2, projection = "3d") else: ax1 = fig.gca() fig2 = pylab.figure() ax2 = fig2.gca(projection = "3d") pendSetup(ax1) line1, = ax1.plot([], [], 'k', linestyle = '-', marker = 'o', \ markeredgecolor = 'k', markerfacecolor = (0.5, 0.5, 1.0), markersize = 10) line1.set_markevery((1, 1)) line1b, = ax1.plot([], [], 'm--', animated = True) torus3d(ax2, elev = 30.0, azim = 30.0) line2, = ax2.plot([], [], [], 'k-') pendAnimator = PendulumAnimate(line1) pendulumTrackAnimator = PendulumAnimateTrajectory(line1b) torAnimator = TorAnimate(line2) torRotator = TorusViewChanger(ax2) simulation = DopeSimulation([pendAnimator, torAnimator, \ pendulumTrackAnimator, torRotator], nsteps = nsteps) if animate: ax1.set_axis_on() simulation.reset() anim = animation.FuncAnimation(fig, simulation, \ blit = True, init_func = simulation.reset, \ interval = 10, repeat = True) pylab.suptitle("Runge-Kutta Pendulum Simulation", fontsize = 20) pylab.tight_layout(3.0) pylab.show() else: for i in range(nsteps): simulation(i) ax1.set_axis_off() fig.savefig("OnePendulumEvolution.png") fig2.savefig("OnePendulumOnTorus.png")
def plot_simulation_results_initial_and_optimized_controls(time_points, \ y_sim_init, y_sim_opt): pl.rc("text", usetex = True) pl.rc("font", family="serif") pl.subplot2grid((4, 2), (0, 0)) pl.plot(time_points, y_sim_init[:,0], label = "initial") pl.plot(time_points, y_sim_opt[:,0], label = "optimized") pl.title("Simulation results for initial and optimized control") pl.xlabel("$t$") pl.ylabel("$X$", rotation = 0) pl.legend(loc = "lower left") pl.subplot2grid((4, 2), (1, 0)) pl.plot(time_points, y_sim_init[:,1], label = "initial") pl.plot(time_points, y_sim_opt[:,1], label = "optimized") pl.xlabel("$t$") pl.ylabel("$Y$", rotation = 0) pl.legend(loc = "lower left") pl.subplot2grid((4, 2), (2, 0)) pl.plot(time_points, y_sim_init[:,2], label = "initial") pl.plot(time_points, y_sim_opt[:,2], label = "optimized") pl.xlabel("$t$") pl.ylabel("$\psi$", rotation = 0) pl.legend(loc = "lower left") pl.subplot2grid((4, 2), (3, 0)) pl.plot(time_points, y_sim_init[:,3], label = "initial") pl.plot(time_points, y_sim_opt[:,3], label = "optimized") pl.xlabel("$t$") pl.ylabel("$v$", rotation = 0) pl.legend(loc = "upper left") pl.subplot2grid((4, 2), (0, 1), rowspan = 4) pl.plot(y_sim_init[:,0], y_sim_init[:,1], label = "initial") pl.plot(y_sim_opt[:,0], y_sim_opt[:,1], label = "optimized") pl.title("Simulated race car path for initial and optimized controls") pl.xlabel("$X$") pl.ylabel("$Y$", rotation = 0) pl.legend(loc = "lower left") pl.show()
def plot_connexel(mask_file,idx): import nibabel as nb import numpy as np import pylab as plt from nipy.labs.viz_tools.activation_maps import plot_map mask_nii = nb.load(mask_file) fig = plt.figure(figsize=(8, 4)) beh_data = np.recfromcsv('/home/raid3/gorgolewski/Downloads/DataForChris_10_30_12.csv') corr_mmaps = [] for name in beh_data['sub_id_database_brain']: filename = "/scr/adenauer1/workingdir/rs_analysis_test/main_workflow/_subject_id_%s/_fwhm_5/corr_matrix/corr_matrix.int16"%name mmap = np.memmap(filename, dtype='int16', mode='r') corr_mmaps.append(mmap) for i, key in enumerate(['mem_meta_d', 'percep_aroc']): r_values = np.zeros((len(beh_data[key]))) for j, corr_mmap in enumerate(corr_mmaps): r_values[j] = corr_mmap[idx] r_values = np.arctanh(r_values/10000.0) ax = plt.subplot2grid((1,2), (0,i)) ax.scatter(r_values, beh_data[key]) ax.set_xlabel("normalized_correlation") ax.set_ylabel(key) plt.savefig("%d_beh_data.pdf"%idx) plt.savefig("%d_beh_data.svg"%idx) counter = 0 for i in xrange(0,(mask_nii.get_data() > 0).sum()): for j in xrange(i+1,(mask_nii.get_data() > 0).sum()): if counter == idx: print i,j new_mask = (np.zeros(mask_nii.get_data().shape) == 1) sub_mask = new_mask[mask_nii.get_data() > 0] sub_mask[i] = True new_mask[mask_nii.get_data() > 0] = sub_mask print np.where(new_mask) #ax = plt.subplot2grid((2,3), (0,1), colspan=2) plot_map(new_mask, mask_nii.get_affine(), threshold='auto') plt.savefig("%d_endpoint1.pdf"%idx) plt.savefig("%d_endpoint1.svg"%idx) new_mask = (np.zeros(mask_nii.get_data().shape) == 1) sub_mask = new_mask[mask_nii.get_data() > 0] sub_mask[j] = True new_mask[mask_nii.get_data() > 0] = sub_mask print np.where(new_mask) #ax = plt.subplot2grid((2,3), (1,1), colspan=2) plot_map(new_mask, mask_nii.get_affine(), threshold='auto') plt.savefig("%d_endpoint2.pdf"%idx) plt.savefig("%d_endpoint2.svg"%idx) return counter += 1 print counter
def setup_main_screen(self): self.fig = pylab.figure(figsize=(6,8)) pylab.subplots_adjust(top=.95, bottom=0.05, left=.05, right=.95, hspace=.15, wspace=.15) pylab.suptitle('Corsi Blocks') rows = 10 cols = 8 self.ax = {} #Main corsi blocks display self.ax['main'] = pylab.subplot2grid((rows, cols), (0, 0), colspan=cols, rowspan=rows-1) self.clear_main_screen('Move the mouse out of this panel to start.\nA sequence of blocks will appear in this panel.\nAt the end of the sequence the panel will change color.\nAfter the color change, click on the blocks in the order they appeared.') #The staircase display with span estimate self.ax['staircase'] = pylab.subplot2grid((rows, cols), (9, 1), colspan=cols-1) pylab.setp(self.ax['staircase'], 'xticks', [], 'yticks', []) self.cid = self.fig.canvas.mpl_connect('button_press_event', self.onclick) self.cid2 = self.fig.canvas.mpl_connect('axes_leave_event', self.onleaveaxes) self.cid3 = self.fig.canvas.mpl_connect('axes_enter_event', self.onenteraxes)
def compare_classifiers(usps = True, digit = 3): ''' Compares 3 different linear classifiers (Nearest-Centroid, Linear Discriminant Analysis, Perceptron) on either USPS data (for usps=True) or on BCI data (for usps = False) ''' if usps: #load usps data set X,Y = load_usps_data('usps.mat',digit) tit = 'USPS(' + str(digit) + ')' else: #load bci data set X,Y = load_bci_data('bcidata.mat') tit = 'BCI' #Use crossvalidation to estimate the training and test accuracies acc_cv = sp.zeros((5, 6)) (acc_cv[:,0],acc_cv[:,1]) = crossvalidate(X,Y,trainfun=train_ncc) (acc_cv[:,2],acc_cv[:,3]) = crossvalidate(X,Y,trainfun=train_lda) (acc_cv[:,4],acc_cv[:,5]) = crossvalidate(X,Y,trainfun=train_perceptron) #Plot the crossvalidation output pl.figure() ax1 = pl.subplot2grid((2,3), (0,0), colspan = 3) pl.bar(sp.array([1, 2, 3, 4, 5, 6]) - 0.4, acc_cv.mean(0), width = 0.8, yerr = acc_cv.std(0), ecolor = 'k', color = 'g') pl.xticks([1, 2, 3, 4, 5, 6], ['NCC tain', 'NCC test', 'LDA train', 'LDA test', 'PER train', 'PER test']) pl.xlim([0, 7]) pl.ylim([0.5, 1]) pl.ylabel('CV Accuracy') pl.title(tit + ' data set') #Train the classifiers and plot the output histograms w_ncc,b_ncc = train_ncc(X,Y) w_lda,b_lda = train_lda(X,Y) w_per,b_per= train_perceptron(X,Y) ax2 = pl.subplot2grid((2,3), (1,0)) plot_histogram(X, Y, w_ncc, b_ncc, 'NCC') ax3 = pl.subplot2grid((2,3), (1,1)) plot_histogram(X, Y, w_lda, b_lda, 'LDA') ax4 = pl.subplot2grid((2,3), (1,2)) plot_histogram(X, Y, w_per, b_per, 'PER') pl.show()