def imshow_(x, **kwargs): if x.ndim == 2: plt.imshow(x, interpolation="nearest", **kwargs) elif x.ndim == 1: plt.imshow(x[:,None].T, interpolation="nearest", **kwargs) plt.yticks([]) plt.axis("tight")
def plot_fits(direction_rates,fit_curve,title): """ This function takes the x-values and the y-values in units of spikes/s (found in the two columns of direction_rates and fit_curve) and plots the actual values with circles, and the curves as lines in both linear and polar plots. """ curve_xs = np.arange(direction_rates[0,0], direction_rates[-1,0]) fit_ys2 = normal_fit(curve_xs,fit_curve[0],fit_curve[1],fit_curve[2]) plt.subplot(2,2,3) plt.plot(direction_rates[:,0],direction_rates[:,1],'o',hold=True) plt.plot(curve_xs,fit_ys2,'-') plt.xlabel('Direction of Motions (Degrees)') plt.ylabel('Firing Rates (Spikes/sec)') plt.title(title) plt.axis([0, 360, 0, 40]) plt.xticks(direction_rates[:,0]) fit_ys = normal_fit(direction_rates[:,0],fit_curve[0],fit_curve[1],fit_curve[2]) plt.subplot(2,2,4,polar=True) spkiecount = np.append(direction_rates[:,1],direction_rates[0,1]) plt.polar(np.arange(0,361,45)*np.pi/180,spkiecount,'o',label='Firing Rate (spike/s)') plt.hold(True) spkiecount_y = np.append(fit_ys,fit_ys[0]) plt.plot(np.arange(0,361,45)*np.pi/180,spkiecount_y,'-') plt.legend(loc=8) plt.title(title) fit_ys2 = np.transpose(np.vstack((curve_xs,fit_ys2))) return(fit_ys2)
def show(self,figid=-1): """ show the graph as a planar graph Parameters ---------- figid = -1 the figure id in pylab by default a new figure is created Returns ------- figid """ import matplotlib.pylab as mp if figid>-1: figid = mp.figure(int(figid)) else: mp.figure() t = (2*np.pi*np.arange(self.V))/self.V mp.plot(np.cos(t),np.sin(t),'.') for e in range(self.E): A = (self.edges[e,0]*2*np.pi)/self.V B = (self.edges[e,1]*2*np.pi)/self.V mp.plot([np.cos(A),np.cos(B)],[np.sin(A),np.sin(B)],'k') mp.axis('off') return figid
def draw(self, description=None, ofile="test.png"): plt.clf() for f in self.funcs: f() plt.axis("off") ax = plt.gca() ax.set_aspect("equal", "datalim") f = plt.gcf() f.set_size_inches(12.8, 7.2) if description is not None: plt.text(0.025, 0.05, description, transform=f.transFigure) if self.xlim is not None: plt.xlim(*self.xlim) if self.ylim is not None: plt.ylim(*self.ylim) plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) # dpi = 100 for 720p, 150 for 1080p plt.savefig(ofile, dpi=150)
def showKernel(dataOrMatrix, fileName = None, useLabels = True, **args) : labels = None if hasattr(dataOrMatrix, 'type') and dataOrMatrix.type == 'dataset' : data = dataOrMatrix k = data.getKernelMatrix() labels = data.labels else : k = dataOrMatrix if 'labels' in args : labels = args['labels'] import matplotlib if fileName is not None and fileName.find('.eps') > 0 : matplotlib.use('PS') from matplotlib import pylab pylab.matshow(k) #pylab.show() if useLabels and labels.L is not None : numPatterns = 0 for i in range(labels.numClasses) : numPatterns += labels.classSize[i] #pylab.figtext(0.05, float(numPatterns) / len(labels), labels.classLabels[i]) #pylab.figtext(float(numPatterns) / len(labels), 0.05, labels.classLabels[i]) pylab.axhline(numPatterns, color = 'black', linewidth = 1) pylab.axvline(numPatterns, color = 'black', linewidth = 1) pylab.axis([0, len(labels), 0, len(labels)]) if fileName is not None : pylab.savefig(fileName) pylab.close()
def plot_tuning_curves(direction_rates, title): """ This function takes the x-values and the y-values in units of spikes/s (found in the two columns of direction_rates) and plots a histogram and polar representation of the tuning curve. It adds the given title. """ # yank columns and keep in correspondance directions = direction_rates[0:][:,0] rates = direction_rates[0:][:,1] # histogram plot plt.subplot(2, 2, 1) plt.title('Histogram ' + title) plt.axis([0, 360, 0, 70]) plt.xlim(-22.5,337.5) plt.xlabel('Directions (in degrees)') plt.ylabel('Average Firing Rate (in spikes/s)') plt.bar(directions, rates, width=45, align='center') plt.xticks(directions) # polar plot plt.subplot(2,2,2,polar=True) plt.title('Polar plot ' + title) #plt.legend('Diring Rate (spikes/s)') rates = np.append(rates, rates[0]) theta = np.arange(0,361,45)*np.pi/180 plt.polar(theta, rates) plt.show() # end plot_tuning_curves return 0
def set_axis_0(): pylab.xlabel('time (days)') pylab.gcf().subplots_adjust(top=1.0-0.13, bottom=0.2, right=1-0.02, left=0.2) a = list(pylab.axis()) na = [a[0], a[1], 0, a[3]*1.05] pylab.axis(na)
def scatter(title, file_name, x_array, y_array, size_array, x_label, \ y_label, x_range, y_range, print_pdf): ''' Plots the given x value array and y value array with the specified title and saves with the specified file name. The size of points on the map are proportional to the values given in size_array. If print_pdf value is 1, the image is also written to pdf file. Otherwise it is only written to png file. ''' rc('text', usetex=True) rc('font', family='serif') plt.clf() # clear the ploting window, a must. plt.scatter(x_array, y_array, s = size_array, c = 'b', marker = 'o', alpha = 0.4) if x_label != None: plt.xlabel(x_label) if y_label != None: plt.ylabel(y_label) plt.axis ([0, x_range, 0, y_range]) plt.grid(True) plt.suptitle(title) Plotter.print_to_png(plt, file_name) if print_pdf: Plotter.print_to_pdf(plt, file_name)
def __call__(self, **params): p = ParamOverrides(self, params) fig = plt.figure(figsize=(5, 5)) # This one-liner works in Octave, but in matplotlib it # results in lines that are all connected across rows and columns, # so here we plot each line separately: # plt.plot(x,y,"k-",transpose(x),transpose(y),"k-") # Here, the "k-" means plot in black using solid lines; # see matplotlib for more info. isint = plt.isinteractive() # Temporarily make non-interactive for # plotting plt.ioff() for r, c in zip(p.y[::p.skip], p.x[::p.skip]): plt.plot(c, r, "k-") for r, c in zip(np.transpose(p.y)[::p.skip],np.transpose(p.x)[::p.skip]): plt.plot(c, r, "k-") # Force last line avoid leaving cells open if p.skip != 1: plt.plot(p.x[-1], p.y[-1], "k-") plt.plot(np.transpose(p.x)[-1], np.transpose(p.y)[-1], "k-") plt.xlabel('x') plt.ylabel('y') # Currently sets the input range arbitrarily; should presumably figure out # what the actual possible range is for this simulation (which would presumably # be the maximum size of any GeneratorSheet?). plt.axis(p.axis) if isint: plt.ion() self._generate_figure(p) return fig
def plotter(resfile): # Import python matplotlib module try: import matplotlib.pylab as plt except: print >> sys.stderr, '\n Info: Python matplotlib module not found. Skipping plotting.' return None else: # Open input result file try: ifile = open(resfile, 'r') except: print >> sys.stderr, 'Error: Not able to open result file ', resfile sys.exit(-1) # Read data from the input file idata = ifile.readlines() # Close the input file try: ifile.close() except: print >> sys.stderr, 'Warning: Not able to close input file ', resfile # Read configuration file parser = readConfig() # Create and populate python lists x, y = [], [] for value in idata: if value[0] != '#': try: value.split()[2] except IndexError: pass else: x.append(value.split()[0]) y.append(value.split()[2]) # Set graph parameters and plot the completeness graph graph = os.path.splitext(resfile)[0] + '.' + parser.get('plotter', 'save_format') params = {'backend': 'ps', 'font.size': 10, 'axes.labelweight': 'medium', 'dpi' : 300, 'savefig.dpi': 300} plt.rcParams.update(params) fig = plt.figure() plt.title(parser.get('plotter', 'title'), fontweight = 'bold', fontsize = 12) plt.xlabel(parser.get('plotter', 'xlabel')) plt.ylabel(parser.get('plotter', 'ylabel')) plt.axis([float(min(x)) - 0.5, float(max(x)) + 0.5, 0.0, 110]) plt.grid(parser.get('plotter', 'grid'), linestyle = '-', color = '0.75') plt.plot(x, y, parser.get('plotter', 'style')) fig.savefig(graph) return graph
def generic_plot_sequence(r, plotter, space, sequence, axis0=None, annotation=None): axis = plotter.axis_for_sequence(space, sequence) if axis[0] == axis[1]: dx = 1 # dy = 1 axis = (axis[0] - dx, axis[1] + dx, axis[2], axis[3]) axis = enlarge(axis, 0.15) if axis0 is not None: axis = join_axes(axis, axis0) for i, x in enumerate(sequence): caption = space.format(x) caption = None with r.plot('S%d' % i, caption=caption) as pylab: plotter.plot(pylab, axis, space, x) if annotation is not None: annotation(pylab, axis) xlabel, ylabel = plotter.get_xylabels(space) try: if xlabel: pylab.xlabel(xlabel) if ylabel: pylab.ylabel(ylabel) except UnicodeDecodeError as e: print xlabel, xlabel.__repr__(), ylabel, ylabel.__repr__(), e if (axis[0] != axis[1]) or (axis[2] != axis[3]): pylab.axis(axis)
def ZipByDemoCuisine(askNum ,Zipcodes, recorddict): for zips in Zipcodes: if askNum == zips.Zip: print "This is located in " + str(zips.Hood) + "!" labels = ['White', 'Black', 'AI', 'Asian', 'NH/PI', 'Other', 'Multiple', 'Hispanic'] sizes = [zips.White, zips.Black, zips.AI_AN, zips.Asian, zips.NHOPI, zips.OthRace, zips.MultRaces, zips.Hispanic] colors = ['red', 'orange', 'yellow', 'green', 'lightskyblue', 'darkblue','pink', 'purple' ] explode = (0, 0, 0, 0, 0, 0, 0, 0) plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=False, startangle=140) plt.axis('equal') plt.show() xlist = [] ylist = [] x = Counter(recorddict[askNum]) for i in x.most_common(10): xlist.append(i[0]) ylist.append(int(i[1])) #i[0] = category #i[1] = number of category labels = xlist sizes = ylist colors = ['red', 'orange', 'yellow', 'green', 'lightskyblue', 'darkblue', 'pink', 'white', 'silver', 'purple'] explode = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0) plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=False, startangle=140) plt.axis('equal') plt.show()
def setup_fam_matplotlib(Np, P, L, filename, sample_type, verbose, animate_func=animate): """Setup the FAM flow graph and Matplotlib and start it. """ mytb = FAMProcessor(filename=filename, Np=Np, P=P, L=L, sample_type=sample_type, verbose=verbose) # Start Flowgraph in background, then give it some time to fire up mytb.start() time.sleep(3) # Calc First Image to Show, setup axis raw = mytb.cyclo_fam.get_estimate() data = numpy.array(raw) image = plt.imshow(data, interpolation='nearest', animated=True, extent=(-0.5, 0.5-1.0/Np, -1.0, 1.0-1.0/(P*L))) cbar = plt.colorbar(image) plt.xlabel('frequency / fs') plt.ylabel('cycle frequency / fs') plt.axis('normal') plt.title('Magnitude of estimated cyclic spectrum with FAM') # optional: # pylab.axhline(linewidth=1, color='w') # pylab.axvline(linewidth=1, color='w') gobject.idle_add(lambda iter=animate_func(mytb.cyclo_fam, image, cbar): iter.next()) plt.show()
def experiment_plot( ctr, trials, success ): """ Pass in the ctr, trials and success returned by the `experiment` function and plot the Cumulative Number of Turns For Each Arm and the CTR's Convergence Plot side by side """ T, K = trials.shape n = np.arange(T) + 1 fig = plt.figure( figsize = ( 14, 7 ) ) plt.subplot(121) for i in range(K): plt.loglog( n, trials[ :, i ], label = "arm {}".format(i + 1) ) plt.legend( loc = "upper left" ) plt.xlabel("Number of turns") plt.ylabel("Number of turns/arm") plt.title("Cumulative Number of Turns For Each Arm") plt.subplot(122) for i in range(K): plt.semilogx( n, np.zeros(T) + ctr[i], label = "arm {}'s CTR".format( i + 1 ) ) plt.semilogx( n, ( success[ :, 0 ] + success[ :, 1 ] ) / n, label = "CTR at turn t" ) plt.axis([ 0, T, 0, 1 ] ) plt.legend( loc = "upper left" ) plt.xlabel("Number of turns") plt.ylabel("CTR") plt.title("CTR's Convergence Plot") return fig
def doit(): # test it out L = 1 R = 10 theta = np.radians(np.arange(0,361)) # draw a circle plt.plot(R*np.cos(theta), R*np.sin(theta), c="b") # draw some people angles = [30, 60, 90, 120, 180, 270, 300] for l in angles: center = ( (R + 0.5*L)*np.cos(np.radians(l)), (R + 0.5*L)*np.sin(np.radians(l)) ) draw_person(center, L, np.radians(l - 90), color="r") L = 1.1*L plt.axis("off") ax = plt.gca() ax.set_aspect("equal", "datalim") plt.subplots_adjust(left=0.05, right=0.98, bottom=0.05, top=0.98) plt.axis([-1.2*R, 1.2*R, -1.2*R, 1.2*R]) f = plt.gcf() f.set_size_inches(6.0, 6.0) plt.savefig("test.png")
def part2(w): f = plt.figure() for i in range(16): f.add_subplot(4,4,i+1) plt.axis('off') plt.imshow(np.reshape(normalize(w[1:,i]), (20,20)), cmap = matplotlib.cm.Greys_r) plt.savefig('3.png')
def STAplot(self, option = 0): try: self.Files.OpenDatabase(self.NAME + '.h5') STA_TIME = self.Files.QueryDatabase('STA_Analysis', 'STA_TIME')[0] STA_Current = self.Files.QueryDatabase('STA_Analysis', 'STAstim') INTSTEP = self.Files.QueryDatabase('DataProcessing', 'INTSTEP')[0][0] except: print 'Sorry no data found' X = np.arange(-STA_TIME / INTSTEP, STA_TIME / INTSTEP, dtype=float) * INTSTEP if option == 1: fig = plt.figure() ax = fig.add_subplot(111) ax.plot(X[0:(STA_TIME/INTSTEP)],STA_Current[0:(STA_TIME/INTSTEP)], linewidth=3, color='k') ax.plot(np.arange(-190,-170),np.ones(20)*0.35, linewidth=5,color='k') ax.plot(np.ones(200)*-170,np.arange(0.35,0.549,0.001),linewidth=5,color='k') ax.plot(np.arange(-200,0),np.zeros(200), 'k--', linewidth=2) plt.axis('off') plt.show() if option == 0: fig = plt.figure(figsize=(12,8)) ax = fig.add_subplot(111) ax.plot(X[0:(STA_TIME / INTSTEP) + 50], STA_Current[0:(STA_TIME / INTSTEP) + 50], linewidth=3, color='k') plt.xticks(fontsize = 20) plt.yticks(fontsize = 20) plt.ylabel('current(pA)', fontsize = 20) plt.legend(('data'), loc='upper right') plt.show()
def compareAnimals(animals, precision): ''' :param animals:动物列表 :param (int) precision: 精度 :return : 表格,包含任意两个动物之间的欧式距离 ''' columnLabels = [] for a in animals: columnLabels.append(a.getName()) rowLabels = columnLabels[:] tableVals = [] #循环计算任意两个动物间的欧氏距离 for a1 in animals: row =[] for a2 in animals: if a1 == a2: row.append('--') else: distance = a1.distance(a2) row.append(str(round(distance, precision))) tableVals.append(row) #生成表格 table = plt.table(rowLabels=rowLabels, colLabels=columnLabels, cellText=tableVals, cellLoc='center', loc='center', colWidths=[0.2]*len(animals)) table.scale(1, 2.5) plt.axis('off') plt.savefig('chapter19_1.png', dpi=100) plt.show()
def func(im): plt.figure() plt.title(ti) if type(im) == list: im = np.zeros(max_shape) plt.imshow(im,cmap=cmap,vmin=a_min,vmax=a_max) plt.axis('off')
def plot(self, isec=None, ifig=1, coordsys='rotor'): import matplotlib.pylab as plt if coordsys == 'rotor': afs = self.afsorg elif coordsys == 'mold': afs = self.afs plt.figure(ifig) if isec is not None: ni = [isec] else: ni = range(self.ni) for i in ni: plt.title('r = %3.3f' % (self.z[i])) af = afs[i] plt.plot(af.points[:, 0], af.points[:, 1], 'b-') DP = np.array([af.interp_s(af.s_to_01(s)) for s in self.DPs[i, :]]) width = np.diff(self.DPs[i, :]) valid = np.ones(DP.shape[0]) valid[1:] = width > self.min_width for d in DP: plt.plot(d[0], d[1], 'ro') for d in DP[self.cap_DPs, :]: plt.plot(d[0], d[1], 'mo') for web_ix in self.web_def: if valid[web_ix].all(): plt.plot(DP[[web_ix[0], web_ix[1]]][:, 0], DP[[web_ix[0], web_ix[1]]][:, 1], 'g') plt.axis('equal')
def plot_p(frame): sol=Solution(frame,file_format='petsc',read_aux=False,path='./_output/_p/',file_prefix='claw_p') x=sol.state.grid.x.centers; y=sol.state.grid.y.centers mx=len(x); my=len(y) mp=sol.state.num_eqn yy,xx = np.meshgrid(y,x) p=sol.state.q[0,:,:] fig = pl.figure(figsize=(8, 3.5)) #pl.title("t= "+str(sol.state.t),fontsize=20) pl.xticks(size=20); pl.yticks(size=20) pl.xlabel('x',fontsize=20); pl.ylabel('y',fontsize=20) #pl.pcolormesh(xx,yy,p_subxy,cmap=cm.OrRd) pl.pcolormesh(xx,yy,p,cmap='RdBu_r') pl.autoscale(tight=True) cb = pl.colorbar(ticks=[0.5,1,1.5,2]); #pl.clim(ticks=[0.5,1,1.5,2]) imaxes = pl.gca(); pl.axes(cb.ax) pl.yticks(fontsize=20); pl.axes(imaxes) #pl.xticks(fontsize=20); pl.axes(imaxes) #pl.axis('equal') pl.axis('tight') fig.tight_layout() pl.savefig('./_plots_to_paper/sound-speed_FV_t'+str(frame)+'_pcolor.png') pl.close()
def plot_p_leading_order(frame): mat = scipy.io.loadmat('sound-speed_2D-wave.mat') T=5; nt=T/0.5 pp=mat['U'][nt,:,:] xx=mat['xx'] yy=mat['yy'] fig=pl.figure(figsize=(8, 3.5)) #pl.title("t= "+str(sol.state.t),fontsize=20) pl.xticks(size=20); pl.yticks(size=20) pl.xlabel('x',fontsize=20); pl.ylabel('y',fontsize=20) #pl.pcolormesh(xx,yy,p_subxy,cmap=cm.OrRd) pl.pcolormesh(xx,yy,pp,cmap='RdBu_r') pl.autoscale(tight=True) cb = pl.colorbar(ticks=[0.5,1,1.5,2]); #pl.clim(ticks=[0.5,1,1.5,2]) imaxes = pl.gca(); pl.axes(cb.ax) pl.yticks(fontsize=20); pl.axes(imaxes) #pl.xticks(fontsize=20); pl.axes(imaxes) #pl.axis('equal') pl.axis('tight') fig.tight_layout() pl.savefig('./_plots_to_paper/sound-speed_LO_t'+str(frame)+'_pcolor.png') pl.close()
def matrix_plot(self, matrix, figure_name='matrix_plot.pdf'): import numpy from matplotlib import pylab def _blob(x,y,area,colour): hs = numpy.sqrt(area) / 2 xcorners = numpy.array([x - hs, x + hs, x + hs, x - hs]) ycorners = numpy.array([y - hs, y - hs, y + hs, y + hs]) pylab.fill(xcorners, ycorners, colour, edgecolor=colour) reenable = False if pylab.isinteractive(): pylab.ioff() pylab.clf() maxWeight = 2**numpy.ceil(numpy.log(numpy.max(numpy.abs(matrix)))/numpy.log(2)) height, width = matrix.shape pylab.fill(numpy.array([0,width,width,0]),numpy.array([0,0,height,height]),'white') pylab.axis('off') pylab.axis('equal') for x in xrange(width): for y in xrange(height): _x = x+1 _y = y+1 w = matrix[y,x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, 0.2,'#0099CC') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, 0.2,'#660000') if reenable: pylab.ion() pylab.savefig(figure_name)
def filtray(self, itx, irx, tau0, tau1, col='b'): """ filter rays Parameters ---------- itx : irx : tau0 : tau1 : col : Display ray and nstr """ gr = GrRay3D() gr.load(self.dtra[itx][irx], self.L) self.L.display['Thin'] = True self.L.display['Node'] = False self.L.display['NodeNum'] = False self.L.display['EdgeNum'] = False plt.axis('scaled') #self.L.show(fig,ax,nodelist,seglist) self.L.showGs() delays = gr.delay() rayset = np.nonzero((delays >= tau0) & (delays <= tau1))[0] fig = plt.gcf() ax = fig.get_axes()[0] gr.show(ax, rayset, col=col, node=False) plt.title('Tx' + str(itx) + '-Rx' + str(irx) + ' : ' + str( tau0) + ' < tau < ' + str(tau1))
def mass_flux_plot(*args,**kwargs): fltm = idls.read(args[0]) injm = idls.read(args[1]) f1 = plt.figure() ax1 = f1.add_subplot(211) plt.plot(injm.nt_sc,injm.nmf_rscale,'r') plt.plot(injm.nt_sc,injm.nmf_zscale,'b') plt.plot(injm.nt_sc,injm.nmf_z0scale,'k') plt.plot(injm.nt_sc,(injm.nmf_rscale+injm.nmf_zscale),'g') plt.axis([0.0,160.0,0.0,3.5e-5]) plt.minorticks_on() locs,labels = plt.yticks() plt.yticks(locs, map(lambda x: "%.1f" % x, locs*1e5)) plt.text(0.0, 1.03, r'$10^{-5}$', transform = plt.gca().transAxes) plt.xlabel(r'Time [yr]',labelpad=6) plt.ylabel(r'$\dot{\rm M}_{\rm out} [ \rm{M}_{\odot} \rm{yr}^{-1} ]$',labelpad=15) ax2 = f1.add_subplot(212) plt.plot(fltm.nt_sc,fltm.nmf_rscale,'r') plt.plot(fltm.nt_sc,fltm.nmf_zscale,'b') plt.plot(fltm.nt_sc,fltm.nmf_z0scale,'k') plt.plot(fltm.nt_sc,(fltm.nmf_rscale+fltm.nmf_zscale),'g') plt.axis([0.0,160.0,0.0,4.0e-5]) plt.minorticks_on() locs,labels = plt.yticks() plt.yticks(locs, map(lambda x: "%.1f" % x, locs*1e5)) plt.text(0.0, 1.03, r'$10^{-5}$', transform = plt.gca().transAxes) plt.xlabel(r'Time [yr]',labelpad=6) plt.ylabel(r'$\dot{\rm M}_{\rm out} [ \rm {M}_{\odot} \rm{yr}^{-1} ]$',labelpad=15)
def parametric_plot(func): """ Plot the example curves """ MAXX = 100.0 x = np.linspace(0, MAXX, 1000) pylab.figure() for mu in np.linspace(0, 100, 8): lamb = 4.0 pylab.plot(x, func(x, mu, lamb), linewidth=3.0) #pylab.axvline(mu, linestyle='--') pylab.grid(1) pylab.axis([0, MAXX, 0, 1]) pylab.figure() for c, mu in [('r', 0.0), ('b', 50.0)]: for lamb in np.array([0.1, 0.5, 1.0, 2.0, 4.0]): # 1.0, 4.0, 10.0, 20, 50]: pylab.plot(x, func(x, mu, lamb), linewidth=3, c=c) #pylab.axvline(mu, linestyle='--') pylab.grid(1) pylab.axis([0, MAXX, 0, 1]) pylab.show()
def rec_test(file_name, sino_start, sino_end): print "\n#### Processing " + file_name sino_start = sino_start + 200 sino_end = sino_start + 2 print "Test reconstruction of slice [%d]" % sino_start # Read HDF5 file. prj, flat, dark = tomopy.io.exchange.read_aps_32id(file_name, sino=(sino_start, sino_end)) # Manage the missing angles: theta = tomopy.angles(prj.shape[0]) prj = np.concatenate((prj[0 : miss_angles[0], :, :], prj[miss_angles[1] + 1 : -1, :, :]), axis=0) theta = np.concatenate((theta[0 : miss_angles[0]], theta[miss_angles[1] + 1 : -1])) # normalize the prj prj = tomopy.normalize(prj, flat, dark) # reconstruct rec = tomopy.recon(prj, theta, center=best_center, algorithm="gridrec", emission=False) # Write data as stack of TIFs. tomopy.io.writer.write_tiff_stack(rec, fname=output_name) print "Slice saved as [%s_00000.tiff]" % output_name # show the reconstructed slice pl.gray() pl.axis("off") pl.imshow(rec[0])
def minj_mflux(*args,**kwargs): Qu = jana.quantities() Minj_List =[] Minj_MHD_List=[] for i in range(len(args[1])): Minj_List.append(Qu.Mflux(args[1][i],Mstar=args[0][i],scale=True)['Mfr']+Qu.Mflux(args[1][i],Mstar=args[0][i],scale=True)['Mfz']) MHD_30minj = Qu.Mflux(args[2],Mstar=30.0,scale=True)['Mfr']+Qu.Mflux(args[2],Mstar=30.0,scale=True)['Mfz'] for i in args[0]: Minj_MHD_List.append(MHD_30minj*np.sqrt(i/30.0)) f1 = plt.figure(num=1) ax1 = f1.add_subplot(211) plt.axis([10.0,70.0,2.0e-5,7.99e-5]) plt.plot(args[0],Minj_MHD_List,'k*') plt.plot(args[0],Minj_List,'ko') plt.minorticks_on() locs,labels = plt.yticks() plt.yticks(locs, map(lambda x: "%.1f" % x, locs*1e5)) plt.text(0.0, 1.03, r'$10^{-5}$', transform = plt.gca().transAxes) plt.xlabel(r'Stellar Mass : $M_{*} [M_{\odot}]$') plt.ylabel(r' $\dot{M}_{\rm vert} + \dot{M}_{\rm rad}\, [M_{\odot}\,\rm yr^{-1}]$') ax2 = f1.add_subplot(212) plt.axis([10.0,70.0,0.0,50.0]) plt.plot(args[0],100*((np.array(Minj_List)-np.array(Minj_MHD_List))/np.array(Minj_MHD_List)),'k^') plt.minorticks_on() plt.xlabel(r'Stellar Mass : $M_{*} [M_{\odot}]$') plt.ylabel(r'$\%$ Change in Total Mass Outflow Rates')
def main_k_nearest_neighbour(k): X, y = make_blobs(n_samples=100, n_features=2, centers=2, cluster_std=1.0, center_box=(-10.0, 10.0)) h = .4 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) z = np.c_[xx.ravel(), yy.ravel()] z_f = [] for i_z in z: z_f.append(k_nearest_neighbour(X, y, i_z, k, False)) zz = np.array(z_f).reshape(xx.shape) plt.figure() plt.contourf(xx, yy, zz, cmap=plt.cm.Paired) plt.axis('tight') plt.scatter(X[:, 0], X[:, 1], c=y) plt.show()
def show(size=(12, 12)): # Make all plots have square aspect ratio plt.axis('equal') # Make high quality fig = plt.gcf() fig.set_size_inches(*size) plt.show()
y = sol[:, 1] sol2 = balistica(10) x2 = sol2[:, 0] y2 = sol2[:, 1] sol3 = balistica(20) x3 = sol3[:, 0] y3 = sol3[:, 1] plt.figure(1) plt.plot(x, y, color='b') plt.plot(x2, y2, color='orange') plt.plot(x3, y3, color='g') plt.axis([0, 150, 0, 50]) plt.grid(True) plt.legend(('V = 0 m/s', 'V = 10.0 m/s', "V = 20.0 m/s"), prop={'size': 10}, loc='upper right') trickx = [0, 20, 40, 60, 80, 100, 120, 140] trickx_txt = [0, 20, 40, 60, 80, 100, 120, 140] plt.xticks(trickx, trickx_txt) tricky = [0, 10, 20, 30, 40, 50] tricky_txt = [0, 10, 20, 30, 40, 50] plt.yticks(tricky, tricky_txt) plt.xlabel('X (m)')
EbdVecNorms = norm(EmbedVectors, axis=0) plt.figure() plt.hist(EbdVecNorms, bins=30) plt.title("Norm of 128d embed vector of BigGAN-Deep256") plt.xlabel("Norm") plt.savefig(join(homedir, "EmbedVectNormDist.png")) plt.show() #%% Mean Vector meanEmbed = EmbedVectors.mean(axis=1) # norm(meanEmbed) = 0.017733473 #%% imgs_mean = BigGAN_embed_render(meanEmbed[np.newaxis, :], scale=1.0) plt.figure(figsize=[4, 4]) plt.imshow(imgs_mean[0]) plt.title("Mean Class Embedding") plt.axis("image") plt.axis("off") plt.savefig(join(homedir, "class_mean_img.png")) plt.show() #%% imgs_zeros = BigGAN_embed_render(np.zeros((1, 128)), scale=1.0) plt.figure(figsize=[4, 4]) plt.imshow(imgs_zeros[0]) plt.title("Zeros Vector visualized") plt.axis("image") plt.axis("off") plt.savefig(join(homedir, "zero_vect_img.png")) plt.show() #%% from numpy.linalg import svd
M1 /= M1.max() # loss matrix M2 = ot.dist(xs, xt, metric='sqeuclidean') M2 /= M2.max() # loss matrix Mp = np.sqrt(ot.dist(xs, xt, metric='euclidean')) Mp /= Mp.max() # Data pl.figure(1, figsize=(7, 3)) pl.clf() pl.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples') pl.plot(xt[:, 0], xt[:, 1], 'xr', label='Target samples') pl.axis('equal') pl.title('Source and target distributions') # Cost matrices pl.figure(2, figsize=(7, 3)) pl.subplot(1, 3, 1) pl.imshow(M1, interpolation='nearest') pl.title('Euclidean cost') pl.subplot(1, 3, 2) pl.imshow(M2, interpolation='nearest') pl.title('Squared Euclidean cost') pl.subplot(1, 3, 3)
def draw_cut_graph(G, partition_dict=None, pos=None, node_size=1000, edge_width=3, font_size=12, node_label=True, title=''): """Draw a cut graph G using Matplotlib.""" if partition_dict: nx.set_node_attributes(G, gc.PARTITION, partition_dict) if not pos: pos = nx.circular_layout(G, scale=20) blue_nodes, black_nodes, undecided_nodes, marked_nodes = gc.get_partitions(G) # Draw nodes and edges of the first partition nx.draw_networkx_nodes(G, pos, blue_nodes, node_size=node_size, node_color='blue') nx.draw_networkx_edges(G, pos, list(nx.edge_boundary(G, blue_nodes, blue_nodes)), width=edge_width, edge_color='blue') # Draw nodes and edges of the second partition nx.draw_networkx_nodes(G, pos, black_nodes, node_size=node_size, node_color='black') nx.draw_networkx_edges(G, pos, list(nx.edge_boundary(G, black_nodes, black_nodes)), width=edge_width, edge_color='black') # Draw undecided nodes and edges nx.draw_networkx_nodes(G, pos, undecided_nodes, node_size=node_size, node_color='magenta') nx.draw_networkx_edges(G, pos, list(nx.edge_boundary(G, undecided_nodes, undecided_nodes)), width=edge_width, edge_color='magenta') nx.draw_networkx_edges(G, pos, list(nx.edge_boundary(G, blue_nodes, undecided_nodes)), width=edge_width, style='dotted', edge_color='magenta') nx.draw_networkx_edges(G, pos, list(nx.edge_boundary(G, undecided_nodes, black_nodes)), width=edge_width, style='dotted', edge_color='magenta') # Draw marked nodes and edges nx.draw_networkx_nodes(G, pos, marked_nodes, node_size=node_size, node_color='red') nx.draw_networkx_edges(G, pos, list(nx.edge_boundary(G, marked_nodes, marked_nodes)), width=edge_width, edge_color='red') #Draw edges beetween marked and unmarked nx.draw_networkx_edges(G, pos, list(nx.edge_boundary(G, marked_nodes, blue_nodes)), width=edge_width, edge_color='orange') nx.draw_networkx_edges(G, pos, list(nx.edge_boundary(G, marked_nodes, black_nodes)), width=edge_width, edge_color='orange') nx.draw_networkx_edges(G, pos, list(nx.edge_boundary(G, marked_nodes, undecided_nodes)), width=edge_width, edge_color='orange') # Draw cut edges nx.draw_networkx_edges(G, pos, list(nx.edge_boundary(G, blue_nodes, black_nodes)), width=edge_width, style='dashed', edge_color='gray') if node_label: nx.draw_networkx_labels(G, pos, font_color='white', font_size=font_size, font_weight='bold') plt.title(title) plt.axis('off')
# -*- coding: utf-8 -*- """ Created on Tue Aug 7 18:15:53 2018 @author: Editi """ import matplotlib.pylab as plt x_values = list(range(1, 1001)) y_values = [x**3 for x in x_values] plt.scatter(x_values, y_values, edgecolor='none', s=35) plt.title("Scatter Squares", fontsize=24) plt.xlabel("Value", fontsize=14) plt.ylabel("Square of Value", fontsize=14) plt.tick_params(axis='both', which='major', labelsize=14) plt.axis([0, 1100, 0, 1100000000]) plt.show() plt.savefig('squares_plot.png', bbox_inches='tight')
<<<<<<< HEAD (group[pir]*scale).plot.area(ax=axes[i, 1], sharey=True, cmap='gray', figsize=(5, 0.3*n_group)) ((1-group[led])*800).plot.area(linewidth=0, cmap=my_cmap, ax=axes[i, 1], sharey=True) x_axis = axes[i, 1].axes.get_xaxis() x_axis.set_visible(False) axes[i, 1].axes.set_ylim(1, 800) ======= (group[pir]*scale).plot.area(ax=axes[i, 1], sharey=True, cmap='gray', figsize=(4.3, 0.2*n_group)) ((1-group[led])*800).plot.area(linewidth=0, cmap=my_cmap, ax=axes[i, 1], sharey=True) x_axis = axes[i, 1].axes.get_xaxis() x_axis.set_visible(False) axes[i, 1].axes.set_ylim(1,800) >>>>>>> 2a67e3a431247dee1d1dfeba36c8cb70dcc2c91b y_axis = axes[i, 1].axes.get_yaxis() y_axis.set_visible(False) i = i+1 <<<<<<< HEAD fig.subplots_adjust(left=0.12, right=0.88, bottom=0.45, wspace=0, hspace=0) ======= fig.subplots_adjust(left=0.12, right=0.9, bottom=0.3, wspace=0, hspace=0) >>>>>>> 2a67e3a431247dee1d1dfeba36c8cb70dcc2c91b plt.axis('off') plt.suptitle(box, size=9) plt.savefig(box+'.png') # plt.show() a = ScrollableWindow(fig)
def plotImage(image_location): image = cv2.imread(image_name) image = cv2.resize(image, (50,50)) plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)); plt.axis('off') return
image = cv2.imread(image_name) image = cv2.resize(image, (50,50)) plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)); plt.axis('off') return plotImage(image_name) # Plot Multiple Images bunchOfImages = imagePatches i_ = 0 plt.rcParams['figure.figsize'] = (10.0, 10.0) plt.subplots_adjust(wspace=0, hspace=0) for l in bunchOfImages[:25]: im = cv2.imread(l) im = cv2.resize(im, (50, 50)) plt.subplot(5, 5, i_+1) #.set_title(l) plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)); plt.axis('off') i_ += 1 def randomImages(a): r = random.sample(a, 4) plt.figure(figsize=(16,16)) plt.subplot(131) plt.imshow(cv2.imread(r[0])) plt.subplot(132) plt.imshow(cv2.imread(r[1])) plt.subplot(133) plt.imshow(cv2.imread(r[2])); randomImages(imagePatches) patternZero = '*class0.png' patternOne = '*class1.png'
n_skip = int(sys.argv[3]) data = np.loadtxt(sys.argv[2], delimiter=' ') plt.grid() E = data[Nterm:, 1] mean_E = [ np.mean(E[i * Nportemp + n_skip:(i + 1) * Nportemp]) for i in range(len(T)) ] var_E = [ np.std(E[i * Nportemp + n_skip:(i + 1) * Nportemp]) for i in range(len(T)) ] plt.errorbar(T, mean_E, var_E, fmt="b.") m, b = np.polyfit(T, mean_E, 1) plt.plot(np.sort(T), np.sort(T) * m + b, "r-") plt.axis([0, 11, -30000, -18000]) print(m, b) plt.show() if (sys.argv[1] == 'h'): n_skip = 0 dataFile = open(sys.argv[2]) line = dataFile.readline() params = line.split(" ") Npart, L, Nterm, Nportemp = int(params[1]), float(params[2]), int( params[3]), int(params[4]) line = dataFile.readline() params = line.split(" ") T = np.array([float(params[i]) for i in range(1, len(params))]) if (len(sys.argv) == 4): n_skip = int(sys.argv[3])
fig = plt.figure(figsize=(17, 17)) iterations = 0 plt.subplot(2, 2, 1).set_title("Sierpinski Carpet (iterations = 0)") carpet(a, b, c, d, iterations) plt.plot([a[0], b[0], c[0], d[0], a[0]], [a[1], b[1], c[1], d[1], a[1]], 'k-', lw=3) plt.plot([ab[0], dc[0]], [ab[1], dc[1]], 'k--', lw=3) plt.plot([ba[0], cd[0]], [ba[1], cd[1]], 'k--', lw=3) plt.plot([ad[0], bc[0]], [ad[1], bc[1]], 'k--', lw=3) plt.plot([da[0], cb[0]], [da[1], cb[1]], 'k--', lw=3) plt.axis('equal') plt.axis('off') iterations = 1 plt.subplot(2, 2, 2).set_title("Sierpinski Carpet (iterations = 1)") carpet(a, b, c, d, iterations) plt.axis('equal') plt.axis('off') iterations = 2 plt.subplot(2, 2, 3).set_title("Sierpinski Carpet (iterations = 2)")
def draw_bipartite_topic_graph(graph, filename='bipartite_topic_graph', tm_titles=["", ""], label_width=2, figsize=(12, 12)): top_nodes = set(n for n, d in graph.nodes(data=True) if d['bipartite'] == 0) bottom_nodes = set(graph) - top_nodes top_nodes = sorted(list(top_nodes)) bottom_nodes = sorted(list(bottom_nodes)) pos = dict() pos.update( (n, (0, -i)) for i, n in enumerate(top_nodes)) # put top nodes at x=0 pos.update((n, (1, -i)) for i, n in enumerate(bottom_nodes)) # put bottom nodes at x=1 labels = nx.get_node_attributes(graph, 'label') labels1 = [labels[node] for node in top_nodes] labels2 = [labels[node] for node in bottom_nodes] fig = plt.figure(figsize=figsize) # edges weights = nx.get_edge_attributes(graph, 'weight') if weights: weight_array = np.array(list(weights.values())) weight_array = 5. * weight_array / weight_array.max() # nx.draw_networkx_edges(graph,pos,width=weight_array,alpha=0.5) weight_array = np.sort(weight_array) sorted_edgelist = [ i[0] for i in sorted(weights.items(), key=lambda x: x[1]) ] nx.draw_networkx_edges(graph, pos, width=3, edgelist=sorted_edgelist, edge_color=weight_array, edge_cmap=plt.cm.Blues, alpha=0.5) else: nx.draw_networkx_edges(graph, pos, width=2., alpha=0.5) nx.draw_networkx_nodes(graph, pos, node_color='r', node_size=30, alpha=0.8) ax = plt.gca() for i, t in enumerate(labels1): ax.text(-0.1, -i, t, horizontalalignment='right', verticalalignment='center', fontsize=12) for i, t in enumerate(labels2): ax.text(1.1, -i, t, horizontalalignment='left', verticalalignment='center', fontsize=12) # plot topic model titles if len(tm_titles) == 2: ax.text(-0.1, 1, tm_titles[0], horizontalalignment='right', verticalalignment='center', fontsize=14, weight='bold') ax.text(1.1, 1, tm_titles[1], horizontalalignment='left', verticalalignment='center', fontsize=14, weight='bold') plt.ylim([(-1) * max([len(labels1), len(labels2)]), 2]) else: print("topic model titles not drawn: wrong length (not 2)") # nx.draw_networkx_labels(g,pos, labels1,font_size=6) # nx.draw_networkx_labels(g,pos, labels2,font_size=6) plt.xlim([(-1) * label_width, label_width + 1]) plt.axis('off') plt.tight_layout() plt.savefig(filename + ".png", dpi=150, bbox_inches='tight') # save as png plt.savefig(filename + ".pdf", bbox_inches='tight') # save as pd return fig
def kohonen(): """Example for using create_data, plot_data and som_step. """ plb.close('all') dynamicEta = True dynamicSigma = True Equilibrate = False dim = 28 * 28 data_range = 255.0 # load in data and labels data = np.array(np.loadtxt('data.txt')) labels = np.loadtxt('labels.txt') # select 4 digits name = 'Lorkowski' # REPLACE BY YOUR OWN NAME targetdigits = name2digits( name) # assign the four digits that should be used print targetdigits # output the digits that were selected # this selects all data vectors that corresponds to one of the four digits data = data[np.logical_or.reduce([labels == x for x in targetdigits]), :] # filter the label labels = labels[np.logical_or.reduce([labels == x for x in targetdigits])] dy, dx = data.shape #set the size of the Kohonen map. In this case it will be 6 X 6 size_k = 8 #set the width of the neighborhood via the width of the gaussian that #describes it #initial_sigma = 5 initial_sigma = float(size_k / 2) sigma = [initial_sigma] #initialise the centers randomly centers = np.random.rand(size_k**2, dim) * data_range #build a neighborhood matrix neighbor = np.arange(size_k**2).reshape((size_k, size_k)) #set the learning rate eta = [0.1] # HERE YOU HAVE TO SET YOUR OWN LEARNING RATE #set the maximal iteration count tmax = ( 500 * size_k * size_k ) + 1000 # this might or might not work; use your own convergence criterion #tmax = 20000 #set the random order in which the datapoints should be presented i_random = np.arange(tmax) % dy np.random.shuffle(i_random) #convergence criteria tol = 0.1 previousCenters = np.copy(centers) errors = [] mErrors = [] logError = [] finalErrors = [] tailErrors = [0.0] # 500 last errors if ((dynamicEta == True) & (dynamicSigma == True)): filename = 'k' + str(size_k) + 'dynamicEta' + str( eta[0]) + 'dynamicSigma' + str(sigma[0]) + '_tmax' + str(tmax) print filename elif ((dynamicEta == True) & (dynamicSigma == False)): filename = 'k' + str(size_k) + 'dynamicEta' + str( eta[0]) + 'sigma' + str(sigma[0]) + '_tmax' + str(tmax) print filename elif ((dynamicEta == False) & (dynamicSigma == True)): filename = 'k' + str(size_k) + 'eta' + str( eta[0]) + 'dynamicSigma' + str(sigma[0]) + '_tmax' + str(tmax) print filename else: filename = 'k' + str(size_k) + 'eta' + str(eta[0]) + 'sigma' + str( sigma[0]) + '_tmax' + str(tmax) print filename #convergedList=[] #numConverged=0 #holdConvergedLabelsCount=0 #t=-1 for t, i in enumerate(i_random): ''' if ( labels[i] in convergedList ): holdConvergedLabelsCount += 1 if (holdConvergedLabelsCount >= len(targetdigits)): del convergedList[:] holdConvergedLabelsCount = 0 numConverged = 0 print "releasing labels" continue t+=1 # If you use this with t in the iterator to tn ''' if dynamicEta == True: new_eta = eta[0] * exp(-float(t) / float(tmax)) ''' C = tmax/100 new_eta = C * eta[0] / (C+t) ''' eta.append(new_eta) if dynamicSigma == True: if sigma[0] == 1: new_sigma = sigma[0] else: mlambda = tmax / log(sigma[0]) new_sigma = sigma[0] * exp(-float(t / mlambda)) sigma.append(new_sigma) # Change to sigma[0] for static and sigma[t] for dynamic neighborhood function if ((dynamicEta == True) & (dynamicSigma == True)): som_step(centers, data[i, :], neighbor, eta[t], sigma[t]) elif ((dynamicEta == False) & (dynamicSigma == True)): som_step(centers, data[i, :], neighbor, eta[0], sigma[t]) elif ((dynamicEta == True) & (dynamicSigma == False)): som_step(centers, data[i, :], neighbor, eta[t], sigma[0]) else: som_step(centers, data[i, :], neighbor, eta[0], sigma[0]) # convergence check e = sum(sum((centers - previousCenters)**2)) tailErrors.append(e) # Since this is an online method, the centers will most likely change in # the future even though the current iteration has a residual of 0. # Basing the convergence on the residual of the mean of the last 500 errors # may be a better convergence criterion. if (t > 500): if (len(tailErrors) >= 500): tailErrors.pop(0) tailErrors.append(e) # Update the mean error term tmpError = sum(tailErrors) / len(tailErrors) mErrors.append(tmpError) if t > (500 * size_k * size_k): tolerance_check = np.abs(mErrors[-1] - mErrors[-501]) logError.append(tolerance_check) data_print_static("Tol Error Minimum Is: {0}, " "Iteration: {1}, Current Error: {2}".format( np.min(logError), t, tolerance_check)) if logError[-1] < tol: print "" print "Converage after ", t, " iterations" break """ future_tolerance_check = np.sum(mErrors[-500])/500 past_tolerance_check = np.sum(mErrors[-1000:-500])/500 tolerance_check = np.abs((future_tolerance_check - past_tolerance_check)) logError.append(tolerance_check) if np.size(logError) > 2: log_d_v = ((np.sqrt((logError[-2] - logError[-1])**2))) # plb.scatter(t, log_d_v, color='red') # plb.pause(0.1) finalErrors.append(log_d_v) data_print_static("Tol Error Minimum Is: {0}, " "Iteration: {1}, Current Error: {2}". format(np.min(finalErrors), t, log_d_v)) if log_d_v < tol: print "" print "Converage after ", t, " iterations" break """ """ if (len(mErrors) >= 2): tolerance_check = np.abs(mErrors[-1] - mErrors[-2]) finalErrors.append(tolerance_check) data_print_static("Tol Error Minimum Is: {0}, " "Iteration: {1}, Current Error: {2}". format(np.min(finalErrors), t, tolerance_check)) if ((tolerance_check < tol) & (t >= 500*size_k*size_k)): ''' numConverged +=1 convergedList.append(labels[i]) print "Holding "+str(labels[i]) if (numConverged == 4): print "" print "Converage after ", t, " iterations" break ''' print "" print "Converage after ", t, " iterations" break """ errors.append(e) previousCenters = np.copy(centers) if Equilibrate == True: old_eta = eta[-1] new_tmax = 0.10 * tmax i_random = np.arange(new_tmax) % dy np.random.shuffle(i_random) for t, i in enumerate(i_random): new_eta = old_eta eta.append(new_eta) new_sigma = 1.0 sigma.append(new_sigma) # Change to sigma[0] for static and sigma[t] for dynamic neighborhood function if ((dynamicEta == True) & (dynamicSigma == True)): som_step(centers, data[i, :], neighbor, eta[-1], sigma[-1]) elif ((dynamicEta == False) & (dynamicSigma == True)): som_step(centers, data[i, :], neighbor, eta[0], sigma[-1]) elif ((dynamicEta == True) & (dynamicSigma == False)): som_step(centers, data[i, :], neighbor, eta[-1], sigma[0]) else: som_step(centers, data[i, :], neighbor, eta[0], sigma[0]) # convergence check e = sum(sum((centers - previousCenters)**2)) tailErrors.append(e) # Since this is an online method, the centers will most likely change in # the future even though the current iteration has a residual of 0. # Basing the convergence on the residual of the mean of the last 500 errors # may be a better convergence criterion. if (len(tailErrors) >= 500): tailErrors.pop(0) tailErrors.append(e) # Update the mean error term tmpError = sum(tailErrors) / len(tailErrors) mErrors.append(tmpError) if (len(mErrors) >= 2): tolerance_check = np.abs(mErrors[-1] - mErrors[-501]) logError.append(tolerance_check) data_print_static("Tol Error Minimum Is: {0}, " "Iteration: {1}, Current Error: {2}".format( np.min(logError), t, tolerance_check)) if logError[-1] < tol: print "" print "Converage after ", t, " iterations" break errors.append(e) previousCenters = np.copy(centers) # Find the digit assigned to each center index = 0 digits = [] for i in range(0, size_k**2): index = np.argmin(np.sum((data[:] - centers[i, :])**2, 1)) digits.append(labels[index]) print "Digit assignement to the clusters: \n" print np.resize(digits, (size_k, size_k)) np.savetxt('data/' + filename + '_cluster.txt', np.resize(digits, (size_k, size_k)), fmt='%i') # for visualization, you can use this: for i in range(size_k**2): plb.subplot(size_k, size_k, i + 1) plb.imshow(np.reshape(centers[i, :], [28, 28]), interpolation='bilinear') plb.axis('off') plb.draw() # leave the window open at the end of the loop plb.savefig('data/' + filename + '_kohonen.pdf') plb.show() # plb.draw() import seaborn as sb if dynamicSigma == True: plb.plot(sigma) plb.ylabel('Sigma values') plb.xlabel('Iterations') plb.savefig('data/sigma.pdf') plb.show() if dynamicEta == True: plb.plot(eta) plb.ylabel('Learning Rate') plb.xlabel('Iterations') plb.savefig('data/eta.pdf') plb.show() plb.plot(errors) plb.ylabel('Sum of the Squared Errors') plb.xlabel('Iterations') plb.savefig('data/' + filename + '_sqerrors.pdf') plb.show() plb.plot(mErrors) plb.ylabel('Mean of last 500 errors') plb.xlabel('Iterations') plb.savefig('data/' + filename + '_mean500.pdf') plb.show() plb.plot(logError) plb.ylabel('Convergence Criteria') plb.xlabel('Iterations') plb.savefig('data/' + filename + '_convergence.pdf') plb.show()
filegrid = p.indatadir + 'OREGON_grd.nc' fileswot = p.outdatadir + 'OREGON_swot292_c01_p024.nc' vmin = -0.01 vmax = 0.01 fig = plt.figure(figsize=(30,10)) tloc=0.11 tfont=24 data = rw_data.Sat_SWOT(file=fileswot) data.load_swath(bd_err=[], x_ac=[], x_al=[]) x_al, x_ac = numpy.meshgrid(data.x_al, data.x_ac) x_al = x_al - numpy.min(numpy.min(x_al)) SSH = data.bd_err stitle = 'Baseline dilation error along swath' nac = numpy.shape(data.lon)[1] SSH[abs(SSH) > 1000] = numpy.nan norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) SSH[SSH == 0] = numpy.nan SSH = numpy.ma.array(SSH, mask=numpy.isnan(SSH)) print(numpy.shape(x_al), numpy.shape(x_ac), numpy.shape(SSH)) col = plt.pcolormesh(x_al[(nac/2), :], x_ac[:int(nac/2), 0], numpy.transpose(SSH[:,:int(nac/2)]), norm=norm) col = plt.pcolormesh(x_al[(nac/2), :], x_ac[int(nac/2):, 0], numpy.transpose(SSH[:,int(nac/2):]), norm=norm) plt.xlabel('along track (km)') plt.ylabel('across track (km)') plt.colorbar() plt.title(stitle, y=-tloc, fontsize=tfont) #size[1]) plt.axis('tight') plt.savefig('Fig12.png')
figure(3) clf() #plot(allR/RQ, allD, 'r.') #plot(allR/RQ, vstack((allD, allDist)).min(axis=0), 'r.') plot( #allR/RQ, vstack((allD, allDist)).min(axis=0), 'mo', allR / RQ, allD, 'r+', allR / RQ, allDist, 'bx') xlabel('R (quad radiuses)') #ylabel('min( Dist, D(R+A) )') ylabel('Dist, D(R,A)') a = axis() axis([a[0], a[1], 0, 2.0]) legend(('D(R,A)', 'D')) #allDist = array([]) #allRDist = array([]) #for i in IR: # Dist = sqrt((ix[i] - fx)**2 + (iy[i] - fy)**2) # iSmall = array(find(Dist < 5)) # allDist = hstack((allDist, Dist[iSmall])) # allRDist = hstack((allRDist, repeat(RI[i], len(iSmall)))) #figure(4) #clf() #plot(allRDist/RQ, allDist, 'r.') #xlabel('R') #ylabel('Dist')
def main(argv): # load preprocessed data samples print 'loading data...\t', #data_train, data_test = genData() #load('../data/vanhateren.npz') DIR1 = "../data/changedetection/camerajitter/traffic" data_train_0, data_train_1, data_train_2, data_test = load_data_BS( DIR1 + "/orignal_color.pkl") print data_train_0.shape img = Image.open(DIR1 + "/gt001537.png") x_, y_ = (asarray(img)[:, :]).shape print x_, "and", y_ print "Doie : ", x_, y_ groundtruth = (((asarray(img)[:, :]) / 255.0 > 0.5) * 1).flatten() #groundtruth = (((asarray(img)[:,:])/255.0 > 0.5) * 1).flatten() print '[DONE]' print data_test.shape # remove DC component (first component) # data_train = data['train'][1:, :] # data_test = data['test'][1:, :] # create 1st layer dbn = DBN(GaussianRBM(num_visibles=data_train_0.shape[0], num_hiddens=8)) dbn1 = DBN(GaussianRBM(num_visibles=data_train_1.shape[0], num_hiddens=8)) dbn2 = DBN(GaussianRBM(num_visibles=data_train_2.shape[0], num_hiddens=8)) dbn[0].learning_rate = 0.001 dbn1[0].learning_rate = 0.001 dbn2[0].learning_rate = 0.001 # train 1st layer print 'training...\t', dbn.train(data_train_0, num_epochs=10, batch_size=1, shuffle=False) dbn1.train(data_train_1, num_epochs=10, batch_size=1, shuffle=False) dbn2.train(data_train_2, num_epochs=10, batch_size=1, shuffle=False) print '[DONE]' data_test_0 = ((data_test.T)[:, ::3]).T data_test_1 = ((data_test.T)[:, 1::3]).T data_test_2 = ((data_test.T)[:, 2::3]).T # global runtime # sFilename = "data\\weightlogs" # f = h5.File(sFileName+".hdf5") # f.create_group(runtime) # group.create_dataset('parameters',data=par) #storeWeights(category,"data\\weightlogs", dbn[0].W, dbn[0].vsigma,dbn1[0].W, dbn1[0].vsigma,dbn2[0].W, dbn2[0].vsigma ) Ndat = 20 #data_test_0.shape[1] Nsteps = 5 # evaluate 1st layer print 'evaluating 1...\t', dataout = zeros(x_ * y_) # #datasub = zeros(x_*y_) for point in xrange(Ndat): #X = asmatrix(data_test_0[:,point]).T X = asmatrix(data_test_0[:, -1]).T #dataout = vstack((dataout,X.flatten())) #print "testing:", X.shape for recstep in xrange(Nsteps): Y = dbn[0].forward(X) # self.activ(1) X = dbn[0].backward(Y, X) #print "S hsape:", X.shape #dataout = vstack((dataout,X.flatten())) dataout = vstack((dataout, subtract(asarray(X), data_test_0[:, -1], asarray(dbn[0].vsigma), point + 1))) print 'evaluating 2...\t', dataout1 = zeros(x_ * y_) # #datasub = zeros(x_*y_) for point in xrange(Ndat): #X = asmatrix(data_test_1[:,point]).T X = asmatrix(data_test_1[:, -1]).T #dataout1 = vstack((dataout1,X.flatten())) #print "testing:", X.shape for recstep in xrange(Nsteps): Y = dbn1[0].forward(X) # self.activ(1) X = dbn1[0].backward(Y, X) #print "S hsape:", X.shape #dataout1 = vstack((dataout1,X.flatten())) dataout1 = vstack((dataout1, subtract(asarray(X), data_test_1[:, -1], asarray(dbn1[0].vsigma), point + 1))) print 'evaluating 3...\t', dataout2 = zeros(x_ * y_) # #datasub = zeros(x_*y_) for point in xrange(Ndat): #X = asmatrix(data_test_2[:,point]).T X = asmatrix(data_test_2[:, -1]).T #dataout2 = vstack((dataout2,X.flatten())) #print "testing:", X.shape for recstep in xrange(Nsteps): Y = dbn2[0].forward(X) # self.activ(1) X = dbn2[0].backward(Y, X) #print "S hsape:", X.shape #dataout2 = vstack((dataout2,X.flatten())) dataout2 = vstack((dataout2, subtract(asarray(X), data_test_2[:, -1], asarray(dbn2[0].vsigma), point + 1))) # plt.imshow((reshape(data_test[::3,5],(x_,y_))), cmap = cm.Greys_r, interpolation ="nearest") # plt.axis('off') # plt.show() fmeasureV = zeros(Ndat) plt.figure(1) for i in range(Ndat): plt.subplot(5, 5, i + 1) d = multiply(asarray(dataout[i + 1, :]), asarray(dataout1[i + 1, :]), asarray(dataout2[i + 1, :])) d = mod(d + 1, 2) fmeasureV[i] = f_measure(d, groundtruth) print "Image Example Fmeaure: ", i, " : ", fmeasureV[i] * 100 # d[0::3] = asarray(dataout[i+1,:]) # d[1::3] = asarray(dataout1[i+1,:]) # d[2::3] = asarray(dataout2[i+1,:]) # d[:,:,0] = (reshape(asarray(dataout[i+1,:]),(x_,y_))) # d[:,:,1] = (reshape(asarray(dataout1[i+1,:]),(x_,y_))) # d[:,:,2] = (reshape(asarray(dataout2[i+1,:]),(x_,y_))) # img_s = Image.fromarray(asarray(reshape(d,(x_,y_))*255,dtype="uint8")) # img_s.save("C:\work\\backgdSubt\dataset\datasets\change detection\\baseline\\baseline\office\grbm" + "\\" + str(i) + ".bmp") plt.imshow(reshape(d, (x_, y_)), cmap=cm.Greys_r, interpolation="nearest") plt.axis('off') #plt.figure(2) plt.show() DIR2 = "../data/changedetection/camerajitter/traffic" srcDir = DIR2 + "/input" targetDir = DIR2 + "/grbm" scalevaraince = input("Enter value: ") #argmax(fmeasureV) + 12 ii = 1 for k in os.listdir(srcDir): imf = Image.open(srcDir + '/' + k) print array(imf).shape data_test = (array(imf)).flatten() #dataset = np.vstack((dataset,d)) data_test_0 = ((data_test)[::3]).T data_test_1 = ((data_test)[1::3]).T data_test_2 = ((data_test)[2::3]).T Nsteps = 5 # evaluate 1st layer print 'evaluating 1...\t', # #datasub = zeros(x_*y_) #for point in xrange(Ndat): #X = asmatrix(data_test_0[:,point]).T X = asmatrix(data_test_0).T #dataout = vstack((dataout,X.flatten())) #print "testing:", X.shape for recstep in xrange(Nsteps): Y = dbn[0].forward(X) # self.activ(1) X = dbn[0].backward(Y, X) #print "S hsape:", X.shape #dataout = vstack((dataout,X.flatten())) dataout = subtract(asarray(X), data_test_0, asarray(dbn[0].vsigma), scalevaraince + 1) #X = asmatrix(data_test_1[:,point]).T X = asmatrix(data_test_1).T #dataout1 = vstack((dataout1,X.flatten())) #print "testing:", X.shape for recstep in xrange(Nsteps): Y = dbn1[0].forward(X) # self.activ(1) X = dbn1[0].backward(Y, X) #print "S hsape:", X.shape #dataout1 = vstack((dataout1,X.flatten())) dataout1 = subtract(asarray(X), data_test_1, asarray(dbn1[0].vsigma), scalevaraince + 1) X = asmatrix(data_test_2).T #dataout2 = vstack((dataout2,X.flatten())) #print "testing:", X.shape for recstep in xrange(Nsteps): Y = dbn2[0].forward(X) # self.activ(1) X = dbn2[0].backward(Y, X) #print "S hsape:", X.shape #dataout2 = vstack((dataout2,X.flatten())) # plt.imshow(reshape(X,(x_,y_))) # plt.show() dataout2 = subtract(asarray(X), data_test_2, asarray(dbn2[0].vsigma), scalevaraince + 1) # plt.imshow((reshape(data_test[::3,5],(x_,y_))), cmap = cm.Greys_r, interpolation ="nearest") # plt.axis('off') # plt.show() # plt.figure(1) # for i in range(Ndat): # plt.subplot(5,5,i+1) d = multiply(asarray(dataout), asarray(dataout1), asarray(dataout2)) d = mod(d + 1, 2) #print type(d[0]) # #plt.savefig(targetDir + "\\" + str(ii) + ".png") #print img_s = Image.fromarray( asarray(reshape(d, (x_, y_)) * 255, dtype="uint8")) # plt.figure(2) # plt.imshow(img_s)#,cmap = cm.Greys_r, interpolation ="nearest") # plt.show() if (ii < 1000): img_s.save(targetDir + "\\bin000" + str(ii) + ".bmp") else: img_s.save(targetDir + "\\bin00" + str(ii) + ".bmp") ii = ii + 1
x.set(0) b.set(1) its, norm = cg(A, b, x, 100, 1e-5) print("iterations: %d residual norm: %g" % (its, norm)) OptDB = PETSc.Options() if OptDB.getBool('plot', True): da = PETSc.DA().create([m, n]) u = da.createGlobalVec() x.copy(u) draw = PETSc.Viewer.DRAW() OptDB['draw_pause'] = 1 draw(u) if OptDB.getBool('plot_mpl', False): try: from matplotlib import pylab except ImportError: print("matplotlib not available") else: from numpy import mgrid X, Y = mgrid[0:1:1j * m, 0:1:1j * n] Z = x[...].reshape(m, n) pylab.figure() pylab.contourf(X, Y, Z) pylab.plot(X.ravel(), Y.ravel(), '.k') pylab.axis('equal') pylab.colorbar() pylab.show()
import matplotlib.pylab as plt from skimage import color from skimage.io import imread, imsave, imshow, show im = imread( "../images/parrot.png") # read image from disk, provide the correct path print(im.shape, im.dtype, type(im)) # (362, 486, 3) uint8 <class 'numpy.ndarray'> hsv = color.rgb2hsv(im) # from RGB to HSV color space hsv[:, :, 1] = 0.5 # change the saturation im1 = color.hsv2rgb(hsv) # from HSV back to RGB imsave('../images/parrot_hsv.png', im1) # save image to disk im = imread("../images/parrot_hsv.png") plt.axis('off'), imshow(im), show()
KLAVG=np.mean([KL0,KL1,KL2,KL3,KL4]) KLAVGBRUH[indexuu]=KLAVG #end of KDE estimation of KL Div z=np.sqrt(2)*np.random.randn(5*batch_size, z_dim) xin=np.repeat(xgen,batch_size) xin=xin.reshape(5*batch_size, 1) noise=np.random.randn(5*batch_size, noise_dim) feed_dict = {prior_input: z, x_input: xin, noise_input: noise} dl, NELBO = sess.run([ratio_loss, nelbo], feed_dict=feed_dict) ISTHISLOSS[indexuu]=dl #Plots for i in range(5): plt.subplot(2,5,i+1) sns.kdeplot(z_samples[i,:,0], z_samples[i,:,1], cmap='Greens') #plt.scatter(z_samples[i,:,0],z_samples[i,:,1]) plt.axis('square'); plt.title('q(z|x={})'.format(y[i])) plt.xlim([xmin,xmax]) plt.ylim([xmin,xmax]) plt.xticks([]) plt.yticks([]); plt.subplot(2,5,5+i+1) plt.contour(xrange, xrange, np.exp(logprior+llh[i]).reshape(300,300).T, cmap='Greens') plt.axis('square'); plt.title('p(z|x={})'.format(y[i])) plt.xlim([xmin,xmax]) plt.ylim([xmin,xmax]) plt.xticks([]) plt.yticks([]); plt.text(-60,20,'KLR Loss: %f, NELBO: %f, KL0: %f, KL1: %f, KL2: %f, KL3: %f, KL4: %f' % (dl, NELBO, KL0, KL1, KL2, KL3, KL4)) plt.text(-28,-7,'KLAVG: %f' %(KLAVG))
1. Read in GDP per capita """ from pandas.io import wb wb.search('gdp.*capita.*const').iloc[:,:2] dat = wb.download(indicator='NY.GDP.PCAP.KD', country=['US', 'CA', 'MX'], start=2005, end=2008) dat['NY.GDP.PCAP.KD'].groupby(level=0).mean() wb.search('cell.*%').iloc[:,:2] ind = ['NY.GDP.PCAP.KD', 'IT.MOB.COV.ZS'] dat = wb.download(indicator=ind, country='all', start=2011, end=2011).dropna() dat.columns = ['gdp', 'cellphone'] """ 2. Read in complete csv (see Sargent-Stachurski) """ #%% # OLD PLOTS FROM ANOTHER PROGRAM plt.plot(calls_strikes, calls_mid, 'r', lw=2, label='calls') #plt.plot(calls_strikes, calls_ask, 'r', lw=2, label='calls ask') plt.plot(puts_strikes, puts_mid, 'b', lw=2, label='puts') plt.axis([120, 250, 0, 50]) plt.axvline(x=atm, color='k', linestyle='--', lw=2, label='atm') plt.xlabel('Strike') plt.ylabel('Option Price') plt.legend(loc='upperleft')
plt.imshow(y, origin='lower') plt.subplot(2, 2, 3) plt.imshow(x, origin='upper') plt.subplot(2, 2, 4) plt.imshow(y, origin='upper') # %% xx, yy = np.mgrid[-50:50, -50:50] plt.figure(figsize=(3, 3)) plt.imshow(np.angle(1j * yy + xx, deg=True).T, extent=[-50, 50, -50, 50], origin='upper') plt.axis('on') plt.colorbar() plt.figure(figsize=(3, 3)) plt.imshow(np.abs(xx + 1j * yy), extent=[-50, 50, -50, 50]) plt.axis('on') plt.colorbar() plt.show() # %% from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(figsize=(5, 4)) ax = Axes3D(fig) X = np.arange(-4, 4, 0.2)
idx1 = r.randint(X1.shape[0], size=(nb,)) idx2 = r.randint(X2.shape[0], size=(nb,)) Xs = X1[idx1, :] Xt = X2[idx2, :] ############################################################################## # Plot original image # ------------------- pl.figure(1, figsize=(6.4, 3)) pl.subplot(1, 2, 1) pl.imshow(I1) pl.axis('off') pl.title('Image 1') pl.subplot(1, 2, 2) pl.imshow(I2) pl.axis('off') pl.title('Image 2') ############################################################################## # Scatter plot of colors # ---------------------- pl.figure(2, figsize=(6.4, 3)) pl.subplot(1, 2, 1)
def WaveletTreatment(loadpath, savepathCsv, savepathPng, conf): data = numpy.genfromtxt(fname=loadpath, dtype=int, delimiter=',') cA, (cH, cV, cD) = pywt.dwt2(data=data, wavelet=conf) with open(savepathCsv + '-cA.csv', 'w') as file: treatData = cA for indexX in range(numpy.shape(treatData)[0]): for indexY in range(numpy.shape(treatData)[1]): if indexY != 0: file.write(',') file.write(str(treatData[indexX][indexY])) file.write('\n') with open(savepathCsv + '-cD.csv', 'w') as file: treatData = cD for indexX in range(numpy.shape(treatData)[0]): for indexY in range(numpy.shape(treatData)[1]): if indexY != 0: file.write(',') file.write(str(treatData[indexX][indexY])) file.write('\n') with open(savepathCsv + '-cH.csv', 'w') as file: treatData = cH for indexX in range(numpy.shape(treatData)[0]): for indexY in range(numpy.shape(treatData)[1]): if indexY != 0: file.write(',') file.write(str(treatData[indexX][indexY])) file.write('\n') with open(savepathCsv + '-cV.csv', 'w') as file: treatData = cV for indexX in range(numpy.shape(treatData)[0]): for indexY in range(numpy.shape(treatData)[1]): if indexY != 0: file.write(',') file.write(str(treatData[indexX][indexY])) file.write('\n') plt.figure(figsize=(numpy.shape(cA)[0] / 100, numpy.shape(cA)[1] / 100)) plt.axis('off') plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.imshow(cA, cmap='gray') plt.savefig(savepathPng + '-cA.png') plt.clf() plt.close() plt.figure(figsize=(numpy.shape(cA)[0] / 100, numpy.shape(cA)[1] / 100)) plt.axis('off') plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.imshow(cD, cmap='gray') plt.savefig(savepathPng + '-cD.png') plt.clf() plt.close() plt.figure(figsize=(numpy.shape(cA)[0] / 100, numpy.shape(cA)[1] / 100)) plt.axis('off') plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.imshow(cH, cmap='gray') plt.savefig(savepathPng + '-cH.png') plt.clf() plt.close() plt.figure(figsize=(numpy.shape(cA)[0] / 100, numpy.shape(cA)[1] / 100)) plt.axis('off') plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.imshow(cV, cmap='gray') plt.savefig(savepathPng + '-cV.png') plt.clf() plt.close()
sns.set_style('whitegrid') sns.set_context('poster') plt.subplots(figsize=(20,8)) #make 5000 noise and 1000 of each x sample N_samples=1000 noise=np.random.randn(5*N_samples, noise_dim).astype('float32') x_gen=np.repeat(xgen,1000) x_gen=x_gen.reshape(5000,1) #plug into posterior z_samples=posterior(x_gen,noise) z_samples=tf.reshape(z_samples,[xgen.shape[0], N_samples, 2]).eval() for i in range(5): plt.subplot(2,5,i+1) sns.kdeplot(z_samples[i,:,0], z_samples[i,:,1], cmap='Greens') plt.axis('square') plt.title('q(z|x={})'.format(y[i])) plt.xlim([xmin,xmax]) plt.ylim([xmin,xmax]) plt.xticks([]) plt.yticks([]); plt.subplot(2,5,5+i+1) plt.contour(xrange, xrange, np.exp(logprior+llh[i]).reshape(300,300).T, cmap='Greens') plt.axis('square') plt.title('p(z|x={})'.format(y[i])) plt.xlim([xmin,xmax]) plt.ylim([xmin,xmax]) plt.xticks([]) plt.yticks([]) plt.savefig('JCKLD Final Fig') plt.close()
import matplotlib.pylab as plt import numpy as np # pie : 원 형태를유지하기 위해 plt.axis('equal') 을 먼저 실행해야 함 # pie(ratio(비율들), # explode(강조를 위한 옵션), # labels, # colors, # autopct(퍼센트로 환산), # shadow(그림자/입체감), # startangle(시작 각도)) labels = 'a', 'b', 'c', 'd' ratio = [10, 30, 40, 20] colors = ['red', 'blue', 'yellow', 'green'] explode = (0, 0.1, 0, 0) plt.axis('equal') # 동그란 원으로 그려줌 plt.pie(ratio, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90) plt.show()
# Create segment AB. A = ga.Point2D(2, 1, name='A') B = ga.Point2D(6, 4, name='B') AB = ga.Segment2D(A, B) # Create segment CD. C = ga.Point2D(5, 2, name='C') D = ga.Point2D(3, 3, name='D') CD = ga.Segment2D(C, D) # Plot the points and the segments. for p in [A, B, C, D]: p.plot() AB.plot() CD.plot() # Compute first intersection point. X, Y = AB.intersect_segment(CD) X.name = 'X' X.plot(color='red') # Their is no second intersection point. print('Second intersection point:', Y) # Adjust the plot. plt.axis('scaled') plt.xlim(1, 7) plt.ylim(0, 5) plt.grid() plt.show()
# SOMLine = np.arange(size) * dX[0] SOMLine = np.array([[0, 0], [dY.mean(), dX.mean()]]) # SOMLine = np.linspace(-1, 1, size) return dX, dY, SOMLine if __name__ == '__main__': # The size of the weights matrix n = 16 m = 2 # If you want to give the full path of the weight matrix # folder = '/home/Local/SOM/Final_Results/32Grid16Receptors5Noise/' filename = './data/weights_6999.npy' # Read weights from a file W = np.load(filename) # Calculating the representation dy-dx W = W.reshape(n, n, m) dX, dY, SOMLine = som_regularity(W) # Plotting plt.figure() plt.scatter(dY, dX, s=1, c='k', marker='s') plt.plot(SOMLine, 'r', lw=1.5) plt.axis([0, dY.max()+0.15, 0, dX.max()+0.15]) plt.xlabel('dy') plt.ylabel('dx') plt.show()
if __name__ == '__main__': solver = PolicyIterationSolver() for ii in range(4): solver.policy_evaluation() solver.policy_update() print(solver.policy) import matplotlib.pylab as plt plt.subplot(121) CS = plt.contour(solver.policy, levels=range(-6, 6)) plt.clabel(CS) plt.xlim([0, 20]) plt.ylim([0, 20]) plt.axis('equal') plt.xticks(range(21)) plt.yticks(range(21)) plt.grid('on') plt.subplot(122) plt.pcolor(solver.value) plt.colorbar() plt.axis('equal') plt.show()
if __name__ == '__main__': eps = 0.01 B = 15 spacing = uniformPhase #spacing = uniformTime(eps) T = np.arange(0, 1, 0.001) (means, std_devs) = spacing(B, 0, 1) bases = np.array( [[np.exp(-(t - means[b])**2 / (2 * std_devs[b]**2)) for t in T] for b in range(B)]) plt.subplot(121) for b in range(B): plt.plot(T, bases[b]) plt.title('Bases in s') plt.xlabel('s') plt.ylabel('f(s)') plt.subplot(122) for b in range(B): plt.plot(np.log(T) / np.log(eps), bases[b]) plt.title('Bases in t') plt.xlabel('t') plt.ylabel('f(t)') plt.axis((0, 1, 0, 1)) plt.show()
import matplotlib.pylab as plt import numpy as np import pandas as pd import seaborn as sns from math import cos, sin, log, tan, gamma, pi, exp, sqrt p = plt.figure(figsize=(12, 12), facecolor='black', dpi=400) p = plt.axis('off') for m in np.linspace(-10, 10, 20): x = np.random.normal(m, 1, size=15) p = sns.kdeplot(x, shade=True) p = plt.ylim(-0.60, 1) plt.savefig(f'C:/Users/Alejandro/Pictures/RandomPlots/07012020.png', facecolor='black')
def _report_loop_sequence(report, R, sips, converged, do_movie): """ Returns a dictionary dict(str: list of png data) """ sequences = {} UR = UpperSets(R) from matplotlib import pylab ieee_fonts(pylab) RepRepDefaults.savefig_params = dict(dpi=400, bbox_inches='tight', pad_inches=0.01, transparent=False) figsize = (2, 2) try: available_plotters = list( get_plotters(get_all_available_plotters(), UR)) except NotPlottable as e: msg = 'Could not find plotter for space UR = %s.' % UR raise_wrapped(DPInternalError, e, msg, UR=UR, compact=True) with report.subsection('sip') as r2: for name, plotter in available_plotters: sequences[name] = [] # sequence of png f = r2.figure(name, cols=5) axis = plotter.axis_for_sequence(UR, sips) axis = list(axis) axis[0] = 0.0 axis[2] = 0.0 axis[1] = min(axis[1], 1000.0) axis[3] = min(axis[3], 1000.0) axis = tuple(axis) visualized_axis = enlarge(axis, extra_space_top * 2) for i, sip in enumerate(sips): with f.plot('step%03d' % i, figsize=figsize) as pylab: logger.debug('Plotting iteration %d/%d' % (i, len(sips))) ieee_spines(pylab) c_orange = '#FFA500' c_red = [1, 0.5, 0.5] plotter.plot(pylab, axis, UR, R.U(R.get_bottom()), params=dict(color_shadow=c_red, markers=None)) marker_params = dict(markersize=5, markeredgecolor='none') plotter.plot(pylab, axis, UR, sip, params=dict(color_shadow=c_orange, markers_params=marker_params)) conv = converged[i] c_blue = [0.6, 0.6, 1.0] plotter.plot(pylab, axis, UR, conv, params=dict(color_shadow=c_blue)) for c in conv.minimals: p = plotter.toR2(c) pylab.plot(p[0], p[1], 'go', markersize=5, markeredgecolor='none', markerfacecolor='g', clip_on=False) pylab.axis(visualized_axis) from mcdp_ipython_utils.plotting import color_resources, set_axis_colors set_axis_colors(pylab, color_resources, color_resources) if do_movie: node = f.resolve_url('step%03d/png' % i) png = node.raw_data sequences[name].append(png) return sequences