def sample_streamdf_pal5_nobarpot(nobarpot, fot, N=500, trailing=True):

    if trailing:

        sdf_trailing = pal5_util.setup_pal5model(pot=nobarpot)

        R, vR, vT, z, vz, phi, dt = sdf_trailing.sample(n=N, returndt=True)
        fo = '/ufrc/tan/nilanjan1/galpy/sampled_SCFbar/testpeak_1010Msun_nobarpot_streamdf/trailing/' + fot
        fo = open(fo, 'w')

    else:

        sdf_leading = pal5_util.setup_pal5model(pot=nobarpot, leading=True)

        R, vR, vT, z, vz, phi, dt = sdf_leading.sample(n=N, returndt=True)

        fol = '/ufrc/tan/nilanjan1/galpy/sampled_SCFbar/testpeak_1010Msun_nobarpot_streamdf/trailing/' + fot
        fo_lead = fol.replace('trailing', 'leading')

        fo = open(fo_lead, 'w')

    fo.write("#R   phi   z   vR    vT    vz    ts" + "\n")
    for jj in range(N):

        fo.write(
            str(R[jj]) + "   " + str(phi[jj]) + "   " + str(z[jj]) + "   " +
            str(vR[jj]) + "   " + str(vT[jj]) + "   " + str(vz[jj]) + "   " +
            str(dt[jj]) + "\n")

    fo.close()

    return None
Exemplo n.º 2
0
def sample_streamdf_pal5_noprog(N,barpot,nobarpot,fo='blah_trailing.dat',trailing=True):
    
              
        if trailing :
            sdf_trailing= pal5_util.setup_pal5model(pot=nobarpot)
            R,vR,vT,z,vz,phi,dt= sdf_trailing.sample(n=N,returndt=True)
            fo=open(fo,'w')
          
        
        else :
            sdf_leading= pal5_util.setup_pal5model(pot=nobarpot,leading=True)
            R,vR,vT,z,vz,phi,dt= sdf_leading.sample(n=N,returndt=True)
            fo_lead=fo.replace('trailing','leading')
            fo=open(fo_lead,'w')
              
        finalR= numpy.empty(N)
        finalvR=numpy.empty(N)
        finalvT=numpy.empty(N)
        finalvz=numpy.empty(N)
        finalphi= numpy.empty(N)
        finalz= numpy.empty(N)
        tt=numpy.empty(N)

        for ii in range(N):

                o= Orbit([R[ii],vR[ii],vT[ii],z[ii],vz[ii],phi[ii]])
                o.turn_physical_off()
                ts= numpy.linspace(0.,-dt[ii],1001)

                o.integrate(ts,nobarpot)
                orb=Orbit([o.R(ts[-1]),o.vR(ts[-1]),o.vT(ts[-1]),o.z(ts[-1]),o.vz(ts[-1]),o.phi(ts[-1])])
                                
                ts_future= numpy.linspace(-dt[ii],0.,1001)
                #forward integrate in barred potential
                orb.integrate(ts_future,barpot)
                finalR[ii]= orb.R(ts_future[-1])
                finalphi[ii]= orb.phi(ts_future[-1])
                finalz[ii]= orb.z(ts_future[-1])
                finalvR[ii]=orb.vR(ts_future[-1])
                finalvT[ii]=orb.vT(ts_future[-1])
                finalvz[ii]=orb.vz(ts_future[-1])
                tt[ii]=dt[ii]
                
        fo.write("#R   phi   z   vR    vT    vz    ts" + "\n")
    
        for jj in range(N):
            fo.write(str(finalR[jj]) + "   " + str(finalphi[jj]) + "   " + str(finalz[jj]) + "   " + str(finalvR[jj]) + "   " + str(finalvT[jj]) + "   " + str(finalvz[jj]) + "   " + str(tt[jj]) + "\n")
        
        fo.close()
    
        return None
Exemplo n.º 3
0
def sample_streamdf_smooth(N,
                           nobarpot,
                           stream='Pal5',
                           fo='sample_trailing.dat',
                           write=False,
                           trailing=True):
    '''
        Sample N points for a given stream using the freq-angle framework
        i.e., sample in the nobarpot, then integrate them back to stripping time
        and then integrat them forward in barred potential. Effects of progenitor's motion
        is not considered
        '''

    if stream == 'Pal5':
        sdf_trailing = pal5_util.setup_pal5model(pot=nobarpot)
        sdf_leading = pal5_util.setup_pal5model(pot=nobarpot, leading=True)

    elif stream == 'GD1':
        sdf_trailing = gd1_util.setup_gd1model(pot=nobarpot, leading=False)
        sdf_leading = gd1_util.setup_gd1model(pot=nobarpot)

    fo = stream + fo
    if trailing:

        R, vR, vT, z, vz, phi, dt = sdf_trailing.sample(n=N, returndt=True)
        fo = open(fo, 'w')

    else:

        R, vR, vT, z, vz, phi, dt = sdf_leading.sample(n=N, returndt=True)
        fo_lead = fo.replace('trailing', 'leading')
        fo = open(fo_lead, 'w')

    if write:
        fo.write("#R   phi   z   vR    vT    vz    ts" + "\n")

        for jj in range(N):
            fo.write(
                str(R[jj]) + "   " + str(phi[jj]) + "   " + str(z[jj]) +
                "   " + str(vR[jj]) + "   " + str(vT[jj]) + "   " +
                str(vz[jj]) + "   " + str(dt[jj]) + "\n")

        fo.close()

    else:

        return (R, phi, z, vR, vT, vz, dt)
