def mvlosnonaxi(params, interpObj, interpObjAxi, thesedata, options, logpiso,
                phio):
    l = thesedata['GLON'] * _DEGTORAD
    b = thesedata['GLAT'] * _DEGTORAD
    cosb = math.cos(b)
    sinb = math.sin(b)
    out = 0.
    norm = 0.
    ds = numpy.linspace(_BINTEGRATEDMAX, _BINTEGRATEDMIN,
                        _BINTEGRATENBINS) / params[1] / _REFR0
    for ii in range(_BINTEGRATENBINS):
        #Calculate R and phi
        R, phi = bovy_coords.dl_to_rphi_2d(ds[ii], l, degree=False, phio=phio)
        if R < 0.5 or R > 2.: continue  #Not in the model
        logpd = _logpd(params, ds[ii], l, b, 0., 0., None, options, R, phi,
                       cosb, sinb, logpiso[ii])
        out += math.exp(logpd) * (
            (interpObj.meanvt(R, phi) * numpy.sin(phi + l - phio) -
             interpObj.meanvr(R, phi) * numpy.cos(phi + l - phio)) -
            (interpObjAxi.meanvt(R, phi) * numpy.sin(phi + l - phio) -
             interpObjAxi.meanvr(R, phi) * numpy.cos(phi + l - phio)))
        norm += math.exp(logpd)
    if norm == 0.: return 0.
    out /= norm
    #if l < 35.*_DEGTORAD: print out
    if options.dwarf:
        out *= (1. - params[5 - options.nooutliermean])
        R, phi = 1., phio
        out += params[5 - options.nooutliermean] * (
            (interpObj.meanvt(R, phi) * numpy.sin(phi + l - phio) -
             interpObj.meanvr(R, phi) * numpy.cos(phi + l - phio)) -
            (interpObjAxi.meanvt(R, phi) * numpy.sin(phi + l - phio) -
             interpObjAxi.meanvr(R, phi) * numpy.cos(phi + l - phio)))
    return out[0][0]
def mvlosnonaxi(params, interpObj, interpObjAxi, thesedata, options, logpiso, phio):
    l = thesedata["GLON"] * _DEGTORAD
    b = thesedata["GLAT"] * _DEGTORAD
    cosb = math.cos(b)
    sinb = math.sin(b)
    out = 0.0
    norm = 0.0
    ds = numpy.linspace(_BINTEGRATEDMAX, _BINTEGRATEDMIN, _BINTEGRATENBINS) / params[1] / _REFR0
    for ii in range(_BINTEGRATENBINS):
        # Calculate R and phi
        R, phi = bovy_coords.dl_to_rphi_2d(ds[ii], l, degree=False, phio=phio)
        if R < 0.5 or R > 2.0:
            continue  # Not in the model
        logpd = _logpd(params, ds[ii], l, b, 0.0, 0.0, None, options, R, phi, cosb, sinb, logpiso[ii])
        out += math.exp(logpd) * (
            (
                interpObj.meanvt(R, phi) * numpy.sin(phi + l - phio)
                - interpObj.meanvr(R, phi) * numpy.cos(phi + l - phio)
            )
            - (
                interpObjAxi.meanvt(R, phi) * numpy.sin(phi + l - phio)
                - interpObjAxi.meanvr(R, phi) * numpy.cos(phi + l - phio)
            )
        )
        norm += math.exp(logpd)
    if norm == 0.0:
        return 0.0
    out /= norm
    # if l < 35.*_DEGTORAD: print out
    if options.dwarf:
        out *= 1.0 - params[5 - options.nooutliermean]
        R, phi = 1.0, phio
        out += params[5 - options.nooutliermean] * (
            (
                interpObj.meanvt(R, phi) * numpy.sin(phi + l - phio)
                - interpObj.meanvr(R, phi) * numpy.cos(phi + l - phio)
            )
            - (
                interpObjAxi.meanvt(R, phi) * numpy.sin(phi + l - phio)
                - interpObjAxi.meanvr(R, phi) * numpy.cos(phi + l - phio)
            )
        )
    return out[0][0]
