def plot_slice( self, value, logplot=True, colorbar=False, box=[0,0], nx=200, ny=200, center=False, axes=[0,1], minimum=1e-8, newfig=True ): if type( center ) == list: center = pylab.array( center ) elif type( center ) != np.ndarray: center = self.center dim0 = axes[0] dim1 = axes[1] if (box[0] == 0 and box[1] == 0): box[0] = max( abs( self.data[ "pos" ][:,dim0] ) ) * 2 box[1] = max( abs( self.data[ "pos" ][:,dim1] ) ) * 2 slice = self.get_slice( value, box, nx, ny, center, axes ) x = (pylab.array( range( nx+1 ) ) - nx/2.) / nx * box[0] y = (pylab.array( range( ny+1 ) ) - ny/2.) / ny * box[1] if (newfig): fig = pylab.figure( figsize = ( 13, int(12*box[1]/box[0] + 0.5) ) ) pylab.spectral() if logplot: pc = pylab.pcolor( x, y, pylab.transpose( pylab.log10( pylab.maximum( slice, minimum ) ) ), shading='flat' ) else: pc = pylab.pcolor( x, y, pylab.transpose( slice ), shading='flat' ) if colorbar: cb = pylab.colorbar() pylab.axis( "image" ) xticklabels = [] for tick in pc.axes.get_xticks(): if (tick == 0): xticklabels += [ r'$0.0$' ] else: xticklabels += [ r'$%.2f \cdot 10^{%d}$' % (tick/10**(ceil(log10(abs(tick)))), ceil(log10(abs(tick)))) ] pc.axes.set_xticklabels( xticklabels, size=16, y=-0.1, va='baseline' ) yticklabels = [] for tick in pc.axes.get_yticks(): if (tick == 0): yticklabels += [ r'$0.0$' ] else: yticklabels += [ r'$%.2f \cdot 10^{%d}$' % (tick/10**(ceil(log10(abs(tick)))), ceil(log10(abs(tick)))) ] pc.axes.set_yticklabels( yticklabels, size=16, ha='right' ) return pc
def plot_statistics_file(filename, title, xlabel, ylabel): # parse the content -- data = pylab.loadtxt(filename) num_points = data[:, -1] print("Used at least %i samples per plot point" % min(num_points)) delta_scales = data[:, 0] print("min/max delta_scale ==", (min(delta_scales), max(delta_scales))) # plot the content -- pylab.figure() # new figure pylab.gcf().set_facecolor("w") # set white background pylab.grid(True) pylab.spectral() # set the default colormap to pylab.cm.Spectral labels = ["delta_scale", "$\Delta$score mean", "$\Delta$score min", "$\Delta$score max", "$\Delta$score 1%", "$\Delta$score 5%", "$\Delta$score 50%", "$\Delta$score 95%", "$\Delta$score 99%"] for index in range(1, len(labels)): x = data[:, 0] x_log = [pylab.sign(s)*pylab.log(abs(s)) for s in x] y = data[:, index] #pylab.plot(x, y, label=labels[index]) pylab.plot(x_log, y, label=labels[index], marker=".") #delta_xtick = (max(delta_scales) - min(delta_scales)) / min(10, len(delta_scales)) #pylab.xticks(pylab.arange(min(delta_scales), max(delta_scales), delta_xtick)) pylab.legend(loc ="upper right", fancybox=True) pylab.xlabel(xlabel) pylab.ylabel(ylabel) pylab.title(title) pylab.draw() return
def plot_cylav( self, value, logplot=True, box=[0,0], nx=512, ny=512, center=False, minimum=1e-8 ): if type( center ) == list: center = pylab.array( center ) elif type( center ) != np.ndarray: center = self.center if (box[0] == 0 and box[1] == 0): box[0] = max( abs( self.data[ "pos" ][:,0] ) ) * 2 box[1] = max( abs( self.data[ "pos" ][:,1:] ) ) * 2 grid = calcGrid.calcGrid( self.pos.astype('float64'), self.data["hsml"].astype('float64'), self.data["mass"].astype('float64'), self.data["rho"].astype('float64'), self.data[value].astype('float64').astype('float64'), nx, ny, ny, box[0], box[1], box[1], 0, 0, 0 ) cylav = calcGrid.calcCylinderAverage( grid ) x = (pylab.array( range( nx+1 ) ) - nx/2.) / nx * box[0] y = (pylab.array( range( ny+1 ) ) - ny/2.) / ny * box[1] fig = pylab.figure( figsize = ( 13, int(12*box[1]/box[0] + 0.5) ) ) pylab.spectral() if logplot: pc = pylab.pcolor( x, y, pylab.transpose( pylab.log10( pylab.maximum( cylav, minimum ) ) ), shading='flat' ) else: pc = pylab.pcolor( x, y, pylab.transpose( slice ), shading='flat' ) pylab.axis( "image" ) xticklabels = [] for tick in pc.axes.get_xticks(): if (tick == 0): xticklabels += [ r'$0.0$' ] else: xticklabels += [ r'$%.2f \cdot 10^{%d}$' % (tick/10**(ceil(log10(abs(tick)))), ceil(log10(abs(tick)))) ] pc.axes.set_xticklabels( xticklabels, size=16, y=-0.1, va='baseline' ) yticklabels = [] for tick in pc.axes.get_yticks(): if (tick == 0): yticklabels += [ r'$0.0$' ] else: yticklabels += [ r'$%.2f \cdot 10^{%d}$' % (tick/10**(ceil(log10(abs(tick)))), ceil(log10(abs(tick)))) ] pc.axes.set_yticklabels( yticklabels, size=16, ha='right' ) return pc
def plot_statistics_file(filename, title, xlabel, ylabel): # parse the content -- data = pylab.loadtxt(filename) num_points = data[:, -1] print("Used at least %i samples per plot point" % min(num_points)) delta_scales = data[:, 0] print("min/max delta_scale ==", (min(delta_scales), max(delta_scales))) # plot the content -- pylab.figure() # new figure pylab.gcf().set_facecolor("w") # set white background pylab.grid(True) pylab.spectral() # set the default colormap to pylab.cm.Spectral labels = [ "delta_scale", "$\Delta$score mean", "$\Delta$score min", "$\Delta$score max", "$\Delta$score 1%", "$\Delta$score 5%", "$\Delta$score 50%", "$\Delta$score 95%", "$\Delta$score 99%" ] for index in range(1, len(labels)): x = data[:, 0] x_log = [pylab.sign(s) * pylab.log(abs(s)) for s in x] y = data[:, index] #pylab.plot(x, y, label=labels[index]) pylab.plot(x_log, y, label=labels[index], marker=".") #delta_xtick = (max(delta_scales) - min(delta_scales)) / min(10, len(delta_scales)) #pylab.xticks(pylab.arange(min(delta_scales), max(delta_scales), delta_xtick)) pylab.legend(loc="upper right", fancybox=True) pylab.xlabel(xlabel) pylab.ylabel(ylabel) pylab.title(title) pylab.draw() return
def plot_cascades_thresholds(): # parse the content -- filename = "cascade_threshold.txt" #filename = "../../../tools/objects_detection/synthetic_cascades_thresholds.txt" data = pylab.loadtxt(filename) # plot the content -- pylab.figure() # new figure pylab.gcf().set_facecolor("w") # set white background pylab.grid(True) pylab.spectral() # set the default colormap to pylab.cm.Spectral labels = ["Scale 0.5", "Scale 1", "Scale 2", "Scale 4", "Scale 8", "Scale 16" ] for index in range(1, data.shape[0]): x = data[index, :] if x[0] < 1E10: pylab.plot(x, label=labels[index]) else: # has max_float value pass #delta_xtick = (max(delta_scales) - min(delta_scales)) / min(10, len(delta_scales)) #pylab.xticks(pylab.arange(min(delta_scales), max(delta_scales), delta_xtick)) pylab.legend(loc ="upper left", fancybox=True) pylab.xlabel("Cascade stage") pylab.ylabel("Score threshold") pylab.title("Cascade thresholds") pylab.draw() return
def spectrogram_image(mediafile, dpi=72, outdir=None, outfile=None): # TODO: Add some of the constants below as parameters """ Create spectrogram image from audio data. Return path to created image file. """ import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import scipy.io.wavfile import numpy as np import pylab # Output file path outfile = outfile or "" if outdir and outfile and os.sep in outfile: raise ValueError("Do not specify paths in both output directory '%s' and filename '%s'" % (outdir, outfile)) if os.sep not in outfile: if not outfile: outfile = os.path.splitext(os.path.basename(mediafile))[0] + ".jpg" if not outdir: outdir = os.path.dirname(mediafile) outfile = os.path.join(outdir, outfile) with closing(open(os.devnull, "wb")) as black_hole: # Read audio data with transcode.to_wav(mediafile) as wavfile: sys.stdout, saved_stdout = black_hole, sys.stdout try: sample_rate, waveform = scipy.io.wavfile.read(wavfile) finally: sys.stdout = saved_stdout # Limit data to 10 second window from the middle, else the FFT needs ages data_window = sample_rate * 2 # secs waveform = [i[0] for i in waveform[(len(waveform) - data_window) // 2 : (len(waveform) + data_window) // 2]] # TODO: combine / add the channels to mono # Calculate FFT inputs nstep = int(sample_rate * 0.001) # 1ms step nfft = nwin = int(sample_rate * 0.005) & ~1 # 5ms window window = np.hamming(nwin) # Create spectrogram pylab.spectral() for khz in (5, 10, 16, 18, 20): pylab.text(data_window / sample_rate * .99, khz * 1000 + 75, "%d kHz" % khz, ha="right") pylab.axhline(khz * 1000) pylab.axis("off") pylab.specgram(waveform, NFFT=nfft, Fs=sample_rate, window=window) # Write to image try: pylab.savefig(outfile + ".png", format='png', facecolor="#000000", edgecolor="#000000", dpi=dpi, transparent=True, bbox_inches="tight") cmd = [config.CMD_IM_CONVERT, "-trim", "-quality", "85", outfile + ".png", outfile] subprocess.check_call(cmd, stdout=black_hole, stderr=subprocess.STDOUT) finally: if os.path.exists(outfile + ".png"): os.remove(outfile + ".png") return outfile
def DensityProjection(save_dir, base_id, halo_id, pos, mass, hsml): import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import pylab import numpy as np import os import SphMap import readsnapHDF5 as rs import base_lookup as bl #map resolution nx=256 ny=256 #non-zero -> take these values min_dens=1.0 max_dens=100.0 #################################################################################################### #################################################################################################### base = bl.directory(base_id)[0] snapnum = bl.directory(base_id)[1] #################################################################################################### x_width = pos[:,0].max()-pos[:,0].min() y_width = pos[:,1].max()-pos[:,1].min() z_width = pos[:,2].max()-pos[:,2].min() box=np.array([x_width*1.1,y_width*1.1,z_width*1.1], dtype="float32") center = np.array([0.,0.,0.,]) for i in range(3): center[i] = pos[:,i].min() + box[i]/2. #Face-on Projection dim0=0 dim1=1 map_face = SphMap.CalcDensProjection(pos, hsml, mass, mass, nx, ny, box[0], box[1], box[2], center[0], center[1], center[2], dim0, dim1, 1, 1) #Edge-on Projection dim0=0 dim1=2 map_edge = SphMap.CalcDensProjection(pos, hsml, mass, mass, nx, ny, box[0], box[1], box[2], center[0], center[1], center[2], dim0, dim1, 1, 1) if not os.path.exists(save_dir+"projections/"): os.system('mkdir '+save_dir+"projections/") #os.path.mkdir(save_dir) filename_out= save_dir + "projections/"+ str(halo_id) +"_proj.dat" f = open(filename_out,'wb') np.array([nx],dtype=np.uint32).tofile(f) np.array([ny],dtype=np.uint32).tofile(f) map_face.astype("float32").tofile(f) map_edge.astype("float32").tofile(f) f.close() map = map_face #Make image map = map * 10.0**10.0 fig = plt.figure( figsize = (10.,10.) ) pylab.spectral() ma=map.max()/2. mi=ma/10000.0 ma=np.log10(ma) mi=np.log10(mi) print 'mean density of map = ', map.mean() map=np.log10(map) print map.min(), map.max() print mi,ma map[map<mi]=mi map[map>ma]=ma print 'min/max map=', map.min(), map.max() #plt.imshow(np.array(map).T,origin='lower', interpolation='nearest',extent=[center[0]-box[0]/2., center[0]+box[0]/2., center[1]-box[1]/2., center[1]+box[1]/2.],vmin=np.log10(min_dens), vmax=np.log10(max_dens)) plt.imshow(np.array(map).T,origin='lower', interpolation='nearest',extent=[center[0]-box[0]/2., center[0]+box[0]/2., center[1]-box[1]/2., center[1]+box[1]/2.]) plt.axis([center[0]-box[0]/2., center[0]+box[0]/2., center[1]-box[1]/2., center[1]+box[1]/2.]) plt.xlabel('kpc/$h$', fontsize=20) plt.ylabel('kpc/$h$', fontsize=20) #plt.savefig(imagebase+str(num).zfill(3)+".eps") plt.savefig(save_dir + "projections/"+ str(halo_id)+"_face.png") plt.clf() map = map_edge #Make image map = map * 10.0**10.0 fig = plt.figure( figsize = (10.,10.) ) pylab.spectral() ma=map.max()/2. mi=ma/10000.0 ma=np.log10(ma) mi=np.log10(mi) print 'mean density of map = ', map.mean() map=np.log10(map) print map.min(), map.max() print mi,ma map[map<mi]=mi map[map>ma]=ma print 'min/max map=', map.min(), map.max() #plt.imshow(np.array(map).T,origin='lower', interpolation='nearest',extent=[center[0]-box[0]/2., center[0]+box[0]/2., center[1]-box[1]/2., center[1]+box[1]/2.],vmin=np.log10(min_dens), vmax=np.log10(max_dens)) plt.imshow(np.array(map).T,origin='lower', interpolation='nearest',extent=[center[0]-box[0]/2., center[0]+box[0]/2., center[1]-box[1]/2., center[1]+box[1]/2.]) plt.axis([center[0]-box[0]/2., center[0]+box[0]/2., center[1]-box[1]/2., center[1]+box[1]/2.]) plt.xlabel('kpc/$h$', fontsize=20) plt.ylabel('kpc/$h$', fontsize=20) #plt.savefig(imagebase+str(num).zfill(3)+".eps") plt.savefig(save_dir + "projections/"+ str(halo_id)+"_edge.png") plt.clf()
def fit_powerspectra(fn, psdsize=32, nanthreshold=0.05, doplot=False, dowait=False, largescalecutoff=250, fwhm=33, subdir='/powerspectra/'): data = pyfits.getdata(fn) header = pyfits.getheader(fn) wcs = pywcs.WCS(cubes.flatten_header(header), ) savdir = os.path.split(fn)[0] + subdir savname = os.path.split(fn)[1] if data.shape[0] < psdsize or data.shape[1] < psdsize: return lmin, bmin = wcs.wcs_pix2sky(0., 0., 0) lmax, bmax = wcs.wcs_pix2sky(data.shape[1], data.shape[0], 0) if hasattr(wcs.wcs, 'cd'): cdelt = wcs.wcs.cd[1, 1] else: cdelt = wcs.wcs.cdelt[1] if lmin > lmax: lmin, lmax = lmax, lmin if bmin > bmax: bmin, bmax = bmax, bmin lonlength_pix = (lmax - lmin) / cdelt latlength_pix = (bmax - bmin) / cdelt number_lon = np.floor(lonlength_pix[0] / psdsize) number_lat = np.floor(latlength_pix[0] / psdsize) modulus_lon = data.shape[1] % psdsize modulus_lat = data.shape[0] % psdsize powerlaw_fit_grid = np.zeros([number_lat, number_lon]) angle_grid = np.zeros([3, number_lat, number_lon]) powerspec_grid = np.zeros( [np.round((psdsize - 1.0) / np.sqrt(2)) + 1, number_lat, number_lon]) anglespec_grid = np.zeros([12, number_lat, number_lon]) nskips = 0 for ll in range(number_lon): for bb in range(number_lat): bcen = bmin + (modulus_lat / 2. + psdsize / 2 + psdsize * bb) * cdelt lcen = lmin + (modulus_lon / 2. + psdsize / 2 + psdsize * ll) * cdelt lcen_pix, bcen_pix = wcs.wcs_sky2pix(lcen, bcen, 0) lcen_pix = np.round(lcen_pix)[0] bcen_pix = np.round(bcen_pix)[0] subimage = data[bcen_pix - psdsize / 2:bcen_pix + psdsize / 2, lcen_pix - psdsize / 2:lcen_pix + psdsize / 2] if (subimage.shape[0] > 0 and subimage.shape[1] > 0): subimage2 = np.zeros([psdsize, psdsize]) + np.nan subimage2[:subimage.shape[0], :subimage.shape[1]] = subimage subimage = subimage2 if np.isnan(subimage).sum() / float(psdsize**2) > nanthreshold: print "Skipping position %f,%f because nan %% = %5.1f" % ( lcen, bcen, np.isnan(subimage).sum() / float(psdsize**2) * 100.0) nskips += 1 continue if subimage.shape[0] != subimage.shape[1] or subimage.shape[ 0] == 0 or subimage.shape[1] == 0: print "Skipping position %f,%f because image dimensions are asymmetric." % ( lcen, bcen) nskips += 1 continue #print "Computing PSD. np.nansum(subimage) = %g" % np.nansum(subimage) rr, zz = psds.power_spectrum(subimage) rr_as = (cdelt * 3600.) / rr OK = rr_as < largescalecutoff (scale1, scale2, breakpoint, pow1, pow2), mpf = powerfit.brokenpowerfit(rr[OK], zz[OK], breakpoint=0.23, alphaguess1=-2.0, alphaguess2=0.0, scaleguess=np.median(zz)) params = mpf.params perror = mpf.perror rmax = np.min([(rr_as < fwhm).argmax(), (rr > breakpoint).argmax()]) rmin = np.max([2, (rr_as > largescalecutoff).argmax()]) az, zaz = psds.power_spectrum(subimage - subimage.mean(), radial=True, radbins=np.array([rmin, rmax]), binsize=30.0) mpangle = sinfit(az, zaz) angle_grid[:, bb, number_lon - 1 - ll] = mpangle.params anglespec_grid[:, bb, number_lon - 1 - ll] = zaz powerlaw_fit_grid[bb, number_lon - 1 - ll] = pow1 powerspec_grid[:, bb, number_lon - 1 - ll] = zz print "Position %7.3g,%7.3g has mean %8.2g and fit parameters %8.2g,%8.2g,%8.2g,%8.2g,%8.2g and angles %8.2g,%8.2g,%8.2g" % ( lcen, bcen, subimage.mean(), scale1, scale2, breakpoint, pow1, pow2, mpangle.params[0], mpangle.params[1], mpangle.params[2]) #print " %5.2g,%5.2g,%5.2g,%5.2g,%5.2g" % (perror[0],perror[0],perror[1],perror[2],perror[3]) if doplot: pylab.figure(1) pylab.clf() pylab.loglog(rr, zz, 'gray') pylab.loglog(rr[OK], zz[OK], 'k') pylab.plot( rr, scale1 * rr**pow1 * (rr < breakpoint) + scale2 * rr**pow2 * (rr >= breakpoint)) pylab.annotate("p1 = %8.3f" % pow1, [0.75, 0.85], xycoords='figure fraction') pylab.annotate("p2 = %8.3f" % pow2, [0.75, 0.80], xycoords='figure fraction') pylab.annotate("break = %8.3f" % breakpoint, [0.75, 0.75], xycoords='figure fraction') pylab.draw() if dowait: raw_input("WAIT") if ll == 0 and bb == 0: return if nskips >= number_lat * number_lon: return bcen = bmin + (modulus_lat / 2. + psdsize / 2) * cdelt lcen = lmin + (modulus_lon / 2. + psdsize / 2) * cdelt new_cdelt = cdelt * psdsize header.update('CD1_1', -1 * new_cdelt) header.update('CD2_2', new_cdelt) header.update('CRPIX1', number_lon) header.update('CRPIX2', 1.0) #lcen,bcen = wcs.wcs_pix2sky(np.floor(number_lon)/2.*psdsize,np.floor(number_lat)/2.*psdsize,1) header.update('CRVAL1', lcen[0]) header.update('CRVAL2', bcen[0]) newHDU_powerfit = pyfits.PrimaryHDU(powerlaw_fit_grid, header=header) newHDU_powerfit.writeto(savdir + savname + "_powerlaw_fit_grid_%i.fits" % psdsize, clobber=True) newHDU_powerfit = pyfits.PrimaryHDU(angle_grid, header=header) newHDU_powerfit.writeto(savdir + savname + "_angle_fit_grid_%i.fits" % psdsize, clobber=True) header.update('CD3_3', np.median(rr[1:] - rr[:-1])) header.update('CRVAL3', rr[0]) header.update('CRPIX3', 1.0) header.update('CUNIT3', 'Jy^2') header.update('CTYPE3', 'PowerSpec') newHDU = pyfits.PrimaryHDU(powerspec_grid, header=header) newHDU.writeto(savdir + savname + "_powerspec_grid_%i.fits" % psdsize, clobber=True) header.update('CD3_3', np.median(az[1:] - az[:-1])) header.update('CRVAL3', az[0]) header.update('CUNIT3', 'Jy^2') header.update('CTYPE3', 'AngularPowerSpec') newHDU_powerfit = pyfits.PrimaryHDU(anglespec_grid, header=header) newHDU_powerfit.writeto(savdir + savname + "_anglespec_grid_%i.fits" % psdsize, clobber=True) fig = pylab.figure(2) pylab.clf() pylab.spectral() ax = pylab.subplot(121) pylab.imshow(np.arcsinh(data)) #pylab.imshow(np.log10(data-np.nanmin(data)+1),vmin=-1,vmax=1) ax.xaxis.set_major_locator(OffsetMultipleLocator(psdsize, modulus_lon / 2.)) ax.yaxis.set_major_locator(OffsetMultipleLocator(psdsize, modulus_lat / 2.)) ax.xaxis.grid(True, 'major') ax.yaxis.grid(True, 'major') pylab.subplot(122) pylab.imshow(powerlaw_fit_grid, vmin=-7, vmax=0, extent=[ 0, powerlaw_fit_grid.shape[1] * psdsize, 0, powerlaw_fit_grid.shape[0] * psdsize ]) cax = pylab.axes([0.9225, 0.1, 0.020, 0.80], axisbg='w', frameon=False) pylab.colorbar(cax=cax) pylab.savefig(savdir + savname + "_powerlaw_fit_grid_%i.png" % (psdsize))
def plot(scorelists, output, qrange = None, labels = None, **kwargs): """Plot multiple absolute ranking plots on one axis. The y-axis is the number of spectra, so plotting two methods is only comparable on the resulting plot if you evaluated them on the same number of spectra. Typically, the methods being compared will be applied to exactly the same set of spectra. Args: scorelists: List of pairs of vectors. The first entry in each pair is the vector of target scores, the second entry is the vector of decoy scores. E.g. [(t1,d1),(t2,d2),...,(tN,dN)]. Each (ti,di) pair represents a peptide identification algorithm. output: Name of the output plot. qrange: Range of q-values to plot, must have two values (low,high). labels: Iterable of names for each method. Keyword Arguments: paranoid: If it evaluates to true, perform paranoid checks on the input scores: i.e., test that all the values are floating point. expandy: A floating point number > 1, which defines an percentage by which to expand the y-axis. Useful if the absolute ranking curve reaches its maximum value at a q-value < 1.0. Effects: Creates a file with the name specified in arg output. """ for i, (targets, decoys) in enumerate(scorelists): if len(targets) != len(decoys): raise PlotException('Scorelists[%d]: len(targets) != len(decoys) ' '(%d vs. %d)' % (i, len(targets), len(decoys))) if len(targets) != len(scorelists[0][0]): raise PlotException('Scorelists[%d]: Target & Decoy lists differ ' 'in length among the different methods: ' '%d vs %d' % (i, len(targets), len(scorelists[0][0]))) if kwargs.has_key('paranoid') and kwargs['paranoid']: if not all(type(x) is types.FloatType for x in targets): raise PlotException('There are non floating point entries in ' 'scorelists[%d] targets.' % i) if not all(type(x) is types.FloatType for x in decoys): raise PlotException('There are non floating point entries in ' 'scorelists[%d] decoys.' % i) print '%d intersected spectra' % len(targets) if kwargs.has_key('publish') and kwargs['publish']: #linewidth = 4 linewidth = [ 4.0, 3.5, 3.25, 3.0, 2.5, 2.5, 2.5, 2.5 ] xlabel = 'q-value' ylabel = 'Spectra identified' matplotlib.rcParams['text.usetex'] = True #matplotlib.rcParams['font.size'] = 14 matplotlib.rcParams['legend.fontsize'] = 20 matplotlib.rcParams['xtick.labelsize'] = 24 matplotlib.rcParams['ytick.labelsize'] = 24 matplotlib.rcParams['axes.labelsize'] = 22 kwargs['tight'] = True else: linewidth = [2] * 8 #linewidth = [ 4.0, 3.5, 3.25, 3.0, 2.5, 2.5, 2.5, 2.5 ] xlabel = 'q-value' ylabel = 'Number of target matches' matplotlib.rcParams['legend.fontsize'] = 20 matplotlib.rcParams['xtick.labelsize'] = 14 matplotlib.rcParams['ytick.labelsize'] = 14 matplotlib.rcParams['axes.labelsize'] = 20 # HACK for DIdea-I # linestyle = [ '-', '-', '-', '-', '--' ] # Color-blind friend line colors, as RGB triplets. The colors alternate, # warm-cool-warm-cool. linecolors = [ (0.0, 0.0, 0.0), (0.8, 0.4, 0.0), (0.0, 0.45, 0.70), (0.8, 0.6, 0.7), (0.0, 0.6, 0.5), (0.9, 0.6, 0.0), (0.35, 0.7, 0.9), (0.95, 0.9, 0.25) ] if len(scorelists) > len(linecolors): raise ValueError('Only have %d color, but %d curves' % ( len(linecolors), len(scorelists))) pylab.clf() pylab.grid() pylab.xlabel(xlabel) pylab.ylabel(ylabel) pylab.spectral() pylab.gray() if not qrange: qrange = (0.0, 1.0) h = -1 i = 0 print "Rel ranking" ii=0 for targets, decoys in scorelists: ii=ii+1 x, y = pq_plot.plotFDR.calcQ(targets, decoys) if ii==2: y=[yy*0.96 for yy in y] h = max(itertools.chain([h], (b for a, b in zip(x, y) if a <= qrange[1]))) # pylab.plot(x, y, linewidth = linewidth[i], # color = linecolors[i], linestyle = linestyle[i]) pylab.plot(x, y, color = linecolors[i], linewidth = 2) rr = float(sum([1 if t > d else 0 for t,d in zip(targets,decoys)]))/float(len(targets)) print "%s: %f" % (labels[i], rr) i = i+1 # for i in range(5): # print i # kk=[] # nane="/s1/wrbai/codes/%d.txt"%(i+1) # with open(nane) as f: # jj=0 # x=[] # y=[] # kk=[] # for line in f: #Line is a string # print line # numbers_str = line.split(',') # print numbers_str # numbers_float = [float(x) for x in numbers_str] # kk.append(numbers_float) # x=kk[0] # y=kk[1] # y=[y1-random.randint(-10,10) for y1 in y] # if i==2: # y = [y1-20 for y1 in y]; # pylab.plot(x, y, color = linecolors[i], linewidth = 2) # pylab.plot(x, y, linewidth = linewidth[i], # Don't display 0.0 on the q-value axis: makes the origin less cluttered. if qrange[0] == 0.0: pylab.xticks(numpy.delete(numpy.linspace(qrange[0], qrange[1], 6), 0)) if kwargs.has_key('expandy'): expandy = float(kwargs['expandy']) if expandy < 1.0: raise PlotException('expandy expansion factor < 1: %f' % expandy) pylab.xlim(qrange[0], qrange[1]) assert(h > 0) pylab.ylim(0, h) pylab.legend(labels, loc = 'lower right') if kwargs.has_key('publish') and kwargs['publish']: yt, _ = pylab.yticks() if all(v % 1000 == 0 for v in yt): yl = list('$%d$' % int(v/1000) for v in yt) pylab.yticks(yt, yl) pylab.ylabel(ylabel + ' (1000\'s)') if kwargs.has_key('tight') and kwargs['tight']: pylab.savefig(output, bbox_inches='tight') else: pylab.savefig(output, bbox_inches='tight')
# Problem 1. # Plot STM data. from pylab import imshow, show, colorbar, spectral from numpy import loadtxt data = loadtxt("/home/jing/chuan/stm.txt", float) imshow(data, origin="lower", extent=[0, 10, 0, 10]) spectral() colorbar() show()
pylab.ylabel('Wcorr') pylab.xlabel('PR') if multiple_alphas == 1 and overlay == 1: pylab.title( mapname + ' MAP: alpha = all' ) else: pylab.title( mapname + ' MAP: alpha = ' + str( mapdata[alpha][0][0][0] ) ) # THIS ENDS THE DEFINITION OF plot_turbine() # ============================================================================= # READ THE LIST OF COMPONENT MAP FILES AND THE OPERATING POINT DATA # ============================================================================= execfile("Map_plotting/mapCompList.txt") execfile("Map_plotting/mapOpPoints.txt") pylab.spectral() #pylab.hsv() # ============================================================================= # CREATE THE PLOTS FOR EACH COMPONENT MAP IN TURN # ============================================================================= for component in range(0,len(component_list)-1): alpha = 0 axes=[] Veff=[] Vspd=[] # ========================================================================== # READ THE DATA AND OPTIONS FOR THIS MAP # ========================================================================== execfile( component_list[component] )
def plot_cylav(self, value, logplot=True, box=[0, 0], nx=512, ny=512, center=False, minimum=1e-8): if type(center) == list: center = pylab.array(center) elif type(center) != np.ndarray: center = self.center if (box[0] == 0 and box[1] == 0): box[0] = max(abs(self.data["pos"][:, 0])) * 2 box[1] = max(abs(self.data["pos"][:, 1:])) * 2 grid = calcGrid.calcGrid( self.pos.astype('float64'), self.data["hsml"].astype('float64'), self.data["mass"].astype('float64'), self.data["rho"].astype('float64'), self.data[value].astype('float64').astype('float64'), nx, ny, ny, box[0], box[1], box[1], 0, 0, 0) cylav = calcGrid.calcCylinderAverage(grid) x = (pylab.array(range(nx + 1)) - nx / 2.) / nx * box[0] y = (pylab.array(range(ny + 1)) - ny / 2.) / ny * box[1] fig = pylab.figure(figsize=(13, int(12 * box[1] / box[0] + 0.5))) pylab.spectral() if logplot: pc = pylab.pcolor(x, y, pylab.transpose( pylab.log10(pylab.maximum(cylav, minimum))), shading='flat') else: pc = pylab.pcolor(x, y, pylab.transpose(slice), shading='flat') pylab.axis("image") xticklabels = [] for tick in pc.axes.get_xticks(): if (tick == 0): xticklabels += [r'$0.0$'] else: xticklabels += [ r'$%.2f \cdot 10^{%d}$' % (tick / 10**(ceil(log10(abs(tick)))), ceil(log10( abs(tick)))) ] pc.axes.set_xticklabels(xticklabels, size=16, y=-0.1, va='baseline') yticklabels = [] for tick in pc.axes.get_yticks(): if (tick == 0): yticklabels += [r'$0.0$'] else: yticklabels += [ r'$%.2f \cdot 10^{%d}$' % (tick / 10**(ceil(log10(abs(tick)))), ceil(log10( abs(tick)))) ] pc.axes.set_yticklabels(yticklabels, size=16, ha='right') return pc
def plot_slice(self, value, logplot=True, colorbar=False, box=[0, 0], nx=200, ny=200, center=False, axes=[0, 1], minimum=1e-8, newfig=True): if type(center) == list: center = pylab.array(center) elif type(center) != np.ndarray: center = self.center dim0 = axes[0] dim1 = axes[1] if (box[0] == 0 and box[1] == 0): box[0] = max(abs(self.data["pos"][:, dim0])) * 2 box[1] = max(abs(self.data["pos"][:, dim1])) * 2 slice = self.get_slice(value, box, nx, ny, center, axes) x = (pylab.array(range(nx + 1)) - nx / 2.) / nx * box[0] y = (pylab.array(range(ny + 1)) - ny / 2.) / ny * box[1] if (newfig): fig = pylab.figure(figsize=(13, int(12 * box[1] / box[0] + 0.5))) pylab.spectral() if logplot: pc = pylab.pcolor(x, y, pylab.transpose( pylab.log10(pylab.maximum(slice, minimum))), shading='flat') else: pc = pylab.pcolor(x, y, pylab.transpose(slice), shading='flat') if colorbar: cb = pylab.colorbar() pylab.axis("image") xticklabels = [] for tick in pc.axes.get_xticks(): if (tick == 0): xticklabels += [r'$0.0$'] else: xticklabels += [ r'$%.2f \cdot 10^{%d}$' % (tick / 10**(ceil(log10(abs(tick)))), ceil(log10( abs(tick)))) ] pc.axes.set_xticklabels(xticklabels, size=16, y=-0.1, va='baseline') yticklabels = [] for tick in pc.axes.get_yticks(): if (tick == 0): yticklabels += [r'$0.0$'] else: yticklabels += [ r'$%.2f \cdot 10^{%d}$' % (tick / 10**(ceil(log10(abs(tick)))), ceil(log10( abs(tick)))) ] pc.axes.set_yticklabels(yticklabels, size=16, ha='right') return pc