Exemplo n.º 4
0
def aparxv_stream_from_pkl(pot=MWPotential2014, sampling=256, nchunks=16):
    '''
    compute apar,x,v from one or multiple pickle files
    '''

    apar = []
    x_stream = []
    y_stream = []
    z_stream = []
    vx_stream = []
    vy_stream = []
    vz_stream = []
    timpact = []

    sdf_smooth = pal5_util.setup_pal5model(pot=pot)

    if nchunks > 1:

        for i in range(nchunks):

            with open(
                    'pkl_files/pal5pepper_{}sampling_pot8_peri6.41_{}.pkl'.
                    format(sampling, i), 'rb') as savefile:

                print(sampling, i)

                sdf_pepper = pickle.load(savefile, encoding='latin1')
                ap, x, y, z, vx, vy, vz = aparxv_stream(sdf_smooth, sdf_pepper)
                apar.extend(ap)
                x_stream.extend(x)
                y_stream.extend(y)
                z_stream.extend(z)
                vx_stream.extend(vx)
                vy_stream.extend(vy)
                vz_stream.extend(vz)
                timpact.extend(sdf_pepper._timpact)

    else:

        with open(
                'pkl_files/pal5pepper_{}sampling_MW2014.pkl'.format(sampling),
                'rb') as savefile:

            sdf_pepper = pickle.load(savefile, encoding='latin1')
            ap, x, y, z, vx, vy, vz = aparxv_stream(sdf_smooth, sdf_pepper)
            apar.extend(ap)
            x_stream.extend(x)
            y_stream.extend(y)
            z_stream.extend(z)
            vx_stream.extend(vx)
            vy_stream.extend(vy)
            vz_stream.extend(vz)
            timpact.extend(sdf_pepper._timpact)

    return (timpact, apar, x_stream, y_stream, z_stream, vx_stream, vy_stream,
            vz_stream)
def aparxv_stream_from_multiple_pkl(pot=MWPotential2014,
                                    sampling=4096,
                                    npart=64):
    '''
    compute apar,x,v from one or multiple pickle files
    pot_ind: can be either default MWPotential2014 or the chain_ind 
    pkl_fname : without fragment index and extension
    '''
    if pot != MWPotential2014:
        chain_ind = int(pot)
        prog, _pot, sigv, tvo = set_prog_potential(chain_ind)
        sdf_smooth = pal5_util.setup_pal5model_MWfit(ro=_REFR0,
                                                     vo=tvo,
                                                     sigv=sigv,
                                                     pot=_pot,
                                                     orb=prog)
        pkl_file = 'pkl_files/pal5pepper_Plummer_{}sampling_chainind{}'.format(
            sampling, chain_ind)
        pkl_file = pkl_file + '_{}.pkl'
    else:
        sdf_smooth = pal5_util.setup_pal5model(pot=pot)
        pkl_file = 'pkl_files/pal5pepper_{}sampling_MW2014'.format(sampling)
        pkl_file = pkl_file + '_{}.pkl'

    apar = []
    x_stream = []
    y_stream = []
    z_stream = []
    vx_stream = []
    vy_stream = []
    vz_stream = []
    timpact = []

    for ii in range(npart):
        pkl_fname = pkl_file.format(ii)
        with open(pkl_fname, 'rb') as savefile:

            print(pkl_fname)

            sdf_pepper = pickle.load(savefile, encoding='latin1')
            ap, x, y, z, vx, vy, vz = aparxv_stream(sdf_smooth, sdf_pepper)
            apar.extend(ap)
            x_stream.extend(x)
            y_stream.extend(y)
            z_stream.extend(z)
            vx_stream.extend(vx)
            vy_stream.extend(vy)
            vz_stream.extend(vz)
            timpact.extend(sdf_pepper._timpact)

    return (timpact, apar, x_stream, y_stream, z_stream, vx_stream, vy_stream,
            vz_stream)
Exemplo n.º 6
0
    def __init__(self, remodel=False, save=False, leading=False):
        if remodel == True:
            from streampepper_utils import parse_times
            self.sp = pal5_util.setup_pal5model(timpact=parse_times(
                '64sampling', 5),
                                                leading=leading)
            if save:
                self.pepperfilename = './data/pal5_64sample.pkl'
                save_pickles(self.pepperfilename, self.sp)

        if remodel == False:
            self.pepperfilename = 'data/pal5_64sampling_trailing.pkl'
            with open(self.pepperfilename, 'rb') as savefile:
                self.sp = pickle.load(savefile)
        self.sp._useInterp = True
Exemplo n.º 7
0
def sample_streamdf_noprog(nsamp,
                           barpot,
                           nobarpot,
                           stream='Pal5',
                           sigv=0.3,
                           prog=0.,
                           trail_dir='',
                           fo='sample_trailing.dat',
                           write=False,
                           trailing=True):
    '''
        Sample N points for a given stream using the freq-angle framework
        i.e., sample in the nobarpot, then integrate them back to stripping time
        and then integrat them forward in barred potential. Effects of progenitor's motion
        is not considered
        '''
    print("WARNING: Effects of progenitor's motion neglected")

    if stream == 'Pal5':
        sdf_trailing = pal5_util.setup_pal5model(pot=nobarpot)
        sdf_leading = pal5_util.setup_pal5model(pot=nobarpot, leading=True)

    elif stream == 'GD1':
        if prog == 0:
            sdf_trailing = gd1_util.setup_gd1model(pot=nobarpot, leading=False)
            sdf_leading = gd1_util.setup_gd1model(pot=nobarpot)

        elif prog == -40.:
            new_orb_lb = [
                188.04928416766532, 51.848594007807456, 7.559027173643999,
                12.260258757214746, -5.140630283489461, 7.162732847549563
            ]
            isob = 0.45
            td = 3.2
            sdf_trailing = gd1_util.setup_gd1model(pot=nobarpot,
                                                   leading=False,
                                                   age=td,
                                                   new_orb_lb=new_orb_lb,
                                                   isob=isob,
                                                   sigv=sigv)
            sdf_leading = gd1_util.setup_gd1model(pot=nobarpot,
                                                  age=td,
                                                  new_orb_lb=new_orb_lb,
                                                  isob=isob,
                                                  sigv=sigv)

    fo = stream + fo
    if trailing:

        R, vR, vT, z, vz, phi, dt = sdf_trailing.sample(n=nsamp, returndt=True)
        fo = open(trail_dir + fo, 'w')

    else:

        R, vR, vT, z, vz, phi, dt = sdf_leading.sample(n=nsamp, returndt=True)
        lead_dir = trail_dir.replace('trailing', 'leading')
        fo_lead = fo.replace('trailing', 'leading')
        fo = open(lead_dir + fo_lead, 'w')

    finalR = numpy.empty(nsamp)
    finalvR = numpy.empty(nsamp)
    finalvT = numpy.empty(nsamp)
    finalvz = numpy.empty(nsamp)
    finalphi = numpy.empty(nsamp)
    finalz = numpy.empty(nsamp)
    tt = numpy.empty(nsamp)

    for ii in range(nsamp):

        o = Orbit([R[ii], vR[ii], vT[ii], z[ii], vz[ii], phi[ii]])
        o.turn_physical_off()
        ts = numpy.linspace(0., -dt[ii], 1001)

        o.integrate(ts, nobarpot)
        orb = Orbit([
            o.R(ts[-1]),
            o.vR(ts[-1]),
            o.vT(ts[-1]),
            o.z(ts[-1]),
            o.vz(ts[-1]),
            o.phi(ts[-1])
        ])

        ts_future = numpy.linspace(-dt[ii], 0., 1001)
        #forward integrate in barred potential
        orb.integrate(ts_future, barpot)
        finalR[ii] = orb.R(ts_future[-1])
        finalphi[ii] = orb.phi(ts_future[-1])
        finalz[ii] = orb.z(ts_future[-1])
        finalvR[ii] = orb.vR(ts_future[-1])
        finalvT[ii] = orb.vT(ts_future[-1])
        finalvz[ii] = orb.vz(ts_future[-1])
        tt[ii] = dt[ii]

    if write:
        fo.write("#R   phi   z   vR    vT    vz    ts" + "\n")

        for jj in range(nsamp):
            fo.write(
                str(finalR[jj]) + "   " + str(finalphi[jj]) + "   " +
                str(finalz[jj]) + "   " + str(finalvR[jj]) + "   " +
                str(finalvT[jj]) + "   " + str(finalvz[jj]) + "   " +
                str(tt[jj]) + "\n")

        fo.close()

    else:

        return (finalR, finalphi, finalz, finalvR, finalvT, finalvz, tt)
