def plotF_curves(fs): """Plot some characteristics over the 'focal plane'. """ wavelen = fs.wavelen x = numpy.arange(fs.x.min(), fs.x.max()) y = numpy.arange(fs.y.min(), fs.y.max()) xx, yy = numpy.meshgrid(x, y) for f in fs.filterlist: throughputs = fs.all[f] # Max throughputs pylab.figure() pylab.title('Filter %s - max throughput' % (f)) maxthroughput = numpy.zeros(len(fs.x), 'float') for i in range(len(fs.x)): maxthroughput[i] = throughputs[i].max() zz = pylab.griddata(fs.x, fs.y, maxthroughput, xx, yy, interp='linear') pylab.contourf(xx, yy, zz, 50) pylab.colorbar() # Red/Blue edges red50 = numpy.zeros(len(fs.x), 'float') blue50 = numpy.zeros(len(fs.x), 'float') for i in range(len(fs.x)): maxwavelen = wavelen[throughputs[i] == throughputs[i].max()] if len(maxwavelen) > 1: maxwavelen = maxwavelen.mean() condition2 = (wavelen < maxwavelen) wavelen2 = numpy.arange(wavelen.min(), maxwavelen, 0.02) tmp = numpy.interp(wavelen2, wavelen[condition2], throughputs[i][condition2]) condition3 = (numpy.abs(tmp - throughputs[i].max() * 0.5) < 0.01) red50[i] = wavelen2[condition3].mean() condition2 = (wavelen > maxwavelen) wavelen2 = numpy.arange(maxwavelen, wavelen.max(), 0.02) tmp = numpy.interp(wavelen2, wavelen[condition2], throughputs[i][condition2]) condition3 = (numpy.abs(tmp - throughputs[i].max() * 0.5) < 0.01) blue50[i] = wavelen2[condition3].mean() red50 = red50 / red50[0] * 100.0 blue50 = blue50 / blue50[0] * 100.0 pylab.figure() pylab.title('Change in red 50 percent wavelength %s' % (f)) zz = pylab.griddata(fs.x, fs.y, red50, xx, yy, interp='linear') pylab.contourf(xx, yy, zz, 50) pylab.colorbar() pylab.figure() pylab.title('Change in blue 50 percent wavelength %s' % (f)) zz = pylab.griddata(fs.x, fs.y, blue50, xx, yy, interp='linear') pylab.contourf(xx, yy, zz, 50) pylab.colorbar() pylab.show()
def build_vels(vels, **kwargs): from scipy import interpolate cdps = np.array(kwargs['cdp']) times = np.array(kwargs['times']) keys = vels.keys() x = [] t = [] values = [] for i in vels.items(): cdp = i[0] picks= i[1] for pick in picks: x.append(cdp) t.append(pick[0]) values.append(pick[1]) grid_x, grid_y = np.meshgrid(cdps, times) #top left x.append(min(cdps)) t.append(min(times)) values.append(min(values)) #top right t.append(min(times)) x.append(max(cdps)) values.append(min(values)) #bottom left x.append(min(cdps)) t.append(max(times)) values.append(max(values)) #bottom right t.append(max(times)) x.append(max(cdps)) values.append(max(values)) try: zi = pylab.griddata(x, t, values, grid_x, grid_y, interp='nn') except RuntimeError: zi = pylab.griddata(x, t, values, grid_x, grid_y, interp='linear') window = 50 filter = np.ones((window,window), 'f')/(1.0*window**2) zi = convolve2d(zi, filter, boundary='symm', mode='same') return zi.T
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 grid(x, y, z , resX=90, resY=90): "Convert 3 column data to matplotlib grid" xi = pl.linspace(min(x), max(x), resX) yi = pl.linspace(min(y), max(y), resY) Z = pl.griddata(x, y, z, xi, yi , interp='linear') X, Y = pl.meshgrid(xi, yi ) return X, Y, Z
def connection_field_plot_continuous(self,index,afferent=True,density=30): weights = self.proj.getWeights(format='array') x = [] y = [] w = [] if afferent: weights = weights[:,index].ravel() p = self.proj.pre else: weights = weights[index,:].ravel() p = self.proj.post for (ww,i) in zip(weights,numpy.arange(0,len(weights),1)): x.append(p.positions[0][i]) y.append(p.positions[1][i]) w.append(ww) bx = min([min(p.positions[0]),min(p.positions[0])]) by = max([max(p.positions[1]),max(p.positions[1])]) xi = numpy.linspace(min(p.positions[0]),max(p.positions[0]),100) yi = numpy.linspace(min(p.positions[1]),max(p.positions[1]),100) zi = griddata(x,y,w,xi,yi) pylab.figure() pylab.imshow(zi) pylab.title('Connection field from %s to %s of neuron %d' % (self.source.name,self.target.name,index)) pylab.colorbar()
def draw_bandstructure( jobname, kspace, band, ext=".csv", format="pdf", filled=True, levels=15, lines=False, labeled=False, legend=False ): # clf() fig = figure(figsize=fig_size) ax = fig.add_subplot(111, aspect="equal") x, y, z = loadtxt(jobname + ext, delimiter=", ", skiprows=1, usecols=(1, 2, 4 + band), unpack=True) if kspace.dimensions == 1: pylab.plot(x, y, z) elif kspace.dimensions == 2: xi = linspace(-0.5, 0.5, kspace.x_res) yi = linspace(-0.5, 0.5, kspace.y_res) zi = griddata(x, y, z, xi, yi) if filled: cs = ax.contourf(xi, yi, zi, levels, **contour_filled) legend and colorbar(cs, **colorbar_style) cs = lines and ax.contour(xi, yi, zi, levels, **contour_lines) labeled and lines and clabel(cs, fontsize=8, inline=1) else: cs = ax.contour(xi, yi, zi, levels, **contour_plain) legend and colorbar(cs, **colorbar_style) labeled and clabel(cs, fontsize=8, inline=1) ax.set_xlim(-0.5, 0.5) ax.set_ylim(-0.5, 0.5) savefig(jobname + format, format=format, transparent=True)
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_wt_layout(wt_layout, borders=None, depth=None): fig = plt.figure(figsize=(6, 6), dpi=2000) fs = 14 ax = plt.subplot(111) if depth is not None: N = 100 X, Y = plt.meshgrid( plt.linspace(depth[:, 0].min(), depth[:, 0].max(), N), plt.linspace(depth[:, 1].min(), depth[:, 1].max(), N)) Z = plt.griddata(depth[:, 0], depth[:, 1], depth[:, 2], X, Y, interp='linear') plt.contourf(X, Y, Z, label='depth [m]') plt.colorbar().set_label('water depth [m]') #ax.plot(wt_layout.wt_positions[:,0], wt_layout.wt_positions[:,1], 'or', label='baseline position') ax.scatter(wt_layout.wt_positions[:, 0], wt_layout.wt_positions[:, 1], wt_layout._wt_list('rotor_diameter'), label='baseline position') if borders is not None: ax.plot(borders[:, 0], borders[:, 1], 'r--', label='border') ax.set_xlabel('x [m]') ax.set_ylabel('y [m]') ax.axis('equal') ax.legend(loc='lower left')
def _plot_spatial_values(ax, spatial_values, channel_names, title=""): # TODO: Move to common spatial filter superclass import pylab ec_2d = StreamDataset.project2d(StreamDataset.ec) # Define x and y coordinates of electrodes in the order of the channels # of data x = numpy.array([ec_2d[key][0] for key in channel_names]) y = numpy.array([ec_2d[key][1] for key in channel_names]) # define grid. xi = numpy.linspace(-150, 150, 100) yi = numpy.linspace(-125, 125, 100) # grid the data. try: zi = pylab.griddata(x, y, spatial_values, xi, yi) except RuntimeError: warnings.warn( "Natbib packackage is not available for interpolating a" " grid. Using linear interpolation instead.") zi = pylab.griddata(x, y, spatial_values, xi, yi, interpl='linear') # contour the gridded data, plotting dots at the nonuniform data points. ax.contour(xi, yi, zi, 15, linewidths=0.5, colors='k') CS = ax.contourf(xi, yi, zi, 15, cmap=pylab.cm.jet) cb = pylab.colorbar(CS, ax=ax) # plot data points. pylab.scatter(x, y, marker='o', c='b', s=5) # Add channel labels for label, position in ec_2d.iteritems(): if label in channel_names: ax.text(position[0], position[1], label, fontsize='x-small') ax.set_xlim(-125, 125) ax.set_ylim(-100, 100) ax.text(0, 80, title, fontweight='bold', horizontalalignment='center', verticalalignment='center')
def removenodata_value(inputfile, outputfile, topotypein=2, topotypeout=2, nodata_value=None, method='fill'): """ remove the nodata_values in a topo file by interpolating from meaningful values. """ import pylab (X, Y, Z) = topofile2griddata(inputfile, topotypein) if topotypein > 1 and not nodata_value: topoheader = topoheaderread(inputfile) nodata_value = topoheader['nodata_value'] elif not nodata_value: print 'provide a value for nodata_value when using topotype1' if method == 'fill': ind = fixdata.findbadindices(Z, nodata_value) if size(ind) > 0: print("Changing %s nodata_value points" % size(ind)) Z = fixdata.fillbaddata(Z, ind) griddata2topofile(X, Y, Z, outputfile, topotypeout, nodata_value, nodata_value) return nrows = shape(Z)[0] ncols = shape(Z)[1] npts = nrows * ncols xi = X[0, :] yi = Y[:, 0] X.np.reshape(npts) Y.np.reshape(npts) Z.np.reshape(npts) ind = np.where(Z != nodata_value) X = X[ind] Y = Y[ind] Z = Z[ind] ptsremove = npts - len(Z) if ptsremove > 0: print("Removing %s nodata_value points" % ptsremove) Z = pylab.griddata(X, Y, Z, xi, yi) (X, Y) = np.meshgrid(xi, yi) griddata2topofile(X, Y, Z, outputfile, topotypeout, nodata_value, nodata_value) return
def grid_model(xz, media, n=30): """ :param xz: :param media: :param n: :return: """ xi = np.linspace(min(xz[:,0]),max(xz[:,0]),n) zi = np.linspace(min(xz[:,1]),max(xz[:,1]),n) media = griddata(xz[:, 0], xz[:, 1], media.ravel(), xi, zi, interp='linear') return media, xi, zi
def elipse_vis(points, bins, N, elogf=1.1): #slowly steps through points showing how eliplse changed lib_vals = get_fitting_info(lib_path) lib_vals[0][:, 0] = 10**nu.log10( lib_vals[0][:, 0]) #to keep roundoff error constistant metal_unq = nu.log10(nu.unique(lib_vals[0][:, 0])) age_unq = nu.unique(lib_vals[0][:, 1]) #plot first N points fig = lab.figure() current = fig.add_subplot(111) #plot chi squared landscape using griddata metal, age = nu.linspace(metal_unq[0], metal_unq[-1], 200), nu.linspace(age_unq[0], age_unq[-1], 200) z = lab.griddata(points[:, 0], points[:, 1], points[:, -1], metal, age) current.pcolor(metal, age, nu.log10(z)) #lab.colorbar() for i in xrange(N): current.plot(points[i, 0], points[i, 1], 'yo', markersize=5) current.set_xlim((metal_unq.min(), metal_unq.max())) current.set_ylim((age_unq.min(), age_unq.max())) current.set_xlabel('Log Metalicity') current.set_ylabel('Age') #plot current elipse curren_ellipse = Ellipse(xy=[ metal_unq[0] + metal_unq.ptp() / 2., age_unq[0] + age_unq.ptp() / 2. ], width=metal_unq.ptp() * elogf, height=age_unq.ptp() * elogf) current.add_artist(curren_ellipse) curren_ellipse.set_alpha(.5) #curren_ellipse.set_facecolor(nu.random.rand(3)) #current.lines.pop fig.canvas.show() for i in xrange( i, points[:, 0].shape[0]): #add and remove ploints like in program #remove last point and add new one in red current.lines[i - N - 1].set_visible(False) #make last new point blue current.lines[i - 1].set_color('y') current.plot(points[i, 0], points[i, 1], 'ro', markersize=5) #change ellipse size current.artists.pop(0) curren_ellipse = Ellipse( xy=nu.mean(points[i - N + 1:i + 1, :2], 0), width=points[i - N + 1:i + 1, 0].ptp() * elogf, height=points[i - N + 1:i + 1, 1].ptp() * elogf) curren_ellipse.set_alpha(.5) current.add_artist(curren_ellipse) fig.canvas.show()
def build_vels(vels, **kwargs): from scipy import interpolate cdps = np.array(kwargs['cdp']) times = np.array(kwargs['times']) keys = vels.keys() x = [] t = [] values = [] for i in vels.items(): cdp = i[0] picks= i[1] for pick in picks: x.append(cdp) t.append(pick[0]) values.append(pick[1]) grid_x, grid_y = np.meshgrid(cdps, times) #top left x.append(min(cdps)) t.append(min(times)) values.append(min(values)) #top right t.append(min(times)) x.append(max(cdps)) values.append(min(values)) #bottom left x.append(min(cdps)) t.append(max(times)) values.append(max(values)) #bottom right t.append(max(times)) x.append(max(cdps)) values.append(max(values)) zi = pylab.griddata(x, t, values, grid_x, grid_y, interp='linear') #~ zi = griddata((np.array(x), np.array(t)), values.flatten(), (grid_x, grid_y), method='nearest') #~ window = 50 #~ filter = np.ones((window,window), 'f')/(1.0*window**2) #~ zi = convolve2d(zi, filter, boundary='symm', mode='same') return zi.T
def plot_contour_irregulargrid(x, y, z, nxbins=360, nybins=180): """Make a contour plot of irregularly gridded data.""" # Grid the data. dx = (max(x) - min(x))/float(nxbins) dy = (max(y) - min(y))/float(nybins) xi = n.arange(min(x), max(x), dx) yi = n.arange(min(y), max(y), dy) xi, yi = n.meshgrid(xi, yi) zi = pyl.griddata(x, y, z, xi, yi) # Contour the gridded data. CS = pyl.contour(xi, yi, zi) CS = pyl.contourf(xi, yi, zi) pyl.colorbar() # Plot data points #pyl.scatter(x, y, 'b.') return
def pre_plot(self): plt.ion() #plt.show() ### Plot the water depth N = 100 self.X, self.Y = plt.meshgrid(plt.linspace(self.depth[:,0].min(), self.depth[:,0].max(), N), plt.linspace(self.depth[:,1].min(), self.depth[:,1].max(), N)) self.Z = plt.griddata(self.depth[:,0],self.depth[:,1],self.depth[:,2],self.X,self.Y, interp='linear') Zin = points_in_poly(self.X,self.Y, self.borders) self.Z.mask = Zin.__neg__() #Z.mask = False #Z.data[Zin.__neg__()] = -20.0 display(plt.gcf()) # def refresh(self): self.shape_plot.clear() self.shape_plot.contourf(self.X, self.Y, self.Z, 10, vmax=self.depth[:,2].max()) #, cmap=self.pal self.shape_plot.set_aspect('equal') self.shape_plot.autoscale(tight=True) Plot = lambda b, *args, **kwargs: self.shape_plot.plot(b[:,0], b[:,1],*args, **kwargs) if self.distribution == 'spiral': spiral = lambda t_, a_, x_: [a_*t_**(1./x_) * np.cos(t_), a_*t_**(1./x_) * np.sin(t_)] spirals = lambda ts_, a_, x_: np.array([spiral(t_, a_, x_) for t_ in ts_]) for P in self.baseline: Plot(P + spirals(plt.linspace(0.,10*np.pi,1000), self.spiral_param, 1.), 'g-', linewidth=0.1) self.shape_plot.plot(self.borders[:,0], self.borders[:,1],'k-') self.posi = self.shape_plot.plot(self.wt_positions[:,0], self.wt_positions[:,1],'ro') self.plotel = self.shape_plot.plot(np.array([self.baseline[[i,j],0] for i, j in self.elnet_layout.keys()]).T, np.array([self.baseline[[i,j],1] for i, j in self.elnet_layout.keys()]).T, 'y--', linewidth=1) #print self.plotel self.objf_plot.clear() targarr = np.array(self.targvalue) self.posb = [] for i in range(targarr.shape[1]): self.posb.append(self.objf_plot.plot(self.iterations, self.targvalue[0][i],'.', label=self.targname[i])) print 'posb', self.posb self.legend = self.objf_plot.legend(loc=3, bbox_to_anchor=(1.1, 0.0)) plt.title('Foundation = %8.2f'%(self.foundation_length)) plt.draw()
def removenodata_value (inputfile,outputfile,topotypein=2,topotypeout=2,nodata_value=None,method='fill'): """ remove the nodata_values in a topo file by interpolating from meaningful values. """ import pylab (X,Y,Z)=topofile2griddata(inputfile,topotypein) if topotypein>1 and not nodata_value: topoheader=topoheaderread(inputfile) nodata_value=topoheader['nodata_value'] elif not nodata_value: print 'provide a value for nodata_value when using topotype1' if method=='fill': ind=fixdata.findbadindices(Z,nodata_value) if size(ind)>0: print("Changing %s nodata_value points" % size(ind)) Z=fixdata.fillbaddata(Z,ind) griddata2topofile(X,Y,Z,outputfile,topotypeout,nodata_value,nodata_value) return nrows= shape(Z)[0] ncols= shape(Z)[1] npts = nrows*ncols xi=X[0,:] yi=Y[:,0] X.np.reshape(npts) Y.np.reshape(npts) Z.np.reshape(npts) ind=np.where(Z!=nodata_value) X=X[ind] Y=Y[ind] Z=Z[ind] ptsremove=npts-len(Z) if ptsremove>0: print("Removing %s nodata_value points" % ptsremove) Z = pylab.griddata(X,Y,Z,xi,yi) (X,Y)=np.meshgrid(xi,yi) griddata2topofile(X,Y,Z,outputfile,topotypeout,nodata_value,nodata_value) return
def histo_plot(x,y,z=None): '''plots 2-d histogram from frequency in poins (x,y) will plot x,y,z pcolor plot with 1 sigma contours if z is given''' assert len(x.shape) == 1 and len(y.shape) == 1 if nu.any(z): assert z.shape[0] == x.shape[0] #create histogram Z,X,Y = nu.histogram2d(x,y,[200,200]) Z = Z.T #get likelhood brute force if z not there if nu.any(z): Zz = lab.griddata(x,y,z,X,Y) else: Zz = make_chi_grid(data, points=100, metal=X, age=Y) #get hist plot ready from pylab docs left, width = 0.1, 0.65 bottom, height = 0.1, 0.65 bottom_h = left_h = left+width+0.02 rect_scatter = [left, bottom, width, height] rect_histx = [left, bottom_h, width, 0.2] rect_histy = [left_h, bottom, 0.2, height] # start with a rectangular Figure lab.figure(1, figsize=(8,8)) axMain = lab.axes(rect_scatter) axHistx = lab.axes(rect_histx) axHisty = lab.axes(rect_histy) #plot 1 sigma contors axMain.contour(X[3:],Y[3:],blur_image(Z,1), nu.percentile(Z[Z.nonzero()],[16,84]),color=('red','red')) axMain.pcolor(X,Y,Zz,cmap='gray') axHistx.hist(x, bins=200) axHisty.hist(y, bins=200, orientation='horizontal') axMain.set_xlabel('Metalicity') axMain.set_ylabel('Age') axHistx.set_xlim( axMain.get_xlim() ) axHisty.set_ylim( axMain.get_ylim() ) lab.show()
def build_vels(vels, **kwargs): from scipy import interpolate cdps = np.array(kwargs['cdp']) times = np.array(kwargs['times']) keys = vels.keys() x = [] t = [] values = [] for i in vels.items(): cdp = i[0] picks= i[1] for pick in picks: x.append(cdp) t.append(pick[1]) values.append(pick[0]) grid_x, grid_y = np.meshgrid(cdps, times) #top left x.append(min(cdps)) t.append(min(times)) values.append(min(values)) #top right t.append(min(times)) x.append(max(cdps)) values.append(min(values)) #bottom left x.append(min(cdps)) t.append(max(times)) values.append(max(values)) #bottom right t.append(max(times)) x.append(max(cdps)) values.append(max(values)) zi = pylab.griddata(x, t, values, grid_x, grid_y, interp='linear') return zi.T
def plot_skymetric_averagesnr_from_file(filename, maxmismatch=0.1, detectors=None): """ Plot the position, error ellipses, and average SNR^2 for the template locations on the sky. Takes in the name of the ascii file containing the sky locations and metric as well as the size of the error ellipses (maxmismatch). """ RAs, decs, gRRs, gRds, gdds = numpy.loadtxt(filename, unpack=True, usecols=(0, 1, 2, 3, 4)) avesnr = metric.average_snr(RAs, decs, detectors) gs = [] for gRR, gRd, gdd in zip(gRRs, gRds, gdds): g = numpy.array([[gRR, gRd], [gRd, gdd]]) gs.append(g) fig = pylab.figure() ax = fig.add_axes((.1, .1, .8, .8)) dRA = 2 * pi / 200 ddec = pi / 200 RA, dec = scipy.mgrid[-pi + dRA:pi:dRA, -pi / 2 + ddec:pi / 2:ddec] z = pylab.griddata(RAs, decs, avesnr, RA, dec) CF = ax.contourf(RA, dec, log(z) / log(10.), 100) matplotlib.pyplot.colorbar(CF) for RA, dec, g in zip(RAs, decs, gs): plotErrorEllipse((RA, dec), g, maxmismatch, ax, edge='k') ax.set_yticks([-pi / 2, -pi / 4, 0, pi / 4, pi / 2]) ax.set_yticklabels(['$-\pi/2$', '$-\pi/4$', '$0$', '$\pi/4$', '$\pi/2$']) ax.set_xticks([-pi, -pi / 2, 0, pi / 2, pi]) ax.set_xticklabels(['$-\pi$', '$-\pi/2$', '$0$', '$\pi/2$', '$\pi$']) ax.set_xlim(-pi, pi) ax.set_ylim(-pi / 2, pi / 2) ax.set_xlabel(r'$\alpha$') ax.set_ylabel(r'$\delta$') ax.invert_xaxis() ax.set_title('Sky Metric and Average SNR')
def elipse_vis(points,bins,N,elogf=1.1): #slowly steps through points showing how eliplse changed lib_vals=get_fitting_info(lib_path) lib_vals[0][:,0]=10**nu.log10(lib_vals[0][:,0]) #to keep roundoff error constistant metal_unq=nu.log10(nu.unique(lib_vals[0][:,0])) age_unq=nu.unique(lib_vals[0][:,1]) #plot first N points fig=lab.figure() current=fig.add_subplot(111) #plot chi squared landscape using griddata metal,age=nu.linspace(metal_unq[0],metal_unq[-1],200),nu.linspace(age_unq[0],age_unq[-1],200) z=lab.griddata(points[:,0],points[:,1],points[:,-1],metal,age) current.pcolor(metal,age,nu.log10(z)) #lab.colorbar() for i in xrange(N): current.plot(points[i,0],points[i,1],'yo',markersize=5) current.set_xlim((metal_unq.min(),metal_unq.max())) current.set_ylim((age_unq.min(),age_unq.max())) current.set_xlabel('Log Metalicity') current.set_ylabel('Age') #plot current elipse curren_ellipse=Ellipse(xy=[metal_unq[0]+metal_unq.ptp()/2., age_unq[0]+age_unq.ptp()/2.], width=metal_unq.ptp()*elogf,height=age_unq.ptp()*elogf) current.add_artist(curren_ellipse) curren_ellipse.set_alpha(.5) #curren_ellipse.set_facecolor(nu.random.rand(3)) #current.lines.pop fig.canvas.show() for i in xrange(i,points[:,0].shape[0]): #add and remove ploints like in program #remove last point and add new one in red current.lines[i-N-1].set_visible(False) #make last new point blue current.lines[i-1].set_color('y') current.plot(points[i,0],points[i,1],'ro',markersize=5) #change ellipse size current.artists.pop(0) curren_ellipse=Ellipse(xy=nu.mean(points[i-N+1:i+1,:2],0), width=points[i-N+1:i+1,0].ptp()*elogf,height=points[i-N+1:i+1,1].ptp()*elogf) curren_ellipse.set_alpha(.5) current.add_artist(curren_ellipse) fig.canvas.show()
def build_vels(vels, **kwargs): from scipy import interpolate cdps = np.array(kwargs['cdp']) times = np.array(kwargs['times']) keys = vels.keys() x = [] t = [] values = [] for i in vels.items(): cdp = i[0] picks = i[1] for pick in picks: x.append(cdp) t.append(pick[1]) values.append(pick[0]) grid_x, grid_y = np.meshgrid(cdps, times) #top left x.append(min(cdps)) t.append(min(times)) values.append(min(values)) #top right t.append(min(times)) x.append(max(cdps)) values.append(min(values)) #bottom left x.append(min(cdps)) t.append(max(times)) values.append(max(values)) #bottom right t.append(max(times)) x.append(max(cdps)) values.append(max(values)) zi = pylab.griddata(x, t, values, grid_x, grid_y, interp='linear') return zi.T
def plot_skymetric_from_file(filename, maxmismatch=0.1): """ Plot the position, error ellipses, and square root of the determinant of the metric for the template locations on the sky. Takes in the name of the ascii file containing the sky locations and metric as well as the size of the error ellipses (maxmismatch). """ RAs, decs, gRRs, gRds, gdds = numpy.loadtxt(filename, unpack=True, usecols=(0, 1, 2, 3, 4)) gs = [] rootdetgs = [] for gRR, gRd, gdd in zip(gRRs, gRds, gdds): g = numpy.array([[gRR, gRd], [gRd, gdd]]) rootdetgs.append((scipy.linalg.det(g))**.5) gs.append(g) fig = pylab.figure() ax = fig.add_axes((.1, .1, .8, .8)) dRA = 2 * pi / 200 ddec = pi / 200 RA, dec = scipy.mgrid[-pi + dRA:pi:dRA, -pi / 2 + ddec:pi / 2:ddec] z = pylab.griddata(RAs, decs, rootdetgs, RA, dec) levels = scipy.linspace(-1., 2., 101) CF = ax.contourf(RA, dec, log10(z), levels=levels) matplotlib.pyplot.colorbar(CF) for RA, dec, g in zip(RAs, decs, gs): plotErrorEllipse((RA, dec), g, maxmismatch, ax, edge='k') ax.set_yticks([-pi / 2, -pi / 4, 0, pi / 4, pi / 2]) ax.set_yticklabels(['$-\pi/2$', '$-\pi/4$', '$0$', '$\pi/4$', '$\pi/2$']) ax.set_xticks([-pi, -pi / 2, 0, pi / 2, pi]) ax.set_xticklabels(['$-\pi$', '$-\pi/2$', '$0$', '$\pi/2$', '$\pi$']) ax.set_xlim(-pi, pi) ax.set_ylim(-pi / 2, pi / 2) ax.set_xlabel(r'$\alpha$') ax.set_ylabel(r'$\delta$') ax.invert_xaxis() ax.set_title('Sky Metric')
def plot_skymetric_averagesnr_from_file(filename, maxmismatch=0.1, detectors=None): """ Plot the position, error ellipses, and average SNR^2 for the template locations on the sky. Takes in the name of the ascii file containing the sky locations and metric as well as the size of the error ellipses (maxmismatch). """ RAs,decs,gRRs,gRds,gdds = numpy.loadtxt(filename, unpack=True, usecols=(0,1,2,3,4)) avesnr = metric.average_snr(RAs, decs, detectors) gs = [] for gRR,gRd,gdd in zip(gRRs,gRds,gdds): g = numpy.array([[gRR,gRd],[gRd,gdd]]) gs.append(g) fig = pylab.figure() ax = fig.add_axes((.1,.1,.8,.8)) dRA = 2*pi/200 ddec = pi/200 RA,dec = scipy.mgrid[-pi+dRA:pi:dRA, -pi/2+ddec:pi/2:ddec] z = pylab.griddata(RAs,decs,avesnr,RA,dec) CF = ax.contourf(RA, dec, log(z)/log(10.), 100) matplotlib.pyplot.colorbar(CF) for RA,dec,g in zip(RAs,decs,gs): plotErrorEllipse((RA,dec),g,maxmismatch,ax,edge='k') ax.set_yticks([-pi/2,-pi/4,0,pi/4,pi/2]) ax.set_yticklabels(['$-\pi/2$','$-\pi/4$','$0$','$\pi/4$','$\pi/2$']) ax.set_xticks([-pi,-pi/2,0,pi/2,pi]) ax.set_xticklabels(['$-\pi$','$-\pi/2$','$0$','$\pi/2$','$\pi$']) ax.set_xlim(-pi,pi) ax.set_ylim(-pi/2,pi/2) ax.set_xlabel(r'$\alpha$') ax.set_ylabel(r'$\delta$') ax.invert_xaxis() ax.set_title('Sky Metric and Average SNR')
def plot_skymetric_from_file(filename,maxmismatch=0.1): """ Plot the position, error ellipses, and square root of the determinant of the metric for the template locations on the sky. Takes in the name of the ascii file containing the sky locations and metric as well as the size of the error ellipses (maxmismatch). """ RAs,decs,gRRs,gRds,gdds = numpy.loadtxt(filename, unpack=True, usecols=(0,1,2,3,4)) gs = [] rootdetgs = [] for gRR,gRd,gdd in zip(gRRs,gRds,gdds): g = numpy.array([[gRR,gRd],[gRd,gdd]]) rootdetgs.append((scipy.linalg.det(g))**.5) gs.append(g) fig = pylab.figure() ax = fig.add_axes((.1,.1,.8,.8)) dRA = 2*pi/200 ddec = pi/200 RA,dec = scipy.mgrid[-pi+dRA:pi:dRA, -pi/2+ddec:pi/2:ddec] z = pylab.griddata(RAs,decs,rootdetgs,RA,dec) levels = scipy.linspace(-1.,2.,101) CF = ax.contourf(RA, dec, log10(z), levels=levels) matplotlib.pyplot.colorbar(CF) for RA,dec,g in zip(RAs,decs,gs): plotErrorEllipse((RA,dec),g,maxmismatch,ax,edge='k') ax.set_yticks([-pi/2,-pi/4,0,pi/4,pi/2]) ax.set_yticklabels(['$-\pi/2$','$-\pi/4$','$0$','$\pi/4$','$\pi/2$']) ax.set_xticks([-pi,-pi/2,0,pi/2,pi]) ax.set_xticklabels(['$-\pi$','$-\pi/2$','$0$','$\pi/2$','$\pi$']) ax.set_xlim(-pi,pi) ax.set_ylim(-pi/2,pi/2) ax.set_xlabel(r'$\alpha$') ax.set_ylabel(r'$\delta$') ax.invert_xaxis() ax.set_title('Sky Metric')
def plot_massmetric_on_sky_from_file(filename): """ Plot the position, and square root of the determinant of the mass metric for the template locations on the sky. Takes in the name of the ascii file containing the locations and metric as well as the size of the error ellipses (maxmismatch). """ RAs, decs, gmms, gmes, gees = numpy.loadtxt(filename, unpack=True, usecols=(0, 1, 5, 6, 7)) gs = [] rootdetgs = [] for gmm, gme, gee in zip(gmms, gmes, gees): g = numpy.array([[gmm, gme], [gme, gee]]) rootdetgs.append((scipy.linalg.det(g))**.5) gs.append(g) fig = pylab.figure() ax = fig.add_axes((.1, .1, .8, .8)) dRA = 2 * pi / 200 ddec = pi / 200 RA, dec = scipy.mgrid[-pi + dRA:pi:dRA, -pi / 2 + ddec:pi / 2:ddec] z = pylab.griddata(RAs, decs, rootdetgs, RA, dec) CF = ax.contourf(RA, dec, log(z), 100) ax.plot(RAs, decs, 'kx') matplotlib.pyplot.colorbar(CF) ax.set_yticks([-pi / 2, -pi / 4, 0, pi / 4, pi / 2]) ax.set_yticklabels(['$-\pi/2$', '$-\pi/4$', '$0$', '$\pi/4$', '$\pi/2$']) ax.set_xticks([-pi, -pi / 2, 0, pi / 2, pi]) ax.set_xticklabels(['$-\pi$', '$-\pi/2$', '$0$', '$\pi/2$', '$\pi$']) ax.set_xlim(-pi, pi) ax.set_ylim(-pi / 2, pi / 2) ax.set_xlabel(r'$\alpha$') ax.set_ylabel(r'$\delta$') ax.invert_xaxis() ax.set_title('Mass Metric')
def interp3(x,y,b,xnew,ynew,method): xf=x.flatten() yf=y.flatten() bf=b.flatten() interpm=method if interpm=='tri': xnewf=xnew.flatten() ynewf=ynew.flatten() print 'tri interp ...' from delaunay import triangulate tri=triangulate.Triangulation(xf, yf) interp_b=tri.nn_extrapolator(bf) bnewf = interp_b(xnewf,ynewf) bnew=bnewf.reshape(xnew.shape) elif interpm=='csa' : print 'csa interp ...' import octant.csa as csa csa_interp = csa.CSA(xf, yf,bf) bnew = csa_interp(xnew,ynew) elif interpm=='grd' : print 'griddata interp ...' bnew=pl.griddata(xf,yf,bf,xnew,ynew) return bnew
def interp3(x, y, b, xnew, ynew, method): xf = x.flatten() yf = y.flatten() bf = b.flatten() interpm = method if interpm == 'tri': xnewf = xnew.flatten() ynewf = ynew.flatten() print 'tri interp ...' from delaunay import triangulate tri = triangulate.Triangulation(xf, yf) interp_b = tri.nn_extrapolator(bf) bnewf = interp_b(xnewf, ynewf) bnew = bnewf.reshape(xnew.shape) elif interpm == 'csa': print 'csa interp ...' import octant.csa as csa csa_interp = csa.CSA(xf, yf, bf) bnew = csa_interp(xnew, ynew) elif interpm == 'grd': print 'griddata interp ...' bnew = pl.griddata(xf, yf, bf, xnew, ynew) return bnew
def plot_wt_layout(wt_layout, borders=None, depth=None): fig = plt.figure(figsize=(6,6), dpi=2000) fs = 14 ax = plt.subplot(111) if depth is not None: N = 100 X, Y = plt.meshgrid(plt.linspace(depth[:,0].min(), depth[:,0].max(), N), plt.linspace(depth[:,1].min(), depth[:,1].max(), N)) Z = plt.griddata(depth[:,0],depth[:,1],depth[:,2],X,Y, interp='linear') plt.contourf(X,Y,Z, label='depth [m]') plt.colorbar().set_label('water depth [m]') #ax.plot(wt_layout.wt_positions[:,0], wt_layout.wt_positions[:,1], 'or', label='baseline position') ax.scatter(wt_layout.wt_positions[:,0], wt_layout.wt_positions[:,1], wt_layout._wt_list('rotor_diameter'), label='baseline position') if borders is not None: ax.plot(borders[:,0], borders[:,1], 'r--', label='border') ax.set_xlabel('x [m]'); ax.set_ylabel('y [m]') ax.axis('equal'); ax.legend(loc='lower left')
def plot_massmetric_on_sky_from_file(filename): """ Plot the position, and square root of the determinant of the mass metric for the template locations on the sky. Takes in the name of the ascii file containing the locations and metric as well as the size of the error ellipses (maxmismatch). """ RAs,decs,gmms,gmes,gees = numpy.loadtxt(filename, unpack=True, usecols=(0,1,5,6,7)) gs = [] rootdetgs = [] for gmm,gme,gee in zip(gmms,gmes,gees): g = numpy.array([[gmm,gme],[gme,gee]]) rootdetgs.append((scipy.linalg.det(g))**.5) gs.append(g) fig = pylab.figure() ax = fig.add_axes((.1,.1,.8,.8)) dRA = 2*pi/200 ddec = pi/200 RA,dec = scipy.mgrid[-pi+dRA:pi:dRA, -pi/2+ddec:pi/2:ddec] z = pylab.griddata(RAs,decs,rootdetgs,RA,dec) CF = ax.contourf(RA, dec, log(z), 100) ax.plot(RAs, decs, 'kx') matplotlib.pyplot.colorbar(CF) ax.set_yticks([-pi/2,-pi/4,0,pi/4,pi/2]) ax.set_yticklabels(['$-\pi/2$','$-\pi/4$','$0$','$\pi/4$','$\pi/2$']) ax.set_xticks([-pi,-pi/2,0,pi/2,pi]) ax.set_xticklabels(['$-\pi$','$-\pi/2$','$0$','$\pi/2$','$\pi$']) ax.set_xlim(-pi,pi) ax.set_ylim(-pi/2,pi/2) ax.set_xlabel(r'$\alpha$') ax.set_ylabel(r'$\delta$') ax.invert_xaxis() ax.set_title('Mass Metric')
def bvContourf(x1, x2, z, **kwargs): contour_plot = plt.figure() outfile = kwargs.pop("savefig", None) # create interpolation grid support points xx = np.linspace(x1.min(), x1.max(), 150) yy = np.linspace(x2.min(), x2.max(), 150) # create grid required by pl.contour x_grid, y_grid = np.meshgrid(xx, yy) # interpolate data to meshgrid z_grid = griddata( x1, x2, z, x_grid, y_grid, interp='linear', ) # plot contour contour_plot = plt.figure() plt.subplot(1, 1, 1) cf = plt.contourf(x_grid, y_grid, z_grid, alpha=0.8, cmap="GnBu") cs = plt.contour(x_grid, y_grid, z_grid, 25, colors='k', hold='on', antialiased=True) plt.clabel(cs, fontsize=8, inline=1) cs = plt.colorbar(cf, shrink=0.8, extend='both', alpha=0.8) plt.grid(b=True, which='major', color='k', linestyle='--') if outfile: plt.title(kwargs.pop("title", "")) contour_plot.savefig(outfile) plt.close() return contour_plot
def plot_stress_fields(atoms, r_range=None, initial_params=None, fix_params=None, sigma=None, avg_sigma=None, avg_decay=0.005, calc=None): """ Fit and plot atomistic and continuum stress fields Firstly a fit to the Irwin `K`-field solution is carried out using :func:`fit_crack_stress_field`, and parameters have the same meaning as for that function. Then plots of the :math:`\sigma_{xx}`, :math:`\sigma_{yy}`, :math:`\sigma_{xy}` fields are produced for atomistic and continuum cases, and for the residual error after fitting. """ from pylab import griddata, meshgrid, subplot, cla, contourf, colorbar, draw, title, clf, gca params, err = fit_crack_stress_field(atoms, r_range, initial_params, fix_params, sigma, avg_sigma, avg_decay, calc) K, x0, y0, sxx0, syy0, sxy0 = (params['K'], params['x0'], params['y0'], params['sxx0'], params['syy0'], params['sxy0']) x = atoms.positions[:, 0] y = atoms.positions[:, 1] X = np.linspace((x-x0).min(), (x-x0).max(), 500) Y = np.linspace((y-y0).min(), (y-y0).max(), 500) t = np.arctan2(y-y0, x-x0) r = np.sqrt((x-x0)**2 + (y-y0)**2) if r_range is not None: rmin, rmax = r_range mask = (r > rmin) & (r < rmax) else: mask = Ellipsis atom_sigma = sigma if atom_sigma is None: atom_sigma = atoms.get_stresses() grid_sigma = np.dstack([griddata(x[mask]-x0, y[mask]-y0, atom_sigma[mask,0,0], X, Y), griddata(x[mask]-x0, y[mask]-y0, atom_sigma[mask,1,1], X, Y), griddata(x[mask]-x0, y[mask]-y0, atom_sigma[mask,0,1], X, Y)]) X, Y = meshgrid(X, Y) R = np.sqrt(X**2+Y**2) T = np.arctan2(Y, X) grid_sigma[((R < rmin) | (R > rmax)),:] = np.nan # mask outside fitting region isotropic_sigma = isotropic_modeI_crack_tip_stress_field(K, R, T, x0, y0) isotropic_sigma[...,0,0] += sxx0 isotropic_sigma[...,1,1] += syy0 isotropic_sigma[...,0,1] += sxy0 isotropic_sigma[...,1,0] += sxy0 isotropic_sigma = ma.masked_array(isotropic_sigma, mask=grid_sigma.mask) isotropic_sigma[((R < rmin) | (R > rmax)),:,:] = np.nan # mask outside fitting region contours = [np.linspace(0, 20, 10), np.linspace(0, 20, 10), np.linspace(-10,10, 10)] dcontours = [np.linspace(0, 5, 10), np.linspace(0, 5, 10), np.linspace(-5, 5, 10)] clf() for i, (ii, jj), label in zip(range(3), [(0,0), (1,1), (0,1)], ['\sigma_{xx}', r'\sigma_{yy}', r'\sigma_{xy}']): subplot(3,3,i+1) gca().set_aspect('equal') contourf(X, Y, grid_sigma[...,i]*GPA, contours[i]) colorbar() title(r'$%s^\mathrm{atom}$' % label) draw() subplot(3,3,i+4) gca().set_aspect('equal') contourf(X, Y, isotropic_sigma[...,ii,jj]*GPA, contours[i]) colorbar() title(r'$%s^\mathrm{Isotropic}$' % label) draw() subplot(3,3,i+7) gca().set_aspect('equal') contourf(X, Y, abs(grid_sigma[...,i] - isotropic_sigma[...,ii,jj])*GPA, dcontours[i]) colorbar() title(r'$|%s^\mathrm{atom} - %s^\mathrm{isotropic}|$' % (label, label)) draw()
def plot_stress_fields(atoms, r_range=None, initial_params=None, fix_params=None, sigma=None, avg_sigma=None, avg_decay=0.005, calc=None): """ Fit and plot atomistic and continuum stress fields Firstly a fit to the Irwin `K`-field solution is carried out using :func:`fit_crack_stress_field`, and parameters have the same meaning as for that function. Then plots of the :math:`\sigma_{xx}`, :math:`\sigma_{yy}`, :math:`\sigma_{xy}` fields are produced for atomistic and continuum cases, and for the residual error after fitting. """ from pylab import griddata, meshgrid, subplot, cla, contourf, colorbar, draw, title, clf, gca params, err = fit_crack_stress_field(atoms, r_range, initial_params, fix_params, sigma, avg_sigma, avg_decay, calc) K, x0, y0, sxx0, syy0, sxy0 = (params['K'], params['x0'], params['y0'], params['sxx0'], params['syy0'], params['sxy0']) x = atoms.positions[:, 0] y = atoms.positions[:, 1] X = np.linspace((x-x0).min(), (x-x0).max(), 500) Y = np.linspace((y-y0).min(), (y-y0).max(), 500) t = np.arctan2(y-y0, x-x0) r = np.sqrt((x-x0)**2 + (y-y0)**2) if r_range is not None: rmin, rmax = r_range mask = (r > rmin) & (r < rmax) else: mask = Ellipsis atom_sigma = sigma if atom_sigma is None: atom_sigma = atoms.get_stresses() grid_sigma = np.dstack([griddata(x[mask]-x0, y[mask]-y0, atom_sigma[mask,0,0], X, Y), griddata(x[mask]-x0, y[mask]-y0, atom_sigma[mask,1,1], X, Y), griddata(x[mask]-x0, y[mask]-y0, atom_sigma[mask,0,1], X, Y)]) X, Y = meshgrid(X, Y) R = np.sqrt(X**2+Y**2) T = np.arctan2(Y, X) grid_sigma[((R < rmin) | (R > rmax)),:] = np.nan # mask outside fitting region irwin_sigma = irwin_modeI_crack_tip_stress_field(K, R, T, x0, y0) irwin_sigma[...,0,0] += sxx0 irwin_sigma[...,1,1] += syy0 irwin_sigma[...,0,1] += sxy0 irwin_sigma[...,1,0] += sxy0 irwin_sigma = ma.masked_array(irwin_sigma, mask=grid_sigma.mask) irwin_sigma[((R < rmin) | (R > rmax)),:,:] = np.nan # mask outside fitting region contours = [np.linspace(0, 20, 10), np.linspace(0, 20, 10), np.linspace(-10,10, 10)] dcontours = [np.linspace(0, 5, 10), np.linspace(0, 5, 10), np.linspace(-5, 5, 10)] clf() for i, (ii, jj), label in zip(range(3), [(0,0), (1,1), (0,1)], ['\sigma_{xx}', r'\sigma_{yy}', r'\sigma_{xy}']): subplot(3,3,i+1) gca().set_aspect('equal') contourf(X, Y, grid_sigma[...,i]*GPA, contours[i]) colorbar() title(r'$%s^\mathrm{atom}$' % label) draw() subplot(3,3,i+4) gca().set_aspect('equal') contourf(X, Y, irwin_sigma[...,ii,jj]*GPA, contours[i]) colorbar() title(r'$%s^\mathrm{Irwin}$' % label) draw() subplot(3,3,i+7) gca().set_aspect('equal') contourf(X, Y, abs(grid_sigma[...,i] - irwin_sigma[...,ii,jj])*GPA, dcontours[i]) colorbar() title(r'$|%s^\mathrm{atom} - %s^\mathrm{Irwin}|$' % (label, label)) draw()
def compareData(name1, name2, str): filename = name1 + '.ini' ini = ConfigParser() ini.read(filename) distrWE = ini.get("demand", "distrWE") distr = ("poisson" if (distrWE == 'p') else "uniform") vehphWEA = eval(ini.get("demand", "vehphWEA")) vehphNSA = eval(ini.get("demand", "vehphNSA")) filename1 = name1 + ".dat" data1 = load(filename1) flowWEA1 = data1[:, 0] flowNSA1 = data1[:, 1] # qWEA1 = data1[:, 2] # qNSA1 = data1[:, 3] avgDelayWEA1 = data1[:, 4] avgDelayNSA1 = data1[:, 5] avgDelayA1 = data1[:, 6] # greenWEA1 = data1[:, 7] # greenNSA1 = data1[:, 8] filename2 = name2 + ".dat" data2 = load(filename2) flowWEA2 = data2[:, 0] flowNSA2 = data2[:, 1] # qWEA2 = data2[:, 2] # qNSA2 = data2[:, 3] avgDelayWEA2 = data2[:, 4] avgDelayNSA2 = data2[:, 5] avgDelayA2 = data2[:, 6] # greenWEA2 = data2[:, 7] # greenNSA2 = data2[:, 8] [X, Y] = meshgrid(vehphWEA, vehphNSA) figure(figsize=(6, 6)) Z1 = array(griddata(flowWEA1, flowNSA1, avgDelayA1, X, Y)) Z2 = array(griddata(flowWEA2, flowNSA2, avgDelayA2, X, Y)) Z = Z1 / Z2 subplot(1, 1, 1) contourf(X, Y, Z, concatenate((frange(0, 2, 0.1), frange(2, 3, 1)))) xlabel('Input flow WE') ylabel('Input flow NS') colorbar() title('Average Delay VA vs. FC (ratio), ' + distr) savefig(str + ".png") Z1 = array(griddata(flowWEA1, flowNSA1, avgDelayWEA1, X, Y)) Z2 = array(griddata(flowWEA2, flowNSA2, avgDelayWEA2, X, Y)) Z = Z1 / Z2 figure(figsize=(12, 6)) subplot(1, 2, 1) contourf(X, Y, Z, concatenate((frange(0, 2, 0.1), frange(2, 3, 1)))) xlabel('Input flow WE') ylabel('Input flow NS') title('Average Delay WE') colorbar() Z1 = array(griddata(flowWEA1, flowNSA1, avgDelayNSA1, X, Y)) Z2 = array(griddata(flowWEA2, flowNSA2, avgDelayNSA2, X, Y)) Z = Z1 / Z2 subplot(1, 2, 2) contourf(X, Y, Z, concatenate((frange(0, 2, 0.1), frange(2, 3, 1)))) xlabel('Input flow WE') ylabel('Input flow NS') title('Average Delay NS') colorbar() subtitle('Average Delay VA vs. FC (ratio), ' + distr) savefig(str + "WENS.png")
def scatter2gridded(scatterdatafile=" ", boundarydatafile=" ", headerfile=" ", outputfile=" "): """ scatter2gridded (scatterdatafile=" ",boundarydatafile=" ", headerfile=" ", outputfile=" "): function converts scattered data points (x,y,z) into gridded data, with z values given at uniformly spaced points. 'scatterdatafile' and optional 'boundarydatafile' should each have three columns containing x,y,z coordinates respectively of each point. 'headerfile' specifies the format of the grid parameters for the output data. The header should have the following form: int ncols int nrows float xll float yll float cellsize float nodata_value see topotools.headerwriter and topotools.headerreader. 'outputfile' will have the same header followed by the data advancing from northwest across eastward then down, one z value per row. """ import pylab # Input data==========================: # read scattered data fin = open(scatterdatafile, 'r') a = fromfile(fin, sep=" ", count=-1, dtype=float) fin.close #read boundary data ie: points specifying a quadrilateral bounding the scattered data if it is needed if boundarydatafile != " ": fin = open(boundarydatafile, 'r') b = fromfile(fin, sep=" ", count=-1, dtype=float) fin.close a = np.hstack((a, b)) #reshape data into (#pts , 3) array pts = len(a) / 3 a = np.reshape(a, (pts, 3)) #determine what the output grid will look like from headerfile topoheader = topoheaderread(inputfile=headerfile) # manipulate data============================: #Create the gridded data using pylab "griddata function." xgrid = np.arange(topoheader['xll'], \ topoheader['xll']+topoheader['ncols']*topoheader['cellsize'], \ step=topoheader['cellsize'],dtype=float) ygrid = np.arange(topoheader['yll'], \ topoheader['yll']+topoheader['nrows']*topoheader['cellsize'], \ step=topoheader['cellsize'],dtype=float) X, Y = np.meshgrid(xgrid, ygrid) Z = pylab.griddata(a[:, 0], a[:, 1], a[:, 2], X, Y) Y = np.flipud(Y) Z = np.flipud(Z) # pyplot.contour(X,Y,Z) #write the output file =====================: if outputfile != " ": fout = topoheaderwrite(topoheader, outputfile, closefile=False) for i in xrange(topoheader['nrows']): for j in xrange(topoheader['ncols']): fout.write("%s\n" % Z[i, j]) fout.close() return (X, Y, Z)
def hitlist2int(x, y, z, xi, yi): """Function that estimates an intensity distribution on a plane from a ray hitlist """ from pylab import griddata, meshgrid from scipy import interpolate #if xi.ndim != yi.ndim: # raise TypeError("inputs xi and yi must have same number of dimensions (1 or 2)") #if xi.ndim != 1 and xi.ndim != 2: # raise TypeError("inputs xi and yi must be 1D or 2D.") #if not len(x)==len(y)==len(z): # raise TypeError("inputs x,y,z must all be 1D arrays of the same length") # remove masked points. #if hasattr(z,'mask'): # x = x.compress(z.mask == False) # y = y.compress(z.mask == False) # z = z.compressed() #if xi.ndim == 1: # xi,yi = meshgrid(xi,yi) #triangulate data tri = Triangulation(x, y) #calculate triangles area #ntriangles=tri.circumcenters.shape[0] coord = array(zip(tri.x, tri.y)) #I=zeros((ntriangles, )) #xc=zeros((ntriangles, )) #yc=zeros((ntriangles, )) # for i in range(ntriangles): # i1, i2, i3=tri.triangle_nodes[i] # p1=coord[i1] # p2=coord[i2] # p3=coord[i3] # v1=p1-p2 # v2=p3-p2 # I[i]=1./(abs(v1[0]*v2[1]-v1[1]*v2[0])) # # the circumcenter data from the triangulation, has some problems so we # # recalculate it # xc[i], yc[i]=(p1+p2+p3)/3. # The previous code was replaced by the following code ### i1 = tri.triangles[:, 0] i2 = tri.triangles[:, 1] i3 = tri.triangles[:, 2] p1 = coord[i1] p2 = coord[i2] p3 = coord[i3] v1 = p1 - p2 v2 = p3 - p2 I = abs(1. / (v1[:, 0] * v2[:, 1] - v1[:, 1] * v2[:, 0])) c = (p1 + p2 + p3) / 3. xc = c[:, 0] yc = c[:, 1] ### # Because of the triangulation algorithm, there are some really high values # in the intensity data. To filter these values, remove the 5% points of the # higher intensity. ni = int(0.1 * len(I)) j = I.argsort()[:-ni] xc = xc[j] yc = yc[j] I = I[j] I = I / I.max() # #print tri.circumcenters[:, 0] # #print tri.circumcenters.shape # print ntriangles, tri.circumcenters[:, 0].shape, tri.circumcenters[:, 0].flatten().shape #itri=delaunay.Triangulation(xc,yc) #inti=itri.linear_interpolator(I) #xi,yi = meshgrid(xi,yi) #d1=itri(xi, yi) #Interpolacion con Splines #di=interpolate.SmoothBivariateSpline(xc, yc, I) #d1=di(xi,yi) #Interpolacion nn, y generaciĆ³n de pupila xi, yi = meshgrid(xi, yi) d1 = griddata(xc, yc, I, xi, yi) return d1
def plot_slice(args): verbose = args.verbose output_file = args.output_file[0] input_file = args.input_file[0] variable = args.variable[0] cmap = args.colourmap dpi = args.dpi fmt = args.format minimum = args.minvalue maximum = args.maxvalue vscale = args.velocityscale addvelocity = None on_sphere = args.on_sphere subsample = args.subsample if (args.mask_file): mask_file = args.mask_file[0] else: mask_file = False hardlimit = args.hardlimit resolution = args.resolution if (not args.addvelocity == None): addvelocity=args.addvelocity[0] if (cmap == "jet"): colourmap = pylab.cm.jet elif (cmap == "hot"): colourmap = pylab.cm.hot elif (cmap == "Blues"): colourmap = pylab.cm.Blues elif (cmap == "gray"): colourmap = pylab.cm.gray elif (cmap == "rainbow"): colourmap = pylab.cm.gist_rainbow_r else: colourmap = pylab.cm.jet if (fmt == None): fmt = output_file[-3:] if (not str.lower(fmt) == 'png' and not str.lower(fmt) == 'pdf'): print "Format should be one of pdf or png" print "Defaulting to png" fmt = 'png' if (verbose): print "Loading data: "+input_file data = pickle.load( open( input_file, "rb" ) ) xi = data[0] yi = data[1] zi = data[2] axes_info = data[3] index_1 = axes_info[0] index_2 = axes_info[1] x_axis = axes_info[2] y_axis = axes_info[3] plotting_velocity = False n_comp = len(np.shape(zi[0])) if n_comp < 1: n_comp = 1 if (mask_file): from Scientific.IO import NetCDF file = NetCDF.NetCDFFile(mask_file, 'r') longitude = file.variables['lon'][:] latitude = file.variables['lat'][:] mask = file.variables['z'][:, :] lon,lat = np.meshgrid(longitude, latitude) lon = np.reshape(lon,len(longitude)*len(latitude)) lat = np.reshape(lat,len(longitude)*len(latitude)) mask = np.reshape(mask,len(longitude)*len(latitude)) # subsample data x = xi[0::subsample] y = yi[0::subsample] z = zi[0::subsample] zi = np.array(z) yi = np.array(y) xi = np.array(x) z =[];x=[];y=[] if (n_comp > 1): plotting_velocity = True if (verbose): print "Creating uniform mesh" # Need to have different numebr of points for X and Y # Warning or error if n points is huge X, Y = np.meshgrid(np.linspace( xi.min(), xi.max(), 360./resolution ), np.linspace(yi.min(), yi.max(), 180./resolution)) params = { 'legend.fontsize': 18, 'xtick.labelsize': 16, 'ytick.labelsize': 16, 'font.size' : 18, 'axes.labelsize' : 18, 'text.fontsize' : 18, 'figure.subplot.hspace' : 0.5 } pylab.rcParams.update(params) fig = pylab.figure(figsize=(15,8),dpi=90) if (index_1 == 0 and index_2 == 1): ax = fig.add_subplot(111, aspect='equal') else: ax = fig.add_subplot(111) if (verbose): print "Interpolating data" if (plotting_velocity): u = zi[index_1,:] v = zi[index_2,:] U = pylab.griddata(xi, yi, u, X, Y) V = pylab.griddata(xi, yi, v, X, Y) q = pylab.quiver(X,Y,U,V,scale=vscale,color='k') else: #tri = Triangulation(xi,yi) #interp = tri.nn_interpolator(zi) #zi = interp(X,Y) Z = pylab.griddata(xi, yi, zi, X, Y) if (mask_file): mask_grd = pylab.griddata(lat, lon, mask, X, Y) # loop over mask_grd. Where land, set Z to NaN, which will mask out these areas in the plot for i in range(0,len(mask_grd)): for j in range(0,len(mask_grd[0])): if (mask_grd[i][j] == 0): Z[i][j] = float('NaN') # define min/max and spacing of data if not given (so we see all of the data) spacing = None if (minimum == None): minimum = zi.min() minimum = minimum - (0.05*minimum) if (maximum == None): maximum = zi.max() maximum = maximum + (0.05*maximum) if (spacing == None): spacing = (maximum - minimum) /256. if (hardlimit): if (verbose): print "applying hard limit" for i in range(0,len(Z)): for j in range(0,len(Z[0])): if (Z[i][j] <= minimum): Z[i][j] = minimum+(0.01*minimum) if (Z[i][j] >= maximum): Z[i][j] = maximum-(0.01*maximum) if (verbose): print "Plotting" cs=ax.contour(Y,X,Z,np.arange(minimum,maximum,spacing),cmap=colourmap) #cs=pylab.scatter(yi,xi,marker='.',s=2,c=zi,cmap=colourmap,edgecolors='none') cs=ax.contourf(Y,X,Z,np.arange(minimum,maximum,spacing),cmap=colourmap) #print "triangulation" #triang = tri.Triangulation(xi, yi) #print "plotting" #cs=pylab.tricontour(xi, yi, zi, 15, linewidths=0.5, colors='k') #cs=pylab.tricontourf(xi, yi, zi, 15, cmap=plt.cm.jet) pp=pylab.colorbar(cs,format='%.2f') pp.set_label(variable) if (not addvelocity == None): data = pickle.load( open( addvelocity, "rb" ) ) xi = data[0] yi = data[1] zi = data[2] axes_info = data[3] index_1 = axes_info[0] index_2 = axes_info[1] x_axis = axes_info[2] y_axis = axes_info[3] u = zi[:,index_1] v = zi[:,index_2] U = pylab.griddata(xi, yi, u, X, Y) V = pylab.griddata(xi, yi, v, X, Y) q = pylab.quiver(X,Y,U,V,scale=vscale,color='k',zorder=100) pylab.xlabel(x_axis+' (m)') pylab.ylabel(y_axis+' (m)') pylab.savefig(output_file, dpi=dpi,format=fmt)
def plotDiagram(name): filename = name + ".dat" X = load(filename) flowWEA = X[:, 0] flowNSA = X[:, 1] qWEA = X[:, 2] qNSA = X[:, 3] avgDelayWEA = X[:, 4] avgDelayNSA = X[:, 5] avgDelayA = X[:, 6] greenWEA = X[:, 7] greenNSA = X[:, 8] filename = name + '.ini' ini = ConfigParser() ini.read(filename) ini.getint("general", "N") ini.getboolean("general", "cut") distrWE = ini.get("demand", "distrWE") distrNS = ini.get("demand", "distrNS") tlType = ini.get("TL", "tlType") vehphWEA = eval(ini.get("demand", "vehphWEA")) vehphNSA = eval(ini.get("demand", "vehphNSA")) max(max(avgDelayWEA), max(avgDelayNSA)) maxD = max(avgDelayA) c = maxD / (exp(1) - 1) [c * (exp(i) - 1) for i in frange(0, 1, 0.01)] [X, Y] = meshgrid(vehphWEA, vehphNSA) Z = griddata(flowWEA, flowNSA, avgDelayWEA, X, Y) figure(figsize=(12, 12)) subplot(2, 2, 1) # contour(X, Y, Z, 100) contourf(X, Y, Z, range(0, 180, 5)) colorbar() title('Average Delay WE') xlabel('Input flow WE') ylabel('Input flow NS') Z = griddata(flowWEA, flowNSA, avgDelayNSA, X, Y) subplot(2, 2, 2) # contour(X, Y, Z, 100) contourf(X, Y, Z, range(0, 180, 5)) colorbar() title('Average Delay NS') xlabel('Input flow WE') ylabel('Input flow NS') Z = griddata(qWEA, qNSA, avgDelayWEA, X, Y) avgDelayWECut = [Z[i][i] for i in range(len(Z))] subplot(2, 2, 3) # contour(X, Y, Z, 100) contourf(X, Y, Z, range(0, 180, 5)) colorbar() title('Average Delay WE') xlabel('Flow q WE') ylabel('Flow q NS') Z = griddata(qWEA, qNSA, avgDelayNSA, X, Y) avgDelayNSCut = [Z[i][i] for i in range(len(Z))] subplot(2, 2, 4) # contour(X, Y, Z, 100) contourf(X, Y, Z, range(0, 180, 5)) colorbar() title('Average Delay NS') xlabel('Flow q WE') ylabel('Flow q NS') subtitle("Average Delay (WE " + ("poisson" if distrWE == 'p' else "uniform") + ", NS " + ("poisson" if distrNS == 'p' else "uniform") + ", " + tlType + ")") savefig(name + "AvgDelayNSWE.png") close() Z = griddata(flowWEA, flowNSA, avgDelayA, X, Y) figure(figsize=(12, 6)) subplot(1, 2, 1) # contour(X, Y, Z, 100) contourf(X, Y, Z, range(0, 180, 5)) colorbar() title('Average Delay') xlabel('Input flow WE') ylabel('Input flow NS') Z = griddata(qWEA, qNSA, avgDelayA, X, Y) avgDelayCut = [Z[i][i] for i in range(len(Z))] subplot(1, 2, 2) # contour(X, Y, Z, 100) contourf(X, Y, Z, range(0, 180, 5)) # clim(0, maxDelay) colorbar() title('Average Delay') xlabel('Flow q WE') ylabel('Flow q NS') subtitle("Average Delay (WE " + ("poisson" if distrWE == 'p' else "uniform") + ", NS " + ("poisson" if distrNS == 'p' else "uniform") + ", " + tlType + ")") savefig(name + "AvgDelay.png") close() Z = griddata(flowWEA, flowNSA, qWEA, X, Y) figure(figsize=(12, 6)) subplot(1, 2, 1) contourf(X, Y, Z, range(0, 1250, 50)) colorbar() title('Flow q WE') xlabel('Input flow WE') ylabel('Input flow NS') Z = griddata(flowWEA, flowNSA, qNSA, X, Y) subplot(1, 2, 2) contourf(X, Y, Z, range(0, 1250, 50)) colorbar() title('Flow q NS') xlabel('Input flow WE') ylabel('Input flow NS') subtitle("Input flow vs. flow q (WE " + ("poisson" if distrWE == 'p' else "uniform") + ", NS " + ("poisson" if distrNS == 'p' else "uniform") + ", " + tlType + ")") savefig(name + "flowvsq.png") close() max(max(greenWEA), max(greenNSA)) Z = griddata(flowWEA, flowNSA, greenWEA, X, Y) figure(figsize=(12, 12)) subplot(2, 2, 1) contourf(X, Y, Z, range(0, 100, 5)) # clim(0, maxGreen) colorbar() title('Green-time WE') xlabel('Input flow WE') ylabel('Input flow NS') Z = griddata(flowWEA, flowNSA, greenNSA, X, Y) subplot(2, 2, 2) contourf(X, Y, Z, range(0, 100, 5)) # clim(0, maxGreen) colorbar() title('Green-time NS') xlabel('Input flow WE') ylabel('Input flow NS') Z = griddata(qWEA, qNSA, greenWEA, X, Y) greenWECut = [Z[i][i] for i in range(len(Z))] subplot(2, 2, 3) contourf(X, Y, Z, range(0, 100, 5)) # clim(0, maxGreen) colorbar() title('Green-time WE') xlabel('Flow q WE') ylabel('Flow q NS') Z = griddata(qWEA, qNSA, greenNSA, X, Y) greenNSCut = [Z[i][i] for i in range(len(Z))] subplot(2, 2, 4) contourf(X, Y, Z, range(0, 100, 5)) colorbar() title('Green-time NS') xlabel('Flow q WE') ylabel('Flow q NS') subtitle("Green-time (WE " + ("poisson" if distrWE == 'p' else "uniform") + ", NS " + ("poisson" if distrNS == 'p' else "uniform") + ", " + tlType + ")") savefig(name + "GreenTime.png") close() q = X[0] figure() title("CUT (WE " + ("poisson" if distrWE == 'p' else "uniform") + ", NS " + ("poisson" if distrNS == 'p' else "uniform") + ", " + tlType + ")") xlabel('Flow q') plot(q[0:15], avgDelayWECut[0:15], q[0:15], avgDelayNSCut[0:15], q[0:15], avgDelayCut[0:15], q[0:15], greenWECut[0:15], q[0:15], greenNSCut[0:15]) legend(('avgDelayWE', 'avgDelayNS', 'avgDelay', 'greenWE', 'greenNS'), loc='upper left') savefig(name + "CUT.png") close()
import pylab as plt plt.rcParams['axes.labelsize'] = 14 plt.rcParams['legend.fontsize'] = 14 plt.rcParams['axes.titleweight'] = 'bold' plt.rcParams['axes.titlesize'] = 14 # To see all the options: #plt.rcParams.keys() plt.draw() # In[7]: N = 100 X, Y = plt.meshgrid(plt.linspace(depth[:, 0].min(), depth[:, 0].max(), N), plt.linspace(depth[:, 1].min(), depth[:, 1].max(), N)) Z = plt.griddata(depth[:, 0], depth[:, 1], depth[:, 2], X, Y, interp='linear') fig = plt.figure(figsize=(6, 6), dpi=2000) fs = 14 ax = plt.subplot(111) plt.contourf(X, Y, Z, label='depth [m]') #ax.plot(wt_layout.wt_positions[:,0], wt_layout.wt_positions[:,1], 'or', label='baseline position') ax.scatter(wt_layout.wt_positions[:, 0], wt_layout.wt_positions[:, 1], wt_layout._wt_list('rotor_diameter'), label='baseline position') ax.plot(borders[:, 0], borders[:, 1], 'r--', label='border') ax.set_xlabel('x [m]') ax.set_ylabel('y [m]') ax.axis('equal') ax.legend(loc='lower left')
def plotSuccStateError(self, stateSpace, logFile): """ Estimate the error the model makes and plot this to the given logFile """ if self.stateDims is None or self.exampleSet is None: return numberOfSamples = self.exampleSet.states.shape[1] if numberOfSamples <= 3: return succStateModel = lwpr.LWPR(self.stateDims, self.stateDims) succStateModel.init_D = numpy.diag( [self.init_d for i in range(succStateModel.init_D.shape[1])]) # Split data into train and test set trainSet = [] testSet = [] for counter, index in enumerate( numpy.random.permutation(range(numberOfSamples))): sample = (self.exampleSet.states[:, index], self.exampleSet.succStates[:, index], self.exampleSet.rewards[:, index]) if counter < numberOfSamples * 0.66: trainSet.append(sample) else: testSet.append(sample) # Train the model for i in range(10000): transition = random.choice(trainSet) state, succState, reward = transition succStateModel.update(state, succState - state) # Determine error of test set samples errors = {} for transition in testSet: state, succState, reward = transition state = numpy.array(list(state)) succState = numpy.array(list(succState)) errors[tuple(transition[0])] = numpy.linalg.norm( state + succStateModel.predict(state) - succState) # Plot error import pylab import matplotlib pylab.figure(100) contour = pylab.contourf(zip(errors.values(), errors.values())) fig = pylab.figure(0, figsize=(24, 13)) pylab.subplots_adjust( left=0.05, # the left side of the subplots of the figure right=0.95, # the right side of the subplots of the figure bottom=0.05, # the bottom of the subplots of the figure top=0.95, # the top of the subplots of the figure wspace= 0.1, # the amount of width reserved for blank space between subplots hspace= 0.1, # the amount of height reserved for white space between subplots ) fig.clear() normalizer = matplotlib.colors.Normalize( vmin=numpy.min(errors.values()), vmax=numpy.max(errors.values())) for dim1 in range(self.stateDims): for dim2 in range(dim1 + 1, self.stateDims): pylab.subplot(self.stateDims - 1, self.stateDims, (self.stateDims - 1) * dim1 + dim2 + 1) dim1Values = [] dim2Values = [] errorValues = [] for state, error in errors.iteritems(): dim1Values.append(state[dim1]) dim2Values.append(state[dim2]) errorValues.append(error) # define grid. xi = numpy.linspace(0.0, 1.0, 100) yi = numpy.linspace(0.0, 1.0, 100) # grid the data. zi = pylab.griddata(numpy.array(dim2Values), numpy.array(dim1Values), numpy.array(errorValues), xi, yi) # contour the gridded data CS = pylab.contour(xi, yi, zi, 15, linewidths=0.5, colors='k', norm=normalizer) CS = pylab.contourf(xi, yi, zi, 15, norm=normalizer) pylab.xlim(0, 1) pylab.ylim(0, 1) pylab.xlabel(stateSpace.keys()[dim2]) pylab.ylabel(stateSpace.keys()[dim1]) ax = pylab.subplot(self.stateDims - 1, self.stateDims, (self.stateDims - 1) * (self.stateDims - 2) + 1) pylab.colorbar(mappable=contour, cax=ax) # Save the plot to the log file fig.savefig(logFile) fig.clear()
def plotDiagram(name): filename = name + ".dat" X = load(filename) flowWEA = X[:, 0] flowNSA = X[:, 1] qWEA = X[:, 2] qNSA = X[:, 3] avgDelayWEA = X[:, 4] avgDelayNSA = X[:, 5] avgDelayA = X[:, 6] greenWEA = X[:, 7] greenNSA = X[:, 8] filename = name + '.ini' ini = ConfigParser() ini.read(filename) ini.getint("general", "N") ini.getboolean("general", "cut") distrWE = ini.get("demand", "distrWE") distrNS = ini.get("demand", "distrNS") tlType = ini.get("TL", "tlType") vehphWEA = eval(ini.get("demand", "vehphWEA")) vehphNSA = eval(ini.get("demand", "vehphNSA")) max(max(avgDelayWEA), max(avgDelayNSA)) maxD = max(avgDelayA) c = maxD / (exp(1) - 1) [c * (exp(i) - 1) for i in frange(0, 1, 0.01)] [X, Y] = meshgrid(vehphWEA, vehphNSA) Z = griddata(flowWEA, flowNSA, avgDelayWEA, X, Y) figure(figsize=(12, 12)) subplot(2, 2, 1) # contour(X, Y, Z, 100) contourf(X, Y, Z, range(0, 180, 5)) colorbar() title('Average Delay WE') xlabel('Input flow WE') ylabel('Input flow NS') Z = griddata(flowWEA, flowNSA, avgDelayNSA, X, Y) subplot(2, 2, 2) # contour(X, Y, Z, 100) contourf(X, Y, Z, range(0, 180, 5)) colorbar() title('Average Delay NS') xlabel('Input flow WE') ylabel('Input flow NS') Z = griddata(qWEA, qNSA, avgDelayWEA, X, Y) avgDelayWECut = [Z[i][i] for i in range(len(Z))] subplot(2, 2, 3) # contour(X, Y, Z, 100) contourf(X, Y, Z, range(0, 180, 5)) colorbar() title('Average Delay WE') xlabel('Flow q WE') ylabel('Flow q NS') Z = griddata(qWEA, qNSA, avgDelayNSA, X, Y) avgDelayNSCut = [Z[i][i] for i in range(len(Z))] subplot(2, 2, 4) # contour(X, Y, Z, 100) contourf(X, Y, Z, range(0, 180, 5)) colorbar() title('Average Delay NS') xlabel('Flow q WE') ylabel('Flow q NS') subtitle("Average Delay (WE " + ("poisson" if distrWE == 'p' else "uniform") + ", NS " + ("poisson" if distrNS == 'p' else "uniform") + ", " + tlType + ")") savefig(name + "AvgDelayNSWE.png") close() Z = griddata(flowWEA, flowNSA, avgDelayA, X, Y) figure(figsize=(12, 6)) subplot(1, 2, 1) # contour(X, Y, Z, 100) contourf(X, Y, Z, range(0, 180, 5)) colorbar() title('Average Delay') xlabel('Input flow WE') ylabel('Input flow NS') Z = griddata(qWEA, qNSA, avgDelayA, X, Y) avgDelayCut = [Z[i][i] for i in range(len(Z))] subplot(1, 2, 2) # contour(X, Y, Z, 100) contourf(X, Y, Z, range(0, 180, 5)) # clim(0, maxDelay) colorbar() title('Average Delay') xlabel('Flow q WE') ylabel('Flow q NS') subtitle("Average Delay (WE " + ("poisson" if distrWE == 'p' else "uniform") + ", NS " + ("poisson" if distrNS == 'p' else "uniform") + ", " + tlType + ")") savefig(name + "AvgDelay.png") close() Z = griddata(flowWEA, flowNSA, qWEA, X, Y) figure(figsize=(12, 6)) subplot(1, 2, 1) contourf(X, Y, Z, range(0, 1250, 50)) colorbar() title('Flow q WE') xlabel('Input flow WE') ylabel('Input flow NS') Z = griddata(flowWEA, flowNSA, qNSA, X, Y) subplot(1, 2, 2) contourf(X, Y, Z, range(0, 1250, 50)) colorbar() title('Flow q NS') xlabel('Input flow WE') ylabel('Input flow NS') subtitle("Input flow vs. flow q (WE " + ("poisson" if distrWE == 'p' else "uniform") + ", NS " + ("poisson" if distrNS == 'p' else "uniform") + ", " + tlType + ")") savefig(name + "flowvsq.png") close() max(max(greenWEA), max(greenNSA)) Z = griddata(flowWEA, flowNSA, greenWEA, X, Y) figure(figsize=(12, 12)) subplot(2, 2, 1) contourf(X, Y, Z, range(0, 100, 5)) # clim(0, maxGreen) colorbar() title('Green-time WE') xlabel('Input flow WE') ylabel('Input flow NS') Z = griddata(flowWEA, flowNSA, greenNSA, X, Y) subplot(2, 2, 2) contourf(X, Y, Z, range(0, 100, 5)) # clim(0, maxGreen) colorbar() title('Green-time NS') xlabel('Input flow WE') ylabel('Input flow NS') Z = griddata(qWEA, qNSA, greenWEA, X, Y) greenWECut = [Z[i][i] for i in range(len(Z))] subplot(2, 2, 3) contourf(X, Y, Z, range(0, 100, 5)) # clim(0, maxGreen) colorbar() title('Green-time WE') xlabel('Flow q WE') ylabel('Flow q NS') Z = griddata(qWEA, qNSA, greenNSA, X, Y) greenNSCut = [Z[i][i] for i in range(len(Z))] subplot(2, 2, 4) contourf(X, Y, Z, range(0, 100, 5)) colorbar() title('Green-time NS') xlabel('Flow q WE') ylabel('Flow q NS') subtitle("Green-time (WE " + ("poisson" if distrWE == 'p' else "uniform") + ", NS " + ("poisson" if distrNS == 'p' else "uniform") + ", " + tlType + ")") savefig(name + "GreenTime.png") close() q = X[0] figure() title("CUT (WE " + ("poisson" if distrWE == 'p' else "uniform") + ", NS " + ("poisson" if distrNS == 'p' else "uniform") + ", " + tlType + ")") xlabel('Flow q') plot(q[0:15], avgDelayWECut[0:15], q[0:15], avgDelayNSCut[0:15], q[ 0:15], avgDelayCut[0:15], q[0:15], greenWECut[0:15], q[0:15], greenNSCut[0:15]) legend( ('avgDelayWE', 'avgDelayNS', 'avgDelay', 'greenWE', 'greenNS'), loc='upper left') savefig(name + "CUT.png") close()
def convert_to_xyz(args): """ To big to plot? Convert to the PKL file to XYZ and use GMT""" verbose = args.verbose subsample = args.subsample output_file = args.output_file[0] input_file = args.input_file[0] resolution = args.resolution mask_file = args.mask_file[0] grid = args.grid if (verbose): print "Loading data: "+input_file data = pickle.load( open( input_file, "rb" ) ) xi = data[0] yi = data[1] zi = data[2] axes_info = data[3] index_1 = axes_info[0] index_2 = axes_info[1] x_axis = axes_info[2] y_axis = axes_info[3] if (not mask_file == "no_mask"): from Scientific.IO import NetCDF file = NetCDF.NetCDFFile(mask_file, 'r') longitude = file.variables['lon'][:] latitude = file.variables['lat'][:] mask = file.variables['z'][:, :] lon,lat = np.meshgrid(longitude, latitude) lon = np.reshape(lon,len(longitude)*len(latitude)) lat = np.reshape(lat,len(longitude)*len(latitude)) mask = np.reshape(mask,len(longitude)*len(latitude)) # subsample data x = xi[0::subsample] y = yi[0::subsample] z = zi[0::subsample] zi = z yi = y xi = x z =[];x=[];y=[] if (grid): if (verbose): print "Creating uniform mesh" # Need to have different numebr of points for X and Y # Warning or error if n points is huge X, Y = np.meshgrid(np.linspace( xi.min(), xi.max(), (180./resolution)+1), np.linspace(yi.min(), yi.max(), (360./resolution)+1)) Z = pylab.griddata(xi, yi, zi, X, Y) if (not mask_file == "no_mask"): mask_grd = pylab.griddata(lat, lon, mask, X, Y) # loop over mask_grd. Where land, set Z to NaN, which will mask out these areas in the plot for i in range(0,len(mask_grd)): for j in range(0,len(mask_grd[0])): if (mask_grd[i][j] == 0): Z[i][j] = float('NaN') f = open(output_file,"w") for i in range(0,len(X)): for j in range(0,len(Y[0])): val = Z[i][j] # skip NaNs - GMT fills them in for us if (str(val) == "--"): continue f.write(str(Y[i][j])+" "+str(X[i][j])+" "+str(Z[i][j])+"\n") f.close() else: f = open(output_file,"w") for i in range(0,len(xi)): val = zi[i] # skip NaNs - GMT fills them in for us if (str(val) == "--"): continue f.write(str(yi[i])+" "+str(xi[i])+" "+str(zi[i])+"\n") f.close()
import pylab as plt plt.rcParams['axes.labelsize'] = 14 plt.rcParams['legend.fontsize'] = 14 plt.rcParams['axes.titleweight'] = 'bold' plt.rcParams['axes.titlesize'] = 14 # To see all the options: #plt.rcParams.keys() plt.draw() # In[7]: N = 100 X, Y = plt.meshgrid(plt.linspace(depth[:,0].min(), depth[:,0].max(), N), plt.linspace(depth[:,1].min(), depth[:,1].max(), N)) Z = plt.griddata(depth[:,0],depth[:,1],depth[:,2],X,Y, interp='linear') fig = plt.figure(figsize=(6,6), dpi=2000) fs = 14 ax = plt.subplot(111) plt.contourf(X,Y,Z, label='depth [m]') #ax.plot(wt_layout.wt_positions[:,0], wt_layout.wt_positions[:,1], 'or', label='baseline position') ax.scatter(wt_layout.wt_positions[:,0], wt_layout.wt_positions[:,1], wt_layout._wt_list('rotor_diameter'), label='baseline position') ax.plot(borders[:,0], borders[:,1], 'r--', label='border') ax.set_xlabel('x [m]'); ax.set_ylabel('y [m]') ax.axis('equal'); ax.legend(loc='lower left') plt.colorbar().set_label('water depth [m]') plt.draw()
def hitlist2int(x, y, z, xi, yi): """Function that estimates an intensity distribution on a plane from a ray hitlist """ import matplotlib.delaunay as delaunay from pylab import griddata, meshgrid from scipy import interpolate #if xi.ndim != yi.ndim: # raise TypeError("inputs xi and yi must have same number of dimensions (1 or 2)") #if xi.ndim != 1 and xi.ndim != 2: # raise TypeError("inputs xi and yi must be 1D or 2D.") #if not len(x)==len(y)==len(z): # raise TypeError("inputs x,y,z must all be 1D arrays of the same length") # remove masked points. #if hasattr(z,'mask'): # x = x.compress(z.mask == False) # y = y.compress(z.mask == False) # z = z.compressed() #if xi.ndim == 1: # xi,yi = meshgrid(xi,yi) #triangulate data tri=delaunay.Triangulation(x, y) #calculate triangles area ntriangles=tri.circumcenters.shape[0] coord=array(zip(tri.x, tri.y)) #I=zeros((ntriangles, )) #xc=zeros((ntriangles, )) #yc=zeros((ntriangles, )) # for i in range(ntriangles): # i1, i2, i3=tri.triangle_nodes[i] # p1=coord[i1] # p2=coord[i2] # p3=coord[i3] # v1=p1-p2 # v2=p3-p2 # I[i]=1./(abs(v1[0]*v2[1]-v1[1]*v2[0])) # # the circumcenter data from the triangulation, has some problems so we # # recalculate it # xc[i], yc[i]=(p1+p2+p3)/3. # The previous code was replaced by the following code ### i1=tri.triangle_nodes[:, 0] i2=tri.triangle_nodes[:, 1] i3=tri.triangle_nodes[:, 2] p1=coord[i1] p2=coord[i2] p3=coord[i3] v1=p1-p2 v2=p3-p2 I=abs(1./(v1[:, 0]*v2[:, 1]-v1[:, 1]*v2[:, 0])) c=(p1+p2+p3)/3. xc=c[:, 0] yc=c[:, 1] ### # Because of the triangulation algorithm, there are some really high values # in the intensity data. To filter these values, remove the 5% points of the # higher intensity. ni=int(0.1*len(I)) j=I.argsort()[:-ni] xc=xc[j] yc=yc[j] I=I[j] I=I/I.max() # #print tri.circumcenters[:, 0] # #print tri.circumcenters.shape # print ntriangles, tri.circumcenters[:, 0].shape, tri.circumcenters[:, 0].flatten().shape #itri=delaunay.Triangulation(xc,yc) #inti=itri.linear_interpolator(I) #xi,yi = meshgrid(xi,yi) #d1=itri(xi, yi) #Interpolacion con Splines #di=interpolate.SmoothBivariateSpline(xc, yc, I) #d1=di(xi,yi) #Interpolacion nn, y generaciĆ³n de pupila xi,yi = meshgrid(xi,yi) d1=griddata(xc, yc, I,xi, yi ) return d1
def griddata(x, xres, y, yres, z): yi = N.linspace(-2, N.max(y)+0.5, yres) xi = N.linspace(N.min(x)-0.5, 4.5, xres) X, Y = N.meshgrid(xi,yi) Z = P.griddata(x,y,z,xi, yi) return X, Y, Z
def scatter2gridded (scatterdatafile=" ",boundarydatafile=" ", headerfile=" ", outputfile=" "): """ scatter2gridded (scatterdatafile=" ",boundarydatafile=" ", headerfile=" ", outputfile=" "): function converts scattered data points (x,y,z) into gridded data, with z values given at uniformly spaced points. 'scatterdatafile' and optional 'boundarydatafile' should each have three columns containing x,y,z coordinates respectively of each point. 'headerfile' specifies the format of the grid parameters for the output data. The header should have the following form: int ncols int nrows float xll float yll float cellsize float nodata_value see topotools.headerwriter and topotools.headerreader. 'outputfile' will have the same header followed by the data advancing from northwest across eastward then down, one z value per row. """ import pylab # Input data==========================: # read scattered data fin=open(scatterdatafile,'r') a=fromfile(fin,sep=" ",count=-1,dtype=float) fin.close #read boundary data ie: points specifying a quadrilateral bounding the scattered data if it is needed if boundarydatafile !=" " : fin=open(boundarydatafile,'r') b=fromfile(fin,sep=" ",count=-1,dtype=float) fin.close a=np.hstack((a,b)) #reshape data into (#pts , 3) array pts=len(a)/3 a=np.reshape(a,(pts,3)) #determine what the output grid will look like from headerfile topoheader=topoheaderread(inputfile=headerfile) # manipulate data============================: #Create the gridded data using pylab "griddata function." xgrid = np.arange(topoheader['xll'], \ topoheader['xll']+topoheader['ncols']*topoheader['cellsize'], \ step=topoheader['cellsize'],dtype=float) ygrid = np.arange(topoheader['yll'], \ topoheader['yll']+topoheader['nrows']*topoheader['cellsize'], \ step=topoheader['cellsize'],dtype=float) X,Y=np.meshgrid(xgrid,ygrid) Z = pylab.griddata(a[:,0],a[:,1],a[:,2],X,Y) Y=np.flipud(Y) Z=np.flipud(Z) # pyplot.contour(X,Y,Z) #write the output file =====================: if outputfile != " ": fout=topoheaderwrite(topoheader,outputfile,closefile=False) for i in xrange(topoheader['nrows']) : for j in xrange(topoheader['ncols']) : fout.write("%s\n" % Z[i,j]) fout.close() return (X,Y,Z)
def pre_plot(self): plt.ion() #plt.show() ### Plot the water depth N = 100 self.X, self.Y = plt.meshgrid( plt.linspace(self.depth[:, 0].min(), self.depth[:, 0].max(), N), plt.linspace(self.depth[:, 1].min(), self.depth[:, 1].max(), N)) self.Z = plt.griddata(self.depth[:, 0], self.depth[:, 1], self.depth[:, 2], self.X, self.Y, interp='linear') Zin = points_in_poly(self.X, self.Y, self.borders) self.Z.mask = Zin.__neg__() #Z.mask = False #Z.data[Zin.__neg__()] = -20.0 display(plt.gcf()) # def refresh(self): self.shape_plot.clear() self.shape_plot.contourf(self.X, self.Y, self.Z, 10, vmax=self.depth[:, 2].max()) #, cmap=self.pal self.shape_plot.set_aspect('equal') self.shape_plot.autoscale(tight=True) Plot = lambda b, *args, **kwargs: self.shape_plot.plot( b[:, 0], b[:, 1], *args, **kwargs) if self.distribution == 'spiral': spiral = lambda t_, a_, x_: [ a_ * t_**(1. / x_) * np.cos(t_), a_ * t_** (1. / x_) * np.sin(t_) ] spirals = lambda ts_, a_, x_: np.array( [spiral(t_, a_, x_) for t_ in ts_]) for P in self.baseline: Plot(P + spirals(plt.linspace(0., 10 * np.pi, 1000), self.spiral_param, 1.), 'g-', linewidth=0.1) self.shape_plot.plot(self.borders[:, 0], self.borders[:, 1], 'k-') self.posi = self.shape_plot.plot(self.wt_positions[:, 0], self.wt_positions[:, 1], 'ro') self.plotel = self.shape_plot.plot( np.array([ self.baseline[[i, j], 0] for i, j in self.elnet_layout.keys() ]).T, np.array([ self.baseline[[i, j], 1] for i, j in self.elnet_layout.keys() ]).T, 'y--', linewidth=1) #print self.plotel self.objf_plot.clear() targarr = np.array(self.targvalue) self.posb = [] for i in range(targarr.shape[1]): self.posb.append( self.objf_plot.plot(self.iterations, self.targvalue[0][i], '.', label=self.targname[i])) print 'posb', self.posb self.legend = self.objf_plot.legend(loc=3, bbox_to_anchor=(1.1, 0.0)) plt.title('Foundation = %8.2f' % (self.foundation_length)) plt.draw()
def plot_results(self, node_param_list=None, vmin=None, vmax=None, cmap=None, log_x=False, axes=None, title=None, plot_variance=True): ''' Plot the results of the optimization. Works for 1D and 2D linear sweeps, yielding a 2D resp. 3D plot of the parameter(s) vs. the error. Arguments: - node_param_list: a list of (node, param_string) tuples. Before plotting, the mean will be taken over all these node.param_string combinations, which is useful to plot/reduce multi-dimensional parameter sweeps. - vmin/vmax: can be used to truncate the errors between lower and upper bounds before plotting. - cmap: passed as a matplotlib colormap when plotting 2D images. - log_x: boolean to indicate if a 1D plot should use a log scale for the x-axis. - axes: optional Axes object to use for plotting - title: optional title for the plot - plot_variance: should variance be plotted in case of taking the mean over certain parameters. Default True. ''' try: import pylab except ImportError: print "It looks like matplotlib isn't installed. Plotting is impossible." return if axes is None: axes = pylab.axes() errors_to_plot, var_errors, parameters = self.mean_and_var( node_param_list) if vmin != None: errors_to_plot[errors_to_plot < vmin] = vmin if vmax != None: errors_to_plot[errors_to_plot > vmax] = vmax # If we have ranged over only one parameter if len(parameters) == 1: # Get the index of the remaining parameter to plot using the correct # parameter ranges param_index = self.parameters.index(parameters[0]) if var_errors is not None and plot_variance: pylab.errorbar(self.parameter_ranges[param_index], errors_to_plot, var_errors, axes=axes) else: if log_x: pylab.semilogx(self.parameter_ranges[param_index], errors_to_plot, axes=axes) else: pylab.plot(self.parameter_ranges[param_index], errors_to_plot, axes=axes) pylab.xlabel(str(parameters[0][0]) + '.' + parameters[0][1]) pylab.ylabel(self.loss_function.__name__) if title is not None: pylab.title(title) pylab.show() elif len(parameters) == 2: # Get the extreme values of the parameter values p1 = self.parameters.index(parameters[0]) p2 = self.parameters.index(parameters[1]) xm = mdp.numx.amin(self.parameter_ranges[p1]) ym = mdp.numx.amin(self.parameter_ranges[p2]) xM = mdp.numx.amax(self.parameter_ranges[p1]) yM = mdp.numx.amax(self.parameter_ranges[p2]) # For optimization algorithms which have non-uniform sampling of the parameter space, we interpolate here # This has no effect on the plot for optimizations using gridsearch xi = mdp.numx.linspace(xm, xM, len(self.parameter_ranges[p1])) yi = mdp.numx.linspace(ym, yM, len(self.parameter_ranges[p2])) (x, y) = mdp.numx.meshgrid(self.parameter_ranges[p1], self.parameter_ranges[p2]) # Create an interpolation grid zi = mdp.numx.fliplr( pylab.griddata(x.flatten(), y.flatten(), errors_to_plot.flatten('F'), xi, yi)).T pylab.imshow(zi, cmap=pylab.jet(), interpolation='nearest', extent=self.get_extent(parameters), aspect="auto", axes=axes) pylab.xlabel(str(parameters[1][0]) + '.' + parameters[1][1]) pylab.ylabel(str(parameters[0][0]) + '.' + parameters[0][1]) if title is not None: pylab.suptitle(title) pylab.colorbar() if var_errors is not None and plot_variance: pylab.figure() pylab.imshow(mdp.numx.flipud(var_errors), cmap=cmap, interpolation='nearest', extent=self.get_extent(parameters), aspect="auto", vmin=vmin, vmax=vmax) pylab.xlabel(str(parameters[1][0]) + '.' + parameters[1][1]) pylab.ylabel(str(parameters[0][0]) + '.' + parameters[0][1]) pylab.suptitle('variance') pylab.colorbar() pylab.show() else: raise Exception("Too many parameter dimensions to plot: " + str(errors_to_plot.ndim))
def plot_results(self, node_param_list=None, vmin=None, vmax=None, cmap=None, log_x=False, axes=None, title=None, plot_variance=True): ''' Plot the results of the optimization. Works for 1D and 2D linear sweeps, yielding a 2D resp. 3D plot of the parameter(s) vs. the error. Arguments: - node_param_list: a list of (node, param_string) tuples. Before plotting, the mean will be taken over all these node.param_string combinations, which is useful to plot/reduce multi-dimensional parameter sweeps. - vmin/vmax: can be used to truncate the errors between lower and upper bounds before plotting. - cmap: passed as a matplotlib colormap when plotting 2D images. - log_x: boolean to indicate if a 1D plot should use a log scale for the x-axis. - axes: optional Axes object to use for plotting - title: optional title for the plot - plot_variance: should variance be plotted in case of taking the mean over certain parameters. Default True. ''' try: import pylab except ImportError: print "It looks like matplotlib isn't installed. Plotting is impossible." return if axes is None: axes = pylab.axes() errors_to_plot, var_errors, parameters = self.mean_and_var(node_param_list) if vmin != None: errors_to_plot[errors_to_plot < vmin] = vmin if vmax != None: errors_to_plot[errors_to_plot > vmax] = vmax # If we have ranged over only one parameter if len(parameters) == 1: # Get the index of the remaining parameter to plot using the correct # parameter ranges param_index = self.parameters.index(parameters[0]) if var_errors is not None and plot_variance: pylab.errorbar(self.parameter_ranges[param_index], errors_to_plot, var_errors, axes=axes) else: if log_x: pylab.semilogx(self.parameter_ranges[param_index], errors_to_plot, axes=axes) else: pylab.plot(self.parameter_ranges[param_index], errors_to_plot, axes=axes) pylab.xlabel(str(parameters[0][0]) + '.' + parameters[0][1]) pylab.ylabel(self.loss_function.__name__) if title is not None: pylab.title(title) pylab.show() elif len(parameters) == 2: # Get the extreme values of the parameter values p1 = self.parameters.index(parameters[0]) p2 = self.parameters.index(parameters[1]) xm = mdp.numx.amin(self.parameter_ranges[p1]) ym = mdp.numx.amin(self.parameter_ranges[p2]) xM = mdp.numx.amax(self.parameter_ranges[p1]) yM = mdp.numx.amax(self.parameter_ranges[p2]) # For optimization algorithms which have non-uniform sampling of the parameter space, we interpolate here # This has no effect on the plot for optimizations using gridsearch xi = mdp.numx.linspace(xm, xM, len(self.parameter_ranges[p1])) yi = mdp.numx.linspace(ym, yM, len(self.parameter_ranges[p2])) (x, y) = mdp.numx.meshgrid(self.parameter_ranges[p1], self.parameter_ranges[p2]) # Create an interpolation grid zi = mdp.numx.fliplr(pylab.griddata(x.flatten(), y.flatten(), errors_to_plot.flatten('F'), xi, yi)).T pylab.imshow(zi, cmap=pylab.jet(), interpolation='nearest', extent=self.get_extent(parameters), aspect="auto", axes=axes) pylab.xlabel(str(parameters[1][0]) + '.' + parameters[1][1]) pylab.ylabel(str(parameters[0][0]) + '.' + parameters[0][1]) if title is not None: pylab.suptitle(title) pylab.colorbar() if var_errors is not None and plot_variance: pylab.figure() pylab.imshow(mdp.numx.flipud(var_errors), cmap=cmap, interpolation='nearest', extent=self.get_extent(parameters), aspect="auto", vmin=vmin, vmax=vmax) pylab.xlabel(str(parameters[1][0]) + '.' + parameters[1][1]) pylab.ylabel(str(parameters[0][0]) + '.' + parameters[0][1]) pylab.suptitle('variance') pylab.colorbar() pylab.show() else: raise Exception("Too many parameter dimensions to plot: " + str(errors_to_plot.ndim))