def plotField(x, F, titleStr, filename): import pylab as p import griddata as g import numpy p.ion() p.clf() xhat = Vector3d(1, 0, 0) yhat = Vector3d(0, 1, 0) numInternalNodes = len(x.internalValues()) indices = [i for i in xrange(numInternalNodes) if abs(x[i].z) < 1e-8] xs = numpy.array([x[i].dot(xhat) for i in indices]) ys = numpy.array([x[i].dot(yhat) for i in indices]) x1 = p.linspace(-0.5, 1.5, 50) y1 = p.linspace(-0.5, 1.5, 50) xg, yg = p.meshgrid(x1, y1) if isinstance(F, VectorField3d) or isinstance(F[0], Vector3d): Fxs = numpy.array([F[i].dot(xhat) for i in indices]) Fys = numpy.array([F[i].dot(yhat) for i in indices]) Fxg = g.griddata(xs, ys, Fxs, xg, yg) Fyg = g.griddata(xs, ys, Fys, xg, yg) p.quiver(xg, yg, Fxg, Fyg) else: # levels = [0.1*i for i in xrange(32)] Fs = numpy.array([F[i] for i in indices]) Fg = g.griddata(xs, ys, Fs, xg, yg) p.contour(xg, yg, Fg, 30) p.colorbar() p.title(titleStr) p.savefig(filename)
def gen_windfiles(windata, grid, steeringtimes, model_config, output_path): if (windata == None): quit('\n CANNOT GENERATE INPUT FILE: MISSING WIND DATA \n') #import constants tmpdir = tempfile.gettempdir() nx = int(model_config['nx']) ny = int(model_config['ny']) winspeed = windata['speed'] windir = windata['dir'] wintime = windata['time'] winx = windata['x'] winy = windata['y'] gridx = array(grid[0]) gridy = array(grid[1]) ugrid, vgrid = [[], []] windfn = '/'.join([tmpdir, 'wind.dat']) avewindfn = '/'.join([tmpdir, 'avewind.dat']) winfile = open(windfn, 'w') avewinfile = open(avewindfn, 'w') line = str(nx) + ' ' + str(ny) + '\n' winfile.write(line) for mytime in steeringtimes: filter = (wintime == mytime) if (all(filter == False)): #CANT HANDLE MISSING DATA quit('\n\nno data exists for time: ' + str(mytime) + '\n\n') else: #INTERPOLATE SINGLE TIMESTEP myx = winx[filter] myy = winy[filter] vel_x = winspeed[filter] * map(cos, windir[filter]) vel_y = winspeed[filter] * map(sin, windir[filter]) newvel_x = griddata(myx, myy, vel_x, gridx, gridy) newvel_y = griddata(myx, myy, vel_y, gridx, gridy) avevel_x = mean(newvel_x) avevel_y = mean(newvel_y) win_speed = sqrt(avevel_x**2 + avevel_y**2) win_dir = degrees(atan2(avevel_y, avevel_x)) #WRITE SINGLE TIMESTEP TO INPUT FILE winfile.write(mytime.strftime('%m%d%H') + '\n') lines = [ '\n'.join([ ' '.join([ str(newvel_x[i][j]) + ' ' + str(newvel_y[i][j]) for j in range(nx) ]) ]) for i in range(ny)[::-1] ] lines = '\n'.join(lines) winfile.write(lines + '\n') avewinfile.write('{0} {1}\n'.format(win_speed, win_dir)) winfile.close() avewinfile.close() os.system('mv ' + windfn + ' ' + output_path) os.system('mv ' + avewindfn + ' ' + output_path + '.ave') return
def gen_windfiles(windata,grid,steeringtimes,model_config,output_path): if (windata==None): quit('\n CANNOT GENERATE INPUT FILE: MISSING WIND DATA \n') #import constants tmpdir = tempfile.gettempdir() nx = int(model_config['nx']) ny = int(model_config['ny']) winspeed = windata['speed'] windir = windata['dir'] wintime = windata['time'] winx = windata['x'] winy = windata['y'] gridx=array(grid[0]) gridy=array(grid[1]) ugrid,vgrid=[[],[]] windfn = '/'.join([tmpdir,'wind.dat']) avewindfn = '/'.join([tmpdir,'avewind.dat']) winfile = open(windfn,'w') avewinfile = open(avewindfn, 'w') line = str(nx)+' '+str(ny)+'\n' winfile.write(line) for mytime in steeringtimes: filter = (wintime==mytime) if (all(filter==False)): #CANT HANDLE MISSING DATA quit('\n\nno data exists for time: '+str(mytime)+'\n\n') else: #INTERPOLATE SINGLE TIMESTEP myx = winx[filter] myy = winy[filter] vel_x = winspeed[filter]*map(cos,windir[filter]) vel_y = winspeed[filter]*map(sin,windir[filter]) newvel_x = griddata(myx,myy,vel_x,gridx,gridy) newvel_y = griddata(myx,myy,vel_y,gridx,gridy) avevel_x = mean(newvel_x) avevel_y = mean(newvel_y) win_speed = sqrt(avevel_x**2 + avevel_y**2) win_dir = degrees(atan2(avevel_y, avevel_x)) #WRITE SINGLE TIMESTEP TO INPUT FILE winfile.write(mytime.strftime('%m%d%H')+'\n') lines = ['\n'.join([' '.join([str(newvel_x[i][j])+' '+ str(newvel_y[i][j]) for j in range(nx)])]) for i in range(ny)[::-1]] lines = '\n'.join(lines) winfile.write(lines+'\n') avewinfile.write('{0} {1}\n'.format(win_speed, win_dir)) winfile.close() avewinfile.close() os.system('mv ' + windfn + ' ' + output_path) os.system('mv ' + avewindfn + ' ' + output_path + '.ave') return
def fig3(isos,isow): """ Plot contour diagram of isochrone weights """ x,y,z = isovalues(isos,isow) zz = z/sum(z.flat) # xi,yi = pylab.meshgrid(pylab.linspace(8.8,10.3,100),pylab.linspace(-2.5,0.9,100)) # zi = griddata.griddata(x,y,zz,xi,yi) xi,yi = pylab.meshgrid(pylab.linspace(0.5,15,100),pylab.linspace(-2.5,0.9,100)) zi = griddata.griddata(10.**x/1.e9,y,zz,xi,yi) pylab.contourf(xi,yi,zi,20) pylab.xlabel('Age (Gyr)') pylab.ylabel('[Fe/H]') return x,y,z
def fig3(isos, isow): """ Plot contour diagram of isochrone weights """ x, y, z = isovalues(isos, isow) zz = z / sum(z.flat) # xi,yi = pylab.meshgrid(pylab.linspace(8.8,10.3,100),pylab.linspace(-2.5,0.9,100)) # zi = griddata.griddata(x,y,zz,xi,yi) xi, yi = pylab.meshgrid(pylab.linspace(0.5, 15, 100), pylab.linspace(-2.5, 0.9, 100)) zi = griddata.griddata(10.**x / 1.e9, y, zz, xi, yi) pylab.contourf(xi, yi, zi, 20) pylab.xlabel('Age (Gyr)') pylab.ylabel('[Fe/H]') return x, y, z
def bin_cc_index(self, c1I, c2I, h5Path): """Bin the mag table into a colour colour diagram. Produces an color-color table with indexes into models in the mags HDF5 table. Parameters ---------- c1I : tuple of two str Names of the two bands that make the first colour c2I : tuple of two str Names of the two bands that make the second colour """ h5file = tables.openFile(h5Path, mode='a') magTable = h5file.root.mags c1 = np.array([x[c1I[0]]-x[c1I[1]] for x in magTable]) c2 = np.array([x[c2I[0]]-x[c2I[1]] for x in magTable]) mass = np.array([x['mass'] for x in magTable]) logL = np.array([x['lbol'] for x in magTable]) logML = mass - logL grid, gridN, wherebin = griddata(c1, c2, logML, binsize=0.05, retbin=True, retloc=True) print "grid", grid.shape # Set up the cc table if 'cc' in h5file.root: print "cc already exists" h5file.root.cc._f_remove() ccDtype = np.dtype([('c1',np.float),('c2',np.float),('xi',np.int), ('yi',np.int),('ml',np.float),('nmodels',np.int)]) ccTable = h5file.createTable("/", 'cc', ccDtype, "CC Table %s-%s %s-%s" % (c1I[0],c1I[1],c2I[0],c2I[1])) ny, nx = grid.shape c1colors = np.arange(c1.min(), c1.max()+0.05, 0.05) c2colors = np.arange(c2.min(), c2.max()+0.05, 0.05) print "c1 range:", c1.min(), c1.max() print "c2 range:", c2.min(), c2.max() for i in xrange(ny): for j in xrange(nx): ccTable.row['c1'] = float(c1colors[j]) ccTable.row['c2'] = float(c2colors[i]) ccTable.row['yi'] = i ccTable.row['xi'] = j ccTable.row['ml'] = grid[i,j] ccTable.row['nmodels'] = int(gridN[i,j]) print gridN[i,j] ccTable.row.append() h5file.flush() h5file.close()
plt.xlabel('Y') plt.ylabel('V') # now show the dependent data (x vs y). we could represent the v data # as a third axis by either a 3d plot or contour plot, but we need to # grid it first.... plt.plot(x, y, '.') plt.title('X vs Y') plt.xlabel('X') plt.ylabel('Y') # enter the gridding. imagine drawing a symmetrical grid over the # plot above. the binsize is the width and height of one of the grid # cells, or bins in units of x and y. binsize = 5 grid, bins, binloc = griddata.griddata(X, Y, V, binsize=binsize) # see this routine's docstring # minimum values for colorbar. filter our nans which are in the grid vmin = grid[np.where(np.isnan(grid) == False)].min() vmax = grid[np.where(np.isnan(grid) == False)].max() # colorbar stuff palette = plt.matplotlib.colors.LinearSegmentedColormap('jet3',plt.cm.datad['jet'],2048) palette.set_under(alpha=0.0) # plot the results. first plot is x, y vs v, where v is a filled level plot. extent = (X.min(), X.max(), Y.min(), Y.max()) # extent of the plot #plt.subplot(1, 2, 1) plt.imshow(grid, extent=extent, cmap=palette, origin='lower', vmin=vmin, vmax=vmax, aspect='auto', interpolation='bicubic') plt.xlabel(r'$X\, [\mu m]$')
def survey_dbg_image(request, id=0, size=900, cat='pickles'): if request.method == 'GET': if request.GET.has_key('cat'): cat = request.GET.get('cat') image_obj = Images.objects.get(id=id) filename = fix_remote_path(image_obj.filename, image_obj.channel_id) darkname = find_image(image_obj.time, 'dark', image_obj.channel_id) darkname = fix_remote_path(darkname, image_obj.channel_id) flatname = find_image(image_obj.time, 'flat', image_obj.channel_id) flatname = fix_remote_path(flatname, image_obj.channel_id) data = pyfits.getdata(filename, -1) header = pyfits.getheader(filename, -1) # Prepare if posixpath.exists(darkname): dark = pyfits.getdata(darkname, -1) data -= dark if posixpath.exists(flatname): flat = pyfits.getdata(flatname, -1) data *= np.mean(flat) / flat # Calibrate obj = survey.get_objects_from_file(filename, simple=False, filter=True) wcs = pywcs.WCS(header) ra0, dec0, sr0 = survey.get_frame_center(header=header, wcs=wcs) print filename, '-', ra0, dec0, sr0 favor2 = Favor2() if cat == 'apass': cat = favor2.get_stars(ra0, dec0, sr0, catalog='apass', limit=600000, extra=[ "g<14 and g>8.5", "b<20 and v<20 and r<20 and i<20 and g<20", "var = 0", "gerr>0 and rerr>0 and ierr>0" ]) else: cat = favor2.get_stars(ra0, dec0, sr0, catalog='pickles', limit=200000, extra=["var = 0", "rank=1"]) print "%d objects, %d stars" % (len(obj['ra']), len(cat['ra'])) survey.fix_distortion(obj, cat, header=header) Y, YY, corr, oidx = survey.calibrate_objects(obj, cat, sr=10. / 3600, retval='all') # Plot dpi = 72 figsize = (size / dpi, size * 4 * 0.6 / dpi) fig = Figure(facecolor='white', figsize=figsize, tight_layout=True) # 1 ax = fig.add_subplot(411) limits = np.percentile(data, [0.5, 99.5]) i = ax.imshow(data, origin='lower', cmap='hot', interpolation='nearest', vmin=limits[0], vmax=limits[1]) fig.colorbar(i) ax.set_title( "%d / %s / ch=%d at %s" % (image_obj.id, image_obj.type, image_obj.channel_id, image_obj.time)) # 2 ax = fig.add_subplot(412) gmag0, bins, binloc = griddata(obj['x'][oidx], obj['y'][oidx], Y, binsize=100) limits = np.percentile(gmag0[np.isfinite(gmag0)], [0.5, 95.5]) i = ax.imshow(gmag0, origin='lower', extent=[0, header['NAXIS1'], 0, header['NAXIS2']], interpolation='nearest', vmin=limits[0], vmax=limits[1]) fig.colorbar(i) ax.autoscale(False) ax.plot(obj['x'][oidx], obj['y'][oidx], 'b.', alpha=0.3) ax.set_title("Actual zero point") # 3 ax = fig.add_subplot(413) gmag0, bins, binloc = griddata(obj['x'][oidx], obj['y'][oidx], YY, binsize=100) #limits = np.percentile(gmag0[np.isfinite(gmag0)], [0.5, 95.5]) i = ax.imshow(gmag0, origin='lower', extent=[0, header['NAXIS1'], 0, header['NAXIS2']], interpolation='nearest', vmin=limits[0], vmax=limits[1]) fig.colorbar(i) ax.autoscale(False) ax.plot(obj['x'][oidx], obj['y'][oidx], 'b.', alpha=0.3) ax.set_title("Fitted zero point") # 4 ax = fig.add_subplot(414) gmag0, bins, binloc = griddata(obj['x'][oidx], obj['y'][oidx], Y - YY, binsize=100) limits = np.percentile(gmag0[np.isfinite(gmag0)], [0.5, 95.5]) i = ax.imshow(gmag0, origin='lower', extent=[0, header['NAXIS1'], 0, header['NAXIS2']], interpolation='nearest', vmin=limits[0], vmax=limits[1]) fig.colorbar(i) ax.autoscale(False) ax.plot(obj['x'][oidx], obj['y'][oidx], 'b.', alpha=0.3) ax.set_title("Zero point residuals. std=%g" % np.std(Y - YY)) canvas = FigureCanvas(fig) response = HttpResponse(content_type='image/png') canvas.print_png(response) return response
def topoplot(values=None, axes=None, center=(0,0), nose_dir=0., radius=0.5, sensors=None, colors=('black','black','black'), linewidths=(3,2,2,0.5), contours_ls='-', contours=15, resolution=400, cmap=None, axis_props='off', plot_mask='circular'): """ Plot a topographic map of the scalp in a 2-D circular view (looking down at the top of the head). Parameters ---------- values : {None, array-like}, optional Values to plot. There must be one value for each electrode. axes : {matplotlib.axes}, optional Axes to which the topoplot should be added. center : {tuple of floats}, optional x and y coordinates of the center of the head. nose_dir : {float}, optional Angle (in degrees) where the nose is pointing. 0 is up, 90 is left, 180 is down, 270 is right, etc. radius : {float}, optional Radius of the head. sensors : {None, tuple of floats}, optional Polar coordinates of the sensor locations. If not None, sensors[0] specifies the angle (in degrees) and sensors[1] specifies the radius. colors : {tuple of str or None}, optional Colors for the outline of the head, sensor markers, and contours respectively. If any is None, the corresponding feature is not plotted. For contours either a single color or multiple colors can be specified. linewidths : {tuple of floats}, optional Line widths for the head, nose, ears, and contours respectively. For contours either a single linewith or multiple linewidths can be specified. contours_ls : {str}, optional Line style of the contours. contours : {int}, optional Number of countours. resolution : {int}, optional Resolution of the interpolated grid. Higher numbers give smoother edges of the plot, but increase memory and computational demands. cmap : {None,matplotlib.colors.LinearSegmentedColormap}, optional Color map for the contour plot. If colMap==None, the default color map is used. axis_props : {str}, optional Axis properties. plot_mask : {str}, optional The mask around the plotted values. 'linear' conects the outer electrodes with straight lines, 'circular' draws a circle around the outer electrodes, and 'square' (or any other value) draws a square around the electrodes. """ # If no colormap is specified, use default colormap: if cmap is None: cmap = plt.get_cmap() if axes is not None: # axes are given a=axes else: # a new subplot is created a=plt.subplot(1,1,1, aspect='equal') plt.axis(axis_props) if colors[0]: # head should be plotted # Set up head head = plt.Circle(center, radius,fill=False, linewidth=linewidths[0], edgecolor=colors[0]) # Nose: nose_width = 0.18*radius # Distance from the center of the head to the point where the # nose touches the outline of the head: nose_dist = np.cos(np.arcsin((nose_width/2.)/radius))*radius # Distance from the center of the head to the tip of the nose: nose_tip_dist = 1.15*radius # Convert to polar coordinates for rotating: nose_polar_angle,nose_polar_radius = cart2pol( np.array([-nose_width/2,0,nose_width/2]), np.array([nose_dist,nose_tip_dist,nose_dist])) nose_polar_angle = nose_polar_angle+deg2rad(nose_dir) # And back to cartesian coordinates for plotting: nose_x,nose_y = pol2cart(nose_polar_angle,nose_polar_radius) # Move nose with head: nose_x = nose_x + center[0] nose_y = nose_y + center[1] nose = plt.Line2D(nose_x,nose_y,color=colors[0],linewidth=linewidths[1], solid_joinstyle='round',solid_capstyle='round') # Ears: q = .04 # ear lengthening ear_x = np.array([.497-.005,.510,.518,.5299, .5419,.54,.547,.532,.510,.489-.005])*(radius/0.5) ear_y = np.array([q+.0555,q+.0775,q+.0783,q+.0746,q+.0555, -.0055,-.0932,-.1313,-.1384,-.1199])*(radius/0.5) # Convert to polar coordinates for rotating: rightear_polar_angle,rightear_polar_radius = cart2pol(ear_x,ear_y) leftear_polar_angle,leftear_polar_radius = cart2pol(-ear_x,ear_y) rightear_polar_angle=rightear_polar_angle+deg2rad(nose_dir) leftear_polar_angle=leftear_polar_angle+deg2rad(nose_dir) # And back to cartesian coordinates for plotting: rightear_x,rightear_y=pol2cart(rightear_polar_angle, rightear_polar_radius) leftear_x,leftear_y=pol2cart(leftear_polar_angle,leftear_polar_radius) # Move ears with head: rightear_x = rightear_x + center[0] rightear_y = rightear_y + center[1] leftear_x = leftear_x + center[0] leftear_y = leftear_y + center[1] ear_right = plt.Line2D(rightear_x,rightear_y,color=colors[0], linewidth=linewidths[3],solid_joinstyle='round', solid_capstyle='round') ear_left = plt.Line2D(leftear_x,leftear_y,color=colors[0], linewidth=linewidths[3],solid_joinstyle='round', solid_capstyle='round') a.add_artist(head) a.add_artist(nose) a.add_artist(ear_right) a.add_artist(ear_left) if sensors is None: if axes is None: plt.xlim(-radius*1.2+center[0],radius*1.2+center[0]) plt.ylim(-radius*1.2+center[1],radius*1.2+center[1]) return("No sensor locations specified!") # Convert & rotate sensor locations: angles=sensors[0] angles=angles+nose_dir angles = deg2rad(angles) radii=sensors[1] # expand or shrink electrode locations with radius of head: radii = radii*(radius/0.5) # plotting radius is determined by largest sensor radius: plot_radius = max(radii) # convert electrode locations to cartesian coordinates for plotting: x,y = pol2cart(angles,radii) x = x + center[0] y = y + center[1] if colors[1]: # plot electrodes plt.plot(x,y,markerfacecolor=colors[1],marker='o',linestyle='') if values is None: return('No values to plot specified!') if np.size(values) != np.size(sensors,1): return('Numer of values to plot is different from number of sensors!'+ '\nNo values have been plotted!') z = values # resolution determines the number of interpolated points per unit nx = round(resolution*plot_radius) ny = round(resolution*plot_radius) # now set up the grid: xi, yi = np.meshgrid(np.linspace(-plot_radius,plot_radius,nx), np.linspace(-plot_radius,plot_radius,ny)) # and move the center to coincide with the center of the head: xi = xi + center[0] yi = yi + center[1] # interploate points: if plot_mask=='linear': # masked = True means that no extrapolation outside the # electrode boundaries is made this effectively creates a mask # with a linear boundary (connecting the outer electrode # locations) #zi = griddata(x,y,z,xi,yi,masked=True) zi = griddata(x,y,z,xi,yi) else: # we need a custom mask: #zi = griddata(x,y,z,xi,yi,ext=1,masked=False) zi = griddata(x,y,z,xi,yi) if plot_mask=='circular': # the interpolated array doesn't know about its position # in space and hence we need to subtract head center from # xi & xi to calculate the mask mask = (np.sqrt(np.power(xi-center[0],2) + np.power(yi-center[1],2)) > plot_radius) zi[mask] = 0 # other masks may be added here and can be defined as shown # for the circular mask. All other plot_mask values result in # no mask which results in showing interpolated values for the # square surrounding the head. # make contour lines: if linewidths[3] > 0: plt.contour(xi,yi,zi,contours,linewidths=linewidths[3], linestyle=contours_ls,colors=colors[2]) # make countour color patches: plt.contourf(xi,yi,zi,contours,cmap=cmap)
mapping = nc.createVariable("mapping",'c') mapping.ellipsoid = "WGS84" mapping.false_easting = 0. mapping.false_northing = 0. mapping.grid_mapping_name = "polar_stereographic" mapping.latitude_of_projection_origin = 90. mapping.standard_parallel = 71. mapping.straight_vertical_longitude_from_pole = -39. print("Reading file %s" % infile) lon_in, lat_in, dhdt = np.loadtxt(infile, unpack=True) x_in, y_in = proj(lon_in[::stride], lat_in[::stride]) print("Interpolating using griddata...") Dhdt = griddata(x_in, y_in, dhdt[::stride], ee, nn, ext=0, nul=fill_value) print("...done.") if mask_file: nc_mask = CDF(mask_file, 'r') mask = np.squeeze(nc_mask.variables['ftt_mask'][:]) if (mask.shape == Dhdt.shape): Dhdt[mask==0] = fill_value else: print("shape mismatch: %s and %s" % (str(mask.shape), str(Dhdt.shape))) nc_mask.close() var = nc.createVariable("dhdt", 'f', dimensions=("y", "x"), fill_value=fill_value) var.units = "m year-1" var.mapping = "mapping"
time_years, latitude, longitude, usurf, precipitation, temp = read_input(input) # Set up the interpolation code and extract Greenland: lon, lat = meshgrid(longitude, latitude) mask = (lat >= 57.0) & (lat <= 88) & ((lon >= 360.0 - 94.0) | (lon <= 12.0)) h = usurf[:, mask] T = temp[:, mask] P = precipitation[:, mask] lon = lon[mask] lat = lat[mask] ee, nn = (Proj(projection))(lon, lat) ee_out,nn_out = meshgrid(x,y) usurf_out = griddata(ee,nn,h,ee_out,nn_out) output_temp = "air_temp.nc" output_precip = "precipitation.nc" nc_temp, t_temp_var, temp_var, usurf_var_temp = prepare_temp_file(output_temp, x, y) usurf_var_temp[:] = usurf_out nc_precip, t_precip_var, precip_var = prepare_precipitation_file(output_precip, x, y) write("Interpolating") # The main interpolation loop: for j in range(time_years.size): f_temp = griddata(ee,nn,T[j],ee_out,nn_out) f_precip = griddata(ee,nn,P[j],ee_out,nn_out)
x = raw[:,0] y = raw[:,1] z = raw[:,2] sx = set() for i in x: sx.add(i) sy = set() for i in y: sy.add(i) nx = len(sx); ny = len(sy) print nx, ny, x.min(), x.max(), y.min(), y.max() xi, yi = p.meshgrid(p.linspace(x.min(),x.max(),nx),p.linspace(y.min(),y.max(),ny)) # masked=True mean no extrapolation, output is masked array. zi = griddata(x,y,z,xi,yi,masked=True) #print 'min/max = ',zi.min(), zi.max() # Contour the gridded data, plotting dots at the nonuniform data points. CS = p.contour(xi,yi,zi,15,linewidths=0.5,colors=['k']) CS = p.contourf(xi,yi,zi,15,cmap=p.cm.jet) p.colorbar() # draw colorbar #p.xlim(-1.9,1.9) #p.ylim(-1.9,1.9) #p.title('griddata test (%d points)' % npts) p.savefig(opts.file_name+".eps") #p.show()
def topoplot(values=None, axes=None, center=(0,0), nose_dir=0., radius=0.5, sensors=None, colors=('black','black','black'), linewidths=(3,2,2,0.5), contours_ls='-', contours=15, resolution=400, cmap=None, axis_props='off', plot_mask='circular'): """ Plot a topographic map of the scalp in a 2-D circular view (looking down at the top of the head). Parameters ---------- values : {None, array-like}, optional Values to plot. There must be one value for each electrode. axes : {matplotlib.axes}, optional Axes to which the topoplot should be added. center : {tuple of floats}, optional x and y coordinates of the center of the head. nose_dir : {float}, optional Angle (in degrees) where the nose is pointing. 0 is up, 90 is left, 180 is down, 270 is right, etc. radius : {float}, optional Radius of the head. sensors : {None, tuple of floats}, optional Polar coordinates of the sensor locations. If not None, sensors[0] specifies the angle (in degrees) and sensors[1] specifies the radius. colors : {tuple of str or None}, optional Colors for the outline of the head, sensor markers, and contours respectively. If any is None, the corresponding feature is not plotted. For contours either a single color or multiple colors can be specified. linewidths : {tuple of floats}, optional Line widths for the head, nose, ears, and contours respectively. For contours either a single linewith or multiple linewidths can be specified. contours_ls : {str}, optional Line style of the contours. contours : {int}, optional Number of countours. resolution : {int}, optional Resolution of the interpolated grid. Higher numbers give smoother edges of the plot, but increase memory and computational demands. cmap : {None,matplotlib.colors.LinearSegmentedColormap}, optional Color map for the contour plot. If colMap==None, the default color map is used. axis_props : {str}, optional Axis properties. plot_mask : {str}, optional The mask around the plotted values. 'linear' conects the outer electrodes with straight lines, 'circular' draws a circle around the outer electrodes, and 'square' (or any other value) draws a square around the electrodes. """ # If no colormap is specified, use default colormap: if cmap is None: cmap = plt.get_cmap() if axes is not None: # axes are given a=axes else: # a new subplot is created a=plt.subplot(1,1,1, aspect='equal') plt.axis(axis_props) if colors[0]: # head should be plotted # Set up head head = plt.Circle(center, radius,fill=False, linewidth=linewidths[0], edgecolor=colors[0]) # Nose: nose_width = 0.18*radius # Distance from the center of the head to the point where the # nose touches the outline of the head: nose_dist = np.cos(np.arcsin((nose_width/2.)/radius))*radius # Distance from the center of the head to the tip of the nose: nose_tip_dist = 1.15*radius # Convert to polar coordinates for rotating: nose_polar_angle,nose_polar_radius = cart2pol( np.array([-nose_width/2,0,nose_width/2]), np.array([nose_dist,nose_tip_dist,nose_dist])) nose_polar_angle = nose_polar_angle+deg2rad(nose_dir) # And back to cartesian coordinates for plotting: nose_x,nose_y = pol2cart(nose_polar_angle,nose_polar_radius) # Move nose with head: nose_x = nose_x + center[0] nose_y = nose_y + center[1] nose = plt.Line2D(nose_x,nose_y,color=colors[0],linewidth=linewidths[1], solid_joinstyle='round',solid_capstyle='round') # Ears: q = .04 # ear lengthening ear_x = np.array([.497-.005,.510,.518,.5299, .5419,.54,.547,.532,.510,.489-.005])*(radius/0.5) ear_y = np.array([q+.0555,q+.0775,q+.0783,q+.0746,q+.0555, -.0055,-.0932,-.1313,-.1384,-.1199])*(radius/0.5) # Convert to polar coordinates for rotating: rightear_polar_angle,rightear_polar_radius = cart2pol(ear_x,ear_y) leftear_polar_angle,leftear_polar_radius = cart2pol(-ear_x,ear_y) rightear_polar_angle=rightear_polar_angle+deg2rad(nose_dir) leftear_polar_angle=leftear_polar_angle+deg2rad(nose_dir) # And back to cartesian coordinates for plotting: rightear_x,rightear_y=pol2cart(rightear_polar_angle, rightear_polar_radius) leftear_x,leftear_y=pol2cart(leftear_polar_angle,leftear_polar_radius) # Move ears with head: rightear_x = rightear_x + center[0] rightear_y = rightear_y + center[1] leftear_x = leftear_x + center[0] leftear_y = leftear_y + center[1] ear_right = plt.Line2D(rightear_x,rightear_y,color=colors[0], linewidth=linewidths[3],solid_joinstyle='round', solid_capstyle='round') ear_left = plt.Line2D(leftear_x,leftear_y,color=colors[0], linewidth=linewidths[3],solid_joinstyle='round', solid_capstyle='round') a.add_artist(head) a.add_artist(nose) a.add_artist(ear_right) a.add_artist(ear_left) if sensors is None: if axes is None: plt.xlim(-radius*1.2+center[0],radius*1.2+center[0]) plt.ylim(-radius*1.2+center[1],radius*1.2+center[1]) return("No sensor locations specified!") # Convert & rotate sensor locations: angles=sensors[0] angles=angles+nose_dir angles = deg2rad(angles) radii=sensors[1] # expand or shrink electrode locations with radius of head: radii = radii*(radius/0.5) # plotting radius is determined by largest sensor radius: plot_radius = max(radii) # convert electrode locations to cartesian coordinates for plotting: x,y = pol2cart(angles,radii) x = x + center[0] y = y + center[1] if colors[1]: # plot electrodes plt.plot(x,y,markerfacecolor=colors[1],marker='o',linestyle='') if values is None: return('No values to plot specified!') if np.size(values) != np.size(sensors,1): return('Numer of values to plot is different from number of sensors!'+ '\nNo values have been plotted!') z = values # resolution determines the number of interpolated points per unit nx = round(resolution*plot_radius) ny = round(resolution*plot_radius) # now set up the grid: xi, yi = np.meshgrid(np.linspace(-plot_radius,plot_radius,nx), np.linspace(-plot_radius,plot_radius,ny)) # and move the center to coincide with the center of the head: xi = xi + center[0] yi = yi + center[1] # interploate points: if plot_mask=='linear': # masked = True means that no extrapolation outside the # electrode boundaries is made this effectively creates a mask # with a linear boundary (connecting the outer electrode # locations) #zi = griddata(x,y,z,xi,yi,masked=True) zi = griddata(x,y,z,xi,yi) else: # we need a custom mask: #zi = griddata(x,y,z,xi,yi,ext=1,masked=False) zi = griddata(x,y,z,xi,yi) if plot_mask=='circular': # the interpolated array doesn't know about its position # in space and hence we need to subtract head center from # xi & xi to calculate the mask mask = (np.sqrt(np.power(xi-center[0],2) + np.power(yi-center[1],2)) > plot_radius) zi[mask] = 0 # other masks may be added here and can be defined as shown # for the circular mask. All other plot_mask values result in # no mask which results in showing interpolated values for the # square surrounding the head. # make contour lines: plt.contour(xi,yi,zi,contours,linewidths=linewidths[3], linestyle=contours_ls,colors=colors[2]) # make countour color patches: plt.contourf(xi,yi,zi,contours,cmap=cmap)
def etreeminiparser(filename): X = [] Y = [] V = [] tree = ET.parse(filename) root = tree.getroot() plot = plt_graph2d.plot() plot.build(root) title = plot.get_title() saveFile = plot.get_filename() axes = plot.get_axe() for axe in axes: #print "axe.get_name()",axe.get_name() if ( axe.get_name() == 'X' ): Xaxe = axe elif ( axe.get_name() == 'Y' ): Yaxe = axe else: Zaxe = axe graph = plot.get_graph() file=graph.get_data() input_file = open(file,'r') lines = input_file.readlines() for line in lines: tmp = line.split() x = float(tmp[0]) y = float(tmp[1]) v = float(tmp[2]) X.append(x) Y.append(y) V.append(v) input_file.close() npts = len(X) # the total number of data points. X = np.asarray(X) # x data in array format Y = np.asarray(Y) # y data in array format V = np.asarray(V) # v data in array format # plot some profiles / cross-sections for some visualization. our # function is a symmetric, upward opening paraboloid z = x**2 + y**2. # We expect it to be symmetric about and and y, attain a minimum on # the origin and display minor Gaussian noise. plt.ion() # pyplot interactive mode on #plt.rc('text', usetex=True) #plt.rc('font', family='serif') # enter the gridding. imagine drawing a symmetrical grid over the # plot above. the binsize is the width and height of one of the grid # cells, or bins in units of x and y. bs=graph.get_binsize() binsize = bs grid, bins, binloc = griddata.griddata(X, Y, V, binsize=binsize) # see this routine's docstring # minimum values for colorbar. vmin = float( Zaxe.get_min() ) vmax = float( Zaxe.get_max() ) # minimum values for x,y axes. xmin = Xaxe.get_min() xmax = Xaxe.get_max() ymin = Yaxe.get_min() ymax = Yaxe.get_max() # colorbar stuff palette = plt.matplotlib.colors.LinearSegmentedColormap('jet3',plt.cm.datad['jet'],2048) palette.set_under(alpha=0.0) # plot the results. first plot is x, y vs v, where v is a filled level plot. extent = (xmin,xmax,ymin,ymax) # extent of the plot #plt.subplot(1, 2, 1) log = Zaxe.get_log() if ( log ): plt.imshow(grid, extent=extent, cmap=palette, origin='lower', vmin=vmin, vmax=vmax, aspect='auto', interpolation='bicubic', norm=LogNorm()) else: plt.imshow(grid, extent=extent, cmap=palette, origin='lower', vmin=vmin, vmax=vmax, aspect='auto', interpolation='bicubic') xtitle = Xaxe.get_label() plt.xlabel(xtitle) ytitle = Yaxe.get_label() plt.ylabel(ytitle) plt.title(title) cbar = plt.colorbar() ztitle = Zaxe.get_label() cbar.set_label(ztitle) plt.gca().invert_yaxis() #plt.clim(-500,0) plt.clim(vmin,vmax) #plt.zscale('log') #plt.savefig('razor.png') save_pic = saveFile + '.png' print "Results will be saved in:\n\t",save_pic plt.savefig(save_pic) save_pic = saveFile + '.pdf' print "Results will be saved in:\n\t",save_pic plt.savefig(save_pic)