Exemplo n.º 8
0
def sample_streamdf_noprog(N,
                           barpot,
                           nobarpot,
                           stream='Pal5',
                           fo='sample_trailing.dat',
                           write=False,
                           trailing=True):
    '''
        Sample N points for a given stream using the freq-angle framework
        i.e., sample in the nobarpot, then integrate them back to stripping time
        and then integrat them forward in barred potential. Effects of progenitor's motion
        is not considered
        '''
    print("WARNING: Effects of progenitor's motion neglected")

    if stream == 'Pal5':
        sdf_trailing = pal5_util.setup_pal5model(pot=nobarpot)
        sdf_leading = pal5_util.setup_pal5model(pot=nobarpot, leading=True)

    elif stream == 'GD1':
        sdf_trailing = gd1_util.setup_gd1model(pot=nobarpot, leading=False)
        sdf_leading = gd1_util.setup_gd1model(pot=nobarpot)

    fo = stream + fo
    if trailing:

        R, vR, vT, z, vz, phi, dt = sdf_trailing.sample(n=N, returndt=True)
        fo = open(fo, 'w')

    else:

        R, vR, vT, z, vz, phi, dt = sdf_leading.sample(n=N, returndt=True)
        fo_lead = fo.replace('trailing', 'leading')
        fo = open(fo_lead, 'w')

    finalR = numpy.empty(N)
    finalvR = numpy.empty(N)
    finalvT = numpy.empty(N)
    finalvz = numpy.empty(N)
    finalphi = numpy.empty(N)
    finalz = numpy.empty(N)
    tt = numpy.empty(N)

    for ii in range(N):

        o = Orbit([R[ii], vR[ii], vT[ii], z[ii], vz[ii], phi[ii]])
        o.turn_physical_off()
        ts = numpy.linspace(0., -dt[ii], 1001)

        o.integrate(ts, nobarpot)
        orb = Orbit([
            o.R(ts[-1]),
            o.vR(ts[-1]),
            o.vT(ts[-1]),
            o.z(ts[-1]),
            o.vz(ts[-1]),
            o.phi(ts[-1])
        ])

        ts_future = numpy.linspace(-dt[ii], 0., 1001)
        #forward integrate in barred potential
        orb.integrate(ts_future, barpot)
        finalR[ii] = orb.R(ts_future[-1])
        finalphi[ii] = orb.phi(ts_future[-1])
        finalz[ii] = orb.z(ts_future[-1])
        finalvR[ii] = orb.vR(ts_future[-1])
        finalvT[ii] = orb.vT(ts_future[-1])
        finalvz[ii] = orb.vz(ts_future[-1])
        tt[ii] = dt[ii]

    if write:
        fo.write("#R   phi   z   vR    vT    vz    ts" + "\n")

        for jj in range(N):
            fo.write(
                str(finalR[jj]) + "   " + str(finalphi[jj]) + "   " +
                str(finalz[jj]) + "   " + str(finalvR[jj]) + "   " +
                str(finalvT[jj]) + "   " + str(finalvz[jj]) + "   " +
                str(tt[jj]) + "\n")

        fo.close()

    else:

        return (finalR, finalphi, finalz, finalvR, finalvT, finalvz, tt)
    "A sophisticated calculation of LSST magntude limit"
    xgrid = np.linspace(15, 28, 1000)
    err = getMagErrVec(xgrid, filt, survey)
    xid = np.argmax(err * (err < maxerr))
    return xgrid[xid]


#apar= numpy.arange(options.amin,options.amax,options.dapar)

#sdf_smooth= pal5_util.setup_pal5model(age=9.)
#sdf_pepper= pal5_util.setup_pal5model(singleImpact=True)
#
#

if 0:
    sdf_pepper_t = pal5_util.setup_pal5model(timpact=[1.])
    sdf_pepper_l = pal5_util.setup_pal5model(timpact=[1.], leading=True)
    massrange = [7., 9.]
    massexp = -2.
    sp = sdf_pepper_l
    sample_GM= lambda: (10.**((massexp+1.5)*massrange[0])\
                            +(10.**((massexp+1.5)*massrange[1])\
                                  -10.**((massexp+1.5)*massrange[0]))\
                            *numpy.random.uniform())**(1./(massexp+1.5))\
                            /bovy_conversion.mass_in_msol(V0,R0)
    rate_range = numpy.arange(massrange[0] + 0.5, massrange[1] + 0.5, 1)
    rate = numpy.sum([
        dNencdm(sp, 10.**r, Xrs=3., plummer=False, rsfac=1., sigma=120.)
        for r in rate_range
    ])
