def plotDMMetallicityColor(options,args): """Make a density plot of DM vs FeH and g-r""" if options.png: ext= 'png' else: ext= 'ps' if options.metal.lower() == 'rich': yrange=[-0.55,0.5] fehrange= _APOORFEHRANGE elif options.metal.lower() == 'poor': yrange=[-1.6,0.3] fehrange= _ARICHFEHRANGE xrange=[0.46,0.57] grmin, grmax= 0.48, 0.55 colorrange=[0.48,0.55] #Set up arrays nfehs, ngrs= 201,201 grs= numpy.linspace(xrange[0],xrange[1],nfehs) fehs= numpy.linspace(yrange[0],yrange[1],ngrs) plotthis= numpy.zeros((ngrs,nfehs)) for ii in range(ngrs): for jj in range(nfehs): if grs[ii] < colorrange[0] \ or grs[ii] > colorrange[1] \ or fehs[jj] < fehrange[0] \ or fehs[jj] > fehrange[1]: plotthis[ii,jj]= numpy.nan continue plotthis[ii,jj]= segueSelect._mr_gi(segueSelect._gi_gr(grs[ii]),fehs[jj]) if options.sample.lower() == 'g': if options.metal.lower() == 'rich': levels= [4.5,4.75,5.,5.25,5.5] else: levels= [5.25,5.5,5.75,6.,6.25] cntrlabelcolors= ['w' for ii in range(3)] cntrlabelcolors.extend(['k' for ii in range(2)]) #nlevels= 6 #levelsstart= int(20.*numpy.nanmin(plotthis))/20. #levelsd= int(20.*(numpy.nanmax(plotthis)-numpy.nanmin(plotthis)))/20. #levels= [levelsstart+ii/float(nlevels)*levelsd for ii in range(nlevels)] #Plot it bovy_plot.bovy_print() bovy_plot.bovy_dens2d(plotthis.T,origin='lower', xlabel=r'$g-r\ [\mathrm{mag}]$', ylabel=r'$[\mathrm{Fe/H}]$', zlabel=r'$M_r\ [\mathrm{mag}]$', colorbar=True, cmap=pyplot.cm.gist_gray, contours=True, levels=levels, cntrcolors=cntrlabelcolors, cntrlabel=True, cntrlabelcolors=cntrlabelcolors, cntrinline=True, interpolation='nearest', extent=[xrange[0],xrange[1], yrange[0],yrange[1]], aspect=(xrange[1]-xrange[0])/\ (yrange[1]-yrange[0]), shrink=.78) bovy_plot.bovy_end_print(os.path.join(args[0],'dm_FeH_gr_'+options.sample+'_'+options.metal+'.'+ext))
def determine_kxky_error(): #Load fiducial bar model spvlos= galpy_simulations.vlos('../sim/bar_rect_alpha0.015%s.sav' % _HIVRESSTR)[1::2,1::2] #spvlos= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-14%s.sav' % _HIVRESSTR)[1::2,1::2]*0.85 #spvlos= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-7%s.sav' % _HIVRESSTR)[1::2,1::2]*0.25 psd2d= bovy_psd.psd2d(spvlos) kmax= 1./_RCDX #Calculate maximum psd2d[psd2d.shape[0]/2-1:psd2d.shape[0]/2+2,psd2d.shape[1]/2-1:psd2d.shape[1]/2+2]= 0. tmax= numpy.unravel_index(numpy.argmax(psd2d),psd2d.shape) tmax0= float(psd2d.shape[0]/2-tmax[0])/psd2d.shape[0]*2 tmax1= float(tmax[1]-psd2d.shape[1]/2)/psd2d.shape[1]*2 print tmax0*kmax, tmax1*kmax bovy_plot.bovy_print() bovy_plot.bovy_dens2d(psd2d.T,origin='lower',cmap='jet', interpolation='nearest', xrange=[-kmax,kmax], yrange=[-kmax,kmax], xlabel=r'$k_x\,(\mathrm{kpc}^{-1})$', ylabel=r'$k_y\,(\mathrm{kpc}^{-1})$') bovy_plot.bovy_end_print('/Users/bovy/Desktop/test.png') #Read the data for the noise data= apread.rcsample() if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] #Cut indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.) print "Using %i stars for low-Z 2D kinematics analysis" % numpy.sum(indx) data= data[indx] #Get residuals dx= _RCDX pix= pixelize_sample.pixelXY(data, xmin=_RCXMIN,xmax=_RCXMAX, ymin=_RCYMIN,ymax=_RCYMAX, dx=dx,dy=dx) resvunc= pix.plot('VHELIO_AVG', func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)), returnz=True,justcalc=True) #Now do 1000 MC simulations to determine the error on kmax nmc= 1000 kxmax= numpy.zeros(nmc) kymax= numpy.zeros(nmc) for ii in range(nmc): newresv= spvlos+numpy.random.normal(size=spvlos.shape)*resvunc/220. simpsd2d= bovy_psd.psd2d(newresv*220.) simpsd2d[simpsd2d.shape[0]/2-1:simpsd2d.shape[0]/2+2,simpsd2d.shape[1]/2-1:simpsd2d.shape[1]/2+2]= 0. tmax= numpy.unravel_index(numpy.argmax(simpsd2d),psd2d.shape) tmax0= float(psd2d.shape[0]/2-tmax[0])/psd2d.shape[0]*2 tmax1= float(tmax[1]-psd2d.shape[1]/2)/psd2d.shape[1]*2 kmax= 1./_RCDX kxmax[ii]= tmax0*kmax kymax[ii]= tmax1*kmax print numpy.mean(kxmax), numpy.std(kxmax) print numpy.mean(kymax), numpy.std(kymax) return None
def plotCombinedPDF(options,args): if options.sample.lower() == 'g': npops= 62 elif options.sample.lower() == 'k': npops= 54 if options.sample.lower() == 'g': savefile= open('binmapping_g.sav','rb') elif options.sample.lower() == 'k': savefile= open('binmapping_k.sav','rb') fehs= pickle.load(savefile) afes= pickle.load(savefile) savefile.close() #First calculate the derivative properties if not options.group is None: gafes, gfehs, legend= getMultiComparisonBins(options) else: legend= None if not options.multi is None: PDFs= multi.parallel_map((lambda x: calcAllPDFs(x,options,args)), range(npops), numcores=numpy.amin([options.multi, npops, multiprocessing.cpu_count()])) else: PDFs= [] for ii in range(npops): PDFs.append(calcAllPDFs(ii,options,args)) #Go through and combine combined_lnpdf= numpy.zeros((options.nrds,options.nfhs)) for ii in range(npops): if not options.group is None: if numpy.amin((gfehs-fehs[ii])**2./0.1+(gafes-afes[ii])**2./0.0025) > 0.001: continue combined_lnpdf+= PDFs[ii] alogl= combined_lnpdf-numpy.nanmax(combined_lnpdf) #Now plot bovy_plot.bovy_print() bovy_plot.bovy_dens2d(numpy.exp(alogl).T, origin='lower',cmap='gist_yarg', interpolation='nearest', xrange=[1.9,3.5],yrange=[-1./32.,1.+1./32.], xlabel=r'$R_d\ (\mathrm{kpc})$',ylabel=r'$f_h$') if not legend is None: bovy_plot.bovy_text(legend,top_left=True, size=14.) bovy_plot.bovy_end_print(options.outfilename) #Calculate and print derived properties derivProps= rawDerived(alogl,options, vo=options.fixvc/_REFV0,zh=options.fixzh, dlnvcdlnr=options.dlnvcdlnr) for key in derivProps.keys(): if not '_err' in key: print key, derivProps[key], derivProps[key+'_err'], \ derivProps[key]/derivProps[key+'_err'] return None
def plotRdsz_single(ii,options,args): if True: if _NOTDONEYET: spl= options.restart.split('.') else: spl= args[0].split('.') newname= '' for jj in range(len(spl)-1): newname+= spl[jj] if not jj == len(spl)-2: newname+= '.' newname+= '_%i.' % ii newname+= spl[-1] savefile= open(newname,'rb') try: if not _NOTDONEYET: params= pickle.load(savefile) mlogl= pickle.load(savefile) logl= pickle.load(savefile) except: return None finally: savefile.close() if _NOTDONEYET: logl[(logl == 0.)]= -numpy.finfo(numpy.dtype(numpy.float64)).max marglogl= numpy.zeros((logl.shape[0],logl.shape[6])) for jj in range(marglogl.shape[0]): for kk in range(marglogl.shape[1]): indx= True-numpy.isnan(logl[jj,0,0,:,:,:,kk,:,:,:,:].flatten()) if numpy.sum(indx) > 0: marglogl[jj,kk]= misc.logsumexp(logl[jj,0,0,:,:,:,kk,:,:,:,:].flatten()[indx]) else: marglogl[jj,kk]= -numpy.finfo(numpy.dtype(numpy.float64)).max #Normalize alogl= marglogl-numpy.amax(marglogl) bovy_plot.bovy_print() bovy_plot.bovy_dens2d(numpy.exp(alogl).T, origin='lower',cmap='gist_yarg', interpolation='nearest', xrange=[1.5,4.5], yrange=[numpy.log(15./220.),numpy.log(60./220.)], xlabel=r'$R_d$', ylabel=r'$\ln \sigma_Z / 220\ \mathrm{km\,s}^{-1}$') #Plotname spl= options.outfilename.split('.') newname= '' for jj in range(len(spl)-1): newname+= spl[jj] if not jj == len(spl)-2: newname+= '.' newname+= '_%i.' % ii newname+= spl[-1] bovy_plot.bovy_end_print(newname) return None
def plot_dustnearplane(plotname,green=False): if green: savefile= _SAVEFILE_GREEN else: savefile= _SAVEFILE_MARSHALL # Grid ls= numpy.linspace(15.,70.,_NL) bs= numpy.linspace(-2.,2.,_NB) if not os.path.exists(savefile): # Setup dust map if green: dmap= mwdust.Green15(filter='2MASS H') else: dmap= mwdust.Marshall06(filter='2MASS H') plotthis= numpy.empty((_NL,_NB)) rad= 0.5 # deg for jj in range(_NB): print jj for ii in range(_NL): pa, ah= dmap.dust_vals_disk(ls[ii],bs[jj],7.,rad) plotthis[ii,jj]= numpy.sum(pa*ah)/numpy.sum(pa) save_pickles(savefile,plotthis) else: with open(savefile,'rb') as f: plotthis= pickle.load(f) # Now plot bovy_plot.bovy_print(fig_width=8.4,fig_height=4.) bovy_plot.bovy_dens2d(plotthis[::-1].T,origin='lower',cmap=cm.coolwarm, # interpolation='nearest', colorbar=True,shrink=0.45, vmin=0.,vmax=2.-0.75*green,aspect=3., xrange=[ls[-1]+(ls[1]-ls[0])/2., ls[0]-(ls[1]-ls[0])/2.], yrange=[bs[0]-(bs[1]-bs[0])/2., bs[-1]+(bs[1]-bs[0])/2.], xlabel=r'$l\,\mathrm{(deg)}$', ylabel=r'$b\,\mathrm{(deg)}$', zlabel=r'$A_H\,(\mathrm{mag})$', zorder=0) bovy_plot.bovy_text(r'$D = 7\,\mathrm{kpc}$',top_left=True, color='w',size=16.) # Overplot fields glons= [34.,64.,27.] glats= [0.,0.,0.] colors= ['w','w','y'] xs= numpy.linspace(-1.5,1.5,201) ys= numpy.sqrt(1.5**2.-xs**2.) for glon,glat,c in zip(glons,glats,colors): bovy_plot.bovy_plot(xs+glon,ys+glat,'-',overplot=True,zorder=1,lw=2., color=c) bovy_plot.bovy_plot(xs+glon,-ys+glat,'-',overplot=True,zorder=1,lw=2., color=c) bovy_plot.bovy_end_print(plotname) return None
def testErrs(options,args): ndfehs, ndafes= 201,201 dfehs= numpy.linspace(0.01,0.4,ndfehs) dafes= numpy.linspace(0.01,0.3,ndafes) if os.path.exists(args[0]): savefile= open(args[0],'rb') loglike= pickle.load(savefile) ii= pickle.load(savefile) jj= pickle.load(savefile) savefile.close() else: loglike= numpy.zeros((ndfehs,ndafes)) ii, jj= 0, 0 while ii < ndfehs: while jj < ndafes: sys.stdout.write('\r'+"Working on %i / %i" %(ii*ndafes+jj+1,ndafes*ndfehs)) sys.stdout.flush() loglike[ii,jj]= errsLogLike(dfehs[ii],dafes[jj],options) jj+= 1 ii+= 1 jj= 0 save_pickles(args[0],loglike,ii,jj) save_pickles(args[0],loglike,ii,jj) sys.stdout.write('\r'+_ERASESTR+'\r') sys.stdout.flush() if options.prior: prior= numpy.zeros((ndfehs,ndafes)) for ii in range(ndfehs): prior[ii,:]= -0.5*(dafes-0.1)**2./0.1**2.-0.5*(dfehs[ii]-0.2)**2./0.1**2. loglike+= prior loglike-= maxentropy.logsumexp(loglike) loglike= numpy.exp(loglike) loglike/= numpy.sum(loglike)*(dfehs[1]-dfehs[0])*(dafes[1]-dafes[0]) #Plot bovy_plot.bovy_print() bovy_plot.bovy_dens2d(loglike.T,origin='lower', cmap='gist_yarg', xlabel=r'\delta_{[\mathrm{Fe/H}]}', ylabel=r'\delta_{[\alpha/\mathrm{Fe}]}', xrange=[dfehs[0],dfehs[-1]], yrange=[dafes[0],dafes[-1]], contours=True, cntrmass=True, onedhists=True, levels= special.erf(0.5*numpy.arange(1,4))) if options.prior: bovy_plot.bovy_text(r'$\mathrm{with\ Gaussian\ prior:}$'+ '\n'+r'$\delta_{[\mathrm{Fe/H}]}= 0.2 \pm 0.1$' +'\n'+r'$\delta_{[\alpha/\mathrm{Fe}]}= 0.1 \pm 0.1$', top_right=True) bovy_plot.bovy_end_print(options.plotfile)
def plotPotentials(Pot,rmin=0.,rmax=1.5,nrs=21,zmin=-0.5,zmax=0.5,nzs=21, ncontours=21,savefilename=None): """ NAME: plotPotentials PURPOSE: plot a set of potentials INPUT: Pot - Potential or list of Potential instances rmin - minimum R rmax - maximum R nrs - grid in R zmin - minimum z zmax - maximum z nzs - grid in z ncontours - number of contours savefilename - save to or restore from this savefile (pickle) OUTPUT: plot to output device HISTORY: 2010-07-09 - Written - Bovy (NYU) """ if not savefilename == None and os.path.exists(savefilename): print "Restoring savefile "+savefilename+" ..." savefile= open(savefilename,'rb') potRz= pickle.load(savefile) Rs= pickle.load(savefile) zs= pickle.load(savefile) savefile.close() else: Rs= nu.linspace(rmin,rmax,nrs) zs= nu.linspace(zmin,zmax,nzs) potRz= nu.zeros((nrs,nzs)) for ii in range(nrs): for jj in range(nzs): potRz[ii,jj]= evaluatePotentials(Rs[ii],zs[jj],Pot) if not savefilename == None: print "Writing savefile "+savefilename+" ..." savefile= open(savefilename,'wb') pickle.dump(potRz,savefile) pickle.dump(Rs,savefile) pickle.dump(zs,savefile) savefile.close() return plot.bovy_dens2d(potRz.T,origin='lower',cmap='gist_gray',contours=True, xlabel=r"$R/R_0$",ylabel=r"$z/R_0$", xrange=[rmin,rmax], yrange=[zmin,zmax], aspect=.75*(rmax-rmin)/(zmax-zmin), cntrls='-', levels=nu.linspace(nu.nanmin(potRz),nu.nanmax(potRz), ncontours))
def calc_delta_MWPotential2014(savefilename,plotfilename): Lmin, Lmax= 0.01, 10. if not os.path.exists(savefilename): #Setup grid nL, nE= 101,101 Ls= 10.**numpy.linspace(numpy.log10(Lmin),numpy.log10(Lmax),nL) #Integration times ts= numpy.linspace(0.,20.,1001) deltas= numpy.empty((nL,nE)) Einf= evalPot(10.**12.,0.,MWPotential2014) print Einf for ii in range(nL): #Calculate Ec Rc= rl(MWPotential2014,Ls[ii]) print ii, "Rc = ", Rc*8. Ec= evalPot(Rc,0.,MWPotential2014)+0.5*Ls[ii]**2./Rc**2. Es= Ec+(Einf-Ec)*10.**numpy.linspace(-2.,0.,nE) for jj in range(nE): #Setup an orbit with this energy and angular momentum Er= 2.*(Es[jj]-Ec) #Random energy times 2 = vR^2 + vz^2 vR= numpy.sqrt(4./5.*Er) vz= numpy.sqrt(1./5.*Er) o= Orbit([Rc,vR,Ls[ii]/Rc,0.,vz,0.]) o.integrate(ts,MWPotential2014,method='symplec4_c') deltas[ii,jj]= estimateDeltaStaeckel(o.R(ts),o.z(ts), pot=MWPotential2014) #Save save_pickles(savefilename,deltas) else: savefile= open(savefilename,'rb') deltas= pickle.load(savefile) savefile.close() #Plot print numpy.nanmax(deltas) bovy_plot.bovy_print() bovy_plot.bovy_dens2d(deltas.T,origin='lower',cmap='jet', xrange=[numpy.log10(Lmin),numpy.log10(Lmax)], yrange=[-2,0.], xlabel=r'$\log_{10} L$', ylabel=r'$\log_{10}\left(\frac{E-E_c(L)}{E(\infty)-E_c(L)}\right)$', colorbar=True,shrink=0.78, zlabel=r'$\mathrm{Approximate\ focal\ length}$', # interpolation='nearest', vmin=0.,vmax=0.6) bovy_plot.bovy_end_print(plotfilename) return None
def plot_dustinfield(plotname, field, threshold=False): savefile = _SAVEFILE_MARSHALL savefile = savefile.replace('FIELD', '%i' % field) # Grid ls = numpy.linspace(-1.75, 1.75, _NL) + field bs = numpy.linspace(-1.75, 1.75, _NB) if not os.path.exists(savefile): # Setup dust map dmap = mwdust.Marshall06(filter='2MASS H') plotthis = numpy.empty((_NL, _NB)) for jj in range(_NB): print jj for ii in range(_NL): plotthis[ii, jj] = dmap(ls[ii], bs[jj], 7.) save_pickles(savefile, plotthis) else: with open(savefile, 'rb') as f: plotthis = pickle.load(f) # Remove outside the field tls = numpy.tile(ls, (_NB, 1)).T tbs = numpy.tile(bs, (_NL, 1)) plotthis[(tls - field)**2. + tbs**2. > 1.5**2.] = numpy.nan if threshold: plotthis[plotthis > 1.4] = numpy.nan # Now plot bovy_plot.bovy_print() bovy_plot.bovy_dens2d( plotthis[::-1].T, origin='lower', cmap=cm.coolwarm, interpolation='nearest', vmin=0., vmax=2., aspect=1., xrange=[ls[-1] + (ls[1] - ls[0]) / 2., ls[0] - (ls[1] - ls[0]) / 2.], yrange=[bs[0] - (bs[1] - bs[0]) / 2., bs[-1] + (bs[1] - bs[0]) / 2.], xlabel=r'$l\,\mathrm{(deg)}$', ylabel=r'$b\,\mathrm{(deg)}$', zlabel=r'$A_H\,(\mathrm{mag})$', zorder=0) bovy_plot.bovy_text(r'$(l,b) = (%i,0)$' % field, top_left=True, color='k', size=16.) bovy_plot.bovy_end_print(plotname) return None
def plot_cmd(self,type='sf',cut=True): """ NAME: plot_cmd PURPOSE: Plot the distribution of counts in the color-magnitude diagram INPUT: type= ('sf') Plot 'sf': selection function 'tgas': TGAS counts '2mass': 2MASS counts cut= (True) cut to the 'good' part of the sky OUTPUT: Plot to output device HISTORY: 2017-01-17 - Written - Bovy (UofT/CCA) """ jtbins= (numpy.amax(_2mc[0])-numpy.amin(_2mc[0]))/0.1+1 nstar2mass, edges= numpy.histogramdd(\ _2mc[:3].T,bins=[jtbins,3,_BASE_NPIX], range=[[numpy.amin(_2mc[0])-0.05,numpy.amax(_2mc[0])+0.05], [-0.05,1.0],[-0.5,_BASE_NPIX-0.5]],weights=_2mc[3]) findx= (self._full_jk > -0.05)*(self._full_jk < 1.0)\ *(self._full_twomass['j_mag'] < 13.5) nstartgas, edges= numpy.histogramdd(\ numpy.array([self._full_jt[findx],self._full_jk[findx],\ (self._full_tgas['source_id'][findx]\ /2**(35.+2*(12.-numpy.log2(_BASE_NSIDE))))\ .astype('int')]).T, bins=[jtbins,3,_BASE_NPIX], range=[[numpy.amin(_2mc[0])-0.05,numpy.amax(_2mc[0])+0.05], [-0.05,1.0],[-0.5,_BASE_NPIX-0.5]]) if cut: nstar2mass[:,:,self._exclude_mask_skyonly]= numpy.nan nstartgas[:,:,self._exclude_mask_skyonly]= numpy.nan nstar2mass= numpy.nansum(nstar2mass,axis=-1) nstartgas= numpy.nansum(nstartgas,axis=-1) if type == 'sf': pt= nstartgas/nstar2mass vmin= 0. vmax= 1. zlabel=r'$\mathrm{completeness}$' elif type == 'tgas' or type == '2mass': vmin= 0. vmax= 6. zlabel= r'$\log_{10}\mathrm{number\ counts}$' if type == 'tgas': pt= numpy.log10(nstartgas) elif type == '2mass': pt= numpy.log10(nstar2mass) return bovy_plot.bovy_dens2d(pt,origin='lower', cmap='viridis',interpolation='nearest', colorbar=True,shrink=0.78, vmin=vmin,vmax=vmax,zlabel=zlabel, yrange=[edges[0][0],edges[0][-1]], xrange=[edges[1][0],edges[1][-1]], xlabel=r'$J-K_s$', ylabel=r'$J+\Delta J$')
def plot_dustinfield(plotname,field,threshold=False): savefile= _SAVEFILE_MARSHALL savefile= savefile.replace('FIELD','%i' % field) # Grid ls= numpy.linspace(-1.75,1.75,_NL)+field bs= numpy.linspace(-1.75,1.75,_NB) if not os.path.exists(savefile): # Setup dust map dmap= mwdust.Marshall06(filter='2MASS H') plotthis= numpy.empty((_NL,_NB)) for jj in range(_NB): print jj for ii in range(_NL): plotthis[ii,jj]= dmap(ls[ii],bs[jj],7.) save_pickles(savefile,plotthis) else: with open(savefile,'rb') as f: plotthis= pickle.load(f) # Remove outside the field tls= numpy.tile(ls,(_NB,1)).T tbs= numpy.tile(bs,(_NL,1)) plotthis[(tls-field)**2.+tbs**2. > 1.5**2.]= numpy.nan if threshold: plotthis[plotthis > 1.4]= numpy.nan # Now plot bovy_plot.bovy_print() bovy_plot.bovy_dens2d(plotthis[::-1].T,origin='lower',cmap=cm.coolwarm, interpolation='nearest', vmin=0.,vmax=2.,aspect=1., xrange=[ls[-1]+(ls[1]-ls[0])/2., ls[0]-(ls[1]-ls[0])/2.], yrange=[bs[0]-(bs[1]-bs[0])/2., bs[-1]+(bs[1]-bs[0])/2.], xlabel=r'$l\,\mathrm{(deg)}$', ylabel=r'$b\,\mathrm{(deg)}$', zlabel=r'$A_H\,(\mathrm{mag})$', zorder=0) bovy_plot.bovy_text(r'$(l,b) = (%i,0)$' % field,top_left=True, color='k',size=16.) bovy_plot.bovy_end_print(plotname) return None
def plot_elliptical_constraint(plotfilename,future=False): cs= numpy.linspace(-0.25,0.25,201) ss= numpy.linspace(-0.25,0.25,201) cons= numpy.zeros((len(cs),len(ss),200)) for ii in range(len(cs)): for jj in range(len(ss)): twophio= numpy.sqrt(cs[ii]**2.+ss[jj]**2.) phib= math.atan2(ss[jj],cs[ii])/2. q= 1-twophio for zz in range(8+future*10): for ww in range(zz,8+future*10): if future: cons[ii,jj,ww+zz*7]= q**2.*(1./numpy.sqrt(q**2.*numpy.cos((45.-zz*5.)*numpy.pi/180.-phib)**2.+numpy.sin((45.-zz*5.)*numpy.pi/180.-phib)**2.)-1./numpy.sqrt(q**2.*numpy.cos((40.-5.*ww)*numpy.pi/180.-phib)**2.+numpy.sin((40.-ww*5.)*numpy.pi/180.-phib)**2.))**2. else: cons[ii,jj,ww+zz*7]= q**2.*(1./numpy.sqrt(q**2.*numpy.cos((25.-zz*5.)*numpy.pi/180.-phib)**2.+numpy.sin((25.-zz*5.)*numpy.pi/180.-phib)**2.)-1./numpy.sqrt(q**2.*numpy.cos((20.-5.*ww)*numpy.pi/180.-phib)**2.+numpy.sin((20.-ww*5.)*numpy.pi/180.-phib)**2.))**2. #cons[ii,jj,zz]= q**2.*(1./numpy.sqrt(q**2.*numpy.cos((25.*numpy.pi/180.-phib)**2.+numpy.sin(25.*numpy.pi/180.-phib)**2.)-1./numpy.sqrt(q**2.*numpy.cos((20.-5.*zz)*numpy.pi/180.-phib)**2.+numpy.sin((20.-zz*5.)*numpy.pi/180.-phib)**2.))**2. plotthis= numpy.all(cons < 1./40.**2.,axis=2)*0.65 #Plot bovy_plot.bovy_print() bovy_plot.bovy_dens2d(plotthis.T, origin='lower', cmap='gist_yarg', xrange=[-0.25,0.25], yrange=[-0.25,0.25], xlabel=r'$c_\Psi = \varepsilon_\Psi\,\cos 2 \phi_b$', ylabel=r'$s_\Psi = \varepsilon_\Psi\,\sin 2 \phi_b$', vmax=1.) bovy_plot.bovy_plot([-0.15,-0.12],[0.15,0.02],'k-',zorder=1, overplot=True) bovy_plot.bovy_plot([-0.06363636363636363],[0.],'wx',overplot=True,ms=10., mew=2.,zorder=2.) bovy_plot.bovy_plot([-0.06363636363636363,-0.02],[0.,-0.14],'k-',zorder=1, overplot=True) bovy_plot.bovy_text(-0.08,-0.2,r'$\mathrm{model\ with}$'+'\n'+r'$\mathrm{local}\ V_c - \mathrm{global}\ V_c = 14\,\mathrm{km\,s}^{-1}$', size=13.) bovy_plot.bovy_text(r'$\mathrm{Elliptical\ disk\ models\ with}$'+'\n'+r'$\forall i \in [0,7] \cap \mathbb{Z}: \forall j \in [i,7] \cap \mathbb{Z}:$'+'\n'+r'$|\Delta R(\phi=25^\circ - 5^\circ\,i,\phi=20^\circ-5^\circ\,j)| < 200\,\mathrm{pc}$', size=13., top_left=True) bovy_plot.bovy_end_print(plotfilename) return None
def plot_psd2d(plotfilename): data= apread.rcsample() if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] #Cut indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.) print "Using %i stars for low-Z 2D kinematics analysis" % numpy.sum(indx) data= data[indx] #Get residuals dx= _RCDX binsize= .8#.765 pix= pixelize_sample.pixelXY(data, xmin=_RCXMIN,xmax=_RCXMAX, ymin=_RCYMIN,ymax=_RCYMAX, dx=dx,dy=dx) resv= pix.plot(lambda x: dvlosgal(x,vtsun=220.+22.6), returnz=True,justcalc=True) resvunc= pix.plot('VHELIO_AVG', func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)), returnz=True,justcalc=True) psd2d= bovy_psd.psd2d(resv) tmax= numpy.unravel_index(numpy.argmax(psd2d),psd2d.shape) tmax0= float(psd2d.shape[0]/2-tmax[0])/psd2d.shape[0]*2 tmax1= float(tmax[1]-psd2d.shape[1]/2)/psd2d.shape[1]*2 kmax= 1./_RCDX print tmax0*kmax, tmax1*kmax #kmax= numpy.amax(numpy.fft.fftfreq(resv.shape[0]*2,_RCDX)) bovy_plot.bovy_print() bovy_plot.bovy_dens2d(psd2d.T,origin='lower',cmap='jet', interpolation='nearest', xrange=[-kmax,kmax], yrange=[-kmax,kmax], xlabel=r'$k_x\,(\mathrm{kpc}^{-1})$', ylabel=r'$k_y\,(\mathrm{kpc}^{-1})$') bovy_plot.bovy_end_print(plotfilename) if True: spvlos= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_hivres.sav')[1::2,1::2] potscale= 1.
def fakeSlopesFig1(options,args): #Read data for bins raw= read_gdwarfs(logg=True,ebv=True,sn=True) binned= pixelAfeFeh(raw,dfeh=_DFEH,dafe=_DAFE)#these dfehs are binsizes tightbinned= pixelAfeFeh(raw,dfeh=_DFEH,dafe=_DAFE, fehmin=-1.6,fehmax=0.5,afemin=-0.05, afemax=0.55) plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe())) for ii in range(tightbinned.npixfeh()): for jj in range(tightbinned.npixafe()): data= binned(tightbinned.feh(ii),tightbinned.afe(jj)) fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning afeindx= binned.afeindx(tightbinned.afe(jj)) if len(data) < _MINNDATA: plotthis[ii,jj]= numpy.nan continue plotthis[ii,jj]= calcSlope(tightbinned.feh(ii),tightbinned.afe(jj), options.dfeh,options.dafe,options) vmin, vmax= -5.,5. zlabel= r'$\frac{\mathrm{d} \sigma_z(z_{1/2})}{\mathrm{d} z}\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$' xrange=[-1.6,0.5] yrange=[-0.05,0.55] bovy_plot.bovy_print() bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet', interpolation='nearest', xlabel=r'$[\mathrm{Fe/H}]$', ylabel=r'$[\alpha/\mathrm{Fe}]$', zlabel=zlabel, xrange=xrange,yrange=yrange, vmin=vmin,vmax=vmax, contours=False, colorbar=True,shrink=0.78) bovy_plot.bovy_text(r'$\delta_{[\mathrm{Fe/H}]} = %.2f$' % options.dfeh +'\n'+r'$\delta_{[\alpha/\mathrm{Fe}]} = %.2f$' % options.dafe, top_right=True,size=18.) bovy_plot.bovy_end_print(options.plotfile)
def plot(self, log=False, conditional=False, nbins=None): """ NAME: plot PURPOSE: plot the resulting (J-Ks,H) distribution INPUT: log= (default: False) if True, plot log conditional= (default: False) if True, plot conditional distribution of H given J-Ks nbins= if set, set the number of bins OUTPUT: plot to output device HISTORY: 2012-02-17 - Written - Bovy (IAS) """ if not _BOVY_PLOT_LOADED: raise ImportError( "'galpy.util.bovy_plot' plotting package not found") #Form histogram grid if nbins is None: nbins = self._nbins jks = numpy.linspace(self._jkmin + self._djk / 2., self._jkmax - self._djk / 2., nbins) hs = numpy.linspace( self._hmax - self._dh / 2., #we reverse self._hmin + self._dh / 2., nbins) plotthis = numpy.zeros((nbins, nbins)) for ii in range(nbins): for jj in range(nbins): plotthis[ii, jj] = self(jks[ii], hs[jj]) if not log: plotthis = numpy.exp(plotthis) if conditional: #normalize further for ii in range(nbins): plotthis[ii, :] /= numpy.nanmax( plotthis[ii, :]) / numpy.nanmax(plotthis) return bovy_plot.bovy_dens2d(plotthis.T, origin='lower', cmap='gist_yarg', xrange=[self._jkmin, self._jkmax], yrange=[self._hmax, self._hmin], aspect=(self._jkmax - self._jkmin) / (self._hmax - self._hmin), xlabel=r'$(J-K_s)_0\ [\mathrm{mag}]$', ylabel=r'$M_H\ [\mathrm{mag}]$', interpolation='nearest')
def plot(self,log=False,conditional=False,nbins=None): """ NAME: plot PURPOSE: plot the resulting (J-Ks,H) distribution INPUT: log= (default: False) if True, plot log conditional= (default: False) if True, plot conditional distribution of H given J-Ks nbins= if set, set the number of bins OUTPUT: plot to output device HISTORY: 2012-02-17 - Written - Bovy (IAS) """ if not _BOVY_PLOT_LOADED: raise ImportError("'galpy.util.bovy_plot' plotting package not found") #Form histogram grid if nbins is None: nbins= self._nbins jks= numpy.linspace(self._jkmin+self._djk/2., self._jkmax-self._djk/2., nbins) hs= numpy.linspace(self._hmax-self._dh/2.,#we reverse self._hmin+self._dh/2., nbins) plotthis= numpy.zeros((nbins,nbins)) for ii in range(nbins): for jj in range(nbins): plotthis[ii,jj]= self(jks[ii],hs[jj]) if not log: plotthis= numpy.exp(plotthis) if conditional: #normalize further for ii in range(nbins): plotthis[ii,:]/= numpy.nanmax(plotthis[ii,:])/numpy.nanmax(plotthis) return bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='gist_yarg', xrange=[self._jkmin,self._jkmax], yrange=[self._hmax,self._hmin], aspect=(self._jkmax-self._jkmin)/(self._hmax-self._hmin), xlabel=r'$(J-K_s)_0\ [\mathrm{mag}]$', ylabel=r'$M_H\ [\mathrm{mag}]$', interpolation='nearest')
def plot(self,t=0.,rmin=0.,rmax=1.5,nrs=21,zmin=-0.5,zmax=0.5,nzs=21, effective=False,Lz=None, xrange=None,yrange=None, ncontours=21,savefilename=None): """ NAME: plot PURPOSE: plot the potential INPUT: t - time tp plot potential at rmin - minimum R at which to calculate rmax - maximum R nrs - grid in R zmin - minimum z zmax - maximum z nzs - grid in z effective= (False) if True, plot the effective potential Phi + Lz^2/2/R^2 Lz= (None) angular momentum to use for the effective potential when effective=True ncontours - number of contours savefilename - save to or restore from this savefile (pickle) xrange, yrange= can be specified independently from rmin,zmin, etc. OUTPUT: plot to output device HISTORY: 2010-07-09 - Written - Bovy (NYU) 2014-04-08 - Added effective= - Bovy (IAS) """ if xrange is None: xrange= [rmin,rmax] if yrange is None: yrange= [zmin,zmax] if not savefilename == None and os.path.exists(savefilename): print "Restoring savefile "+savefilename+" ..." savefile= open(savefilename,'rb') potRz= pickle.load(savefile) Rs= pickle.load(savefile) zs= pickle.load(savefile) savefile.close() else: if effective and Lz is None: raise RuntimeError("When effective=True, you need to specify Lz=") Rs= nu.linspace(xrange[0],xrange[1],nrs) zs= nu.linspace(yrange[0],yrange[1],nzs) potRz= nu.zeros((nrs,nzs)) for ii in range(nrs): for jj in range(nzs): potRz[ii,jj]= self._evaluate(Rs[ii],zs[jj],t=t) if effective: potRz[ii,:]+= 0.5*Lz**2/Rs[ii]**2. #Don't plot outside of the desired range potRz[Rs < rmin,:]= nu.nan potRz[Rs > rmax,:]= nu.nan potRz[:,zs < zmin]= nu.nan potRz[:,zs > zmax]= nu.nan if not savefilename == None: print "Writing savefile "+savefilename+" ..." savefile= open(savefilename,'wb') pickle.dump(potRz,savefile) pickle.dump(Rs,savefile) pickle.dump(zs,savefile) savefile.close() return plot.bovy_dens2d(potRz.T,origin='lower',cmap='gist_gray',contours=True, xlabel=r"$R/R_0$",ylabel=r"$z/R_0$", xrange=xrange, yrange=yrange, aspect=.75*(rmax-rmin)/(zmax-zmin), cntrls='-', levels=nu.linspace(nu.nanmin(potRz),nu.nanmax(potRz), ncontours))
def plot_vs_jkz(parser): options,args= parser.parse_args() if options.basti: zs= numpy.array([0.004,0.008,0.01,0.0198,0.03,0.04]) elif options.parsec: zs= numpy.arange(0.0005,0.06005,0.0005) else: zs= numpy.arange(0.0005,0.03005,0.0005) if os.path.exists(args[0]): savefile= open(args[0],'rb') plotthis= pickle.load(savefile) jks= pickle.load(savefile) zs= pickle.load(savefile) savefile.close() else: njks= 101 jks= numpy.linspace(0.5,0.8,njks) plotthis= numpy.zeros((njks,len(zs))) funcargs= (zs,options,njks,jks) multOut= multi.parallel_map((lambda x: indiv_calc(x, *funcargs)), range(len(zs)), numcores=numpy.amin([64,len(zs), multiprocessing.cpu_count()])) for ii in range(len(zs)): plotthis[:,ii]= multOut[ii] #Save save_pickles(args[0],plotthis,jks,zs) #Plot if options.type == 'sig': if options.band.lower() == 'age': if options.relative: raise NotImplementedError("relative age not implemented yet") else: vmin, vmax= 0.,.5 zlabel= r'$\mathrm{FWHM} / 2\sqrt{2\,\ln 2}$' else: if options.relative: vmin, vmax= 0.8,1.2 zlabel= r'$\mathrm{FWHM}/\mathrm{FWHM}_{\mathrm{fiducial}}$' else: vmin, vmax= 0., 0.4 zlabel= r'$\mathrm{FWHM} / 2\sqrt{2\,\ln 2}$' elif options.type == 'mode': if options.band.lower() == 'age': if options.relative: raise NotImplementedError("relative age not implemented yet") else: vmin, vmax= 0.,1. zlabel= r'$\Delta\displaystyle\arg\!\max_{\substack{\log_{10}\mathrm{Age}}}{p(\log_{10}\mathrm{Age}|[J-K_s]_0)}$' else: if options.relative: vmin, vmax= -0.05,0.05 zlabel= r'$\Delta\displaystyle\arg\!\max_{\substack{K_s}}{p(M_{K_s}|[J-K_s]_0)}$' else: vmin, vmax= -1.8, -1.5 if options.band.lower() == 'h': zlabel= r'$\displaystyle\arg\!\max_{\substack{H}}{p(M_{H}|[J-K_s]_0)}$' else: zlabel= r'$\displaystyle\arg\!\max_{\substack{K_s}}{p(M_{K_s}|[J-K_s]_0)}$' if options.basti:#Remap the Zs zs= numpy.array([0.004,0.008,0.01,0.0198,0.03,0.04]) regularzs= numpy.arange(0.0005,0.04005,0.0005) njks= len(jks) regularplotthis= numpy.zeros((njks,len(regularzs))) for jj in range(len(regularzs)): #Find z thisindx= numpy.argmin(numpy.fabs(regularzs[jj]-zs)) for ii in range(njks): regularplotthis[ii,jj]= plotthis[ii,thisindx] zs= regularzs plotthis= regularplotthis if options.relative and os.path.exists(options.infilename): savefile= open(options.infilename,'rb') plotthisrel= pickle.load(savefile) savefile.close() if options.basti: plotthisrel= plotthisrel[:,:80] elif not options.parsec: plotthisrel= plotthisrel[:,:60] if options.type == 'mode': plotthis-= plotthisrel elif options.type == 'sig': plotthis/= plotthisrel bovy_plot.bovy_print() if options.type == 'sig': plotthis[numpy.isnan(plotthis)]= vmax if options.relative: #Only plot between the cuts for ii in range(plotthis.shape[0]): indx= zs >= rcmodel.jkzcut(jks[ii],upper=True) indx+= zs <= rcmodel.jkzcut(jks[ii],upper=False) plotthis[ii,indx]= numpy.nan bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet', xrange=[jks[0],jks[-1]], yrange=[zs[0],zs[-1]], vmin=vmin,vmax=vmax, xlabel=r'$(J-K_s)_0$', ylabel=r'$Z$', interpolation='nearest', colorbar=True, shrink=0.78, zlabel=zlabel) #Overplot cuts bovy_plot.bovy_plot(jks,rcmodel.jkzcut(jks), 'w--',lw=2.,overplot=True) bovy_plot.bovy_plot(jks,rcmodel.jkzcut(jks,upper=True), 'w--',lw=2.,overplot=True) if options.basti: pyplot.annotate(r'$\mathrm{BaSTI}$', (0.5,1.08),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=16.) elif not options.parsec: pyplot.annotate(r'$\mathrm{Padova}$', (0.5,1.08),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=16.) elif options.imfmodel == 'kroupa2003': pyplot.annotate(r'$\mathrm{Kroupa\ (2003)\ IMF}$', (0.5,1.08),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=16.) elif 'expsfh' in args[0]: pyplot.annotate(r'$\mathrm{p(\mathrm{Age}) \propto e^{\mathrm{Age}/(8\,\mathrm{Gyr})}}$', (0.5,1.08),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=16.) elif not options.eta is None: pyplot.annotate(r'$\eta_{\mathrm{Reimers}} = %.1f$' % options.eta, (0.5,1.08),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=16.) elif False: pyplot.annotate(r'$\mathrm{Padova}$', (0.5,1.08),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=16.) bovy_plot.bovy_end_print(options.outfilename) return None
def plotDensities(Pot,rmin=0.,rmax=1.5,nrs=21,zmin=-0.5,zmax=0.5,nzs=21, ncontours=21,savefilename=None,aspect=None,log=False, justcontours=False): """ NAME: plotDensities PURPOSE: plot the density a set of potentials INPUT: Pot - Potential or list of Potential instances rmin= minimum R rmax= maximum R nrs= grid in R zmin= minimum z zmax= maximum z nzs= grid in z ncontours= number of contours justcontours= (False) if True, just plot contours savefilename= save to or restore from this savefile (pickle) log= if True, plot the log density OUTPUT: plot to output device HISTORY: 2013-07-05 - Written - Bovy (IAS) """ if not savefilename == None and os.path.exists(savefilename): print "Restoring savefile "+savefilename+" ..." savefile= open(savefilename,'rb') potRz= pickle.load(savefile) Rs= pickle.load(savefile) zs= pickle.load(savefile) savefile.close() else: Rs= nu.linspace(rmin,rmax,nrs) zs= nu.linspace(zmin,zmax,nzs) potRz= nu.zeros((nrs,nzs)) for ii in range(nrs): for jj in range(nzs): potRz[ii,jj]= evaluateDensities(nu.fabs(Rs[ii]), zs[jj],Pot) if not savefilename == None: print "Writing savefile "+savefilename+" ..." savefile= open(savefilename,'wb') pickle.dump(potRz,savefile) pickle.dump(Rs,savefile) pickle.dump(zs,savefile) savefile.close() if aspect is None: aspect=.75*(rmax-rmin)/(zmax-zmin) if log: potRz= nu.log(potRz) return plot.bovy_dens2d(potRz.T,origin='lower',cmap='gist_yarg',contours=True, xlabel=r"$R/R_0$",ylabel=r"$z/R_0$", aspect=aspect, xrange=[rmin,rmax], yrange=[zmin,zmax], cntrls='-', justcontours=justcontours, levels=nu.linspace(nu.nanmin(potRz),nu.nanmax(potRz), ncontours))
def plotForceField(savefig: Optional[str] = None): """Plot MW Force Field. Parameters ---------- savefic: str, optional """ p_b15_pal5gd1_voro = fit(fitc=True, c=None, addpal5=True, addgd1=True, fitvoro=True, mc16=True) # Set up potential p_b15 = p_b15_pal5gd1_voro[0] ro, vo = REFR0, REFV0 pot = setup_potential(p_b15, p_b15_pal5gd1_voro[0][-1], False, False, ro, vo) # Compute force field Rs = np.linspace(0.01, 20.0, 51) zs = np.linspace(-20.0, 20.0, 151) mRs, mzs = np.meshgrid(Rs, zs, indexing="ij") forces = np.zeros((len(Rs), len(zs), 2)) potvals = np.zeros((len(Rs), len(zs))) for ii in tqdm(range(len(Rs))): for jj in tqdm(range(len(zs))): forces[ii, jj, 0] = potential.evaluateRforces( pot, mRs[ii, jj] / ro, mzs[ii, jj] / ro, use_physical=True, ro=ro, vo=vo, ) forces[ii, jj, 1] = potential.evaluatezforces( pot, mRs[ii, jj] / ro, mzs[ii, jj] / ro, use_physical=True, ro=ro, vo=vo, ) potvals[ii, jj] = potential.evaluatePotentials( pot, mRs[ii, jj] / ro, mzs[ii, jj] / ro, use_physical=True, ro=ro, vo=vo, ) fig = plt.figure(figsize=(8, 16)) skip = 10 # Make sure to keep zs symmetric!! scale = 35.0 # Don't plot these # forces[(mRs < 5.)*(np.fabs(mzs) < 4.)]= np.nan forces[(mRs < 2.0) * (np.fabs(mzs) < 5.0)] = np.nan bovy_plot.bovy_dens2d( potvals.T, origin="lower", cmap="viridis", xrange=[Rs[0], Rs[-1]], yrange=[zs[0], zs[-1]], xlabel=r"$R\,(\mathrm{kpc})$", ylabel=r"$Z\,(\mathrm{kpc})$", contours=True, aspect=1.0, ) plt.quiver( mRs[1::skip, 5:-1:skip], mzs[1::skip, 5:-1:skip], forces[1::skip, 5:-1:skip, 0], forces[1::skip, 5:-1:skip, 1], scale=scale, ) # Add a few lines pointing to the GC for angle in tqdm(np.linspace(0.0, np.pi / 2.0, 8)): plt.plot((0.0, 100.0 * np.cos(angle)), (0.0, 100.0 * np.sin(angle)), "k:") plt.plot((0.0, 100.0 * np.cos(angle)), (0.0, -100.0 * np.sin(angle)), "k:") # Add measurements # Pal 5 plt.quiver((8.0, ), (16.0, ), (-0.8, ), (-1.82, ), color="w", zorder=10, scale=scale) # GD-1 plt.quiver( (12.5, ), (6.675, ), (-2.51, ), (-1.47, ), color="w", zorder=10, scale=scale, ) # Disk + flat APOGEE rotation curve: # Use Bovy & Tremaine (2012) method for translating F_R in the plane to F_R # at 1.1 kpc: dFr/dz = dFz / dR diskrs = np.linspace(5.5, 8.5, 3) diskfzs = (-67.0 * np.exp(-(diskrs - 8.0) / 2.7) / bovy_conversion.force_in_2piGmsolpc2(220.0, 8.0) * bovy_conversion.force_in_kmsMyr(220.0, 8.0)) diskfrs = (-(218.0**2.0 / diskrs) * bovy_conversion._kmsInPcMyr / 1000.0 - 1.1 * diskfzs / 2.7) plt.quiver( diskrs, 1.1 * np.ones_like(diskrs), diskfrs, diskfzs, color="w", zorder=10, scale=scale, ) # Labels bovy_plot.bovy_text(5.8, 16.0, r"$\mathbf{Pal\ 5}$", color="w", size=17.0) bovy_plot.bovy_text(12.5, 7.0, r"$\mathbf{GD-1}$", color="w", size=17.0) bovy_plot.bovy_text(8.65, 0.5, r"$\mathbf{disk\ stars}$", color="w", size=17.0) if savefig is not None: fig.savefig(savefig) return fig
def map_vc_like_simple(parser): """ NAME: map_vc_like_simple PURPOSE: map the vc likelihood assuming knowledge of the DF INPUT: parser - from optparse OUTPUT: stuff as specified by the options HISTORY: 2011-04-20 - Written - Bovy (NYU) """ (options, args) = parser.parse_args() if len(args) == 0: parser.print_help() sys.exit(-1) #Set up DF dfc = dehnendf(beta=0., profileParams=(options.rd, options.rs, options.so), correct=True, niter=20) #Load data picklefile = open(args[0], 'rb') out = pickle.load(picklefile) picklefile.close() ndata = len(out) if options.linearfit: plot_linear(out, options.los * _DEGTORAD, options, dfc) return None #Map likelihood vcirc = nu.linspace(options.vmin, options.vmax, options.nvcirc) if not options.nbeta is None: betas = nu.linspace(options.betamin, options.betamax, options.nbeta) like = nu.zeros((options.nvcirc, options.nbeta)) for ii in range(options.nvcirc): for kk in range(options.nbeta): thislike = 0. for jj in range(ndata): thislike += single_vlos_loglike(vcirc[ii], out[jj], dfc, options, options.los * _DEGTORAD, beta=betas[kk]) like[ii, kk] = thislike like -= logsumexp(like.flatten()) + m.log(vcirc[1] - vcirc[0]) bovy_plot.bovy_print() bovy_plot.bovy_dens2d(nu.exp(like).T, origin='lower', xrange=[options.vmin,options.vmax], yrange=[options.betamin,options.betamax], aspect=(options.vmax-options.vmin)/\ (options.betamax-options.betamin), cmap='gist_yarg', xlabel=r'$v_c / v_0$', ylabel=r'$\beta$', contours=True,cntrmass=True, levels=[0.682,0.954,0.997]) bovy_plot.bovy_text(r'$\sigma_R(R_0) = %4.2f \ v_0$' % options.so\ +'\n'+\ r'$l = %i^\circ$' % round(options.los), top_left=True) bovy_plot.bovy_end_print(options.plotfilename) else: like = nu.zeros(options.nvcirc) for ii in range(options.nvcirc): thislike = 0. for jj in range(ndata): thislike += single_vlos_loglike(vcirc[ii], out[jj], dfc, options, options.los * _DEGTORAD) like[ii] = thislike like -= logsumexp(like) + m.log(vcirc[1] - vcirc[0]) #Calculate mean and sigma vcmean = nu.sum(vcirc * nu.exp(like) * (vcirc[1] - vcirc[0])) vc2mean = nu.sum(vcirc**2. * nu.exp(like) * (vcirc[1] - vcirc[0])) #Plot bovy_plot.bovy_print() bovy_plot.bovy_plot(vcirc, nu.exp(like), 'k-', xlabel=r'$v_c / v_0$', ylabel=r'$p(\mathrm{data} | v_c)$') bovy_plot.bovy_text(r'$\langle v_c \rangle = %4.2f \ v_0$' % vcmean +'\n'+ r'$\sqrt{\langle v_c^2 \rangle - \langle v_c \rangle^2} = %4.2f \ v_0$' % (m.sqrt(vc2mean-vcmean**2.)) +'\n'+\ r'$\sigma_R(R_0) = %4.2f \ v_0$' % options.so+'\n'+\ r'$l = %i^\circ$' % round(options.los), top_left=True) bovy_plot.bovy_end_print(options.plotfilename)
def plot_rckinematics(plotfilename,subsun=False): #Set up 3 axes bovy_plot.bovy_print(fig_width=8.,axes_labelsize=14) axdx= 1./3. #APOGEE-RC observations tdy= (_RCYMAX-_RCYMIN+4.5)/(_RCXMAX-_RCXMIN+4.5)*axdx obsAxes= pyplot.axes([0.1,(1.-tdy)/2.,axdx,tdy]) pyplot.sca(obsAxes) data= apread.rcsample() if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] #Cut indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.) data= data[indx] #Get velocity field pixrc= pixelize_sample.pixelXY(data, xmin=_RCXMIN-2.25,xmax=_RCXMAX+2.25, ymin=_RCYMIN-2.25,ymax=_RCYMAX+2.25, dx=_RCDX,dy=_RCDX) if subsun: vmin, vmax= 0., 250. pixrc.plot(lambda x: vlosgal(x), func=lambda x: numpy.fabs(numpy.median(x)), zlabel=r'$|\mathrm{median}\ V^{\mathrm{GC}}_{\mathrm{los}}|\,(\mathrm{km\,s}^{-1})$', vmin=vmin,vmax=vmax) else: vmin, vmax= -75., 75. img= pixrc.plot('VHELIO_AVG', vmin=vmin,vmax=vmax,overplot=True, colorbar=False) resv= pixrc.plot('VHELIO_AVG', justcalc=True,returnz=True) #for later bovy_plot.bovy_text(r'$\mathrm{typical\ uncertainty\!:}\ 3\,\mathrm{km\,s}^{-1}$', bottom_left=True,size=8.25) bovy_plot.bovy_text(r'$|Z| < 250\,\mathrm{pc}$',top_right=True,size=10.) pyplot.annotate(r'$\mathrm{APOGEE\!-\!RC\ data}$', (0.5,1.09),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=10.) pyplot.axis([pixrc.xmin,pixrc.xmax,pixrc.ymin,pixrc.ymax]) bovy_plot._add_ticks() bovy_plot._add_axislabels(r'$X_{\mathrm{GC}}\,(\mathrm{kpc})$', r'$Y_{\mathrm{GC}}\,(\mathrm{kpc})$') #Colorbar cbaxes = pyplot.axes([0.1625,(1.-tdy)/2.+tdy+0.065,2.*axdx-0.195,0.02]) CB1= pyplot.colorbar(img,orientation='horizontal', cax=cbaxes)#,ticks=[-16.,-8.,0.,8.,16.]) CB1.set_label(r'$\mathrm{median}\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',labelpad=-35,fontsize=14.) #Now calculate the expected field xgrid= numpy.arange(_RCXMIN-2.25+_RCDX/2.,_RCXMAX+2.25+_RCDX/2.,_RCDX) ygrid= numpy.arange(_RCYMIN-2.25+_RCDX/2.,_RCYMAX+2.25+_RCDX/2.,_RCDX) xv,yv= numpy.meshgrid(xgrid,ygrid,indexing='ij') rs= numpy.sqrt(xv**2.+yv**2.) phis= numpy.arctan2(yv,xv) d,l= bovy_coords.rphi_to_dl_2d(rs/8.,phis) expec_vlos= numpy.empty((len(xgrid),len(ygrid))) for ii in range(len(xgrid)): for jj in range(len(ygrid)): expec_vlos[ii,jj]= modelvlosgal(rs[ii,jj],phis[ii,jj],l[ii,jj], vc=218.,vtsun=242.) modelAxes= pyplot.axes([0.03+axdx,(1.-tdy)/2.,axdx,tdy]) pyplot.sca(modelAxes) xlabel=r'$X_{\mathrm{GC}}\,(\mathrm{kpc})$' ylabel=r'$Y_{\mathrm{GC}}\,(\mathrm{kpc})$' indx= True-numpy.isnan(resv) plotthis= copy.copy(expec_vlos) plotthis[numpy.isnan(resv)]= numpy.nan #turn these off bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet', interpolation='nearest', xlabel=xlabel,ylabel=ylabel, xrange=[_RCXMIN-2.25,_RCXMAX+2.25], yrange=[_RCYMIN-2.25,_RCYMAX+2.25], contours=False, vmin=vmin,vmax=vmax,overplot=True,zorder=3) if True: #Now plot the pixels outside the APOGEE data set plotthis= copy.copy(expec_vlos) plotthis[True-numpy.isnan(resv)]= numpy.nan #turn these off bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet', interpolation='nearest', alpha=0.3, xrange=[_RCXMIN-2.25,_RCXMAX+2.25], yrange=[_RCYMIN-2.25,_RCYMAX+2.25], contours=False, vmin=vmin,vmax=vmax,overplot=True, zorder=0) pyplot.annotate(r'$\mathrm{Bovy\ et.\ al\ (2012)\ model}$', (1.02,1.09),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=10.,zorder=3) pyplot.axis([_RCXMIN-2.25,_RCXMAX+2.25,_RCYMIN-2.25,_RCYMAX+2.25]) bovy_plot._add_ticks() bovy_plot._add_axislabels(xlabel,r'$ $') #Finally, add a polar plot of the whole disk res= 51 rmin, rmax= 0.2, 2.4 xgrid= numpy.linspace(0.,2.*numpy.pi*(1.-1./res/2.), 2.*res) ygrid= numpy.linspace(rmin,rmax,res) nx= len(xgrid) ny= len(ygrid) savefile= 'expec_vlos.sav' if os.path.exists(savefile): savefile= open(savefile,'rb') expec_vlos= pickle.load(savefile) savefile.close() else: expec_vlos= numpy.zeros((nx,ny)) for ii in range(nx): for jj in range(ny): R, phi= ygrid[jj], xgrid[ii] d,l= bovy_coords.rphi_to_dl_2d(R,phi) expec_vlos[ii,jj]= modelvlosgal(R*8.,phi,l, vc=218.,vtsun=242.) save_pickles(savefile,expec_vlos) plotxgrid= numpy.linspace(xgrid[0]-(xgrid[1]-xgrid[0])/2., xgrid[-1]+(xgrid[1]-xgrid[0])/2., len(xgrid)+1) plotygrid= numpy.linspace(ygrid[0]-(ygrid[1]-ygrid[0])/2., ygrid[-1]+(ygrid[1]-ygrid[0])/2., len(ygrid)+1) fullmodelAxes= pyplot.axes([-0.05+2.*axdx,(1.-tdy)/2.,axdx,tdy],polar=True) ax= fullmodelAxes pyplot.sca(fullmodelAxes) vmin, vmax= -150., 150. zlabel= r'$\mathrm{line\!-\!of\!-\!sight\ velocity}\ (\mathrm{km\,s}^{-1})$' out= ax.pcolor(plotxgrid,plotygrid,expec_vlos.T,cmap='jet', vmin=vmin,vmax=vmax,clip_on=False) shrink= 0.8 if False: CB1= pyplot.colorbar(out,shrink=shrink) bbox = CB1.ax.get_position().get_points() CB1.ax.set_position(transforms.Bbox.from_extents(bbox[0,0]+0.025, bbox[0,1], bbox[1,0], bbox[1,1])) CB1.set_label(zlabel) from matplotlib.patches import FancyArrowPatch arr= FancyArrowPatch(posA=(numpy.pi+0.1,1.8), posB=(3*numpy.pi/2.+0.1,1.8), arrowstyle='->', connectionstyle='arc3,rad=%4.2f' % (numpy.pi/8.-0.05), shrinkA=2.0, shrinkB=2.0, mutation_scale=20.0, mutation_aspect=None,fc='k') ax.add_patch(arr) bovy_plot.bovy_text(numpy.pi+0.17,1.7,r'$\mathrm{Galactic\ rotation}$', rotation=-30.,size=9.) radii= numpy.array([0.5,1.,1.5,2.,2.5]) labels= [] for r in radii: ax.plot(numpy.linspace(0.,2.*numpy.pi,501,), numpy.zeros(501)+r,ls='-',color='0.65',zorder=1,lw=0.5) labels.append(r'$%i$' % int(r*8.)) pyplot.rgrids(radii,labels=labels,angle=147.5) thetaticks = numpy.arange(0,360,45) # set ticklabels location at x times the axes' radius ax.set_thetagrids(thetaticks,frac=1.16,backgroundcolor='w',zorder=3) bovy_plot.bovy_text(3.*numpy.pi/4.+0.06,2.095,r'$\mathrm{kpc}$',size=10.) pyplot.ylim(0.,2.8) #Plot the box xs= numpy.linspace(_RCXMIN-2.25,_RCXMAX+2.25,101) ys= numpy.ones(101)*(_RCYMIN-2.25) rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) ax.plot(phis,rs,'--',lw=1.25,color='k') #Plot the box xs= numpy.linspace(_RCXMIN-2.25,_RCXMAX+2.25,101) ys= numpy.ones(101)*(_RCYMAX+2.25) rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) ax.plot(phis,rs,'--',lw=1.25,color='k') #Plot the box ys= numpy.linspace(_RCYMIN-2.25,_RCYMAX+2.25,101) xs= numpy.ones(101)*(_RCXMIN-2.25) rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) ax.plot(phis,rs,'--',lw=1.25,color='k') #Plot the box ys= numpy.linspace(_RCYMIN-2.25,_RCYMAX+2.25,101) xs= numpy.ones(101)*(_RCXMAX+2.25) rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) ax.plot(phis,rs,'--',lw=1.25,color='k') #Plot the connectors on the modelAxes xlow=-4.*8. ylow= 2.77*8. xs= numpy.linspace(xlow,(_RCXMAX+2.25),101) ys= (ylow-(_RCYMAX+2.25))/(xlow-(_RCXMAX+2.25))*(xs-xlow)+ylow rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) line= ax.plot(phis,rs,':',lw=1.,color='k',zorder=2) line[0].set_clip_on(False) xlow=-4.*8. ylow= -2.77*8. xs= numpy.linspace(xlow,(_RCXMAX+2.25),101) ys= (ylow-(_RCYMIN-2.25))/(xlow-(_RCXMAX+2.25))*(xs-xlow)+ylow rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) line= ax.plot(phis,rs,':',lw=1.,color='k',zorder=2) line[0].set_clip_on(False) #Colorbar cbaxes = pyplot.axes([0.01+2.*axdx,(1.-tdy)/2.+tdy+0.065,axdx-0.125,0.02]) CB1= pyplot.colorbar(out,orientation='horizontal', cax=cbaxes,ticks=[-150.,-75.,0.,75.,150.]) #CB1.set_label(r'$\mathrm{median}\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',labelpad=-35,fontsize=14.) bovy_plot.bovy_end_print(plotfilename,dpi=300) return None
def imf_h_jk(plotfile,Z=None,dwarf=False,log=False,h=12.,basti=False, dartmouth=False,kroupa=False): #Read isochrones if basti: zs= numpy.array([0.0001,0.0003,0.0006,0.001,0.002,0.004,0.008, 0.01,0.0198,0.03,0.04]) elif dartmouth: zs= isodist.FEH2Z(numpy.array([-2.5,-2.,-1.5,-1.,-0.5,0.,0.2,0.3,0.5])) else: zs= numpy.arange(0.0005,0.03005,0.0005) if Z is None: Zs= zs elif not basti and not dartmouth: if Z < 0.01: Zs= [Z-0.001,Z-0.0005,Z,Z+0.0005,Z+0.001] #build up statistics else: Zs= [Z-0.0005,Z,Z+0.0005] #build up statistics else: Zs= [Z] if basti: p= isodist.BastiIsochrone(Z=Zs) elif dartmouth: p= isodist.DartmouthIsochrone(feh=isodist.Z2FEH(Zs),onlyold=True) else: p= isodist.PadovaIsochrone(Z=Zs) #Get relevant data sample= [] weights= [] for logage in p.logages(): for z in Zs: thisiso= p(logage,z) if basti: mini= thisiso['M_ini'] elif dartmouth: mini= thisiso['M'] else: mini= thisiso['M_ini'] if basti: int_IMF= isodist.imf.lognormalChabrier2001(thisiso['M_ini'], int=True) dmpm= numpy.roll(int_IMF,-1)-int_IMF elif dartmouth: int_IMF= isodist.imf.lognormalChabrier2001(thisiso['M'], int=True) dmpm= numpy.roll(int_IMF,-1)-int_IMF else: if kroupa: int_IMF= isodist.imf.kroupa2003(thisiso['M_ini'],int=True) dmpm= numpy.roll(int_IMF,-1)-int_IMF else: dmpm= numpy.roll(thisiso['int_IMF'],-1)-thisiso['int_IMF'] for ii in range(1,len(mini)-1): if basti: JK= thisiso['J'][ii]-thisiso['K'][ii] else: JK= thisiso['J'][ii]-thisiso['Ks'][ii] H= thisiso['H'][ii] if JK < 0.: # or thisiso['logg'][ii] > 3.5: continue if dmpm[ii] > 0.: if basti: sample.append([thisiso['J'][ii]-thisiso['K'][ii], thisiso['H'][ii]]) else: sample.append([thisiso['J'][ii]-thisiso['Ks'][ii], thisiso['H'][ii]]) if dartmouth: if logage > numpy.log10(5.)+9.: weights.append(2.*dmpm[ii]) #Dartmouth are linearly spaced, but spacing is bigger at > 5 Gyr else: weights.append(dmpm[ii]) #Dartmouth are linearly spaced? else: weights.append(dmpm[ii]*10**(logage-7.)) #weights.append(dmpm[ii]*10**(logage-7.)*numpy.exp((10.**(logage-7.))/800.)) else: continue #no use in continuing here #Form array sample= numpy.array(sample) weights= numpy.array(weights) #Histogram if dwarf: hist, edges= numpy.histogramdd(sample,weights=weights,bins=51, range=[[0.,1.6],[2.,9.]]) else: hist, edges= numpy.histogramdd(sample,weights=weights,bins=49, range=[[0.3,1.6],[-11.,2]]) #Normalize each J-K for ii in range(len(hist[:,0])): hist[ii,:]/= numpy.nanmax(hist[ii,:])/numpy.nanmax(hist) rev= copy.copy(hist[ii,::-1]) #reverse, but in one go does not always work hist[ii,:]= rev #Plot bovy_plot.bovy_print() if log: hist= numpy.log(hist) bovy_plot.bovy_dens2d(hist.T,origin='lower',cmap='gist_yarg', xrange=[edges[0][0],edges[0][-1]], yrange=[edges[1][-1],edges[1][0]], aspect=(edges[0][-1]-edges[0][0])/float(edges[1][-1]-edges[1][0]), xlabel=r'$(J-K_s)_0\ [\mathrm{mag}]$', ylabel=r'$M_H\ [\mathrm{mag}]$', interpolation='nearest') #Add extinction arrow djk= 0.45 dh= 1.55/1.5*djk from matplotlib.patches import FancyArrowPatch ax=pyplot.gca() ax.add_patch(FancyArrowPatch((1.,-2.),(1+djk,-2+dh), arrowstyle='->',mutation_scale=20,fill=True, lw=1.25)) bovy_plot.bovy_text(1.05,-2.05,r'$\mathrm{extinction}$', rotation=-math.atan(1.5/1.55*1.3/13.)/math.pi*180., size=14.) #Add color cut bovy_plot.bovy_plot([0.5,0.5],[-20.,20.],'--',color='0.6',overplot=True) ax.add_patch(FancyArrowPatch((0.5,-6.),(0.7,-6.), arrowstyle='->',mutation_scale=20,fill=True, lw=1.25,ls='dashed',color='0.6')) bovy_plot.bovy_text(0.43,-8.,r'$\mathrm{APOGEE\ color\ cut}$',rotation=90., size=14.) #Add twin y axis ax= pyplot.gca() def my_formatter(x, pos): """distance in kpc for m=h""" xs= 10.**((h-x)/5.-2.) return r'$%.0f$' % xs def my_formatter2(x, pos): """distance in kpc for m=h""" xs= 10.**((h-x)/5.+1.) return r'$%.0f$' % xs ax2= pyplot.twinx() if dwarf: major_formatter = FuncFormatter(my_formatter2) else: major_formatter = FuncFormatter(my_formatter) ax2.yaxis.set_major_formatter(major_formatter) ystep= ax.yaxis.get_majorticklocs() ystep= ystep[1]-ystep[0] ax2.yaxis.set_minor_locator(MultipleLocator(ystep/5.)) ax2.yaxis.tick_right() ax2.yaxis.set_label_position('right') ymin, ymax= ax.yaxis.get_view_interval() ax2.yaxis.set_view_interval(ymin,ymax,ignore=True) if dwarf: ax2.set_ylabel('$\mathrm{distance\ for}\ H_0\ =\ %.1f\ [\mathrm{pc}]$' % h) else: ax2.set_ylabel('$\mathrm{distance\ for}\ H_0\ =\ %.1f\ [\mathrm{kpc}]$' % h) xstep= ax.xaxis.get_majorticklocs() xstep= xstep[1]-xstep[0] ax2.xaxis.set_minor_locator(MultipleLocator(xstep/5.)) if Z is None: bovy_plot.bovy_end_print(plotfile) else: bovy_plot.bovy_text(r'$Z\ =\ %.3f$' % Z,top_right=True,size=14.) bovy_plot.bovy_end_print(plotfile) return None
def plotsrsz(options,args): #Go through all of the bins if options.sample.lower() == 'g': npops= 62 elif options.sample.lower() == 'k': npops= 30 for ii in range(npops): if _NOTDONEYET: spl= options.restart.split('.') else: spl= args[0].split('.') newname= '' for jj in range(len(spl)-1): newname+= spl[jj] if not jj == len(spl)-2: newname+= '.' newname+= '_%i.' % ii newname+= spl[-1] savefile= open(newname,'rb') try: if not _NOTDONEYET: params= pickle.load(savefile) mlogl= pickle.load(savefile) logl= pickle.load(savefile) except: continue finally: savefile.close() if _NOTDONEYET: logl[(logl == 0.)]= -numpy.finfo(numpy.dtype(numpy.float64)).max marglogl= numpy.zeros((logl.shape[5],logl.shape[6])) if ii == 0: allmarglogl= numpy.zeros((logl.shape[5],logl.shape[6],npops)) for jj in range(marglogl.shape[0]): for kk in range(marglogl.shape[1]): indx= True-numpy.isnan(logl[:,0,0,:,:,jj,kk,:,:,:,:].flatten()) if numpy.sum(indx) > 0: marglogl[jj,kk]= misc.logsumexp(logl[:,0,0,:,:,jj,kk,:,:,:,:].flatten()[indx]) else: marglogl[jj,kk]= -numpy.finfo(numpy.dtype(numpy.float64)).max allmarglogl[:,:,ii]= marglogl #Normalize alogl= marglogl-numpy.amax(marglogl) bovy_plot.bovy_print() bovy_plot.bovy_dens2d(numpy.exp(alogl).T, origin='lower',cmap='gist_yarg', interpolation='nearest', xrange=[numpy.log(25./220.),numpy.log(70./220.)], yrange=[numpy.log(15./220.),numpy.log(60./220.)], xlabel=r'$\ln \sigma_R / 220\ \mathrm{km\,s}^{-1}$', ylabel=r'$\ln \sigma_Z / 220\ \mathrm{km\,s}^{-1}$') bovy_plot.bovy_plot([-3.,0.],[-3.,0.],'k--',overplot=True) #Plotname spl= options.outfilename.split('.') newname= '' for jj in range(len(spl)-1): newname+= spl[jj] if not jj == len(spl)-2: newname+= '.' newname+= '_%i.' % ii newname+= spl[-1] bovy_plot.bovy_end_print(newname) #Now plot combined alogl= numpy.sum(allmarglogl,axis=2)\ -numpy.amax(numpy.sum(allmarglogl,axis=2)) bovy_plot.bovy_print() bovy_plot.bovy_dens2d(numpy.exp(alogl).T, origin='lower',cmap='gist_yarg', interpolation='nearest', xrange=[numpy.log(25./220.),numpy.log(70./220.)], yrange=[numpy.log(15./220.),numpy.log(60./220.)], xlabel=r'$\ln \sigma_R / 220\ \mathrm{km\,s}^{-1}$', ylabel=r'$\ln \sigma_Z / 220\ \mathrm{km\,s}^{-1}$') bovy_plot.bovy_plot([-3.,0.],[-3.,0.],'k--',overplot=True) bovy_plot.bovy_end_print(options.outfilename)
def plotXDPotPDFs_vc(options,args): #Read all XDs if os.path.exists(args[0]): savefile= open(args[0],'rb') dum= pickle.load(savefile) dum= pickle.load(savefile) dum= pickle.load(savefile) dum= pickle.load(savefile) dum= pickle.load(savefile) dum= pickle.load(savefile) vcdxamp= pickle.load(savefile) vcdxmean= pickle.load(savefile) vcdxcovar= pickle.load(savefile) savefile.close() else: raise IOError("At least one input file has to exist ...") #Plot vcd vs. rd nx= 101 ny= 101 xs= numpy.linspace(180.,290.,nx) ys= numpy.linspace(-0.5,0.5,ny) XDxs= numpy.log(xs/_REFV0) XDys= ys*30. pdf= _eval_gauss_grid(XDxs,XDys,vcdxamp,vcdxmean,vcdxcovar) pdf-= numpy.amax(pdf) pdf= numpy.exp(pdf) #Multiply in Jacobian for ii in range(nx): pdf[ii,:]*= 1./xs[ii] #Plot nlevels= 2 bovy_plot.bovy_print() c1= bovy_plot.bovy_dens2d(pdf.T,origin='lower',cmap='gist_yarg', xrange=[xs[0]-(xs[1]-xs[0])/2.,xs[-1]+(xs[1]-xs[0])/2.], yrange=[ys[0]-(ys[1]-ys[0])/2.,ys[-1]+(ys[1]-ys[0])/2.], xlabel=r'$V_c\,(\mathrm{km\,s}^{-1})$', ylabel=r'$\mathrm{d} \ln V_c / \mathrm{d} \ln R$', contours=True, levels= special.erf(numpy.arange(1,nlevels+1)/numpy.sqrt(2.)), justcontours=True,cntrmass=True, cntrcolors='r', cntrlw=2.,retCont=True) if os.path.exists(args[1]): savefile= open(args[1],'rb') dum= pickle.load(savefile) dum= pickle.load(savefile) dum= pickle.load(savefile) dum= pickle.load(savefile) dum= pickle.load(savefile) dum= pickle.load(savefile) vcdxamp= pickle.load(savefile) vcdxmean= pickle.load(savefile) vcdxcovar= pickle.load(savefile) savefile.close() else: raise IOError("At least one input file has to exist ...") pdf= _eval_gauss_grid(XDxs,XDys,vcdxamp,vcdxmean,vcdxcovar) pdf-= numpy.amax(pdf) pdf= numpy.exp(pdf) #Multiply in Jacobian for ii in range(nx): pdf[ii,:]*= 1./xs[ii] c2= bovy_plot.bovy_dens2d(pdf.T,origin='lower',cmap='gist_yarg', xrange=[xs[0]-(xs[1]-xs[0])/2.,xs[-1]+(xs[1]-xs[0])/2.], yrange=[ys[0]-(ys[1]-ys[0])/2.,ys[-1]+(ys[1]-ys[0])/2.], overplot=True, contours=True, levels= special.erf(numpy.arange(1,nlevels+1)/numpy.sqrt(2.)), justcontours=True,cntrmass=True,cntrcolors='y', cntrlw=2.,retCont=True) if os.path.exists(args[3]): savefile= open(args[3],'rb') vcdxamp= pickle.load(savefile) vcdxmean= pickle.load(savefile) vcdxcovar= pickle.load(savefile) savefile.close() else: raise IOError("At least one input file has to exist ...") pdf= _eval_gauss_grid(XDxs,XDys,vcdxamp,vcdxmean,vcdxcovar) pdf-= numpy.amax(pdf) pdf= numpy.exp(pdf) #Multiply in Jacobian for ii in range(nx): pdf[ii,:]*= 1./xs[ii] c4= bovy_plot.bovy_dens2d(pdf.T,origin='lower',cmap='gist_yarg', xrange=[xs[0]-(xs[1]-xs[0])/2.,xs[-1]+(xs[1]-xs[0])/2.], yrange=[ys[0]-(ys[1]-ys[0])/2.,ys[-1]+(ys[1]-ys[0])/2.], overplot=True, contours=True, levels= special.erf(numpy.arange(1,nlevels+1)/numpy.sqrt(2.)), justcontours=True,cntrmass=True, cntrlw=2.,retCont=True, cntrls='--',cntrcolors='0.5') if os.path.exists(args[2]): savefile= open(args[2],'rb') dum= pickle.load(savefile) dum= pickle.load(savefile) dum= pickle.load(savefile) dum= pickle.load(savefile) dum= pickle.load(savefile) dum= pickle.load(savefile) vcdxamp= pickle.load(savefile) vcdxmean= pickle.load(savefile) vcdxcovar= pickle.load(savefile) savefile.close() else: raise IOError("At least one input file has to exist ...") pdf= _eval_gauss_grid(XDxs,XDys,vcdxamp,vcdxmean,vcdxcovar) pdf-= numpy.amax(pdf) pdf= numpy.exp(pdf) #Multiply in Jacobian for ii in range(nx): pdf[ii,:]*= 1./xs[ii] c3= bovy_plot.bovy_dens2d(pdf.T,origin='lower',cmap='gist_yarg', xrange=[xs[0]-(xs[1]-xs[0])/2.,xs[-1]+(xs[1]-xs[0])/2.], yrange=[ys[0]-(ys[1]-ys[0])/2.,ys[-1]+(ys[1]-ys[0])/2.], overplot=True, contours=True, levels= special.erf(numpy.arange(1,nlevels+1)/numpy.sqrt(2.)), justcontours=True,cntrmass=True, cntrlw=2.,retCont=True) pdf3= copy.copy(pdf) #pdf*= pdf3 #pdf/= numpy.amax(pdf) #c5= bovy_plot.bovy_dens2d(pdf.T,origin='lower',cmap='gist_yarg', # xrange=[xs[0]-(xs[1]-xs[0])/2.,xs[-1]+(xs[1]-xs[0])/2.], # yrange=[ys[0]-(ys[1]-ys[0])/2.,ys[-1]+(ys[1]-ys[0])/2.], # overplot=True, # contours=True, # levels= special.erf(numpy.arange(1,nlevels+1)/numpy.sqrt(2.)), # justcontours=True,cntrmass=True, # cntrlw=2.,retCont=True, # cntrls='--',cntrcolors='c') #Proxies c1= Line2D([0.],[0.],ls='-',lw=2.,color='r') c2= Line2D([0.],[0.],ls='-',lw=2.,color='y') c3= Line2D([0.],[0.],ls='-',lw=2.,color='k') c4= Line2D([0.],[0.],ls='--',lw=2.,color='0.5') pyplot.legend((c1,c2,c3,c4), (r'$K_{Z,1.1}(R)\ \&\ \Sigma_{*}(R_0)$', r'$V_\mathrm{term}\ \mathrm{only}$', r'$\mathrm{Combined}\ \&\ \mathrm{d} \ln V_c / \mathrm{d} \ln R$', r'$\mathrm{APOGEE}\ V_c(R)\ \mathrm{(for\ comparison)}$'), loc='upper left',#bbox_to_anchor=(.91,.375), numpoints=2, prop={'size':14}, frameon=False) bovy_plot.bovy_end_print(options.plotfile) return None
def plotXDPotPDFs_rhodm(options,args): #Read all XDs if os.path.exists(args[0]): savefile= open(args[0],'rb') dum= pickle.load(savefile) dum= pickle.load(savefile) dum= pickle.load(savefile) vcdxamp= pickle.load(savefile) vcdxmean= pickle.load(savefile) vcdxcovar= pickle.load(savefile) savefile.close() else: raise IOError("At least one input file has to exist ...") #Plot vcd vs. rd nx= 101 ny= 101 xs= numpy.linspace(0.000001,0.03,nx) ys= numpy.linspace(0.00001,2.999999,ny) XDxs= numpy.log(xs) XDys= special.logit(ys/3.) pdf= _eval_gauss_grid(XDxs,XDys,vcdxamp,vcdxmean,vcdxcovar) pdf-= numpy.amax(pdf) pdf= numpy.exp(pdf) #Multiply in Jacobian for ii in range(nx): pdf[ii,:]*= 1./xs[ii] for jj in range(ny): pdf[:,jj]*= (3./ys[jj]+1./(1.-ys[jj]/3.)) #Plot nlevels= 2 bovy_plot.bovy_print() c1= bovy_plot.bovy_dens2d(pdf.T,origin='lower',cmap='gist_yarg', xrange=[xs[0]-(xs[1]-xs[0])/2.,xs[-1]+(xs[1]-xs[0])/2.], yrange=[ys[0]-(ys[1]-ys[0])/2.,ys[-1]+(ys[1]-ys[0])/2.], xlabel=r'$\rho_{\mathrm{DM}}(R_0,Z=0)\,(M_\odot\,\mathrm{pc}^{-2})$', ylabel=r'$\mathrm{halo\ power-law\ index}$', contours=True, levels= special.erf(numpy.arange(1,nlevels+1)/numpy.sqrt(2.)), justcontours=True,cntrmass=True, cntrcolors='r', cntrlw=2.,retCont=True) if os.path.exists(args[1]): savefile= open(args[1],'rb') dum= pickle.load(savefile) dum= pickle.load(savefile) dum= pickle.load(savefile) vcdxamp= pickle.load(savefile) vcdxmean= pickle.load(savefile) vcdxcovar= pickle.load(savefile) savefile.close() else: raise IOError("At least one input file has to exist ...") pdf= _eval_gauss_grid(XDxs,XDys,vcdxamp,vcdxmean,vcdxcovar) pdf-= numpy.amax(pdf) pdf= numpy.exp(pdf) #Multiply in Jacobian for ii in range(nx): pdf[ii,:]*= 1./xs[ii] for jj in range(ny): pdf[:,jj]*= (3./ys[jj]+1./(1.-ys[jj]/3.)) c2= bovy_plot.bovy_dens2d(pdf.T,origin='lower',cmap='gist_yarg', xrange=[xs[0]-(xs[1]-xs[0])/2.,xs[-1]+(xs[1]-xs[0])/2.], yrange=[ys[0]-(ys[1]-ys[0])/2.,ys[-1]+(ys[1]-ys[0])/2.], overplot=True, contours=True, levels= special.erf(numpy.arange(1,nlevels+1)/numpy.sqrt(2.)), justcontours=True,cntrmass=True,cntrcolors='y', cntrlw=2.,retCont=True) if os.path.exists(args[2]): savefile= open(args[2],'rb') dum= pickle.load(savefile) dum= pickle.load(savefile) dum= pickle.load(savefile) vcdxamp= pickle.load(savefile) vcdxmean= pickle.load(savefile) vcdxcovar= pickle.load(savefile) savefile.close() else: raise IOError("At least one input file has to exist ...") pdf= _eval_gauss_grid(XDxs,XDys,vcdxamp,vcdxmean,vcdxcovar) pdf-= numpy.amax(pdf) pdf= numpy.exp(pdf) #Multiply in Jacobian for ii in range(nx): pdf[ii,:]*= 1./xs[ii] for jj in range(ny): pdf[:,jj]*= (3./ys[jj]+1./(1.-ys[jj]/3.)) c3= bovy_plot.bovy_dens2d(pdf.T,origin='lower',cmap='gist_yarg', xrange=[xs[0]-(xs[1]-xs[0])/2.,xs[-1]+(xs[1]-xs[0])/2.], yrange=[ys[0]-(ys[1]-ys[0])/2.,ys[-1]+(ys[1]-ys[0])/2.], overplot=True, contours=True, levels= special.erf(numpy.arange(1,nlevels+1)/numpy.sqrt(2.)), justcontours=True,cntrmass=True, cntrlw=2.,retCont=True) #Proxies c1= Line2D([0.],[0.],ls='-',lw=2.,color='r') c2= Line2D([0.],[0.],ls='-',lw=2.,color='y') c3= Line2D([0.],[0.],ls='-',lw=2.,color='k') pyplot.legend((c1,c2,c3), (r'$K_{Z,1.1}(R)\ \&\ \Sigma_{*}(R_0)$', r'$V_\mathrm{term}\ \&\ \mathrm{d} \ln V_c / \mathrm{d} \ln R$', r'$\mathrm{Combined}$'), loc='upper right',#bbox_to_anchor=(.91,.375), numpoints=2, prop={'size':14}, frameon=False) bovy_plot.bovy_end_print(options.plotfile) return None
def plot(self,quant,func=numpy.median,minnstar=20.,submediany=False, returnz=False,justcalc=False, **kwargs): """ NAME: plot PURPOSE: make a plot of a quantity as a function of X and Y INPUT: quant - the quantity (string that returns the quantity, like 'METALS') or a function of the data func - function of quantity to plot minnstar= minimum number of stars (20) submeany= subtract the median y justcalc= (False) if True, do not plot bovy_plot.bovy_dens2d kwargs OUTPUT: plot to output device HISTORY: 2015-04-06 - Written - Bovy (IAS) """ #First create 2D nx= int((self.xmax-self.xmin)/self.dx) ny= int((self.ymax-self.ymin)/self.dy) gx= numpy.linspace(self.xmin+self.dx/2.,self.xmax-self.dx/2.,nx) gy= numpy.linspace(self.ymin+self.dy/2.,self.ymax-self.dy/2.,ny) z2d= numpy.empty((nx,ny)) if isinstance(quant,numpy.ndarray): z2d= numpy.reshape(quant,(nx,ny)) for ii in range(z2d.shape[0]): for jj in range(z2d.shape[1]): tdata= self(gx[ii],gy[jj]) if len(tdata) < minnstar: z2d[ii,jj]= numpy.nan else: nbins= 0 for ii in range(z2d.shape[0]): for jj in range(z2d.shape[1]): tdata= self(gx[ii],gy[jj]) if len(tdata) < minnstar: z2d[ii,jj]= numpy.nan else: nbins+= 1 if hasattr(quant, '__call__'): z2d[ii,jj]= func(quant(tdata)) else: z2d[ii,jj]= func(tdata[quant]) if submediany: z2d[ii,:]-= \ numpy.median(z2d[ii,True-numpy.isnan(z2d[ii,:])]) if justcalc: if returnz: return z2d else: return None #Now plot xrange= kwargs.pop('xrange',[self.xmin,self.xmax]) yrange= kwargs.pop('yrange',[self.ymin,self.ymax]) if not kwargs.has_key('colorbar'): kwargs['colorbar']= True if not kwargs.has_key('shrink'): kwargs['shrink']= 0.78 if not kwargs.has_key('vmin'): kwargs['vmin']= numpy.nanmin(z2d) if not kwargs.has_key('vmax'): kwargs['vmax']= numpy.nanmax(z2d) xlabel= r'$[\mathrm{Fe/H}]$' ylabel= _AFELABEL cmap= kwargs.pop('cmap','coolwarm') out= bovy_plot.bovy_dens2d(z2d.T,origin='lower',cmap=cmap, interpolation='nearest', xlabel=xlabel,ylabel=ylabel, xrange=xrange,yrange=yrange, **kwargs) if returnz: return z2d else: return out
def plotplanarPotentials(Pot,*args,**kwargs): """ NAME: plotplanarPotentials PURPOSE: plot a planar potential INPUT: Rrange - range xrange, yrange - if relevant grid, gridx, gridy - number of points to plot savefilename - save to or restore from this savefile (pickle) ncontours - number of contours to plot (if applicable) +bovy_plot(*args,**kwargs) or bovy_dens2d(**kwargs) OUTPUT: plot to output device HISTORY: 2010-07-13 - Written - Bovy (NYU) """ if kwargs.has_key('Rrange'): Rrange= kwargs['Rrange'] kwargs.pop('Rrange') else: Rrange= [0.01,5.] if kwargs.has_key('xrange'): xrange= kwargs['xrange'] kwargs.pop('xrange') else: xrange= [-5.,5.] if kwargs.has_key('yrange'): yrange= kwargs['yrange'] kwargs.pop('yrange') else: yrange= [-5.,5.] if kwargs.has_key('grid'): grid= kwargs['grid'] kwargs.pop('grid') else: grid= 1000 #avoid zero if kwargs.has_key('gridx'): gridx= kwargs['gridx'] kwargs.pop('gridx') else: gridx= 1000 #avoid zero if kwargs.has_key('gridy'): gridy= kwargs['gridy'] kwargs.pop('gridy') else: gridy= gridx if kwargs.has_key('savefilename'): savefilename= kwargs['savefilename'] kwargs.pop('savefilename') else: savefilename= None isList= isinstance(Pot,list) nonAxi= ((isList and Pot[0].isNonAxi) or (not isList and Pot.isNonAxi)) if not savefilename == None and os.path.exists(savefilename): print "Restoring savefile "+savefilename+" ..." savefile= open(savefilename,'rb') potR= pickle.load(savefile) Rs= pickle.load(savefile) if nonAxi: xs= pickle.load(savefile) ys= pickle.load(savefile) else: Rs= pickle.load(savefile) savefile.close() else: if nonAxi: xs= nu.linspace(xrange[0],xrange[1],gridx) ys= nu.linspace(yrange[0],yrange[1],gridy) potR= nu.zeros((gridx,gridy)) for ii in range(gridx): for jj in range(gridy): thisR= nu.sqrt(xs[ii]**2.+ys[jj]**2.) if xs[ii] >= 0.: thisphi= nu.arcsin(ys[jj]/thisR) else: thisphi= -nu.arcsin(ys[jj]/thisR)+nu.pi potR[ii,jj]= evaluateplanarPotentials(thisR,Pot, phi=thisphi) else: Rs= nu.linspace(Rrange[0],Rrange[1],grid) potR= nu.zeros(grid) for ii in range(grid): potR[ii]= evaluateplanarPotentials(Rs[ii],Pot) if not savefilename == None: print "Writing savefile "+savefilename+" ..." savefile= open(savefilename,'wb') pickle.dump(potR,savefile) if nonAxi: pickle.dump(xs,savefile) pickle.dump(ys,savefile) else: pickle.dump(Rs,savefile) savefile.close() if nonAxi: if not kwargs.has_key('origin'): kwargs['origin']= 'lower' if not kwargs.has_key('cmap'): kwargs['cmap']= 'gist_yarg' if not kwargs.has_key('contours'): kwargs['contours']= True if not kwargs.has_key('xlabel'): kwargs['xlabel']= r"$x / R_0$" if not kwargs.has_key('ylabel'): kwargs['ylabel']= "$y / R_0$" if not kwargs.has_key('aspect'): kwargs['aspect']= 1. if not kwargs.has_key('cntrls'): kwargs['cntrls']= '-' if kwargs.has_key('ncontours'): ncontours= kwargs['ncontours'] kwargs.pop('ncontours') else: ncontours=10 if not kwargs.has_key('levels'): kwargs['levels']= nu.linspace(nu.nanmin(potR),nu.nanmax(potR),ncontours) return plot.bovy_dens2d(potR.T, xrange=xrange, yrange=yrange,**kwargs) else: kwargs['xlabel']=r"$R/R_0$" kwargs['ylabel']=r"$\Phi(R)$", kwargs['xrange']=Rrange return plot.bovy_plot(Rs,potR,*args,**kwargs)
def plot(self, quant, func=numpy.median, minnstar=20., submediany=False, returnz=False, justcalc=False, **kwargs): """ NAME: plot PURPOSE: make a plot of a quantity as a function of X and Y INPUT: quant - the quantity (string that returns the quantity, like 'METALS') or a function of the data func - function of quantity to plot minnstar= minimum number of stars (20) submeany= subtract the median y justcalc= (False) if True, do not plot bovy_plot.bovy_dens2d kwargs OUTPUT: plot to output device HISTORY: 2015-04-06 - Written - Bovy (IAS) """ #First create 2D nx = int((self.xmax - self.xmin) / self.dx) ny = int((self.ymax - self.ymin) / self.dy) gx = numpy.linspace(self.xmin + self.dx / 2., self.xmax - self.dx / 2., nx) gy = numpy.linspace(self.ymin + self.dy / 2., self.ymax - self.dy / 2., ny) z2d = numpy.empty((nx, ny)) if isinstance(quant, numpy.ndarray): z2d = numpy.reshape(quant, (nx, ny)) for ii in range(z2d.shape[0]): for jj in range(z2d.shape[1]): tdata = self(gx[ii], gy[jj]) if len(tdata) < minnstar: z2d[ii, jj] = numpy.nan else: nbins = 0 for ii in range(z2d.shape[0]): for jj in range(z2d.shape[1]): tdata = self(gx[ii], gy[jj]) if len(tdata) < minnstar: z2d[ii, jj] = numpy.nan else: nbins += 1 if hasattr(quant, '__call__'): z2d[ii, jj] = func(quant(tdata)) else: z2d[ii, jj] = func(tdata[quant]) if submediany: z2d[ii,:]-= \ numpy.median(z2d[ii,True-numpy.isnan(z2d[ii,:])]) if justcalc: if returnz: return z2d else: return None #Now plot xrange = kwargs.pop('xrange', [self.xmin, self.xmax]) yrange = kwargs.pop('yrange', [self.ymin, self.ymax]) if not kwargs.has_key('colorbar'): kwargs['colorbar'] = True if not kwargs.has_key('shrink'): kwargs['shrink'] = 0.78 if not kwargs.has_key('vmin'): kwargs['vmin'] = numpy.nanmin(z2d) if not kwargs.has_key('vmax'): kwargs['vmax'] = numpy.nanmax(z2d) xlabel = r'$[\mathrm{Fe/H}]$' ylabel = _AFELABEL cmap = kwargs.pop('cmap', 'coolwarm') out = bovy_plot.bovy_dens2d(z2d.T, origin='lower', cmap=cmap, interpolation='nearest', xlabel=xlabel, ylabel=ylabel, xrange=xrange, yrange=yrange, **kwargs) if returnz: return z2d else: return out
def plot(self, log=False, conditional=False, nbins=None, overlay_mode=False, nmodebins=21): """ NAME: plot PURPOSE: plot the resulting (J-Ks,H) distribution INPUT: log= (default: False) if True, plot log conditional= (default: False) if True, plot conditional distribution of H given J-Ks nbins= if set, set the number of bins overlay_mode= False, if True, plot the mode and half-maxs nmodebins= (21) number of bins to calculate the mode etc. at OUTPUT: plot to output device HISTORY: 2012-02-17 - Written - Bovy (IAS) """ if not _BOVY_PLOT_LOADED: raise ImportError( "'galpy.util.bovy_plot' plotting package not found") #Form histogram grid if nbins is None: nbins = self._nbins djk = (self._jkmax - self._jkmin) / float(nbins) dh = (self._hmax - self._hmin) / float(nbins) jks = numpy.linspace(self._jkmin + djk / 2., self._jkmax - djk / 2., nbins) hs = numpy.linspace( self._hmax - dh / 2., #we reverse self._hmin + dh / 2., nbins) plotthis = numpy.zeros((nbins, nbins)) for ii in range(nbins): for jj in range(nbins): plotthis[ii, jj] = self(jks[ii], hs[jj]) if not log: plotthis = numpy.exp(plotthis) if conditional: #normalize further for ii in range(nbins): plotthis[ii, :] /= numpy.nanmax( plotthis[ii, :]) / numpy.nanmax(plotthis) if self._band == 'J': ylabel = r'$M_J$' ylim = [self._hmax, self._hmin] elif self._band == 'H': ylabel = r'$M_H$' ylim = [self._hmax, self._hmin] elif self._band == 'K': ylabel = r'$M_K$' ylim = [self._hmax, self._hmin] elif self._band == 'Ks': ylabel = r'$M_{K_s}$' ylim = [self._hmax, self._hmin] out = bovy_plot.bovy_dens2d(plotthis.T, origin='lower', cmap='gist_yarg', xrange=[self._jkmin, self._jkmax], yrange=ylim, aspect=(self._jkmax - self._jkmin) / (self._hmax - self._hmin), xlabel=r'$(J-K_s)_0$', ylabel=ylabel, interpolation='nearest') if overlay_mode: #Calculate mode and hm njks = nmodebins jks = numpy.linspace(self._jkmin, self._jkmax, njks) modes = numpy.array([self.mode(jk) for jk in jks]) hms = numpy.zeros((njks, 2)) for ii in range(njks): try: minhm, maxhm = self.sigmafwhm(jks[ii], straight=True) except ValueError: minhm, maxhm = numpy.nan, numpy.nan hms[ii, 0] = minhm hms[ii, 1] = maxhm bovy_plot.bovy_plot(jks, modes, 'w-', lw=2., overplot=True) bovy_plot.bovy_plot(jks, hms[:, 0], '-', lw=2., color='0.85', overplot=True) bovy_plot.bovy_plot(jks, hms[:, 1], '-', lw=2., color='0.85', overplot=True) return out
#Setup this Orbit o= Orbit([ra,dec,ds[ii],0.,0.,vloss[jj]], radec=True,vo=1.,ro=1.,zo=0., solarmotion=[0.,25./218.,0.]) vlos_dist[ii,jj]= dfc(o,marginalizeVperp=True) plotds= ds*8. plotvloss= vloss*218. save_pickles(dist_savefilename,plotds,plotvloss,vlos_dist) #Now plot bovy_plot.bovy_print() for ii in range(nds): vlos_dist[ii,:]/= numpy.sum(vlos_dist[ii,:]) bovy_plot.bovy_dens2d(vlos_dist.T,origin='lower',cmap='gist_yarg', xrange=[0.001-(ds[1]-ds[0])/2., 8.+(ds[1]-ds[0])/2.], yrange=[-0.7*218.-(plotvloss[1]-plotvloss[0])/2., 0.25*218.+(plotvloss[1]-plotvloss[0])/2.], xlabel=r'$\mathrm{distance}\,(\mathrm{kpc})$', ylabel=r'$\mathrm{line\!-\!of\!-\!sight\ velocity}\,(\mathrm{km\,s}^{-1})$') mid50= numpy.zeros(len(ds)) up95= numpy.zeros(len(ds)) down95= numpy.zeros(len(ds)) for ii in range(len(ds)): tdist= numpy.cumsum(vlos_dist[ii,:])/numpy.sum(vlos_dist[ii,:]) mid50[ii]= plotvloss[numpy.argmin(numpy.fabs(tdist-0.5))] down95[ii]= plotvloss[numpy.argmin(numpy.fabs(tdist-0.025))] up95[ii]= plotvloss[numpy.argmin(numpy.fabs(tdist-0.975))] interpmid50= interpolate.UnivariateSpline(ds,mid50,k=3) interpup95= interpolate.UnivariateSpline(ds,up95,k=3) interpdown95= interpolate.UnivariateSpline(ds,down95,k=3) #Plot median
def plot_dustnearplane(plotname, green=False): if green: savefile = _SAVEFILE_GREEN else: savefile = _SAVEFILE_MARSHALL # Grid ls = numpy.linspace(15., 70., _NL) bs = numpy.linspace(-2., 2., _NB) if not os.path.exists(savefile): # Setup dust map if green: dmap = mwdust.Green15(filter='2MASS H') else: dmap = mwdust.Marshall06(filter='2MASS H') plotthis = numpy.empty((_NL, _NB)) rad = 0.5 # deg for jj in range(_NB): print jj for ii in range(_NL): pa, ah = dmap.dust_vals_disk(ls[ii], bs[jj], 7., rad) plotthis[ii, jj] = numpy.sum(pa * ah) / numpy.sum(pa) save_pickles(savefile, plotthis) else: with open(savefile, 'rb') as f: plotthis = pickle.load(f) # Now plot bovy_plot.bovy_print(fig_width=8.4, fig_height=4.) bovy_plot.bovy_dens2d( plotthis[::-1].T, origin='lower', cmap=cm.coolwarm, # interpolation='nearest', colorbar=True, shrink=0.45, vmin=0., vmax=2. - 0.75 * green, aspect=3., xrange=[ls[-1] + (ls[1] - ls[0]) / 2., ls[0] - (ls[1] - ls[0]) / 2.], yrange=[bs[0] - (bs[1] - bs[0]) / 2., bs[-1] + (bs[1] - bs[0]) / 2.], xlabel=r'$l\,\mathrm{(deg)}$', ylabel=r'$b\,\mathrm{(deg)}$', zlabel=r'$A_H\,(\mathrm{mag})$', zorder=0) bovy_plot.bovy_text(r'$D = 7\,\mathrm{kpc}$', top_left=True, color='w', size=16.) # Overplot fields glons = [34., 64., 27.] glats = [0., 0., 0.] colors = ['w', 'w', 'y'] xs = numpy.linspace(-1.5, 1.5, 201) ys = numpy.sqrt(1.5**2. - xs**2.) for glon, glat, c in zip(glons, glats, colors): bovy_plot.bovy_plot(xs + glon, ys + glat, '-', overplot=True, zorder=1, lw=2., color=c) bovy_plot.bovy_plot(xs + glon, -ys + glat, '-', overplot=True, zorder=1, lw=2., color=c) bovy_plot.bovy_end_print(plotname) return None
def plot_popmass(self): """ NAME: plot_popmass PURPOSE: plot the stellar-population mass for each RC star INPUT: bovy_plot.bovy_plot **kwargs OUTPUT: bovy_plot.bovy_plot output HISTORY: 2014-02-28 - Written in this form - Bovy (IAS) """ if not _BOVY_PLOT_LOADED: raise ImportError("galpy.util.bovy_plot could not be imported") fehs = numpy.linspace(-1., 0.5, 101) lages = self._coarselages plotthis = numpy.empty((len(fehs), len(lages))) for ii in range(len(fehs)): for jj in range(len(lages)): plotthis[ii, jj] = self.popmass(fehs[ii], lages[jj]) fig = pyplot.gcf() left, bottom, width, height = 0.1, 0.1, 0.8, 0.6 axBottom = pyplot.axes([left, bottom, width, height]) fig.sca(axBottom) xlimits = [fehs[0], fehs[-1]] dlages = (lages[1] - lages[0]) ylimits = [lages[0] - dlages, lages[-1] + dlages] vmin, vmax = 0., 50000. vmin2, vmax2 = 0., 25000. zlabel = r'$\mathrm{Stellar\ population\ mass\ per\ RC\ star}\,(M_\odot)$' xlabel = r'$[\mathrm{Fe/H}]\,(\mathrm{dex})$' out = bovy_plot.bovy_dens2d(plotthis.T, origin='lower', cmap='jet', xrange=xlimits, yrange=ylimits, vmin=vmin, vmax=vmax, interpolation='nearest', colorbar=True, shrink=.9, zlabel=zlabel, overplot=True) extent = xlimits + ylimits pyplot.axis(extent) bovy_plot._add_axislabels( xlabel, r'$\log_{10}\,\mathrm{Age} / 1\,\mathrm{Gyr}$') bovy_plot._add_ticks() left, bottom, width, height = 0.1, 0.68, 0.64, 0.2 axTop = pyplot.axes([left, bottom, width, height]) fig.sca(axTop) #Plot the average over SFH lages = numpy.linspace(-1., 1., 16) mtrend = numpy.zeros(len(self._zs)) exppage = 10.**self._coarselages * numpy.exp( (10.**(self._coarselages + 2.)) / 800.) #e.g., Binney (2010) exexppage = 10.**self._coarselages * numpy.exp( (10.**(self._coarselages + 2.)) / 100.) #e.g., Binney (2010) page = 10.**self._coarselages plotthis = self._coarsemass[:-1, :] / self._omega[:-1, :] mtrend = 1. / (numpy.sum(page * 1. / plotthis, axis=1) / numpy.sum(page)) expmtrend = 1. / (numpy.sum(exppage * 1. / plotthis, axis=1) / numpy.sum(exppage)) exexpmtrend = 1. / (numpy.sum(exexppage * 1. / plotthis, axis=1) / numpy.sum(exexppage)) fehs = isodist.Z2FEH(self._zs[:-1], zsolar=zsolar()) pyplot.plot(fehs, mtrend, 'k-') pyplot.plot(fehs, expmtrend, 'k--') pyplot.plot(fehs, exexpmtrend, 'k-.') pyplot.ylim(vmin2, vmax2) pyplot.xlim(xlimits[0], xlimits[1]) nullfmt = NullFormatter() # no labels thisax = pyplot.gca() thisax.xaxis.set_major_formatter(nullfmt) bovy_plot._add_ticks() return out
def plotXDPotPDFs_RD(options,args): #Read all XDs if os.path.exists(args[0]): savefile= open(args[0],'rb') vcdxamp= pickle.load(savefile) vcdxmean= pickle.load(savefile) vcdxcovar= pickle.load(savefile) savefile.close() else: raise IOError("At least one input file has to exist ...") #Plot vcd vs. rd nx= 101 ny= 101 xs= numpy.linspace(1.,5.,nx) ys= numpy.linspace(0.00001,0.999999,ny) XDxs= numpy.log(xs/_REFR0) XDys= special.logit(ys) pdf= _eval_gauss_grid(XDxs,XDys,vcdxamp,vcdxmean,vcdxcovar) pdf-= numpy.amax(pdf) pdf= numpy.exp(pdf) #Multiply in Jacobian for ii in range(nx): pdf[ii,:]*= 1./xs[ii] for jj in range(ny): pdf[:,jj]*= (1./ys[jj]+1./(1.-ys[jj])) #Plot nlevels= 2 bovy_plot.bovy_print() c1= bovy_plot.bovy_dens2d(pdf.T,origin='lower',cmap='gist_yarg', xrange=[xs[0]-(xs[1]-xs[0])/2.,xs[-1]+(xs[1]-xs[0])/2.], yrange=[ys[0]-(ys[1]-ys[0])/2.,ys[-1]+(ys[1]-ys[0])/2.], xlabel=r'$\mathrm{stellar\ disk\ scale\ length\,(kpc)}$', ylabel=r'$\mathrm{disk\ maximality}\equiv V_{c,\mathrm{disk}}/V_c$', contours=True, levels= special.erf(numpy.arange(1,nlevels+1)/numpy.sqrt(2.)), justcontours=True,cntrmass=True, cntrcolors='r', cntrlw=2.,retCont=True) if os.path.exists(args[1]): savefile= open(args[1],'rb') vcdxamp= pickle.load(savefile) vcdxmean= pickle.load(savefile) vcdxcovar= pickle.load(savefile) savefile.close() else: raise IOError("At least one input file has to exist ...") pdf= _eval_gauss_grid(XDxs,XDys,vcdxamp,vcdxmean,vcdxcovar) pdf-= numpy.amax(pdf) pdf= numpy.exp(pdf) #Multiply in Jacobian for ii in range(nx): pdf[ii,:]*= 1./xs[ii] for jj in range(ny): pdf[:,jj]*= (1./ys[jj]+1./(1.-ys[jj])) c2= bovy_plot.bovy_dens2d(pdf.T,origin='lower',cmap='gist_yarg', xrange=[xs[0]-(xs[1]-xs[0])/2.,xs[-1]+(xs[1]-xs[0])/2.], yrange=[ys[0]-(ys[1]-ys[0])/2.,ys[-1]+(ys[1]-ys[0])/2.], overplot=True, contours=True, levels= special.erf(numpy.arange(1,nlevels+1)/numpy.sqrt(2.)), justcontours=True,cntrmass=True,cntrcolors='y', cntrlw=2.,retCont=True) if os.path.exists(args[2]): savefile= open(args[2],'rb') vcdxamp= pickle.load(savefile) vcdxmean= pickle.load(savefile) vcdxcovar= pickle.load(savefile) savefile.close() else: raise IOError("At least one input file has to exist ...") pdf= _eval_gauss_grid(XDxs,XDys,vcdxamp,vcdxmean,vcdxcovar) pdf-= numpy.amax(pdf) pdf= numpy.exp(pdf) #Multiply in Jacobian for ii in range(nx): pdf[ii,:]*= 1./xs[ii] for jj in range(ny): pdf[:,jj]*= (1./ys[jj]+1./(1.-ys[jj])) c3= bovy_plot.bovy_dens2d(pdf.T,origin='lower',cmap='gist_yarg', xrange=[xs[0]-(xs[1]-xs[0])/2.,xs[-1]+(xs[1]-xs[0])/2.], yrange=[ys[0]-(ys[1]-ys[0])/2.,ys[-1]+(ys[1]-ys[0])/2.], overplot=True, contours=True, levels= special.erf(numpy.arange(1,nlevels+1)/numpy.sqrt(2.)), justcontours=True,cntrmass=True, cntrlw=2.,retCont=True) #Proxies c1= Line2D([0.],[0.],ls='-',lw=2.,color='r') c2= Line2D([0.],[0.],ls='-',lw=2.,color='y') c3= Line2D([0.],[0.],ls='-',lw=2.,color='k') pyplot.legend((c1,c2,c3), (r'$K_{Z,1.1}(R)\ \mathrm{only}$', r'$V_\mathrm{term}, \Sigma_{*}(R_0), \&\ \mathrm{d} \ln V_c / \mathrm{d} \ln R$', r'$\mathrm{Combined}$'), loc='lower left',#bbox_to_anchor=(.91,.375), numpoints=2, prop={'size':14}, frameon=False) bovy_plot.bovy_plot([xs[0],xs[-1]],[0.75,0.75],'-',color='0.6', overplot=True,lw=2.) bovy_plot.bovy_plot([xs[0],xs[-1]],[0.95,0.95],'-',color='0.6', overplot=True,lw=2.) ax= pyplot.gca() ax.add_patch(FancyArrowPatch((3.1,0.75),(3.1,0.95), arrowstyle='<->',mutation_scale=20,fill=True, lw=1.25,color='0.6')) bovy_plot.bovy_text(3.2,.79,r'$\mathrm{Maximal}$'+'\n'+r'$\mathrm{disk}$', size=18.,color='0.35') bovy_plot.bovy_end_print(options.plotfile) return None
def main(args: Optional[list] = None, opts: Optional[Namespace] = None): """Fit MWPotential2014 Script Function. Parameters ---------- args : list, optional an optional single argument that holds the sys.argv list, except for the script name (e.g., argv[1:]) opts : Namespace, optional pre-constructed results of parsed args if not None, used ONLY if args is None """ if opts is not None and args is None: pass else: if opts is not None: warnings.warn("Not using `opts` because `args` are given") parser = make_parser() opts = parser.parse_args(args) fpath = opts.fpath + "/" if not opts.fpath.endswith("/") else opts.fpath opath = opts.opath + "/" if not opts.opath.endswith("/") else opts.opath # plot chains print("Plotting Chains") fig = mcmc_util.plot_chains(opath) fig.savefig(fpath + "chains.pdf") plt.close(fig) print("Need to continue chains:", end=" ") for i in range(32): ngood = mcmc_util.determine_nburn( filename=opath + f"mwpot14-fitsigma-{i:02}.dat", return_nsamples=True, ) if ngood < 4000: print(f"{i:02} (N={ngood})", end=", ") ############################################################### # RESULTING PDFS data, _, weights, _ = read_mcmc(nburn=None, skip=1, evi_func=lambda x: 1.0) plot_corner(data, weights=weights) plt.savefig("figures/PDFs/corner.pdf") plt.close() # -------------- savefilename = "output/pal5_forces_mcmc.pkl" if not os.path.exists(savefilename): data_wf, index_wf, weights_wf, evi_wf = read_mcmc( nburn=None, addforces=True, skip=1, evi_func=lambda x: 1.0 ) save_pickles(savefilename, data_wf, index_wf, weights_wf, evi_wf) else: with open(savefilename, "rb") as savefile: data_wf = pickle.load(savefile) index_wf = pickle.load(savefile) weights_wf = pickle.load(savefile) evi_wf = pickle.load(savefile) # -------------- plot_corner(data_wf, weights=weights_wf, addvcprior=False) plt.savefig("figures/PDFs/corner_wf.pdf") plt.close() # -------------- # Which potential is preferred? data_noforce, potindx, weights, evidences = read_mcmc(evi_func=evi_harmonic) fig = plt.figure(figsize=(6, 4)) bovy_plot.bovy_plot( potindx, np.log(evidences), "o", xrange=[-1, 34], yrange=[-35, -22], xlabel=r"$\mathrm{Potential\ index}$", ylabel=r"$\ln\ \mathrm{evidence}$", ) data_noforce, potindx, weights, evidences = read_mcmc(evi_func=evi_laplace) bovy_plot.bovy_plot(potindx, np.log(evidences) - 30.0, "d", overplot=True) data_noforce, potindx, weights, evidences = read_mcmc( evi_func=lambda x: np.exp(np.amax(x[:, -1])) ) bovy_plot.bovy_plot(potindx, np.log(evidences) - 8.0, "s", overplot=True) data_noforce, potindx, weights, evidences = read_mcmc( evi_func=lambda x: np.exp(-25.0) if (np.log(evi_harmonic(x)) > -25.0) else np.exp(-50.0) ) bovy_plot.bovy_plot(potindx, np.log(evidences), "o", overplot=True) plt.savefig("figures/PDFs/preferred_pot.pdf") plt.close() ############################################################### # Look at the results for individual potentials # -------------- # The flattening $c$ npot = 32 nwalkers = 12 plt.figure(figsize=(16, 6)) cmap = cm.plasma maxl = np.zeros((npot, 2)) for en, ii in enumerate(range(npot)): data_ip, _, weights_ip, evi_ip = read_mcmc(singlepot=ii, evi_func=evi_harmonic) try: maxl[en, 0] = np.amax(data_ip[:, -1]) maxl[en, 1] = np.log(evi_ip[0]) except ValueError: maxl[en] = -10000000.0 plt.subplot(2, 4, en // 4 + 1) bovy_plot.bovy_hist( data_ip[:, 0], range=[0.5, 2.0], bins=26, histtype="step", color=cmap((en % 4) / 3.0), normed=True, xlabel=r"$c$", lw=1.5, overplot=True, ) if en % 4 == 0: bovy_plot.bovy_text( r"$\mathrm{Potential\ %i\ to\ % i}$" % (en, en + 3), size=17.0, top_left=True, ) plt.tight_layout() plt.savefig("figures/flattening_c.pdf") plt.close() ############################################################### # What is the effective prior in $(F_R,F_Z)$? frfzprior_savefilename = "frfzprior.pkl" if not os.path.exists(frfzprior_savefilename): # Compute for each potential separately nvoc = 10000 ro = 8.0 npot = 32 fs = np.zeros((2, nvoc, npot)) for en, ii in tqdm(enumerate(range(npot))): fn = f"output/fitsigma/mwpot14-fitsigma-{i:02}.dat" # Read the potential parameters with open(fn, "r") as savefile: line1 = savefile.readline() potparams = [float(s) for s in (line1.split(":")[1].split(","))] for jj in range(nvoc): c = np.random.uniform() * 1.5 + 0.5 tvo = np.random.uniform() * 50.0 + 200.0 pot = mw_pot.setup_potential(potparams, c, False, False, REFR0, tvo) fs[:, jj, ii] = np.array(pal5_util.force_pal5(pot, 23.46, REFR0, tvo))[ :2 ] save_pickles(frfzprior_savefilename, fs) else: with open(frfzprior_savefilename, "rb") as savefile: fs = pickle.load(savefile) # -------------- plt.figure(figsize=(6, 6)) bovy_plot.scatterplot( fs[0].flatten(), fs[1].flatten(), "k,", xrange=[-1.75, -0.25], yrange=[-2.5, -1.2], xlabel=r"$F_R(\mathrm{Pal\ 5})$", ylabel=r"$F_Z(\mathrm{Pal\ 5})$", onedhists=True, ) bovy_plot.scatterplot( data_wf[:, 7], data_wf[:, 8], weights=weights_wf, bins=26, xrange=[-1.75, -0.25], yrange=[-2.5, -1.2], justcontours=True, cntrcolors="w", overplot=True, onedhists=True, ) plt.axvline(-0.81, color=sns.color_palette()[0]) plt.axhline(-1.85, color=sns.color_palette()[0]) plt.savefig("figures/effective_force_prior.pdf") plt.close() # -------------- # The ratio of the posterior and the prior bovy_plot.bovy_print( axes_labelsize=17.0, text_fontsize=12.0, xtick_labelsize=14.0, ytick_labelsize=14.0, ) plt.figure(figsize=(12.5, 4)) def axes_white(): for k, spine in plt.gca().spines.items(): # ax.spines is a dictionary spine.set_color("w") plt.gca().tick_params(axis="x", which="both", colors="w") plt.gca().tick_params(axis="y", which="both", colors="w") [t.set_color("k") for t in plt.gca().xaxis.get_ticklabels()] [t.set_color("k") for t in plt.gca().yaxis.get_ticklabels()] return None bins = 32 trange = [[-1.75, -0.25], [-2.5, -1.2]] tw = copy.deepcopy(weights_wf) tw[index_wf == 14] = 0.0 # Didn't converge properly H_prior, xedges, yedges = np.histogram2d( fs[0].flatten(), fs[1].flatten(), bins=bins, range=trange, normed=True ) H_post, xedges, yedges = np.histogram2d( data_wf[:, 7], data_wf[:, 8], weights=tw, bins=bins, range=trange, normed=True, ) H_like = H_post / H_prior H_like[H_prior == 0.0] = 0.0 plt.subplot(1, 3, 1) bovy_plot.bovy_dens2d( H_prior.T, origin="lower", cmap="viridis", interpolation="nearest", xrange=[xedges[0], xedges[-1]], yrange=[yedges[0], yedges[-1]], xlabel=r"$F_R(\mathrm{Pal\ 5})\,(\mathrm{km\,s}^{-1}\,\mathrm{Myr}^{-1})$", ylabel=r"$F_Z(\mathrm{Pal\ 5})\,(\mathrm{km\,s}^{-1}\,\mathrm{Myr}^{-1})$", gcf=True, ) bovy_plot.bovy_text(r"$\mathbf{Prior}$", top_left=True, size=19.0, color="w") axes_white() plt.subplot(1, 3, 2) bovy_plot.bovy_dens2d( H_post.T, origin="lower", cmap="viridis", interpolation="nearest", xrange=[xedges[0], xedges[-1]], yrange=[yedges[0], yedges[-1]], xlabel=r"$F_R(\mathrm{Pal\ 5})\,(\mathrm{km\,s}^{-1}\,\mathrm{Myr}^{-1})$", gcf=True, ) bovy_plot.bovy_text(r"$\mathbf{Posterior}$", top_left=True, size=19.0, color="w") axes_white() plt.subplot(1, 3, 3) bovy_plot.bovy_dens2d( H_like.T, origin="lower", cmap="viridis", interpolation="nearest", vmin=0.1, vmax=4.0, xrange=[xedges[0], xedges[-1]], yrange=[yedges[0], yedges[-1]], xlabel=r"$F_R(\mathrm{Pal\ 5})\,(\mathrm{km\,s}^{-1}\,\mathrm{Myr}^{-1})$", gcf=True, ) bovy_plot.bovy_text(r"$\mathbf{Likelihood}$", top_left=True, size=19.0, color="w") axes_white() def qline(FR, q=0.95): return 2.0 * FR / q ** 2.0 q = 0.94 plt.plot([-1.25, -0.2], [qline(-1.25, q=q), qline(-0.2, q=q)], "w--") bovy_plot.bovy_text(-1.7, -2.2, r"$q_\Phi = 0.94$", size=16.0, color="w") plt.plot((-1.25, -1.02), (-2.19, qline(-1.02, q=q)), "w-", lw=0.8) plt.tight_layout() plt.savefig( "figures/pal5post.pdf", bbox_inches="tight", ) plt.close() # -------------- # Projection onto the direction perpendicular to constant $q = 0.94$: frs = np.tile(0.5 * (xedges[:-1] + xedges[1:]), (len(yedges) - 1, 1)).T fzs = np.tile(0.5 * (yedges[:-1] + yedges[1:]), (len(xedges) - 1, 1)) plt.figure(figsize=(6, 4)) txlabel = r"$F_\perp$" dum = bovy_plot.bovy_hist( (-2.0 * (frs + 0.8) + 0.94 ** 2.0 * (fzs + 1.82)).flatten(), weights=H_prior.flatten(), bins=21, histtype="step", lw=2.0, xrange=[-1.5, 1.5], xlabel=txlabel, normed=True, ) dum = bovy_plot.bovy_hist( (-2.0 * (frs + 0.8) + 0.94 ** 2.0 * (fzs + 1.82)).flatten(), weights=H_post.flatten(), bins=21, histtype="step", lw=2.0, overplot=True, xrange=[-1.5, 1.5], normed=True, ) dum = bovy_plot.bovy_hist( (-2.0 * (frs + 0.8) + 0.94 ** 2.0 * (fzs + 1.82)).flatten(), weights=H_like.flatten(), bins=21, histtype="step", lw=2.0, overplot=True, xrange=[-1.5, 1.5], normed=True, ) plt.savefig("figures/PDFs/projection_perp_to_q0p94.pdf") plt.close() mq = ( np.sum( (-2.0 * (frs + 0.8) + 0.94 ** 2.0 * (fzs + 1.82)).flatten() * H_like.flatten() ) ) / np.sum(H_like.flatten()) print( mq, np.sqrt( ( np.sum( ((-2.0 * (frs + 0.8) + 0.94 ** 2.0 * (fzs + 1.82)).flatten() - mq) ** 2.0 * H_like.flatten() ) ) / np.sum(H_like.flatten()) ), ) # -------------- # Projection onto the direction parallel to constant $q = 0.94$: frs = np.tile(0.5 * (xedges[:-1] + xedges[1:]), (len(yedges) - 1, 1)).T fzs = np.tile(0.5 * (yedges[:-1] + yedges[1:]), (len(xedges) - 1, 1)) plt.figure(figsize=(6, 4)) txlabel = r"$F_\parallel$" dum = bovy_plot.bovy_hist( (0.94 ** 2.0 * (frs + 0.8) + 2.0 * (fzs + 1.82)).flatten(), weights=H_prior.flatten(), bins=21, histtype="step", lw=2.0, xrange=[-2.5, 2.5], xlabel=txlabel, normed=True, ) dum = bovy_plot.bovy_hist( (0.94 ** 2.0 * (frs + 0.8) + 2.0 * (fzs + 1.82)).flatten(), weights=H_post.flatten(), bins=21, histtype="step", lw=2.0, overplot=True, xrange=[-2.5, 2.5], normed=True, ) dum = bovy_plot.bovy_hist( (0.94 ** 2.0 * (frs + 0.8) + 2.0 * (fzs + 1.82)).flatten(), weights=H_like.flatten(), bins=21, histtype="step", lw=2.0, overplot=True, xrange=[-2.5, 2.5], normed=True, ) plt.savefig("figures/PDFs/projection_prll_to_q0p94.pdf") plt.close() mq = ( np.sum( (0.94 ** 2.0 * (frs + 0.8) + 2.0 * (fzs + 1.82)).flatten() * H_like.flatten() ) ) / np.sum(H_like.flatten()) print( mq, np.sqrt( ( np.sum( ((0.94 ** 2.0 * (frs + 0.8) + 2.0 * (fzs + 1.82)).flatten() - mq) ** 2.0 * H_like.flatten() ) ) / np.sum(H_like.flatten()) ), ) # -------------- # Thus, there is only a weak constraint on $F_\parallel$. nrow = int(np.ceil(npot / 4.0)) plt.figure(figsize=(16, nrow * 4)) for en, ii in enumerate(range(npot)): plt.subplot(nrow, 4, en + 1) if ii % 4 == 0: tylabel = r"$F_Z(\mathrm{Pal\ 5})$" else: tylabel = None if ii // 4 == nrow - 1: txlabel = r"$F_R(\mathrm{Pal\ 5})$" else: txlabel = None bovy_plot.scatterplot( fs[0][:, en], fs[1][:, en], "k,", xrange=[-1.75, -0.25], yrange=[-2.5, -1.0], xlabel=txlabel, ylabel=tylabel, gcf=True, ) bovy_plot.scatterplot( data_wf[:, 7], data_wf[:, 8], weights=weights_wf, bins=26, xrange=[-1.75, -0.25], yrange=[-2.5, -1.0], justcontours=True, cntrcolors="w", overplot=True, ) bovy_plot.scatterplot( data_wf[index_wf == ii, 7], data_wf[index_wf == ii, 8], weights=weights_wf[index_wf == ii], bins=26, xrange=[-1.75, -0.25], yrange=[-2.5, -1.0], justcontours=True, # cntrcolors=sns.color_palette()[2], overplot=True, ) plt.axvline(-0.80, color=sns.color_palette()[0]) plt.axhline(-1.83, color=sns.color_palette()[0]) bovy_plot.bovy_text(r"$\mathrm{Potential}\ %i$" % ii, size=17.0, top_left=True) plt.savefig("figures/PDFs/constain_F_prll.pdf") plt.close() # -------------- # Let's plot four representative ones for the paper: bovy_plot.bovy_print( axes_labelsize=17.0, text_fontsize=12.0, xtick_labelsize=14.0, ytick_labelsize=14.0, ) nullfmt = NullFormatter() nrow = 1 plt.figure(figsize=(15, nrow * 4)) for en, ii in enumerate([0, 15, 24, 25]): plt.subplot(nrow, 4, en + 1) if en % 4 == 0: tylabel = ( r"$F_Z(\mathrm{Pal\ 5})\,(\mathrm{km\,s}^{-1}\,\mathrm{Myr}^{-1})$" ) else: tylabel = None if en // 4 == nrow - 1: txlabel = ( r"$F_R(\mathrm{Pal\ 5})\,(\mathrm{km\,s}^{-1}\,\mathrm{Myr}^{-1})$" ) else: txlabel = None bovy_plot.scatterplot( fs[0][:, ii], fs[1][:, ii], "k,", bins=31, xrange=[-1.75, -0.25], yrange=[-2.5, -1.0], xlabel=txlabel, ylabel=tylabel, gcf=True, ) bovy_plot.scatterplot( data_wf[:, 7], data_wf[:, 8], weights=weights_wf, bins=21, xrange=[-1.75, -0.25], yrange=[-2.5, -1.0], justcontours=True, cntrcolors=sns.color_palette("colorblind")[2], cntrls="--", cntrlw=2.0, overplot=True, ) bovy_plot.scatterplot( data_wf[index_wf == ii, 7], data_wf[index_wf == ii, 8], weights=weights_wf[index_wf == ii], bins=21, xrange=[-1.75, -0.25], yrange=[-2.5, -1.0], justcontours=True, cntrcolors=sns.color_palette("colorblind")[0], cntrlw=2.5, overplot=True, ) if en > 0: plt.gca().yaxis.set_major_formatter(nullfmt) plt.tight_layout() plt.savefig( "figures/pal5post_examples.pdf", bbox_inches="tight", ) plt.close() ############################################################### # What about $q_\Phi$? bins = 47 plt.figure(figsize=(6, 4)) dum = bovy_plot.bovy_hist( np.sqrt(2.0 * fs[0].flatten() / fs[1].flatten()), histtype="step", lw=2.0, bins=bins, xlabel=r"$q_\mathrm{\Phi}$", xrange=[0.7, 1.25], normed=True, ) dum = bovy_plot.bovy_hist( np.sqrt(16.8 / 8.4 * data_wf[:, -2] / data_wf[:, -1]), weights=weights_wf, histtype="step", lw=2.0, bins=bins, overplot=True, xrange=[0.7, 1.25], normed=True, ) mq = np.sum( np.sqrt(16.8 / 8.4 * data_wf[:, -2] / data_wf[:, -1]) * weights_wf ) / np.sum(weights_wf) sq = np.sqrt( np.sum( (np.sqrt(16.8 / 8.4 * data_wf[:, -2] / data_wf[:, -1]) - mq) ** 2.0 * weights_wf ) / np.sum(weights_wf) ) print("From posterior samples: q = %.3f +/- %.3f" % (mq, sq)) Hq_post, xedges = np.histogram( np.sqrt(16.8 / 8.4 * data_wf[:, -2] / data_wf[:, -1]), weights=weights_wf, bins=bins, range=[0.7, 1.25], normed=True, ) Hq_prior, xedges = np.histogram( np.sqrt(2.0 * fs[0].flatten() / fs[1].flatten()), bins=bins, range=[0.7, 1.25], normed=True, ) qs = 0.5 * (xedges[:-1] + xedges[1:]) Hq_like = Hq_post / Hq_prior Hq_like[Hq_post == 0.0] = 0.0 mq = np.sum(qs * Hq_like) / np.sum(Hq_like) sq = np.sqrt(np.sum((qs - mq) ** 2.0 * Hq_like) / np.sum(Hq_like)) print("From likelihood of samples: q = %.3f +/- %.3f" % (mq, sq)) plt.savefig("figures/q_phi.pdf") plt.close() # It appears that $q_\Phi$ is the quantity that is the most strongly constrained by the Pal 5 data. ############################################################### # A sampling of tracks from the MCMC savefilename = "mwpot14-pal5-mcmcTracks.pkl" pmdecpar = 2.257 / 2.296 pmdecperp = -2.296 / 2.257 if os.path.exists(savefilename): with open(savefilename, "rb") as savefile: pal5_track_samples = pickle.load(savefile) forces = pickle.load(savefile) all_potparams = pickle.load(savefile) all_params = pickle.load(savefile) else: np.random.seed(1) ntracks = 21 multi = 8 pal5_track_samples = np.zeros((ntracks, 2, 6, pal5varyc[0].shape[1])) forces = np.zeros((ntracks, 2)) all_potparams = np.zeros((ntracks, 5)) all_params = np.zeros((ntracks, 7)) for ii in range(ntracks): # Pick a random potential from among the set, but leave 14 out pindx = 14 while pindx == 14: pindx = np.random.permutation(32)[0] # Load this potential fn = f"output/fitsigma/mwpot14-fitsigma-{pindx:02}.dat" with open(fn, "r") as savefile: line1 = savefile.readline() potparams = [float(s) for s in (line1.split(":")[1].split(","))] all_potparams[ii] = potparams # Now pick a random sample from this MCMC chain tnburn = mcmc_util.determine_nburn(fn) tdata = np.loadtxt(fn, comments="#", delimiter=",") tdata = tdata[tnburn::] tdata = tdata[np.random.permutation(len(tdata))[0]] all_params[ii] = tdata tvo = tdata[1] * REFV0 pot = mw_pot.setup_potential(potparams, tdata[0], False, False, REFR0, tvo) forces[ii, :] = pal5_util.force_pal5(pot, 23.46, REFR0, tvo)[:2] # Now compute the stream model for this setup dist = tdata[2] * 22.0 pmra = -2.296 + tdata[3] + tdata[4] pmdecpar = 2.257 / 2.296 pmdecperp = -2.296 / 2.257 pmdec = -2.257 + tdata[3] * pmdecpar + tdata[4] * pmdecperp vlos = -58.7 sigv = 0.4 * np.exp(tdata[5]) prog = Orbit( [229.018, -0.124, dist, pmra, pmdec, vlos], radec=True, ro=REFR0, vo=tvo, solarmotion=[-11.1, 24.0, 7.25], ) tsdf_trailing, tsdf_leading = pal5_util.setup_sdf( pot, prog, sigv, 10.0, REFR0, tvo, multi=multi, nTrackChunks=8, trailing_only=False, verbose=True, useTM=False, ) # Compute the track for jj, sdf in enumerate([tsdf_trailing, tsdf_leading]): trackRADec = bovy_coords.lb_to_radec( sdf._interpolatedObsTrackLB[:, 0], sdf._interpolatedObsTrackLB[:, 1], degree=True, ) trackpmRADec = bovy_coords.pmllpmbb_to_pmrapmdec( sdf._interpolatedObsTrackLB[:, 4], sdf._interpolatedObsTrackLB[:, 5], sdf._interpolatedObsTrackLB[:, 0], sdf._interpolatedObsTrackLB[:, 1], degree=True, ) # Store the track pal5_track_samples[ii, jj, 0] = trackRADec[:, 0] pal5_track_samples[ii, jj, 1] = trackRADec[:, 1] pal5_track_samples[ii, jj, 2] = sdf._interpolatedObsTrackLB[:, 2] pal5_track_samples[ii, jj, 3] = sdf._interpolatedObsTrackLB[:, 3] pal5_track_samples[ii, jj, 4] = trackpmRADec[:, 0] pal5_track_samples[ii, jj, 5] = trackpmRADec[:, 1] save_pickles( savefilename, pal5_track_samples, forces, all_potparams, all_params ) # -------------- bovy_plot.bovy_print( axes_labelsize=17.0, text_fontsize=12.0, xtick_labelsize=14.0, ytick_labelsize=14.0, ) plt.figure(figsize=(12, 8)) gs = gridspec.GridSpec(2, 2, wspace=0.225, hspace=0.1, right=0.94) ntracks = pal5_track_samples.shape[0] cmap = cm.plasma alpha = 0.7 for ii in range(ntracks): tc = cmap((forces[ii, 1] + 2.5) / 1.0) for jj in range(2): # RA, Dec plt.subplot(gs[0]) plt.plot( pal5_track_samples[ii, jj, 0], pal5_track_samples[ii, jj, 1], "-", color=tc, alpha=alpha, ) # RA, Vlos plt.subplot(gs[1]) plt.plot( pal5_track_samples[ii, jj, 0], pal5_track_samples[ii, jj, 3], "-", color=tc, alpha=alpha, ) # RA, Dist plt.subplot(gs[2]) plt.plot( pal5_track_samples[ii, jj, 0], pal5_track_samples[ii, jj, 2] - all_params[ii, 2] * 22.0, "-", color=tc, alpha=alpha, ) # RA, pm_parallel plt.subplot(gs[3]) plt.plot( pal5_track_samples[ii, jj, 0, : 500 + 500 * (1 - jj)], np.sqrt(1.0 + (2.257 / 2.296) ** 2.0) * ( (pal5_track_samples[ii, jj, 4, : 500 + 500 * (1 - jj)] + 2.296) * pmdecperp - (pal5_track_samples[ii, jj, 5, : 500 + 500 * (1 - jj)] + 2.257) ) / (pmdecpar - pmdecperp), "-", color=tc, alpha=alpha, ) plot_data_add_labels( p1=(gs[0],), p2=(gs[1],), noxlabel_dec=True, noxlabel_vlos=True ) plt.subplot(gs[2]) plt.xlim(250.0, 221.0) plt.ylim(-3.0, 1.5) bovy_plot._add_ticks() plt.xlabel(r"$\mathrm{RA}\,(\mathrm{degree})$") plt.ylabel(r"$\Delta\mathrm{Distance}\,(\mathrm{kpc})$") plt.subplot(gs[3]) plt.xlim(250.0, 221.0) plt.ylim(-0.5, 0.5) bovy_plot._add_ticks() plt.xlabel(r"$\mathrm{RA}\,(\mathrm{degree})$") plt.ylabel(r"$\Delta\mu_\parallel\,(\mathrm{mas\,yr}^{-1})$") # Colorbar gs2 = gridspec.GridSpec(2, 1, wspace=0.0, left=0.95, right=0.975) plt.subplot(gs2[:, -1]) sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=-2.5, vmax=-1.5)) sm._A = [] CB1 = plt.colorbar(sm, orientation="vertical", cax=plt.gca()) CB1.set_label( r"$F_Z(\mathrm{Pal\ 5})\,(\mathrm{km\,s}^{-1}\,\mathrm{Myr}^{-1})$", fontsize=18.0, ) plt.savefig( "figures/pal5tracksamples.pdf", bbox_inches="tight", ) plt.close() ############################################################### # What about Kuepper et al. (2015)? # Can we recover the Kuepper et al. (2015) result as prior + $q_\Phi = # 0.94 \pm 0.05$ + $V_c(R_0)$ between 200 and 280 km/s? For simplicity # we will not vary $R_0$, which should not have a big impact. s = sample_kuepper_flattening_post(50000, 0.94, 0.05) plot_kuepper_samples(s) plt.savefig("figures/kuepper_samples.pdf") plt.close() # The constraint on the potential flattening gets you far, but there # is more going on (the constraint on the halo mass and scale # parameter appear to come completely from the $V_c(R_0)$ constraint). # Let's add the weak constraint on the sum of the forces, scaled to # Kuepper et al.'s best-fit acceleration (which is higher than ours): s = sample_kuepper_flatteningforce_post(50000, 0.94, 0.05, -0.83, 0.36) plot_kuepper_samples(s) plt.savefig("figures/kuepper_samples_flatF.pdf") plt.close() # This gets a tight relation between $M_\mathrm{halo}$ and the scale # parameter of the halo, but does not lead to a constraint on either # independently; the halo potential flattening constraint is that of # Kuepper et al. Based on this, it appears that the information that # ties down $M_\mathrm{halo}$ comes from the overdensities, which may # be spurious (Thomas et al. 2016) and whose use in dynamical modeling # is dubious anyway. # What is Kuepper et al.'s prior on $a_{\mathrm{Pal\ 5}}$? apal5s = [] ns = 100000 for ii in range(ns): Mh = np.random.uniform() * (10.0 - 0.001) + 0.001 a = np.random.uniform() * (100.0 - 0.1) + 0.1 q = np.random.uniform() * (1.8 - 0.2) + 0.2 pot = setup_potential_kuepper(Mh, a) FR, FZ = force_pal5_kuepper(pot, q) apal5s.append(np.sqrt(FR ** 2.0 + FZ ** 2.0)) apal5s = np.array(apal5s) plt.figure(figsize=(6, 4)) dum = bovy_plot.bovy_hist( apal5s, range=[0.0, 10.0], lw=2.0, bins=51, histtype="step", normed=True, ) plt.savefig("figures/kuepper_samples_prior.pdf") plt.close()
def plotRdfh(options,args): #Go through all of the bins if options.sample.lower() == 'g': savefile= open('binmapping_g.sav','rb') elif options.sample.lower() == 'k': savefile= open('binmapping_k.sav','rb') fehs= pickle.load(savefile) afes= pickle.load(savefile) npops= len(fehs) savefile.close() for ii in range(npops): if _NOTDONEYET: spl= options.restart.split('.') else: spl= args[0].split('.') newname= '' for jj in range(len(spl)-1): newname+= spl[jj] if not jj == len(spl)-2: newname+= '.' newname+= '_%i.' % ii newname+= spl[-1] savefile= open(newname,'rb') try: if not _NOTDONEYET: params= pickle.load(savefile) mlogl= pickle.load(savefile) logl= pickle.load(savefile) except: continue finally: savefile.close() if _NOTDONEYET: logl[(logl == 0.)]= -numpy.finfo(numpy.dtype(numpy.float64)).max if options.restrictdvt: logl= logl[:,:,:,:,:,:,:,1:4,:,:,:] if options.restrictdf: hrs= numpy.log(numpy.linspace(1.5,5.,logl.shape[4])/_REFR0) srs= numpy.log(numpy.linspace(25.,70.,logl.shape[5])/_REFV0) szs= numpy.log(numpy.linspace(15.,60.,logl.shape[6])/_REFV0) lnhrin, lnsrin, lnszin= approxFitResult(fehs[ii],afes[ii]) hrindx= numpy.argmin((hrs-lnhrin)**2.) srindx= numpy.argmin((srs-lnsrin)**2.) szindx= numpy.argmin((szs-lnszin)**2.) minhrindx= hrindx-1 maxhrindx= hrindx+1 if minhrindx < 0: minhrindx+= 1 maxhrindx+= 1 elif maxhrindx >= logl.shape[4]: minhrindx-= 1 maxhrindx-= 1 minsrindx= srindx-1 maxsrindx= srindx+1 if minsrindx < 0: minsrindx+= 1 maxsrindx+= 1 elif maxsrindx >= logl.shape[5]: minsrindx-= 1 maxsrindx-= 1 minszindx= szindx-1 maxszindx= szindx+1 if minszindx < 0: minszindx+= 1 maxszindx+= 1 elif maxszindx >= logl.shape[6]: minszindx-= 1 maxszindx-= 1 logl= logl[:,:,:,:,minhrindx:maxhrindx+1,minsrindx:maxsrindx+1, minszindx:maxszindx+1,:,:,:,:] marglogl= numpy.zeros((logl.shape[0],logl.shape[3])) marglogldvt0= numpy.zeros((logl.shape[0],logl.shape[3])) condfh= numpy.zeros((logl.shape[3])) condlogp= numpy.zeros(logl.shape[0]) condfhdvt0= numpy.zeros((logl.shape[3])) condlogpdvt0= numpy.zeros(logl.shape[0]) if ii == 0: allmarglogl= numpy.zeros((logl.shape[0],logl.shape[3],npops)) for jj in range(marglogl.shape[0]): for kk in range(marglogl.shape[1]): indx= True-numpy.isnan(logl[jj,0,0,kk,:,:,:,:,:,:,:].flatten()) indxdvt0= True-numpy.isnan(logl[jj,0,0,kk,:,:,:,2,:,:,:].flatten()) if numpy.sum(indx) > 0: marglogl[jj,kk]= misc.logsumexp(logl[jj,0,0,kk,:,:,:,:,:,:,:].flatten()[indx]) else: marglogl[jj,kk]= -numpy.finfo(numpy.dtype(numpy.float64)).max if numpy.sum(indxdvt0) > 0: marglogldvt0[jj,kk]= misc.logsumexp(logl[jj,0,0,kk,:,:,:,2,:,:,:].flatten()[indxdvt0]) else: marglogldvt0[jj,kk]= -numpy.finfo(numpy.dtype(numpy.float64)).max condlogp[jj]= misc.logsumexp(marglogl[jj,:]) condlogl= marglogl[jj,:]-misc.logsumexp(marglogl[jj,:]) condfh[jj]= numpy.sum(numpy.exp(condlogl)*numpy.linspace(0.,1.,logl.shape[3]))/numpy.sum(numpy.exp(condlogl)) condlogpdvt0[jj]= misc.logsumexp(marglogldvt0[jj,:]) condlogldvt0= marglogldvt0[jj,:]-misc.logsumexp(marglogldvt0[jj,:]) condfhdvt0[jj]= numpy.sum(numpy.exp(condlogldvt0)*numpy.linspace(0.,1.,logl.shape[3]))/numpy.sum(numpy.exp(condlogldvt0)) if monoAbundanceMW.hr(fehs[ii],afes[ii]) < 3.5 \ and numpy.amax(logl) < 0.: #latter removes ridiculous bins allmarglogl[:,:,ii]= marglogl #Normalize alogl= marglogl-numpy.amax(marglogl) bovy_plot.bovy_print() bovy_plot.bovy_dens2d(numpy.exp(alogl).T, origin='lower',cmap='gist_yarg', interpolation='nearest', xrange=[1.5,4.5],yrange=[0.,1.], xlabel=r'$R_d$',ylabel=r'$f_h$') s= 2.*condlogp s-= numpy.amax(s) s+= 16. s*= 3. bovy_plot.bovy_plot(numpy.linspace(1.5,4.5,logl.shape[0]), condfh,color='0.75',ls='-', overplot=True,zorder=2) bovy_plot.bovy_plot(numpy.linspace(1.5,4.5,logl.shape[0]), condfh,color='0.75',marker='o', s=s,scatter=True,overplot=True,zorder=10) maxindx= numpy.argmax(s) bovy_plot.bovy_plot(numpy.linspace(1.5,4.5,logl.shape[0])[maxindx], condfh[maxindx],color='blue',marker='o', ls='none', ms=8.,mec='none', overplot=True,zorder=13) #dvt0 s= 2.*condlogpdvt0 s-= numpy.amax(s) s+= 16. s*= 3. if not options.restrictdvt: bovy_plot.bovy_plot(numpy.linspace(1.5,4.5,logl.shape[0]), condfhdvt0,color='0.25',ls='-', overplot=True,zorder=1) bovy_plot.bovy_plot(numpy.linspace(1.5,4.5,logl.shape[0]), condfhdvt0,color='0.25',marker='o', s=s,scatter=True,overplot=True,zorder=11) maxindx= numpy.argmax(s) bovy_plot.bovy_plot(numpy.linspace(1.5,4.5,logl.shape[0])[maxindx], condfhdvt0[maxindx],color='red',marker='o', ls='none', ms=8.,mec='none', overplot=True,zorder=12) #Plotname spl= options.outfilename.split('.') newname= '' for jj in range(len(spl)-1): newname+= spl[jj] if not jj == len(spl)-2: newname+= '.' newname+= '_%i.' % ii newname+= spl[-1] if options.restrictdf and not options.restrictdvt: bovy_plot.bovy_text(r'$\mathrm{Restricted\ DF\ parameters}$', top_right=True,size=14.) elif options.restrictdvt and not options.restrictdf: bovy_plot.bovy_text(r'$\mathrm{Restricted}\ \Delta \bar{V}_T\ \mathrm{range}$', top_right=True,size=14.) elif options.restrictdvt and options.restrictdf: bovy_plot.bovy_text(r'$\mathrm{Restricted\ DF\ parameters}$' +'\n' +r'$\mathrm{Restricted}\ \Delta \bar{V}_T\ \mathrm{range}$', top_right=True,size=14.) bovy_plot.bovy_end_print(newname) #Now plot combined alogl= numpy.sum(allmarglogl,axis=2)\ -numpy.amax(numpy.sum(allmarglogl,axis=2)) bovy_plot.bovy_print() bovy_plot.bovy_dens2d(numpy.exp(alogl).T, origin='lower',cmap='gist_yarg', interpolation='nearest', xrange=[1.5,4.5],yrange=[0.,1.], xlabel=r'$R_d$',ylabel=r'$f_h$') bovy_plot.bovy_end_print(options.outfilename)
def plot_logg_jk_apokasc(parser): options,args= parser.parse_args() #Setup Zs if os.path.exists(args[0]): savefile= open(args[0],'rb') outhist= pickle.load(savefile) hists= pickle.load(savefile) edgess= pickle.load(savefile) data= pickle.load(savefile) savefile.close() else: zs= numpy.arange(0.0005,0.03005,0.0005) if _DEBUG: zs= numpy.arange(0.0005,0.03005,0.005) fehs= isodist.Z2FEH(zs,zsolar=0.017)#0.017 for APOGEE analysis zs= zs[numpy.fabs(fehs-options.feh) < 0.2] if _DEBUG: zs= [zs[numpy.fabs(fehs-options.feh) < 0.2][0]] fehs= isodist.Z2FEH(zs,zsolar=0.017) #Load the RC models for each feh individually rcms= [] hists= [] edgess= [] for z in zs: print z trc= rcmodel.rcmodel(Z=z,loggmin=1.,loggmax=3.5, band=options.band,basti=options.basti, imfmodel=options.imfmodel, parsec=options.parsec) rcms.append(trc) sample= numpy.vstack([trc._sample[:,0],trc._loggs[:,0]]).T weights= trc._weights hist, edges= numpy.histogramdd(sample,weights=weights,bins=31, range=[[0.5,0.8],[1.,3.5]]) hists.append(hist) edgess.append(edges) #Load APOKASC data data= apread.apokasc() indx= (data['KASC_RG_LOGG_SCALE_2'] > 1.)\ *(data['KASC_RG_LOGG_SCALE_2'] < 3.5)\ *(data['METALS'] > options.feh-0.2)\ *(data['METALS'] <= options.feh+0.2) print "Using %i APOKASC objects ..." % (numpy.sum(indx)) data= data[indx] ndata= numpy.sum(indx) #Stack predictions outhist= numpy.zeros_like(hists[0]) for ii in range(ndata): zindx= numpy.argmin(numpy.fabs(fehs-data['METALS'][ii])) outhist+= hists[zindx] save_pickles(args[0],outhist,hists,edgess,data) #Normalize each J-K for ii in range(len(outhist[:,0])): outhist[ii,:]/= numpy.nanmax(outhist[ii,:])/numpy.nanmax(outhist) rev= copy.copy(outhist[ii,::-1]) #reverse, but in one go does not always work outhist[ii,:]= rev if True: #Reload apokasc data data= apread.apokasc() indx= (data['KASC_RG_LOGG_SCALE_2'] > 1.)\ *(data['KASC_RG_LOGG_SCALE_2'] < 3.5)\ *(data['METALS'] > options.feh-0.2)\ *(data['METALS'] <= options.feh+0.2) data= data[indx] #Plot everything bovy_plot.bovy_print() bovy_plot.bovy_dens2d(outhist.T,origin='lower',cmap='gist_yarg', xrange=[edgess[0][0][0],edgess[0][0][-1]], yrange=[edgess[0][1][-1],edgess[0][1][0]], aspect=(edgess[0][0][-1]-edgess[0][0][0])/float(edgess[0][1][-1]-edgess[0][1][0]), xlabel=r'$(J-K_s)_0\ [\mathrm{mag}]$', ylabel=r'$\mathrm{Seismic}\ \log g$', shrink=0.78, interpolation='nearest') #Overplot APOKASC data noseismo= data['SEISMO EVOL'] == 'UNKNOWN' if numpy.sum(noseismo) > 0: bovy_plot.bovy_plot(data['J0'][noseismo]-data['K0'][noseismo], data['KASC_RG_LOGG_SCALE_2'][noseismo],'bo', overplot=True, mec='none',ms=3.) clumpseismo= data['SEISMO EVOL'] == 'CLUMP' if numpy.sum(clumpseismo) > 0: bovy_plot.bovy_plot(data['J0'][clumpseismo]-data['K0'][clumpseismo], data['KASC_RG_LOGG_SCALE_2'][clumpseismo],'yo', overplot=True, mec='none',ms=4.5) noclumpseismo= (data['SEISMO EVOL'] == 'RGB') \ + (data['SEISMO EVOL'] == 'DWARF/SUBGIANT') if numpy.sum(noclumpseismo) > 0: bovy_plot.bovy_plot(data['J0'][noclumpseismo]-data['K0'][noclumpseismo], data['KASC_RG_LOGG_SCALE_2'][noclumpseismo],'ro', overplot=True, mec='none',ms=3.) bovy_plot.bovy_text(r'$%.1f < [\mathrm{M/H}] \leq %.1f$' % (options.feh-0.2,options.feh+0.2), top_left=True,size=14.) bovy_plot.bovy_end_print(options.outfilename) return None
def plotPixelFunc(feh,afe,z, fehmin=-1.6,fehmax=0.5,afemin=-0.05,afemax=0.55, **kwargs): """ NAME: plotPixelFunc PURPOSE: Plot a function as a function of [Fe/H] and [a/Fe], a la Bovy et al. (2012) INPUT: feh - feh values of z afe - afe values of z z - function to plot (array with the same length as feh and afe) bovy_plot.bovy_dens2d kwargs OUTPUT: plot to output device HISTORY: 2013-03-19 - Written - Bovy (IAS) """ if not _GALPYLOADED: raise ImportError("Use of plotPixelFunc requires galpy's bovy_plot to be installed; install galpy starting at https://github.com/jobovy/galpy") #First create 2D gfeh= numpy.linspace(fehmin+0.05,fehmax-0.05,int((fehmax-fehmin)/0.1)) gafe= numpy.linspace(afemin+0.025,afemax-0.025,int((afemax-afemin)/0.05)) z2d= numpy.empty((int((fehmax-fehmin)/0.1),int((afemax-afemin)/0.05))) for ii in range(z2d.shape[0]): for jj in range(z2d.shape[1]): if numpy.amin((gfeh[ii]-feh)**2./0.01**2. +(gafe[jj]-afe)**2./0.05**2.) < 10.**-4.: indx= numpy.argmin((gfeh[ii]-feh)**2./0.01**2. +(gafe[jj]-afe)**2./0.05**2.) z2d[ii,jj]= z[indx] else: z2d[ii,jj]= numpy.nan #Now plot xrange=[-1.6,0.5] yrange=[-0.05,0.55] if not kwargs.has_key('colorbar'): kwargs['colorbar']= True if not kwargs.has_key('shrink'): kwargs['shrink']= 0.78 if not kwargs.has_key('vmin'): kwargs['vmin']= numpy.nanmin(z2d) if not kwargs.has_key('vmax'): kwargs['vmax']= numpy.nanmax(z2d) return bovy_plot.bovy_dens2d(z2d.T,origin='lower',cmap='jet', interpolation='nearest', xlabel=r'$[\mathrm{Fe/H}]$', ylabel=r'$[\alpha/\mathrm{Fe}]$', xrange=xrange,yrange=yrange, contours=False, **kwargs)
def plotPixelFitVel(options,args): if options.sample.lower() == 'g': if options.select.lower() == 'program': raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=options.snmin, distfac=options.distfac) else: raw= read_gdwarfs(logg=True,ebv=True,sn=options.snmin, distfac=options.distfac) elif options.sample.lower() == 'k': if options.select.lower() == 'program': raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=options.snmin, distfac=options.distfac) else: raw= read_kdwarfs(logg=True,ebv=True,sn=options.snmin, distfac=options.distfac) if not options.bmin is None: #Cut on |b| raw= raw[(numpy.fabs(raw.b) > options.bmin)] #print len(raw) #Bin the data binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe) if options.tighten: tightbinned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe, fehmin=-1.6,fehmax=0.5,afemin=-0.05, afemax=0.55) else: tightbinned= binned #Savefile if os.path.exists(args[0]):#Load savefile savefile= open(args[0],'rb') fits= pickle.load(savefile) savefile.close() #Now plot #Run through the pixels and gather if options.type.lower() == 'afe' or options.type.lower() == 'feh' \ or options.type.lower() == 'fehafe' \ or options.type.lower() == 'afefeh': plotthis= [] else: plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe())) #ndata= 0 #maxndata= 0 for ii in range(tightbinned.npixfeh()): for jj in range(tightbinned.npixafe()): data= binned(tightbinned.feh(ii),tightbinned.afe(jj)) fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning afeindx= binned.afeindx(tightbinned.afe(jj)) if afeindx+fehindx*binned.npixafe() >= len(fits): if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \ or options.type.lower() == 'afefeh': continue else: plotthis[ii,jj]= numpy.nan continue thisfit= fits[afeindx+fehindx*binned.npixafe()] if thisfit is None: if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \ or options.type.lower() == 'afefeh': continue else: plotthis[ii,jj]= numpy.nan continue if len(data) < options.minndata: if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \ or options.type.lower() == 'afefeh': continue else: plotthis[ii,jj]= numpy.nan continue #if len(data) > maxndata: maxndata= len(data) #ndata+= len(data) if options.model.lower() == 'hwr': if options.type == 'sz': plotthis[ii,jj]= numpy.exp(thisfit[1]) elif options.type == 'sz2': plotthis[ii,jj]= numpy.exp(2.*thisfit[1]) elif options.type == 'hs': plotthis[ii,jj]= numpy.exp(thisfit[4]) elif options.type == 'hsm': plotthis[ii,jj]= numpy.exp(-thisfit[4]) elif options.type == 'pbad': plotthis[ii,jj]= thisfit[0] elif options.type == 'slopes': plotthis[ii,jj]= thisfit[2] elif options.type == 'slope': plotthis[ii,jj]= thisfit[2] elif options.type == 'chi2dof': plotthis[ii,jj]= thisfit[6] elif options.type.lower() == 'afe' \ or options.type.lower() == 'feh' \ or options.type.lower() == 'fehafe' \ or options.type.lower() == 'afefeh': plotthis.append([tightbinned.feh(ii), tightbinned.afe(jj), numpy.exp(thisfit[1]), numpy.exp(thisfit[3]), len(data)]) #print ndata #print maxndata #Set up plot #print numpy.nanmin(plotthis), numpy.nanmax(plotthis) if options.type == 'sz': if options.vr: vmin, vmax= 40.,80. zlabel= r'$\sigma_R(z = \langle z \rangle)\ [\mathrm{km\ s}^{-1}]$' else: vmin, vmax= 10.,60. zlabel= r'$\sigma_z(z_{1/2})\ [\mathrm{km\ s}^{-1}]$' elif options.type == 'sz2': if options.vr: vmin, vmax= 40.**2.,80.**2. zlabel= r'$\sigma_R^2(z= \langle z \rangle)\ [\mathrm{km\ s}^{-1}]$' else: vmin, vmax= 15.**2.,50.**2. zlabel= r'$\sigma_z^2(z= \langle z \rangle)\ [\mathrm{km\ s}^{-1}]$' elif options.type == 'hs': if options.vr: vmin, vmax= 3.,25. zlabel= r'$R_\sigma\ [\mathrm{kpc}]$' else: vmin, vmax= 3.,15. zlabel= r'$h_\sigma\ [\mathrm{kpc}]$' elif options.type == 'hsm': if options.vr: vmin, vmax= 0.,0.3 zlabel= r'$R^{-1}_\sigma\ [\mathrm{kpc}^{-1}]$' else: vmin, vmax= 0.,0.3 zlabel= r'$R^{-1}_\sigma\ [\mathrm{kpc}^{-1}]$' elif options.type == 'slope': vmin, vmax= -5.,5. zlabel= r'$\frac{\mathrm{d} \sigma_z}{\mathrm{d} z}(z_{1/2})\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$' elif options.type == 'pbad': vmin, vmax= 0.,0.1 zlabel= r'$P_{\mathrm{bad}}$' elif options.type == 'chi2dof': vmin, vmax= 0.5,1.5 zlabel= r'$\chi^2/\mathrm{dof}$' elif options.type == 'afe': vmin, vmax= 0.05,.4 zlabel=r'$[\alpha/\mathrm{Fe}]$' elif options.type == 'feh': vmin, vmax= -1.5,0. zlabel=r'$[\mathrm{Fe/H}]$' elif options.type == 'fehafe': vmin, vmax= -.7,.7 zlabel=r'$[\mathrm{Fe/H}]-[\mathrm{Fe/H}]_{1/2}([\alpha/\mathrm{Fe}])$' elif options.type == 'afefeh': vmin, vmax= -.15,.15 zlabel=r'$[\alpha/\mathrm{Fe}]-[\alpha/\mathrm{Fe}]_{1/2}([\mathrm{Fe/H}])$' if options.tighten: xrange=[-1.6,0.5] yrange=[-0.05,0.55] else: xrange=[-2.,0.6] yrange=[-0.1,0.6] if options.type.lower() == 'afe' or options.type.lower() == 'feh' \ or options.type.lower() == 'fehafe' \ or options.type.lower() == 'afefeh': print "Update!! Never used until now (afe etc. type fitting is in plotsz2hz" return None bovy_plot.bovy_print(fig_height=3.87,fig_width=5.) #Gather hR and hz hz, hr,afe, feh, ndata= [], [], [], [], [] for ii in range(len(plotthis)): hz.append(plotthis[ii][2]) hr.append(plotthis[ii][3]) afe.append(plotthis[ii][1]) feh.append(plotthis[ii][0]) ndata.append(plotthis[ii][4]) hz= numpy.array(hz) hr= numpy.array(hr) afe= numpy.array(afe) feh= numpy.array(feh) ndata= numpy.array(ndata) #Process ndata ndata= ndata**.5 ndata= ndata/numpy.median(ndata)*35. #ndata= numpy.log(ndata)/numpy.log(numpy.median(ndata)) #ndata= (ndata-numpy.amin(ndata))/(numpy.amax(ndata)-numpy.amin(ndata))*25+12. if options.type.lower() == 'afe': plotc= afe elif options.type.lower() == 'feh': plotc= feh elif options.type.lower() == 'afefeh': #Go through the bins to determine whether feh is high or low for this alpha plotc= numpy.zeros(len(afe)) for ii in range(tightbinned.npixfeh()): fehbin= ii data= tightbinned.data[(tightbinned.data.feh > tightbinned.fehedges[fehbin])\ *(tightbinned.data.feh <= tightbinned.fehedges[fehbin+1])] medianafe= numpy.median(data.afe) for jj in range(len(afe)): if feh[jj] == tightbinned.feh(ii): plotc[jj]= afe[jj]-medianafe else: #Go through the bins to determine whether feh is high or low for this alpha plotc= numpy.zeros(len(feh)) for ii in range(tightbinned.npixafe()): afebin= ii data= tightbinned.data[(tightbinned.data.afe > tightbinned.afeedges[afebin])\ *(tightbinned.data.afe <= tightbinned.afeedges[afebin+1])] medianfeh= numpy.median(data.feh) for jj in range(len(feh)): if afe[jj] == tightbinned.afe(ii): plotc[jj]= feh[jj]-medianfeh yrange= [150,1200] xrange= [1.2,5.] bovy_plot.bovy_plot(hr,hz,s=ndata,c=plotc, cmap='jet', ylabel=r'$\mathrm{vertical\ scale\ height\ [pc]}$', xlabel=r'$\mathrm{radial\ scale\ length\ [kpc]}$', clabel=zlabel, xrange=xrange,yrange=yrange, vmin=vmin,vmax=vmax, scatter=True,edgecolors='none', colorbar=True) elif options.type.lower() == 'slopes': bovy_plot.bovy_print() bovy_plot.bovy_hist(plotthis.flatten(), range=[-5.,5.], bins=11, histtype='step', color='k', xlabel=r'$\sigma_z(z)\ \mathrm{slope\ [km\ s}^{-1}\ \mathrm{kpc}^{-1}]$') else: bovy_plot.bovy_print() bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet', interpolation='nearest', xlabel=r'$[\mathrm{Fe/H}]$', ylabel=r'$[\alpha/\mathrm{Fe}]$', zlabel=zlabel, xrange=xrange,yrange=yrange, vmin=vmin,vmax=vmax, contours=False, colorbar=True,shrink=0.78) if options.observed: bovy_plot.bovy_text(r'$\mathrm{observed}$', top_right=True,size=18.) bovy_plot.bovy_end_print(options.plotfile) return None
def veldist_2d_Rphi(plotfilename,nx=10,ny=8,dx=_XWIDTH/20., dy=_YWIDTH/20.*1.8/1.15, nsx=2,nsy=2,ngrid=101,rrange=[0.6,1.4], phirange=[-m.pi/2.,m.pi/2.], saveDir='../bar/2d/'): """ NAME: veldist_2d_Rphi PURPOSE: plot how the velocity distribution changes as a function of R and phi INPUT: nx - number of plots in the x-direction ny - number of plots in the y direction dx - x-spacing dy - y-spacing nsx, nsy - number of subplots in the middle plot ngrid - number of gridpoints to evaluate the density on rrange - range of Galactocentric radii to consider phirange - range of Galactic azimuths to consider saveDir - directory to save the pickles in OUTPUT: plot! HISTORY: 2010-04-19 - Written - Bovy (NYU) """ #levels= sc.array([2,6,12,21,33,50,68,80,90,95,99,99.9])/100. levels= sc.array([2,12,33,50,68,80,95,99.9])/100. cntrcolors= ['w' for ii in range(len(levels)) if levels[ii] <= .5] cntrcolors+= ['k' for ii in range(len(levels)) if levels[ii] > .5] ulinspace= (-0.9,0.9,ngrid) vlinspace= (-.7,.45,ngrid) picklebasename= '2d_%i_%i_%i_%i_%i_%.1f_%.1f_%.1f_%.1f' % (nx,ny,nsx,nsy,ngrid,rrange[0],rrange[1],phirange[0],phirange[1]) if not os.path.exists(saveDir): os.mkdir(saveDir) left, bottom = 0.1, 0.1 width= (nx*_XWIDTH+(nx-1)*dx)/(1.-2.*left) height= (ny*_YWIDTH+(ny-1)*dy)/(1.-2.*bottom) plot.bovy_print(fig_width=width,fig_height=height, xtick_major_size=2.,ytick_major_size=2., xtick_minor_size=0.,ytick_minor_size=0.) fig= pyplot.figure() #Make theta-R axes fudge= 8.0 thisax= fig.add_axes([left-_XWIDTH/width/fudge, bottom-_XWIDTH/height/fudge, 1.+2*_XWIDTH/width/fudge-2*left, 1.+2*_XWIDTH/height/fudge-2*bottom]) xrange= sc.array(phirange)*_radtodeg yrange=rrange thisax.xaxis.set_label_text(r'$\mathrm{Galactocentric\ azimuth}\ [\mathrm{deg}]$') thisax.set_xlim(-90.01,90.01) thisax.yaxis.set_label_text(r'$\mathrm{Galactocentric\ radius}\ / R_0$') thisax.set_ylim(yrange[0],yrange[1]) thisax.xaxis.set_major_locator(ticker.MultipleLocator(10.)) for ii in range(nx): for jj in range(ny): #Middle plot if ii == nx/2-1 and jj == ny/2-1: thisax= fig.add_axes([left+ii*(_XWIDTH+dx)/width, bottom+jj*(_YWIDTH+dy)/height, (nsx*_XWIDTH+(nsx-1)*dx)/width, (nsy*_YWIDTH+(nsy-1)*dy)/height]) thisR= (rrange[0]+(rrange[1]-rrange[0])/ (ny*_YWIDTH+(ny-1)*dy)*(jj*(_YWIDTH+dy)+_YWIDTH+dy/2.)) thisphi= (phirange[0]+(phirange[1]-phirange[0])/ (nx*_XWIDTH+(nx-1)*dx)*(ii*(_XWIDTH+dx)+_XWIDTH+dx/2.)) elif (ii >= nx/2-1 and ii < nx/2+nsx-1 and jj >= ny/2-1 and jj < ny/2 +nsy-1): continue else: thisax= fig.add_axes([left+ii*(_XWIDTH+dx)/width, bottom+jj*(_YWIDTH+dy)/height, _XWIDTH/width,_YWIDTH/height]) thisR= (rrange[0]+(rrange[1]-rrange[0])/ (ny*_YWIDTH+(ny-1)*dy)*(jj*(_YWIDTH+dy)+_YWIDTH/2.)) thisphi= (phirange[0]+(phirange[1]-phirange[0])/ (nx*_XWIDTH+(nx-1)*dx)*(ii*(_XWIDTH+dx)+_XWIDTH/2.)) thissavefilename= os.path.join(saveDir,picklebasename+'_%i_%i.sav' %(ii,jj)) if os.path.exists(thissavefilename): print "Restoring velocity distribution at %.1f, %.1f ..." %(thisR,thisphi) savefile= open(thissavefilename,'r') thisveldist= pickle.load(savefile) savefile.close() else: print "Calculating velocity distribution at %.1f, %.1f ..." %(thisR,thisphi) thisveldist= calc_veldist_2d(ulinspace, vlinspace, R=thisR, potparams=(0.9,0.01, 25.*_degtorad-thisphi, .8,None)) savefile= open(thissavefilename,'w') pickle.dump(thisveldist,savefile) savefile.close() fig.sca(thisax) plot.bovy_dens2d(thisveldist.T,origin='lower', cmap='gist_yarg', xrange=[ulinspace[0],ulinspace[1]], yrange=[vlinspace[0],vlinspace[1]], contours=True,cntrmass=True, levels=levels,cntrcolors=cntrcolors, overplot=True) thisax.xaxis.set_ticklabels('') thisax.yaxis.set_ticklabels('') plot.bovy_end_print(plotfilename)
def plotPotentials(Pot, rmin=0., rmax=1.5, nrs=21, zmin=-0.5, zmax=0.5, nzs=21, ncontours=21, savefilename=None): """ NAME: plotPotentials PURPOSE: plot a set of potentials INPUT: Pot - Potential or list of Potential instances rmin - minimum R rmax - maximum R nrs - grid in R zmin - minimum z zmax - maximum z nzs - grid in z ncontours - number of contours savefilename - save to or restore from this savefile (pickle) OUTPUT: plot to output device HISTORY: 2010-07-09 - Written - Bovy (NYU) """ if not savefilename == None and os.path.exists(savefilename): print "Restoring savefile " + savefilename + " ..." savefile = open(savefilename, 'rb') potRz = pickle.load(savefile) Rs = pickle.load(savefile) zs = pickle.load(savefile) savefile.close() else: Rs = nu.linspace(rmin, rmax, nrs) zs = nu.linspace(zmin, zmax, nzs) potRz = nu.zeros((nrs, nzs)) for ii in range(nrs): for jj in range(nzs): potRz[ii, jj] = evaluatePotentials(Rs[ii], zs[jj], Pot) if not savefilename == None: print "Writing savefile " + savefilename + " ..." savefile = open(savefilename, 'wb') pickle.dump(potRz, savefile) pickle.dump(Rs, savefile) pickle.dump(zs, savefile) savefile.close() return plot.bovy_dens2d(potRz.T, origin='lower', cmap='gist_gray', contours=True, xlabel=r"$R/R_0$", ylabel=r"$z/R_0$", xrange=[rmin, rmax], yrange=[zmin, zmax], aspect=.75 * (rmax - rmin) / (zmax - zmin), cntrls='-', levels=nu.linspace(nu.nanmin(potRz), nu.nanmax(potRz), ncontours))
def plotMass(options,args): if options.sample.lower() == 'g': if options.select.lower() == 'program': raw= read_gdwarfs(_GDWARFFILE,logg=True,ebv=True,sn=True) else: raw= read_gdwarfs(logg=True,ebv=True,sn=True) elif options.sample.lower() == 'k': if options.select.lower() == 'program': raw= read_kdwarfs(_KDWARFFILE,logg=True,ebv=True,sn=True) else: raw= read_kdwarfs(logg=True,ebv=True,sn=True) #Bin the data binned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe) if options.tighten: tightbinned= pixelAfeFeh(raw,dfeh=options.dfeh,dafe=options.dafe, fehmin=-1.6,fehmax=0.5,afemin=-0.05, afemax=0.55) else: tightbinned= binned #Savefile if os.path.exists(args[0]):#Load savefile savefile= open(args[0],'rb') mass= pickle.load(savefile) ii= pickle.load(savefile) jj= pickle.load(savefile) savefile.close() else: mass= [] ii, jj= 0, 0 #parameters if os.path.exists(args[1]):#Load initial savefile= open(args[1],'rb') fits= pickle.load(savefile) savefile.close() else: print "Error: must provide parameters of best fits" print "Returning ..." return None #Mass uncertainties are in savefile3 if len(args) > 2 and os.path.exists(args[2]): savefile= open(args[2],'rb') masssamples= pickle.load(savefile) savefile.close() masserrors= True else: masssamples= None masserrors= False if len(args) > 3 and os.path.exists(args[3]): #Load savefile savefile= open(args[3],'rb') denssamples= pickle.load(savefile) savefile.close() denserrors= True else: denssamples= None denserrors= False if len(args) > 4 and os.path.exists(args[4]):#Load savefile savefile= open(args[4],'rb') velfits= pickle.load(savefile) savefile.close() velfitsLoaded= True else: velfitsLoaded= False if len(args) > 5 and os.path.exists(args[5]): savefile= open(args[5],'rb') velsamples= pickle.load(savefile) savefile.close() velerrors= True else: velsamples= None velerrors= False #Now plot #Run through the pixels and gather if options.type.lower() == 'afe' or options.type.lower() == 'feh' \ or options.type.lower() == 'fehafe' \ or options.type.lower() == 'afefeh': plotthis= [] else: plotthis= numpy.zeros((tightbinned.npixfeh(),tightbinned.npixafe())) if denserrors: errors= [] for ii in range(tightbinned.npixfeh()): for jj in range(tightbinned.npixafe()): data= binned(tightbinned.feh(ii),tightbinned.afe(jj)) fehindx= binned.fehindx(tightbinned.feh(ii))#Map onto regular binning afeindx= binned.afeindx(tightbinned.afe(jj)) if afeindx+fehindx*binned.npixafe() >= len(fits): if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \ or options.type.lower() == 'afefeh': continue else: plotthis[ii,jj]= numpy.nan continue thismass= mass[afeindx+fehindx*binned.npixafe()] if masserrors: thismasssamples= masssamples[afeindx+fehindx*binned.npixafe()] else: thismasssamples= None thisfit= fits[afeindx+fehindx*binned.npixafe()] if denserrors: thisdenssamples= denssamples[afeindx+fehindx*binned.npixafe()] else: thisdenssamples= None if velfitsLoaded: thisvelfit= velfits[afeindx+fehindx*binned.npixafe()] if velerrors: thisvelsamples= velsamples[afeindx+fehindx*binned.npixafe()] if thisfit is None: if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \ or options.type.lower() == 'afefeh': continue else: plotthis[ii,jj]= numpy.nan continue if len(data) < options.minndata: if options.type.lower() == 'afe' or options.type.lower() == 'feh' or options.type.lower() == 'fehafe' \ or options.type.lower() == 'afefeh': continue else: plotthis[ii,jj]= numpy.nan continue if options.type == 'mass': if not options.distzmin is None or not options.distzmax is None: if options.distzmin is None and not options.distzmax is None: thismass*= (1.-numpy.exp(-options.distzmax/numpy.exp(thisfit[0])/1000.)) elif not options.distzmin is None and options.distzmax is None: thismass*= numpy.exp(-options.distzmin/numpy.exp(thisfit[0])/1000.) else: thismass*= (numpy.exp(-options.distzmin/numpy.exp(thisfit[0])/1000.)-numpy.exp(-options.distzmax/numpy.exp(thisfit[0])/1000.)) if options.logmass: plotthis[ii,jj]= numpy.log10(thismass/10**6.) else: plotthis[ii,jj]= thismass/10**6. elif options.type == 'nstars': if options.logmass: plotthis[ii,jj]= numpy.log10(len(data)) else: plotthis[ii,jj]= len(data) elif options.model.lower() == 'hwr': if options.type == 'hz': plotthis[ii,jj]= numpy.exp(thisfit[0])*1000. elif options.type == 'hr': plotthis[ii,jj]= numpy.exp(thisfit[1]) elif options.type.lower() == 'afe' \ or options.type.lower() == 'feh' \ or options.type.lower() == 'fehafe' \ or options.type.lower() == 'afefeh': plotthis.append([tightbinned.feh(ii), tightbinned.afe(jj), numpy.exp(thisfit[0])*1000., numpy.exp(thisfit[1]), len(data), thismass/10.**6., thismasssamples]) if denserrors: theseerrors= [] thesesamples= denssamples[afeindx+fehindx*binned.npixafe()] if options.model.lower() == 'hwr': for kk in [0,1]: xs= numpy.array([s[kk] for s in thesesamples]) theseerrors.append(0.5*(-numpy.exp(numpy.mean(xs)-numpy.std(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs)))) errors.append(theseerrors) if velfitsLoaded: if options.velmodel.lower() == 'hwr': plotthis[-1].extend([numpy.exp(thisvelfit[1]), numpy.exp(thisvelfit[4]), thisvelfit[2], thisvelfit[3]]) if velerrors: theseerrors= [] thesesamples= velsamples[afeindx+fehindx*binned.npixafe()] for kk in [1,4]: xs= numpy.array([s[kk] for s in thesesamples]) theseerrors.append(0.5*(numpy.exp(numpy.mean(xs))-numpy.exp(numpy.mean(xs)-numpy.std(xs))-numpy.exp(numpy.mean(xs))+numpy.exp(numpy.mean(xs)+numpy.std(xs)))) xs= numpy.array([s[4] for s in thesesamples]) theseerrors.append(0.5*(numpy.exp(-numpy.mean(xs))-numpy.exp(numpy.mean(-xs)-numpy.std(-xs))-numpy.exp(numpy.mean(-xs))+numpy.exp(numpy.mean(-xs)+numpy.std(-xs)))) errors[-1].extend(theseerrors) #Set up plot #print numpy.nanmin(plotthis), numpy.nanmax(plotthis) if options.type == 'mass': if options.logmass: vmin, vmax= numpy.log10(0.01), numpy.log10(2.) zlabel=r'$\log_{10} \Sigma(R_0)\ [M_{\odot}\ \mathrm{pc}^{-2}]$' else: vmin, vmax= 0.,1. zlabel=r'$\Sigma(R_0)\ [M_{\odot}\ \mathrm{pc}^{-2}]$' if not options.distzmin is None or not options.distzmax is None: vmin, vmax= None, None title=r'$\mathrm{mass\ weighted}$' elif options.type == 'nstars': if options.logmass: vmin, vmax= 2., 3. zlabel=r'$\log_{10} \mathrm{raw\ number\ of\ G}$-$\mathrm{type\ dwarfs}$' else: vmin, vmax= 100.,1000. zlabel=r'$\mathrm{raw\ number\ of\ G}$-$\mathrm{type\ dwarfs}$' title= r'$\mathrm{raw\ sample\ counts}$' elif options.type == 'afe': vmin, vmax= 0.0,.5 zlabel=r'$[\alpha/\mathrm{Fe}]$' elif options.type == 'feh': vmin, vmax= -1.5,0. zlabel=r'$[\mathrm{Fe/H}]$' elif options.type == 'fehafe': vmin, vmax= -.7,.7 zlabel=r'$[\mathrm{Fe/H}]-[\mathrm{Fe/H}]_{1/2}([\alpha/\mathrm{Fe}])$' elif options.type == 'afefeh': vmin, vmax= -.15,.15 zlabel=r'$[\alpha/\mathrm{Fe}]-[\alpha/\mathrm{Fe}]_{1/2}([\mathrm{Fe/H}])$' if options.tighten: xrange=[-1.6,0.5] yrange=[-0.05,0.55] else: xrange=[-2.,0.6] yrange=[-0.1,0.6] if options.type.lower() == 'afe' or options.type.lower() == 'feh' \ or options.type.lower() == 'fehafe' \ or options.type.lower() == 'afefeh': bovy_plot.bovy_print(fig_height=3.87,fig_width=5.) #Gather hR and hz sz_err, sz, hz_err, hr_err, mass_err, mass, hz, hr,afe, feh, ndata= [], [], [], [], [], [], [], [], [], [], [] for ii in range(len(plotthis)): if denserrors: hz_err.append(errors[ii][0]*1000.) hr_err.append(errors[ii][1]) mass.append(plotthis[ii][5]) hz.append(plotthis[ii][2]) hr.append(plotthis[ii][3]) afe.append(plotthis[ii][1]) feh.append(plotthis[ii][0]) ndata.append(plotthis[ii][4]) if velfitsLoaded: sz.append(plotthis[ii][7]) if velerrors: sz_err.append(errors[ii][2]) if masserrors: mass_err.append(numpy.std(numpy.array(plotthis[ii][6])/10.**6.)) """ if options.logmass: mass_err.append(numpy.std(numpy.log10(numpy.array(plotthis[ii][6])/10.**6.))) else: mass_err.append(numpy.std(numpy.array(plotthis[ii][6])/10.**6.)) """ if denserrors: hz_err= numpy.array(hz_err) hr_err= numpy.array(hr_err) if velfitsLoaded: sz= numpy.array(sz) if velerrors: sz_err= numpy.array(sz_err) mass= numpy.array(mass) if masserrors: mass_err= numpy.array(mass_err) hz= numpy.array(hz) hr= numpy.array(hr) afe= numpy.array(afe) feh= numpy.array(feh) ndata= numpy.array(ndata) #Process ndata ndata= ndata**.5 ndata= ndata/numpy.median(ndata)*35. #ndata= numpy.log(ndata)/numpy.log(numpy.median(ndata)) #ndata= (ndata-numpy.amin(ndata))/(numpy.amax(ndata)-numpy.amin(ndata))*25+12. if options.type.lower() == 'afe': plotc= afe elif options.type.lower() == 'feh': plotc= feh elif options.type.lower() == 'afefeh': #Go through the bins to determine whether feh is high or low for this alpha plotc= numpy.zeros(len(afe)) for ii in range(tightbinned.npixfeh()): fehbin= ii data= tightbinned.data[(tightbinned.data.feh > tightbinned.fehedges[fehbin])\ *(tightbinned.data.feh <= tightbinned.fehedges[fehbin+1])] medianafe= numpy.median(data.afe) for jj in range(len(afe)): if feh[jj] == tightbinned.feh(ii): plotc[jj]= afe[jj]-medianafe else: #Go through the bins to determine whether feh is high or low for this alpha plotc= numpy.zeros(len(feh)) for ii in range(tightbinned.npixafe()): afebin= ii data= tightbinned.data[(tightbinned.data.afe > tightbinned.afeedges[afebin])\ *(tightbinned.data.afe <= tightbinned.afeedges[afebin+1])] medianfeh= numpy.median(data.feh) for jj in range(len(feh)): if afe[jj] == tightbinned.afe(ii): plotc[jj]= feh[jj]-medianfeh xrange= [150,1200] if options.cumul: #Print total surface mass and uncertainty totmass= numpy.sum(mass) if options.ploterrors: toterr= numpy.sqrt(numpy.sum(mass_err**2.)) else: toterr= 0. print "Total surface-mass density: %4.1f +/- %4.2f" %(totmass,toterr) ids= numpy.argsort(hz) plotc= plotc[ids] ndata= ndata[ids] mass= mass[ids] mass= numpy.cumsum(mass) hz.sort() ylabel=r'$\mathrm{cumulative}\ \Sigma(R_0)\ [M_{\odot}\ \mathrm{pc}^{-2}]$' if options.logmass: yrange= [0.01,30.] else: yrange= [-0.1,30.] else: if options.logmass: yrange= [0.005*0.13/.07,10.*.13/.07] else: yrange= [-0.1,10.*.13/.07] ylabel=r'$\Sigma_{R_0}(h_z)\ [M_{\odot}\ \mathrm{pc}^{-2}]$' if not options.vstructure and not options.hzhr: if options.hr: ploth= hr plotherr= hr_err xlabel=r'$\mathrm{radial\ scale\ length\ [kpc]}$' xrange= [1.2,4.] bins= 11 elif options.sz: ploth= sz**2. plotherr= 2.*sz_err*sz xlabel=r'$\sigma_z^2\ \mathrm{[km}^2\ \mathrm{s}^{-2}]$' xrange= [12.**2.,50.**2.] ylabel=r'$\Sigma_{R_0}(\sigma^2_z)\ [M_{\odot}\ \mathrm{pc}^{-2}]$' bins= 9 else: ploth= hz plotherr= hz_err xlabel=r'$\mathrm{vertical\ scale\ height}\ h_z\ \mathrm{[pc]}$' xrange= [165,1200] bins= 12 bovy_plot.bovy_plot(ploth,mass*.13/0.07, s=ndata,c=plotc, cmap='jet', xlabel=xlabel, ylabel=ylabel, clabel=zlabel, xrange=xrange,yrange=yrange, vmin=vmin,vmax=vmax, scatter=True,edgecolors='none', colorbar=True,zorder=2, semilogy=options.logmass) if not options.cumul and masserrors and options.ploterrors: colormap = cm.jet for ii in range(len(hz)): pyplot.errorbar(ploth[ii],mass[ii]*.13/0.07, yerr=mass_err[ii]*.13/0.07, color=colormap(_squeeze(plotc[ii], numpy.amax([vmin, numpy.amin(plotc)]), numpy.amin([vmax, numpy.amax(plotc)]))), elinewidth=1.,capsize=3,zorder=0) if not options.cumul and denserrors and options.ploterrors: colormap = cm.jet for ii in range(len(hz)): pyplot.errorbar(ploth[ii],mass[ii]*.13/0.07,xerr=plotherr[ii], color=colormap(_squeeze(plotc[ii], numpy.amax([vmin, numpy.amin(plotc)]), numpy.amin([vmax, numpy.amax(plotc)]))), elinewidth=1.,capsize=3,zorder=0) #Add binsize label bovy_plot.bovy_text(r'$\mathrm{points\ use}\ \Delta [\mathrm{Fe/H}] = 0.1,$'+'\n'+r'$\Delta [\alpha/\mathrm{Fe}] = 0.05\ \mathrm{bins}$', bottom_left=True) #Overplot histogram #ax2 = pyplot.twinx() pyplot.hist(ploth,range=xrange,weights=mass*0.13/0.07,color='k',histtype='step', bins=bins,lw=3.,zorder=10) #Also XD? if options.xd: #Set up data ydata= numpy.zeros((len(hz),1)) if options.sz: ydata[:,0]= numpy.log(sz) else: ydata[:,0]= numpy.log(hz) ycovar= numpy.zeros((len(hz),1)) if options.sz: ycovar[:,0]= sz_err**2./sz**2. else: ycovar[:,0]= hz_err**2./hz**2. #Set up initial conditions xamp= numpy.ones(options.k)/float(options.k) xmean= numpy.zeros((options.k,1)) for kk in range(options.k): xmean[kk,:]= numpy.mean(ydata,axis=0)\ +numpy.random.normal()*numpy.std(ydata,axis=0) xcovar= numpy.zeros((options.k,1,1)) for kk in range(options.k): xcovar[kk,:,:]= numpy.cov(ydata.T) #Run XD print extreme_deconvolution(ydata,ycovar,xamp,xmean,xcovar, weight=mass)*len(hz) print xamp, xmean, xcovar #Plot xs= numpy.linspace(xrange[0],xrange[1],1001) xdys= numpy.zeros(len(xs)) for kk in range(options.k): xdys+= xamp[kk]/numpy.sqrt(2.*numpy.pi*xcovar[kk,0,0])\ *numpy.exp(-0.5*(numpy.log(xs)-xmean[kk,0])**2./xcovar[kk,0,0]) xdys/= xs bovy_plot.bovy_plot(xs,xdys,'-',color='0.5',overplot=True) # ax2.set_yscale('log') # ax2.set_yticklabels('') # if options.hr: # pyplot.ylim(10**-2.,10.**0.) # if options.sz: # pyplot.ylim(10**-5.,10.**-2.5) # else: # pyplot.ylim(10**-5.5,10.**-1.5) # pyplot.xlim(xrange[0],xrange[1]) ax= pyplot.gca() if options.sz: def my_formatter(x, pos): """s^2""" xs= int(round(math.sqrt(x))) return r'$%i^2$' % xs major_formatter = FuncFormatter(my_formatter) ax.xaxis.set_major_formatter(major_formatter) xstep= ax.xaxis.get_majorticklocs() xstep= xstep[1]-xstep[0] ax.xaxis.set_minor_locator(MultipleLocator(xstep/5.)) elif options.hzhr: #Make density plot in hR and hz bovy_plot.scatterplot(hr,hz,'k,', levels=[1.01],#HACK such that outliers aren't plotted cmap='gist_yarg', bins=11, xrange=[1.,7.], yrange=[150.,1200.], ylabel=r'$\mathrm{vertical\ scale\ height\ [pc]}$', xlabel=r'$\mathrm{radial\ scale\ length\ [kpc]}$', onedhists=False, weights=mass) else: #Make an illustrative plot of the vertical structure nzs= 1001 zs= numpy.linspace(200.,3000.,nzs) total= numpy.zeros(nzs) for ii in range(len(hz)): total+= mass[ii]/2./hz[ii]*numpy.exp(-zs/hz[ii]) bovy_plot.bovy_plot(zs,total,color='k',ls='-',lw=3., semilogy=True, xrange=[0.,3200.], yrange=[0.000001,0.02], xlabel=r'$\mathrm{vertical\ height}\ Z$', ylabel=r'$\rho_*(R=R_0,Z)\ [\mathrm{M}_\odot\ \mathrm{pc}^{-3}]$', zorder=10) if options.vbinned: #Bin mhist, edges= numpy.histogram(hz,range=xrange, weights=mass,bins=10) stotal= numpy.zeros(nzs) for ii in range(len(mhist)): hz= (edges[ii+1]+edges[ii])/2. if options.vcumul: if ii == 0.: pstotal= numpy.zeros(nzs)+0.0000001 else: pstotal= copy.copy(stotal) stotal+= mhist[ii]/2./hz*numpy.exp(-zs/hz) pyplot.fill_between(zs,stotal,pstotal, color='%.6f' % (0.25+0.5/(len(mhist)-1)*ii)) else: bovy_plot.bovy_plot([zs[0],zs[-1]], 1.*numpy.array([mhist[ii]/2./hz*numpy.exp(-zs[0]/hz), mhist[ii]/2./hz*numpy.exp(-zs[-1]/hz)]), color='0.5',ls='-',overplot=True, zorder=0) else: colormap = cm.jet for ii in range(len(hz)): bovy_plot.bovy_plot([zs[0],zs[-1]], 100.*numpy.array([mass[ii]/2./hz[ii]*numpy.exp(-zs[0]/hz[ii]), mass[ii]/2./hz[ii]*numpy.exp(-zs[-1]/hz[ii])]), ls='-',overplot=True,alpha=0.5, zorder=0, color=colormap(_squeeze(plotc[ii], numpy.amax([vmin, numpy.amin(plotc)]), numpy.amin([vmax, numpy.amax(plotc)])))) else: bovy_plot.bovy_print() bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='gist_yarg', interpolation='nearest', xlabel=r'$[\mathrm{Fe/H}]$', ylabel=r'$[\alpha/\mathrm{Fe}]$', zlabel=zlabel, xrange=xrange,yrange=yrange, vmin=vmin,vmax=vmax, onedhists=True, contours=False) bovy_plot.bovy_text(title,top_right=True,fontsize=16) if not options.distzmin is None or not options.distzmax is None: if options.distzmin is None: distlabel= r'$|Z| < %i\ \mathrm{pc}$' % int(options.distzmax) elif options.distzmax is None: distlabel= r'$|Z| > %i\ \mathrm{pc}$' % int(options.distzmin) else: distlabel= r'$%i < |Z| < %i\ \mathrm{pc}$' % (int(options.distzmin),int(options.distzmax)) bovy_plot.bovy_text(distlabel,bottom_left=True,fontsize=16) bovy_plot.bovy_end_print(options.plotfile) return None
def plotplanarPotentials(Pot, *args, **kwargs): """ NAME: plotplanarPotentials PURPOSE: plot a planar potential INPUT: Rrange - range xrange, yrange - if relevant grid, gridx, gridy - number of points to plot savefilename - save to or restore from this savefile (pickle) ncontours - number of contours to plot (if applicable) +bovy_plot(*args,**kwargs) or bovy_dens2d(**kwargs) OUTPUT: plot to output device HISTORY: 2010-07-13 - Written - Bovy (NYU) """ if kwargs.has_key('Rrange'): Rrange = kwargs['Rrange'] kwargs.pop('Rrange') else: Rrange = [0.01, 5.] if kwargs.has_key('xrange'): xrange = kwargs['xrange'] kwargs.pop('xrange') else: xrange = [-5., 5.] if kwargs.has_key('yrange'): yrange = kwargs['yrange'] kwargs.pop('yrange') else: yrange = [-5., 5.] if kwargs.has_key('grid'): grid = kwargs['grid'] kwargs.pop('grid') else: grid = 1000 #avoid zero if kwargs.has_key('gridx'): gridx = kwargs['gridx'] kwargs.pop('gridx') else: gridx = 1000 #avoid zero if kwargs.has_key('gridy'): gridy = kwargs['gridy'] kwargs.pop('gridy') else: gridy = gridx if kwargs.has_key('savefilename'): savefilename = kwargs['savefilename'] kwargs.pop('savefilename') else: savefilename = None isList = isinstance(Pot, list) nonAxi = ((isList and Pot[0].isNonAxi) or (not isList and Pot.isNonAxi)) if not savefilename == None and os.path.exists(savefilename): print "Restoring savefile " + savefilename + " ..." savefile = open(savefilename, 'rb') potR = pickle.load(savefile) Rs = pickle.load(savefile) if nonAxi: xs = pickle.load(savefile) ys = pickle.load(savefile) else: Rs = pickle.load(savefile) savefile.close() else: if nonAxi: xs = nu.linspace(xrange[0], xrange[1], gridx) ys = nu.linspace(yrange[0], yrange[1], gridy) potR = nu.zeros((gridx, gridy)) for ii in range(gridx): for jj in range(gridy): thisR = nu.sqrt(xs[ii]**2. + ys[jj]**2.) if xs[ii] >= 0.: thisphi = nu.arcsin(ys[jj] / thisR) else: thisphi = -nu.arcsin(ys[jj] / thisR) + nu.pi potR[ii, jj] = evaluateplanarPotentials(thisR, Pot, phi=thisphi) else: Rs = nu.linspace(Rrange[0], Rrange[1], grid) potR = nu.zeros(grid) for ii in range(grid): potR[ii] = evaluateplanarPotentials(Rs[ii], Pot) if not savefilename == None: print "Writing savefile " + savefilename + " ..." savefile = open(savefilename, 'wb') pickle.dump(potR, savefile) if nonAxi: pickle.dump(xs, savefile) pickle.dump(ys, savefile) else: pickle.dump(Rs, savefile) savefile.close() if nonAxi: if not kwargs.has_key('origin'): kwargs['origin'] = 'lower' if not kwargs.has_key('cmap'): kwargs['cmap'] = 'gist_yarg' if not kwargs.has_key('contours'): kwargs['contours'] = True if not kwargs.has_key('xlabel'): kwargs['xlabel'] = r"$x / R_0$" if not kwargs.has_key('ylabel'): kwargs['ylabel'] = "$y / R_0$" if not kwargs.has_key('aspect'): kwargs['aspect'] = 1. if not kwargs.has_key('cntrls'): kwargs['cntrls'] = '-' if kwargs.has_key('ncontours'): ncontours = kwargs['ncontours'] kwargs.pop('ncontours') else: ncontours = 10 if not kwargs.has_key('levels'): kwargs['levels'] = nu.linspace(nu.nanmin(potR), nu.nanmax(potR), ncontours) return plot.bovy_dens2d(potR.T, xrange=xrange, yrange=yrange, **kwargs) else: kwargs['xlabel'] = r"$R/R_0$" kwargs['ylabel'] = r"$\Phi(R)$", kwargs['xrange'] = Rrange return plot.bovy_plot(Rs, potR, *args, **kwargs)
def plotplanarPotentials(Pot,*args,**kwargs): """ NAME: plotplanarPotentials PURPOSE: plot a planar potential INPUT: Rrange - range (can be Quantity) xrange, yrange - if relevant (can be Quantity) grid, gridx, gridy - number of points to plot savefilename - save to or restore from this savefile (pickle) ncontours - number of contours to plot (if applicable) +bovy_plot(*args,**kwargs) or bovy_dens2d(**kwargs) OUTPUT: plot to output device HISTORY: 2010-07-13 - Written - Bovy (NYU) """ Pot= flatten(Pot) Rrange= kwargs.pop('Rrange',[0.01,5.]) xrange= kwargs.pop('xrange',[-5.,5.]) yrange= kwargs.pop('yrange',[-5.,5.]) if _APY_LOADED: if hasattr(Pot,'_ro'): tro= Pot._ro else: tro= Pot[0]._ro if isinstance(Rrange[0],units.Quantity): Rrange[0]= Rrange[0].to(units.kpc).value/tro if isinstance(Rrange[1],units.Quantity): Rrange[1]= Rrange[1].to(units.kpc).value/tro if isinstance(xrange[0],units.Quantity): xrange[0]= xrange[0].to(units.kpc).value/tro if isinstance(xrange[1],units.Quantity): xrange[1]= xrange[1].to(units.kpc).value/tro if isinstance(yrange[0],units.Quantity): yrange[0]= yrange[0].to(units.kpc).value/tro if isinstance(yrange[1],units.Quantity): yrange[1]= yrange[1].to(units.kpc).value/tro grid= kwargs.pop('grid',100) gridx= kwargs.pop('gridx',100) gridy= kwargs.pop('gridy',gridx) savefilename= kwargs.pop('savefilename',None) isList= isinstance(Pot,list) nonAxi= ((isList and Pot[0].isNonAxi) or (not isList and Pot.isNonAxi)) if not savefilename is None and os.path.exists(savefilename): print("Restoring savefile "+savefilename+" ...") savefile= open(savefilename,'rb') potR= pickle.load(savefile) if nonAxi: xs= pickle.load(savefile) ys= pickle.load(savefile) else: Rs= pickle.load(savefile) savefile.close() else: if nonAxi: xs= nu.linspace(xrange[0],xrange[1],gridx) ys= nu.linspace(yrange[0],yrange[1],gridy) potR= nu.zeros((gridx,gridy)) for ii in range(gridx): for jj in range(gridy): thisR= nu.sqrt(xs[ii]**2.+ys[jj]**2.) if xs[ii] >= 0.: thisphi= nu.arcsin(ys[jj]/thisR) else: thisphi= -nu.arcsin(ys[jj]/thisR)+nu.pi potR[ii,jj]= evaluateplanarPotentials(Pot,thisR, phi=thisphi, use_physical=False) else: Rs= nu.linspace(Rrange[0],Rrange[1],grid) potR= nu.zeros(grid) for ii in range(grid): potR[ii]= evaluateplanarPotentials(Pot,Rs[ii], use_physical=False) if not savefilename is None: print("Writing planar savefile "+savefilename+" ...") savefile= open(savefilename,'wb') pickle.dump(potR,savefile) if nonAxi: pickle.dump(xs,savefile) pickle.dump(ys,savefile) else: pickle.dump(Rs,savefile) savefile.close() if nonAxi: if not 'orogin' in kwargs: kwargs['origin']= 'lower' if not 'cmap' in kwargs: kwargs['cmap']= 'gist_yarg' if not 'contours' in kwargs: kwargs['contours']= True if not 'xlabel' in kwargs: kwargs['xlabel']= r"$x / R_0$" if not 'ylabel' in kwargs: kwargs['ylabel']= "$y / R_0$" if not 'aspect' in kwargs: kwargs['aspect']= 1. if not 'cntrls' in kwargs: kwargs['cntrls']= '-' ncontours= kwargs.pop('ncontours',10) if not 'levels' in kwargs: kwargs['levels']= nu.linspace(nu.nanmin(potR),nu.nanmax(potR),ncontours) return plot.bovy_dens2d(potR.T, xrange=xrange, yrange=yrange,**kwargs) else: kwargs['xlabel']=r"$R/R_0$" kwargs['ylabel']=r"$\Phi(R)$" kwargs['xrange']=Rrange return plot.bovy_plot(Rs,potR,*args,**kwargs)
def plot_rovo(filename, plotfilename): if not os.path.exists(filename): raise IOError("given filename does not exist") savefile = open(filename, 'rb') params = pickle.load(savefile) savefile.close() if _ANALYTIC: #Calculate by fixing everything except for Ro anv vo options = plot_pdfs.set_options(None) nros = 15 noos = 15 ros = numpy.linspace(7., 13., nros) oos = numpy.linspace(20., 30., noos) ll = numpy.zeros((noos, nros)) for ii in range(noos): if not _MULTI is None: theseparamss = [] for jj in range(nros): theseparams = copy.copy(params) theseparams[0] = oos[ii] * ros[jj] / _REFV0 theseparams[1] = ros[jj] / _REFR0 theseparamss.append(theseparams) thisll = multi.parallel_map( (lambda x: numpy.sum( logl.logl(init=theseparamss[x], options=options))), range(nros), numcores=numpy.amin( [nros, _MULTI, multiprocessing.cpu_count()])) ll[ii, :] = thisll else: for jj in range(nros): theseparams = copy.copy(params) theseparams[0] = oos[ii] * ros[jj] / _REFV0 theseparams[1] = ros[jj] / _REFR0 ll[ii, jj] = numpy.sum( logl.logl(init=theseparams, options=options)) #Normalize ll -= logsumexp(ll) ll = numpy.exp(ll) levels = list(special.erf(0.5 * numpy.arange(1, 4))) bovy_plot.bovy_dens2d( ll.T, origin='lower', levels=levels, xlabel=r'$\Omega_0\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$', ylabel=r'$R_0\ [\mathrm{kpc}]$', xrange=[20., 35.], yrange=[7., 13.], contours=True, cntrcolors='k', onedhists=True, cmap='gist_yarg') else: vos = numpy.array([s[0] for s in params]) * _REFV0 ros = numpy.array([s[1] for s in params]) * _REFR0 bovy_plot.bovy_print() levels = list(special.erf(0.5 * numpy.arange(1, 4))) levels.append(1.01) #HACK to not plot outliers bovy_plot.scatterplot( vos / ros, ros, 'k,', levels=levels, xlabel=r'$\Omega_0\ [\mathrm{km\ s}^{-1}\ \mathrm{kpc}^{-1}]$', ylabel=r'$R_0\ [\mathrm{kpc}]$', bins=31, xrange=[200. / 8., 250. / 8.], yrange=[7., 9.], contours=True, cntrcolors='k', onedhists=True, cmap='gist_yarg') bovy_plot.bovy_end_print(plotfilename)