def plot_distanceprior(parser):
    (options,args)= parser.parse_args()
    #Read the data
    print "Reading the data ..."
    data= readVclosData(postshutdown=options.postshutdown,
                        fehcut=options.fehcut,
                        cohort=options.cohort,
                        lmin=options.lmin,
                        bmax=options.bmax,
                        ak=True,
                        cutmultiples=options.cutmultiples,
                        validfeh=options.indivfeh, #if indivfeh, we need validfeh
                        jkmax=options.jkmax,
                        datafilename=options.fakedata)
    l= data['GLON']*_DEGTORAD
    b= data['GLAT']*_DEGTORAD
    sinl= numpy.sin(l)
    cosl= numpy.cos(l)
    sinb= numpy.sin(b)
    cosb= numpy.cos(b)
    jk= data['J0MAG']-data['K0MAG']
    jk[(jk < 0.5)]= 0.5 #BOVY: FIX THIS HACK BY EMAILING GAIL
    h= data['H0MAG']
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile= open(options.isofile,'rb')
        iso= pickle.load(isofile)
        if options.indivfeh:
            zs= pickle.load(isofile)
        elif options.varfeh:
            locl= pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso= []
            zs= numpy.arange(0.0005,0.03005,0.0005)
            for ii in range(len(zs)):
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             Z=zs[ii]))
        elif options.varfeh:
            locs= list(set(data['LOCATION']))
            iso= []
            for ii in range(len(locs)):
                indx= (data['LOCATION'] == locs[ii])
                locl= numpy.mean(data['GLON'][indx]*_DEGTORAD)
                iso.append(isomodel.isomodel(imfmodel=options.imfmodel,
                                             expsfh=options.expsfh,
                                             marginalizefeh=True,
                                             glon=locl))
        else:
            iso= isomodel.isomodel(imfmodel=options.imfmodel,Z=options.Z,
                                   expsfh=options.expsfh)
    #Set up polar grid
    res= 51
    xgrid= numpy.linspace(0.,2.*math.pi*(1.-1./res/2.),
                       2*res)
    ygrid= numpy.linspace(0.5,2.8,res)
    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)
    plotthis= numpy.zeros((2*res,res,len(data)))-numpy.finfo(numpy.dtype(numpy.float64)).max
    #_BINTEGRATENBINS= 11 #For quick testing
    ds= numpy.linspace(_BINTEGRATEDMIN,_BINTEGRATEDMAX,_BINTEGRATENBINS)
    logpiso= numpy.zeros((len(data),_BINTEGRATENBINS))
    dm= _dm(ds)
    for ii in range(len(data)):
        mh= h[ii]-dm 
        if options.indivfeh:
            #Find closest Z
            thisZ= isodist.FEH2Z(data[ii]['FEH'])
            indx= numpy.argmin(numpy.fabs(thisZ-zs))
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+jk[ii],mh)
        elif options.varfeh:
            #Find correct iso
            indx= (locl == data[ii]['LOCATION'])
            logpiso[ii,:]= iso[0][indx](numpy.zeros(_BINTEGRATENBINS)+jk[ii],mh)
        else:
            logpiso[ii,:]= iso(numpy.zeros(_BINTEGRATENBINS)+jk[ii],mh)
    for jj in range(_BINTEGRATENBINS):
        d= ds[jj]/_REFR0
        R= numpy.sqrt(1.+d**2.-2.*d*cosl)
        indx= (R == 0.)
        R[indx]+= 0.0001
        theta= numpy.arcsin(d/R*sinl)
        indx= (1./cosl < d)*(cosl > 0.)
        theta[indx]= numpy.pi-theta[indx]
        indx= (theta < 0.)
        theta[indx]+= 2.*math.pi
        thisout= _logpd([0.,1.],d,None,None,
                        None,None,None,
                        options,R,theta,
                        1.,0.,logpiso[:,jj])
        #Find bin to which these contribute
        thetabin= numpy.floor((theta-xgrid[0])/(xgrid[1]-xgrid[0])+0.5)
        Rbin= numpy.floor((R-plotygrid[0])/(plotygrid[1]-plotygrid[0]))
        indx= (thetabin < 0)
        thetabin[indx]= 0
        Rbin[indx]= 0
        thisout[indx]= -numpy.finfo(numpy.dtype(numpy.float64)).max
        indx= (thetabin >= 2*res)
        thetabin[indx]= 0. #Has to be
        #Rbin[indx]= 0
        #thisout[indx]= -numpy.finfo(numpy.dtype(numpy.float64)).max
        indx= (Rbin < 0)
        thetabin[indx]= 0
        Rbin[indx]= 0
        thisout[indx]= -numpy.finfo(numpy.dtype(numpy.float64)).max
        indx= (Rbin >= res)
        thetabin[indx]= 0
        Rbin[indx]= 0
        thisout[indx]= -numpy.finfo(numpy.dtype(numpy.float64)).max
        thetabin= thetabin.astype('int')
        Rbin= Rbin.astype('int')
        for ii in range(len(data)):
            plotthis[thetabin,Rbin,ii]= thisout[ii]
    #Normalize
    for ii in range(2*res):
        for jj in range(res):
            plotthis[ii,jj,0]= logsumexp(plotthis[ii,jj,:])
    plotthis= plotthis[:,:,0]
    plotthis-= numpy.amax(plotthis)
    plotthis= numpy.exp(plotthis)
    plotthis[(plotthis == 0.)]= numpy.nan
    #Get los
    locations= list(set(data['LOCATION']))
    nlocs= len(locations)
    l_plate= numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx= (data['LOCATION'] == locations[ii])
        l_plate[ii]= numpy.mean(data['GLON'][indx])
    bovy_plot.bovy_print()
    ax= pyplot.subplot(111,projection='galpolar')#galpolar is in bovy_plot
    vmin, vmax= 0., 1.
    out= ax.pcolor(plotxgrid,plotygrid,plotthis.T,cmap='gist_yarg',
                   vmin=vmin,vmax=vmax,zorder=2)
    #Overlay los
    for ii in range(nlocs):
        lds= numpy.linspace(0.,2.95,501)
        lt= numpy.zeros(len(lds))
        lr= numpy.zeros(len(lds))
        lr= numpy.sqrt(1.+lds**2.-2.*lds*numpy.cos(l_plate[ii]*_DEGTORAD))
        lt= numpy.arcsin(lds/lr*numpy.sin(l_plate[ii]*_DEGTORAD))
        indx= (1./numpy.cos(l_plate[ii]*_DEGTORAD) < lds)*(numpy.cos(l_plate[ii]*_DEGTORAD) > 0.)
        lt[indx]= numpy.pi-lt[indx]
        ax.plot(lt,lr,
               ls='--',color='w',zorder=3)      
    from matplotlib.patches import Arrow, FancyArrowPatch
    arr= FancyArrowPatch(posA=(-math.pi/2.,1.8),
                         posB=(-math.pi/4.,1.8),
                         arrowstyle='->', 
                         connectionstyle='arc3,rad=%4.2f' % (-math.pi/16.),
                         shrinkA=2.0, shrinkB=2.0, mutation_scale=20.0, 
                         mutation_aspect=None,fc='k')
    ax.add_patch(arr)
    bovy_plot.bovy_text(-math.pi/2.,1.97,r'$\mathrm{Galactic\ rotation}$',
                         rotation=-22.5)
    radii= numpy.array([0.5,1.,1.5,2.,2.5])
    labels= []
    for r in radii:
        ax.plot(numpy.linspace(0.,2.*math.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=-32.5)
    bovy_plot.bovy_text(5.785,2.82,r'$\mathrm{kpc}$')
    azs= numpy.array([0.,45.,90.,135.,180.,225.,270.,315.])*_DEGTORAD
    for az in azs:
        ax.plot(numpy.zeros(501)+az,
                numpy.linspace(0.,2.8,501),'-',color='0.6',lw=0.5,zorder=1)
    #Sun
    bovy_plot.bovy_text(0.065,.9075,r'$\odot$')
    pyplot.ylim(0.,2.8)
    bovy_plot.bovy_end_print(options.plotfile)
Beispiel #4
0
def plot_distanceprior(parser):
    (options, args) = parser.parse_args()
    #Read the data
    print "Reading the data ..."
    data = readVclosData(
        postshutdown=options.postshutdown,
        fehcut=options.fehcut,
        cohort=options.cohort,
        lmin=options.lmin,
        bmax=options.bmax,
        ak=True,
        cutmultiples=options.cutmultiples,
        validfeh=options.indivfeh,  #if indivfeh, we need validfeh
        jkmax=options.jkmax,
        datafilename=options.fakedata)
    l = data['GLON'] * _DEGTORAD
    b = data['GLAT'] * _DEGTORAD
    sinl = numpy.sin(l)
    cosl = numpy.cos(l)
    sinb = numpy.sin(b)
    cosb = numpy.cos(b)
    jk = data['J0MAG'] - data['K0MAG']
    jk[(jk < 0.5)] = 0.5  #BOVY: FIX THIS HACK BY EMAILING GAIL
    h = data['H0MAG']
    #Set up the isochrone
    if not options.isofile is None and os.path.exists(options.isofile):
        print "Loading the isochrone model ..."
        isofile = open(options.isofile, 'rb')
        iso = pickle.load(isofile)
        if options.indivfeh:
            zs = pickle.load(isofile)
        elif options.varfeh:
            locl = pickle.load(isofile)
        isofile.close()
    else:
        print "Setting up the isochrone model ..."
        if options.indivfeh:
            #Load all isochrones
            iso = []
            zs = numpy.arange(0.0005, 0.03005, 0.0005)
            for ii in range(len(zs)):
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      Z=zs[ii]))
        elif options.varfeh:
            locs = list(set(data['LOCATION']))
            iso = []
            for ii in range(len(locs)):
                indx = (data['LOCATION'] == locs[ii])
                locl = numpy.mean(data['GLON'][indx] * _DEGTORAD)
                iso.append(
                    isomodel.isomodel(imfmodel=options.imfmodel,
                                      expsfh=options.expsfh,
                                      marginalizefeh=True,
                                      glon=locl))
        else:
            iso = isomodel.isomodel(imfmodel=options.imfmodel,
                                    Z=options.Z,
                                    expsfh=options.expsfh)
    #Set up polar grid
    res = 51
    xgrid = numpy.linspace(0., 2. * math.pi * (1. - 1. / res / 2.), 2 * res)
    ygrid = numpy.linspace(0.5, 2.8, res)
    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)
    plotthis = numpy.zeros((2 * res, res, len(data))) - numpy.finfo(
        numpy.dtype(numpy.float64)).max
    #_BINTEGRATENBINS= 11 #For quick testing
    ds = numpy.linspace(_BINTEGRATEDMIN, _BINTEGRATEDMAX, _BINTEGRATENBINS)
    logpiso = numpy.zeros((len(data), _BINTEGRATENBINS))
    dm = _dm(ds)
    for ii in range(len(data)):
        mh = h[ii] - dm
        if options.indivfeh:
            #Find closest Z
            thisZ = isodist.FEH2Z(data[ii]['FEH'])
            indx = numpy.argmin(numpy.fabs(thisZ - zs))
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          jk[ii], mh)
        elif options.varfeh:
            #Find correct iso
            indx = (locl == data[ii]['LOCATION'])
            logpiso[ii, :] = iso[0][indx](numpy.zeros(_BINTEGRATENBINS) +
                                          jk[ii], mh)
        else:
            logpiso[ii, :] = iso(numpy.zeros(_BINTEGRATENBINS) + jk[ii], mh)
    for jj in range(_BINTEGRATENBINS):
        d = ds[jj] / _REFR0
        R = numpy.sqrt(1. + d**2. - 2. * d * cosl)
        indx = (R == 0.)
        R[indx] += 0.0001
        theta = numpy.arcsin(d / R * sinl)
        indx = (1. / cosl < d) * (cosl > 0.)
        theta[indx] = numpy.pi - theta[indx]
        indx = (theta < 0.)
        theta[indx] += 2. * math.pi
        thisout = _logpd([0., 1.], d, None, None, None, None, None, options, R,
                         theta, 1., 0., logpiso[:, jj])
        #Find bin to which these contribute
        thetabin = numpy.floor((theta - xgrid[0]) / (xgrid[1] - xgrid[0]) +
                               0.5)
        Rbin = numpy.floor((R - plotygrid[0]) / (plotygrid[1] - plotygrid[0]))
        indx = (thetabin < 0)
        thetabin[indx] = 0
        Rbin[indx] = 0
        thisout[indx] = -numpy.finfo(numpy.dtype(numpy.float64)).max
        indx = (thetabin >= 2 * res)
        thetabin[indx] = 0.  #Has to be
        #Rbin[indx]= 0
        #thisout[indx]= -numpy.finfo(numpy.dtype(numpy.float64)).max
        indx = (Rbin < 0)
        thetabin[indx] = 0
        Rbin[indx] = 0
        thisout[indx] = -numpy.finfo(numpy.dtype(numpy.float64)).max
        indx = (Rbin >= res)
        thetabin[indx] = 0
        Rbin[indx] = 0
        thisout[indx] = -numpy.finfo(numpy.dtype(numpy.float64)).max
        thetabin = thetabin.astype('int')
        Rbin = Rbin.astype('int')
        for ii in range(len(data)):
            plotthis[thetabin, Rbin, ii] = thisout[ii]
    #Normalize
    for ii in range(2 * res):
        for jj in range(res):
            plotthis[ii, jj, 0] = logsumexp(plotthis[ii, jj, :])
    plotthis = plotthis[:, :, 0]
    plotthis -= numpy.amax(plotthis)
    plotthis = numpy.exp(plotthis)
    plotthis[(plotthis == 0.)] = numpy.nan
    #Get los
    locations = list(set(data['LOCATION']))
    nlocs = len(locations)
    l_plate = numpy.zeros(nlocs)
    for ii in range(nlocs):
        indx = (data['LOCATION'] == locations[ii])
        l_plate[ii] = numpy.mean(data['GLON'][indx])
    bovy_plot.bovy_print()
    ax = pyplot.subplot(111, projection='galpolar')  #galpolar is in bovy_plot
    vmin, vmax = 0., 1.
    out = ax.pcolor(plotxgrid,
                    plotygrid,
                    plotthis.T,
                    cmap='gist_yarg',
                    vmin=vmin,
                    vmax=vmax,
                    zorder=2)
    #Overlay los
    for ii in range(nlocs):
        lds = numpy.linspace(0., 2.95, 501)
        lt = numpy.zeros(len(lds))
        lr = numpy.zeros(len(lds))
        lr = numpy.sqrt(1. + lds**2. -
                        2. * lds * numpy.cos(l_plate[ii] * _DEGTORAD))
        lt = numpy.arcsin(lds / lr * numpy.sin(l_plate[ii] * _DEGTORAD))
        indx = (1. / numpy.cos(l_plate[ii] * _DEGTORAD) < lds) * (numpy.cos(
            l_plate[ii] * _DEGTORAD) > 0.)
        lt[indx] = numpy.pi - lt[indx]
        ax.plot(lt, lr, ls='--', color='w', zorder=3)
    from matplotlib.patches import Arrow, FancyArrowPatch
    arr = FancyArrowPatch(posA=(-math.pi / 2., 1.8),
                          posB=(-math.pi / 4., 1.8),
                          arrowstyle='->',
                          connectionstyle='arc3,rad=%4.2f' % (-math.pi / 16.),
                          shrinkA=2.0,
                          shrinkB=2.0,
                          mutation_scale=20.0,
                          mutation_aspect=None,
                          fc='k')
    ax.add_patch(arr)
    bovy_plot.bovy_text(-math.pi / 2.,
                        1.97,
                        r'$\mathrm{Galactic\ rotation}$',
                        rotation=-22.5)
    radii = numpy.array([0.5, 1., 1.5, 2., 2.5])
    labels = []
    for r in radii:
        ax.plot(numpy.linspace(
            0.,
            2. * math.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=-32.5)
    bovy_plot.bovy_text(5.785, 2.82, r'$\mathrm{kpc}$')
    azs = numpy.array([0., 45., 90., 135., 180., 225., 270., 315.]) * _DEGTORAD
    for az in azs:
        ax.plot(numpy.zeros(501) + az,
                numpy.linspace(0., 2.8, 501),
                '-',
                color='0.6',
                lw=0.5,
                zorder=1)
    #Sun
    bovy_plot.bovy_text(0.065, .9075, r'$\odot$')
    pyplot.ylim(0., 2.8)
    bovy_plot.bovy_end_print(options.plotfile)