Exemplo n.º 10
0
    else:
        csvabc = open(abcfile, "w")
        abcwriter = csv.writer(csvabc, delimiter=",")
    for sim in pal5_abc(sdf_pepper, sdf_smooth, options):
        abcwriter.writerow(list(sim)[:-1])
        csvabc.flush()
    return None


if __name__ == "__main__":
    parser = get_options()
    options, args = parser.parse_args()
    # Setup the streampepperdf object
    if not os.path.exists(options.streamsavefilename):
        timpacts = simulate_streampepper.parse_times(options.timpacts, options.age)
        sdf_smooth = pal5_util.setup_pal5model(age=options.age)
        sdf_pepper = pal5_util.setup_pal5model(
            timpact=timpacts, hernquist=not options.plummer, age=options.age, length_factor=options.length_factor
        )
        save_pickles(options.streamsavefilename, sdf_smooth, sdf_pepper)
    else:
        with open(options.streamsavefilename, "rb") as savefile:
            sdf_smooth = pickle.load(savefile)
            sdf_pepper = pickle.load(savefile)
    if options.recomputeall:
        options.recompute = True
        # recompute basic
        recompute(sdf_pepper, sdf_smooth, options)
        # Find and recompute batches
        allfilenames = glob.glob(options.outdens.replace(".dat", ".*.dat"))
        batches = numpy.array([int(fn.split(".dat")[0].split(".")[-1]) for fn in allfilenames], dtype="int")
Exemplo n.º 11
0
def run_simulations(sdf_pepper, sdf_smooth, options):
    # Setup apar grid
    apar = numpy.arange(options.amin, options.amax, options.dapar)
    # Check whether the output files already exist and if so, get the amin, amax, da from them
    if os.path.exists(options.outdens):
        # First read the file to check apar
        apar_file = numpy.genfromtxt(options.outdens,
                                     delimiter=',',
                                     max_rows=1)
        print(numpy.amax(numpy.fabs(apar_file - apar)))
        assert numpy.amax(
            numpy.fabs(apar_file - apar)
        ) < 10.**-5., 'apar according to options does not correspond to apar already in outdens'
        apar_file = numpy.genfromtxt(options.outomega,
                                     delimiter=',',
                                     max_rows=1)
        print(numpy.amax(numpy.fabs(apar_file - apar)))
        assert numpy.amax(
            numpy.fabs(apar_file - apar)
        ) < 10.**-5., 'apar according to options does not correspond to apar already in outomega'
        csvdens = open(options.outdens, 'a')
        csvomega = open(options.outomega, 'a')
        denswriter = csv.writer(csvdens, delimiter=',')
        omegawriter = csv.writer(csvomega, delimiter=',')
    else:
        csvdens = open(options.outdens, 'w')
        csvomega = open(options.outomega, 'w')
        denswriter = csv.writer(csvdens, delimiter=',')
        omegawriter = csv.writer(csvomega, delimiter=',')
        # First write apar and the smooth calculations
        denswriter.writerow([a for a in apar])
        omegawriter.writerow([a for a in apar])
        if sdf_smooth is None and options.stream.lower() == 'gd1like':
            sdf_smooth = gd1_util.setup_gd1model(age=options.age)
        elif sdf_smooth is None and options.stream.lower() == 'pal5like':
            sdf_smooth = pal5_util.setup_pal5model(age=options.age)
        dens_unp = [sdf_smooth._density_par(a) for a in apar]
        denswriter.writerow(dens_unp)
        omega_unp = [sdf_smooth.meanOmega(a, oned=True) for a in apar]
        omegawriter.writerow(omega_unp)
        csvdens.flush()
        csvomega.flush()
    # Parse mass
    massrange = parse_mass(options.mass)
    if len(massrange) == 1:
        sample_GM= lambda: 10.**(massrange[0]-10.)\
            /bovy_conversion.mass_in_1010msol(V0,R0)
        rate = options.timescdm * dNencdm(sdf_pepper,
                                          10.**massrange[0],
                                          Xrs=options.Xrs,
                                          plummer=options.plummer,
                                          rsfac=options.rsfac,
                                          sigma=options.sigma)
    elif len(massrange) == 2:
        # Sample from power-law
        if not options.cutoff is None:
            sample_GM = lambda: powerlaw_wcutoff(massrange, options.cutoff)
        elif numpy.fabs(options.massexp + 1.5) < 10.**-6.:
            sample_GM= lambda: 10.**(massrange[0]\
                                         +(massrange[1]-massrange[0])\
                                         *numpy.random.uniform())\
                                         /bovy_conversion.mass_in_msol(V0,R0)
        else:
            sample_GM= lambda: (10.**((options.massexp+1.5)*massrange[0])\
                                    +(10.**((options.massexp+1.5)*massrange[1])\
                                          -10.**((options.massexp+1.5)*massrange[0]))\
                                    *numpy.random.uniform())**(1./(options.massexp+1.5))\
                                    /bovy_conversion.mass_in_msol(V0,R0)
        rate_range = numpy.arange(massrange[0] + 0.5, massrange[1] + 0.5, 1)
        rate= options.timescdm\
            *numpy.sum([dNencdm(sdf_pepper,10.**r,Xrs=options.Xrs,
                                plummer=options.plummer,rsfac=options.rsfac,
                                sigma=options.sigma)
                        for r in rate_range])
        if not options.cutoff is None:
            rate*= integrate.quad(lambda x: x**-1.5\
                                      *numpy.exp(-10.**options.cutoff/x),
                                  10.**massrange[0],10.**massrange[1])[0]\
                                  /integrate.quad(lambda x: x**-1.5,
                                                  10.**massrange[0],
                                                  10.**massrange[1])[0]
    print("Using an overall rate of %f" % rate)
    sample_rs = lambda x: rs(x * bovy_conversion.mass_in_1010msol(V0, R0) * 10.
                             **10.,
                             plummer=options.plummer,
                             rsfac=options.rsfac)
    # Simulate
    start = time.time()
    ns = 0
    while True:
        if options.nsamples is None and time.time() >= (start +
                                                        options.dt * 60.):
            break
        elif not options.nsamples is None and ns > options.nsamples:
            break
        ns += 1
        sdf_pepper.simulate(rate=rate,
                            sample_GM=sample_GM,
                            sample_rs=sample_rs,
                            Xrs=options.Xrs,
                            sigma=options.sigma / V0)
        # Compute density and meanOmega and save
        try:
            densOmega = numpy.array(
                [sdf_pepper._densityAndOmega_par_approx(a) for a in apar]).T
        except IndexError:  # no hit
            dens_unp = [sdf_smooth._density_par(a) for a in apar]
            omega_unp = [sdf_smooth.meanOmega(a, oned=True) for a in apar]
            denswriter.writerow(dens_unp)
            omegawriter.writerow(omega_unp)
        else:
            denswriter.writerow(list(densOmega[0]))
            omegawriter.writerow(list(densOmega[1]))
        csvdens.flush()
        csvomega.flush()
    csvdens.close()
    csvomega.close()
    return None
Exemplo n.º 12
0
                timpact=timpacts,
                hernquist=not options.plummer,
                age=options.age,
                length_factor=options.length_factor)

    elif options.stream.lower() == 'pal5like':
        timpacts = parse_times(options.timpacts, options.age)
        if options.timpacts == '64sampling':
            # We've cached this one
            with open('pal5_64sampling.pkl', 'rb') as savefile:
                sdf_smooth = pickle.load(savefile)
                sdf_pepper = pickle.load(savefile)
        else:
            sdf_pepper = pal5_util.setup_pal5model(
                timpact=timpacts,
                hernquist=not options.plummer,
                age=options.age,
                length_factor=options.length_factor)
    # Need smooth?
    if options.amax is None or options.amin is None:
        if options.stream.lower() == 'gd1like':
            sdf_smooth = gd1_util.setup_gd1model(age=options.age)
        else:
            sdf_smooth = pal5_util.setup_pal5model(age=options.age)
        sdf_smooth.turn_physical_off()
    else:
        sdf_smooth = None
    if options.amax is None:
        options.amax = sdf_smooth.length() + options.dapar
    if options.amin is None:
        options.amin= 2.*sdf_smooth.meanOmega(0.1,oned=True)\
    apar,
    x_stream,
    y_stream,
    z_stream,
    pot=pot,
    nchunks=64,
    sampling_low=128,
    imp_fac=5.,
    Mmin=10**5.,
    rand_rotate=True)

#load the lower timpact pkl file
with open(
        'pkl_files/pal5pepper_Plummer_128sampling_pot{}_peri{}.pkl'.format(
            pind, peri), 'rb') as savefile:
    sdf_pepper = pickle.load(savefile, encoding='latin1')

sdf_smooth = pal5_util.setup_pal5model(pot=pot)

sdf_pepper.set_impacts(impactb=impactb,
                       subhalovel=v_mc,
                       impact_angle=impact_angle,
                       timpact=tmin,
                       rs=rs_mc,
                       GM=M_mc)

pepperfilename = 'Pal5_4096_on_128impact_Plummer_pot{}_peri{}_Mmin105_MC_rand_rotate_{}.pkl'.format(
    pind, peri)

save_pickles(pepperfilename, sdf_pepper)
Exemplo n.º 14
0
def sample_perturbed_pal5_new(N,
                              barpot,
                              nobarpot,
                              fo='blah_trailing.dat',
                              trailing=True,
                              tpal5age=5.):

    tage = np.linspace(0., -tpal5age, 1001) / bovy_conversion.time_in_Gyr(
        220., 8.)

    if trailing:
        sdf_trailing = pal5_util.setup_pal5model(pot=nobarpot)
        R, vR, vT, z, vz, phi, dt = sdf_trailing.sample(n=N, returndt=True)
        fo = open(fo, 'w')

    else:
        sdf_leading = pal5_util.setup_pal5model(pot=nobarpot, leading=True)
        R, vR, vT, z, vz, phi, dt = sdf_leading.sample(n=N, returndt=True)
        fo_lead = fo.replace('trailing', 'leading')
        fo = open(fo_lead, 'w')

    #integrate Pal 5 progenitor in barpot all the way back to 5 Gyrs,
    #from this orbits will be extracted by interpolation in the for loop
    pal5_bar = Orbit([229.018, -0.124, 23.2, -2.296, -2.257, -58.7],
                     radec=True,
                     solarmotion=[-11.1, 24., 7.25])
    pal5_bar.integrate(tage, barpot)

    #integrate Pal 5 progenitor in nobarpot all the way back to 5 Gyrs,
    #from this orbits will be extracted by interpolation in the for loop
    pal5_nobar = Orbit([229.018, -0.124, 23.2, -2.296, -2.257, -58.7],
                       radec=True,
                       solarmotion=[-11.1, 24., 7.25])
    pal5_nobar.integrate(tage, nobarpot)

    pal5_bar.turn_physical_off()
    pal5_nobar.turn_physical_off()

    finalR = numpy.empty(N)
    finalvR = numpy.empty(N)
    finalvT = numpy.empty(N)
    finalvz = numpy.empty(N)
    finalphi = numpy.empty(N)
    finalz = numpy.empty(N)
    tt = numpy.empty(N)

    for ii in range(N):

        o = Orbit([R[ii], vR[ii], vT[ii], z[ii], vz[ii], phi[ii]])
        o.turn_physical_off()
        ts = numpy.linspace(0., -dt[ii], 1001)

        o.integrate(ts, nobarpot)

        #extract the orbit at the stripping time from the above integrated orbit
        unp_orb = numpy.array([
            o.x(ts[-1]),
            o.y(ts[-1]),
            o.z(ts[-1]),
            o.vx(ts[-1]),
            o.vy(ts[-1]),
            o.vz(ts[-1])
        ])
        pal5_orb_bar = numpy.array([
            pal5_bar.x(ts[-1]),
            pal5_bar.y(ts[-1]),
            pal5_bar.z(ts[-1]),
            pal5_bar.vx(ts[-1]),
            pal5_bar.vy(ts[-1]),
            pal5_bar.vz(ts[-1])
        ])
        pal5_orb_nobar = numpy.array([
            pal5_nobar.x(ts[-1]),
            pal5_nobar.y(ts[-1]),
            pal5_nobar.z(ts[-1]),
            pal5_nobar.vx(ts[-1]),
            pal5_nobar.vy(ts[-1]),
            pal5_nobar.vz(ts[-1])
        ])

        #print (unp_orb)
        #print (pal5_orb_bar)
        #print (pal5_orb_nobar)

        #subtract Pal 5 orb in nobarpot and add Pal 5 orbit in barpot
        pert_orb = (unp_orb - pal5_orb_nobar) + pal5_orb_bar

        #print (unp_orb,dt[ii]*bovy_conversion.time_in_Gyr(220.,8.))
        #print (pert_orb,dt[ii]*bovy_conversion.time_in_Gyr(220.,8.))
        #(R,phi,Z)
        #vR,vT,vz
        #vxvv=[R,vR,vT,z,vz,phi]
        pert_orb_RpZ = bovy_coords.rect_to_cyl(pert_orb[0], pert_orb[1],
                                               pert_orb[2])
        pert_orb_vRpZ = bovy_coords.rect_to_cyl_vec(pert_orb[3], pert_orb[4],
                                                    pert_orb[5], pert_orb[0],
                                                    pert_orb[1], pert_orb[2])
        pert_orb = Orbit([
            pert_orb_RpZ[0], pert_orb_vRpZ[0], pert_orb_vRpZ[1],
            pert_orb_RpZ[2], pert_orb_vRpZ[2], pert_orb_RpZ[1]
        ])

        ts_future = numpy.linspace(-dt[ii], 0., 1001)
        #forward integrate in barred potential
        pert_orb.integrate(ts_future, barpot)
        finalR[ii] = pert_orb.R(ts_future[-1])
        finalphi[ii] = pert_orb.phi(ts_future[-1])
        finalz[ii] = pert_orb.z(ts_future[-1])
        finalvR[ii] = pert_orb.vR(ts_future[-1])
        finalvT[ii] = pert_orb.vT(ts_future[-1])
        finalvz[ii] = pert_orb.vz(ts_future[-1])
        tt[ii] = dt[ii]

    fo.write("#R   phi   z   vR    vT    vz    ts" + "\n")

    for jj in range(N):
        fo.write(
            str(finalR[jj]) + "   " + str(finalphi[jj]) + "   " +
            str(finalz[jj]) + "   " + str(finalvR[jj]) + "   " +
            str(finalvT[jj]) + "   " + str(finalvz[jj]) + "   " + str(tt[jj]) +
            "\n")

    fo.close()

    return None
import pal5_util
from pal5_util import R0, V0
#import run_pal5_abc
#import custom_stripping_df
#import bispectrum
#import seaborn as sns
#from matplotlib import cm, pyplot
#from matplotlib.ticker import FuncFormatter, NullFormatter
scaling= 'spectrum'
#save_figures= False
#minxi=0


# Load the smooth and peppered stream, only need 1 time-sampling, 
# bc only use it to convert to obs. space at present
sdf_smooth= pal5_util.setup_pal5model()
pepperfilename= 'pal5pepper1sampling.pkl'
if os.path.exists(pepperfilename):
    with open(pepperfilename,'rb') as savefile:
        sdf_pepper= pickle.load(savefile)
else:
    import simulate_streampepper
    timpacts= simulate_streampepper.parse_times('1sampling',9.)
    sdf_pepper= pal5_util.setup_pal5model(timpact=timpacts,
                                        hernquist=True)
    save_pickles(pepperfilename,sdf_pepper)

# Convert track to xi, eta
trackRADec=\
  bovy_coords.lb_to_radec(sdf_smooth._interpolatedObsTrackLB[:,0],
                          sdf_smooth._interpolatedObsTrackLB[:,1],
Exemplo n.º 16
0
def sample_perturbed_Pal5(N,
                          barpot,
                          barpot_invert,
                          nobarpot,
                          prog_barpot,
                          prog_barpot_invert,
                          prog_nobarpot,
                          fo='blah_trailing.dat',
                          trailing=True,
                          tpal5age=5.,
                          t_on=2.,
                          tgrow=2,
                          pat_speed=40.):
    #Sample N points from the smooth model today

    tpal5age = tpal5age / bovy_conversion.time_in_Gyr(220., 8.)

    if trailing:
        sdf_trailing = pal5_util.setup_pal5model(pot=nobarpot)

        R, vR, vT, z, vz, phi, dt = sdf_trailing.sample(n=N, returndt=True)
        fo = open(fo, 'w')

    else:
        sdf_leading = pal5_util.setup_pal5model(pot=nobarpot, leading=True)
        R, vR, vT, z, vz, phi, dt = sdf_leading.sample(n=N, returndt=True)
        fo_lead = fo.replace('trailing', 'leading')
        fo = open(fo_lead, 'w')

    tage = numpy.linspace(0., tpal5age, 1001)

    #integrate Pal 5 progenitor in barpot all the way back to 5 Gyrs,
    #from this orbits will be extracted by interpolation in the for loop
    pal5_bar = Orbit([229.018, -0.124, 23.2, -2.296, -2.257, -58.7],
                     radec=True,
                     solarmotion=[-11.1, 24., 7.25]).flip()
    pal5_bar.integrate(tage, prog_barpot_invert)

    #integrate Pal 5 progenitor in nobarpot all the way back to 5 Gyrs,
    #from this orbits will be extracted by interpolation in the for loop
    pal5_nobar = Orbit([229.018, -0.124, 23.2, -2.296, -2.257, -58.7],
                       radec=True,
                       solarmotion=[-11.1, 24., 7.25]).flip()
    pal5_nobar.integrate(tage, prog_nobarpot)

    pal5_bar.turn_physical_off()
    pal5_nobar.turn_physical_off()

    finalR = numpy.empty(N)
    finalvR = numpy.empty(N)
    finalvT = numpy.empty(N)
    finalvz = numpy.empty(N)
    finalphi = numpy.empty(N)
    finalz = numpy.empty(N)
    tt = numpy.empty(N)

    tform = tform_from_t_on(t_on=t_on, pat_speed=pat_speed,
                            tgrow=tgrow)  #in galpy
    t_on = t_on / bovy_conversion.time_in_Gyr(220., 8.)

    for ii in range(N):

        o = Orbit([
            R[ii], vR[ii], vT[ii], z[ii], vz[ii], phi[ii]
        ]).flip()  # flip flips the velocities for backwards integration
        o.turn_physical_off()
        ts = numpy.linspace(0., dt[ii], 1001)

        #for integrating in barpot, time starts 5 Gyrs in the past and goes forward
        ts_future = numpy.linspace(tpal5age - dt[ii], tpal5age, 1001)

        o.integrate(ts, nobarpot)
        #unp_orb=o(ts[-1]).flip()._orb.vxvv

        #extract the orbit at the stripping time from the above integrated orbit
        #pal5_orb_bar = pal5_bar(ts[-1]).flip()._orb.vxvv
        #pal5_orb_nobar = pal5_nobar(ts[-1]).flip()._orb.vxvv

        unp_orb = numpy.array([
            o.x(ts[-1]),
            o.y(ts[-1]),
            o.z(ts[-1]), -o.vx(ts[-1]), -o.vy(ts[-1]), -o.vz(ts[-1])
        ])
        pal5_orb_bar = numpy.array([
            pal5_bar.x(ts[-1]),
            pal5_bar.y(ts[-1]),
            pal5_bar.z(ts[-1]), -pal5_bar.vx(ts[-1]), -pal5_bar.vy(ts[-1]),
            -pal5_bar.vz(ts[-1])
        ])
        pal5_orb_nobar = numpy.array([
            pal5_nobar.x(ts[-1]),
            pal5_nobar.y(ts[-1]),
            pal5_nobar.z(ts[-1]), -pal5_nobar.vx(ts[-1]),
            -pal5_nobar.vy(ts[-1]), -pal5_nobar.vz(ts[-1])
        ])

        #print (unp_orb)
        #print (pal5_orb_bar)
        #print (pal5_orb_nobar)

        #subtract Pal 5 orb in nobarpot and add Pal 5 orbit in barpot
        #pert_orb=(np.array(unp_orb) - np.array(pal5_orb_nobar)) + np.array(pal5_orb_bar)
        #pert_orb=Orbit(list(pert_orb))

        pert_orb = unp_orb - pal5_orb_nobar + pal5_orb_bar

        print(unp_orb, dt[ii] * bovy_conversion.time_in_Gyr(220., 8.))
        print(pert_orb, dt[ii] * bovy_conversion.time_in_Gyr(220., 8.))
        #(R,phi,Z)
        #vR,vT,vz
        #vxvv=[R,vR,vT,z,vz,phi]
        pert_orb_RpZ = bovy_coords.rect_to_cyl(pert_orb[0], pert_orb[1],
                                               pert_orb[2])
        pert_orb_vRpZ = bovy_coords.rect_to_cyl_vec(pert_orb[3], pert_orb[4],
                                                    pert_orb[5], pert_orb[0],
                                                    pert_orb[1], pert_orb[2])
        pert_orb = Orbit([
            pert_orb_RpZ[0], pert_orb_vRpZ[0], pert_orb_vRpZ[1],
            pert_orb_RpZ[2], pert_orb_vRpZ[2], pert_orb_RpZ[1]
        ])

        #forward integrate in barred potential
        pert_orb.integrate(ts_future, barpot)
        finalR[ii] = pert_orb.R(ts_future[-1])
        finalphi[ii] = pert_orb.phi(ts_future[-1])
        finalz[ii] = pert_orb.z(ts_future[-1])
        finalvR[ii] = pert_orb.vR(ts_future[-1])
        finalvT[ii] = pert_orb.vT(ts_future[-1])
        finalvz[ii] = pert_orb.vz(ts_future[-1])
        tt[ii] = dt[ii]

    fo.write("#R   phi   z   vR    vT    vz    ts" + "\n")

    for jj in range(N):
        fo.write(
            str(finalR[jj]) + "   " + str(finalphi[jj]) + "   " +
            str(finalz[jj]) + "   " + str(finalvR[jj]) + "   " +
            str(finalvT[jj]) + "   " + str(finalvz[jj]) + "   " + str(tt[jj]) +
            "\n")

    fo.close()

    return None
Exemplo n.º 17
0
 def add_smooth(self, nsample=10000):
     self.smooth = pal5_util.setup_pal5model(n=nsample,
                                             timpact=None,
                                             leading=False)
Exemplo n.º 18
0
def sample_streamdf_smooth(N,
                           nobarpot,
                           stream='Pal5',
                           prog=0.,
                           sigv=0.3,
                           trail_dir='',
                           fo='sample_trailing.dat',
                           write=False,
                           trailing=True):
    '''
        Sample N points for a given stream using the freq-angle framework
        i.e., sample in the nobarpot, then integrate them back to stripping time
        and then integrat them forward in barred potential. Effects of progenitor's motion
        is not considered
        '''

    if stream == 'Pal5':
        sdf_trailing = pal5_util.setup_pal5model(pot=nobarpot)
        sdf_leading = pal5_util.setup_pal5model(pot=nobarpot, leading=True)

    elif stream == 'GD1':
        if prog == 0:
            sdf_trailing = gd1_util.setup_gd1model(pot=nobarpot, leading=False)
            sdf_leading = gd1_util.setup_gd1model(pot=nobarpot)

        elif prog == -40.:
            new_orb_lb = [
                188.04928416766532, 51.848594007807456, 7.559027173643999,
                12.260258757214746, -5.140630283489461, 7.162732847549563
            ]
            isob = 0.45
            td = 3.2
            sdf_trailing = gd1_util.setup_gd1model(pot=nobarpot,
                                                   leading=False,
                                                   age=td,
                                                   new_orb_lb=new_orb_lb,
                                                   isob=isob,
                                                   sigv=sigv)
            sdf_leading = gd1_util.setup_gd1model(pot=nobarpot,
                                                  age=td,
                                                  new_orb_lb=new_orb_lb,
                                                  isob=isob,
                                                  sigv=sigv)

    fo = stream + fo
    if trailing:

        R, vR, vT, z, vz, phi, dt = sdf_trailing.sample(n=N, returndt=True)
        fo = open(trail_dir + fo, 'w')

    else:

        R, vR, vT, z, vz, phi, dt = sdf_leading.sample(n=N, returndt=True)
        lead_dir = trail_dir.replace('trailing', 'leading')
        fo_lead = fo.replace('trailing', 'leading')
        fo = open(lead_dir + fo_lead, 'w')

    if write:
        fo.write("#R   phi   z   vR    vT    vz    ts" + "\n")

        for jj in range(N):
            fo.write(
                str(R[jj]) + "   " + str(phi[jj]) + "   " + str(z[jj]) +
                "   " + str(vR[jj]) + "   " + str(vT[jj]) + "   " +
                str(vz[jj]) + "   " + str(dt[jj]) + "\n")

        fo.close()

    else:

        return (R, phi, z, vR, vT, vz, dt)
def run_simulations(sdf_pepper,sdf_smooth,options):
    # Setup apar grid
    apar= numpy.arange(options.amin,options.amax,options.dapar)
    # Check whether the output files already exist and if so, get the amin, amax, da from them
    if os.path.exists(options.outdens):
        # First read the file to check apar
        apar_file= numpy.genfromtxt(options.outdens,delimiter=',',max_rows=1)
        print numpy.amax(numpy.fabs(apar_file-apar))
        assert numpy.amax(numpy.fabs(apar_file-apar)) < 10.**-5., 'apar according to options does not correspond to apar already in outdens'
        apar_file= numpy.genfromtxt(options.outomega,delimiter=',',max_rows=1)
        print numpy.amax(numpy.fabs(apar_file-apar))
        assert numpy.amax(numpy.fabs(apar_file-apar)) < 10.**-5., 'apar according to options does not correspond to apar already in outomega'
        csvdens= open(options.outdens,'a')
        csvomega= open(options.outomega,'a')       
        denswriter= csv.writer(csvdens,delimiter=',')
        omegawriter= csv.writer(csvomega,delimiter=',')
    else:
        csvdens= open(options.outdens,'w')
        csvomega= open(options.outomega,'w')
        denswriter= csv.writer(csvdens,delimiter=',')
        omegawriter= csv.writer(csvomega,delimiter=',')
        # First write apar and the smooth calculations
        denswriter.writerow([a for a in apar])
        omegawriter.writerow([a for a in apar])
        if sdf_smooth is None and options.stream.lower() == 'gd1like':
            sdf_smooth= gd1_util.setup_gd1model(age=options.age)
        elif sdf_smooth is None and options.stream.lower() == 'pal5like':
            sdf_smooth= pal5_util.setup_pal5model(age=options.age)
        dens_unp= [sdf_smooth._density_par(a) for a in apar]
        denswriter.writerow(dens_unp)
        omega_unp= [sdf_smooth.meanOmega(a,oned=True) for a in apar]
        omegawriter.writerow(omega_unp)
        csvdens.flush()
        csvomega.flush()
    # Parse mass
    massrange= parse_mass(options.mass)
    if len(massrange) == 1:
        sample_GM= lambda: 10.**(massrange[0]-10.)\
            /bovy_conversion.mass_in_1010msol(V0,R0)
        rate= options.timescdm*dNencdm(sdf_pepper,
                                       10.**massrange[0],Xrs=options.Xrs,
                                       plummer=options.plummer,
                                       rsfac=options.rsfac,
                                       sigma=options.sigma)
    elif len(massrange) == 2:
        # Sample from power-law
        if not options.cutoff is None:
            sample_GM= lambda: powerlaw_wcutoff(massrange,options.cutoff)
        elif numpy.fabs(options.massexp+1.5) < 10.**-6.:
            sample_GM= lambda: 10.**(massrange[0]\
                                         +(massrange[1]-massrange[0])\
                                         *numpy.random.uniform())\
                                         /bovy_conversion.mass_in_msol(V0,R0)
        else:
            sample_GM= lambda: (10.**((options.massexp+1.5)*massrange[0])\
                                    +(10.**((options.massexp+1.5)*massrange[1])\
                                          -10.**((options.massexp+1.5)*massrange[0]))\
                                    *numpy.random.uniform())**(1./(options.massexp+1.5))\
                                    /bovy_conversion.mass_in_msol(V0,R0)
        rate_range= numpy.arange(massrange[0]+0.5,massrange[1]+0.5,1)
        rate= options.timescdm\
            *numpy.sum([dNencdm(sdf_pepper,10.**r,Xrs=options.Xrs,
                                plummer=options.plummer,rsfac=options.rsfac,
                                sigma=options.sigma)
                        for r in rate_range])
        if not options.cutoff is None:
            rate*= integrate.quad(lambda x: x**-1.5\
                                      *numpy.exp(-10.**options.cutoff/x),
                                  10.**massrange[0],10.**massrange[1])[0]\
                                  /integrate.quad(lambda x: x**-1.5,
                                                  10.**massrange[0],
                                                  10.**massrange[1])[0]
    print "Using an overall rate of %f" % rate
    sample_rs= lambda x: rs(x*bovy_conversion.mass_in_1010msol(V0,R0)*10.**10.,
                            plummer=options.plummer,rsfac=options.rsfac)
    # Simulate
    start= time.time()
    ns= 0
    while True:
        if options.nsamples is None and time.time() >= (start+options.dt*60.):
            break
        elif not options.nsamples is None and ns > options.nsamples:
            break
        ns+= 1
        sdf_pepper.simulate(rate=rate,sample_GM=sample_GM,sample_rs=sample_rs,
                            Xrs=options.Xrs,sigma=options.sigma/V0)
        # Compute density and meanOmega and save
        try:
            densOmega= numpy.array([sdf_pepper._densityAndOmega_par_approx(a)
                                    for a in apar]).T
        except IndexError: # no hit
            dens_unp= [sdf_smooth._density_par(a) for a in apar]
            omega_unp= [sdf_smooth.meanOmega(a,oned=True) for a in apar]
            denswriter.writerow(dens_unp)
            omegawriter.writerow(omega_unp)
        else:
            denswriter.writerow(list(densOmega[0]))
            omegawriter.writerow(list(densOmega[1]))
        csvdens.flush()
        csvomega.flush()
    csvdens.close()
    csvomega.close()
    return None