Esempio n. 1
0
def run():
    print('input:')
    print(gpr.fil)
    x0,y0,vlos = np.genfromtxt(gpr.fil, skiprows=0, unpack =  True,
                               usecols = (0,1,5))

    # use only 3000 random particles:
    pdb.set_trace()
    ind = np.arange(len(x0))
    np.random.shuffle(ind)
    ind = ind[:3000]
    x0 = x0[ind];    y0 = y0[ind];    vlos = vlos[ind]
    
    x0 *= 1000.                         # [pc]
    y0 *= 1000.                         # [pc]
    
    # center of mass with means
    #com_x, com_y = com_mean(x0,y0) # [TODO]
    
    # shrinking sphere method
    com_x, com_y, com_vz = com_shrinkcircle_v_2D(x0,y0, vlos)
    print('COM [pc]: ', com_x, com_y)
    print('VOM [km/s]', com_vz)

    x0 -= com_x; y0 -= com_y # [pc]
    vlos -= com_vz #[km/s]
    
    rc = np.sqrt(x0**2+y0**2) # [pc]
    rc.sort() # [pc]
    for i in range(len(rc)-1):
        if rc[i]>rc[i+1]: #[pc]
            print('sorting error!')
            exit(1)
    rhalf = rc[floor(len(rc)/2)] # [pc]
    rscale = rhalf # or gpr.r_DM # [pc]
    print('rscale = ',rscale,' pc')
    print('max(r) = ',max(rc),' pc')
    print('last element of r : ',rc[-1],' pc')
    print('total number of stars: ',len(rc))

    r0 = np.sqrt(x0**2+y0**2)/rscale
    sel = (r0<gpr.rprior)
    x = x0[sel]/rscale; y = y0[sel]/rscale # [r_scale]
    vz=vlos[sel]
    m = np.ones(len(x))
    r = np.sqrt(x*x+y*y) #[r_scale]
    # print("x y z") on first line, to interprete data later on
    crscale = open(gpr.get_params_file(0),'w')
    print('# rscale in [pc], surfdens_central (=dens0) in [munit/rscale**2], and in [munit/pc**2], and totmass [munit], and max(v_LOS) in [km/s]', file=crscale)
    print(rscale, file=crscale)
    crscale.close()

    print('output: ',gpr.get_com_file(0))
    c = open(gpr.get_com_file(0),'w')
    print('# x [rscale],','y [rscale],','vLOS [km/s],','rscale = ',rscale,' pc', file=c)
    for k in range(len(x)):
        print(x[k],y[k],vz[k], file=c) #[rscale], [rscale], [km/s]
    c.close()
        
        
    if not gpr.showplots: return
        
    ion(); ax = subplot(111)
    # res = (abs(x)<3)*(abs(y)<3)
    # x = x[res]; y = y[res] #[rscale]
    en = len(x)

    H, xedges, yedges = np.histogram2d(x, y,  bins=(30,30),  range=[[-3.,3.], [-3.,3.]])
    extent = [yedges[0], yedges[-1], xedges[0], xedges[-1]]
    subplots_adjust(bottom=0.15, left=0.15)


    imshow(H, interpolation='bilinear', origin='lower',
           cmap=cm.gray, extent=(-3,3,-3,3))
    
    levels = np.logspace(2,4,10)
    cset = contour(H, levels, origin='lower', extent=extent) #cmap=cm.gray
    clabel(cset, inline=1, fontsize=8, fmt='%1.0i')
    for c in cset.collections:
        c.set_linestyle('solid')
        
    # scatter(x[:en], y[:en], s=35, vmin=0.95, vmax=1.0, lw=0.0, alpha=0.2)
    # xscale('log'); yscale('log')
    circ_HL=Circle((0,0), radius=rscale/rscale, fc='None', ec='g', lw=3)
    circ_DM=Circle((0,0), radius=gpr.r_DM/rscale, fc='None', ec='r', lw=3)
    gca().add_patch(circ_HL); gca().add_patch(circ_DM)
    
    # visible region
    axes().set_aspect('equal')
    
    xlabel(r'$x [R_s]$'); ylabel(r'$y [R_s]$')
    # title(gpr.fil)
    savefig(gpr.get_com_png(0))
    if gpr.showplots:
        ioff();show();clf()
Esempio n. 2
0
vznew = (vz-com_vz)*np.sqrt(gp.G1*gp.Mscale/gp.ascale) # [km/s], from conversion from system with L=G=M=1


R0 = np.sqrt(xnew**2+ynew**2)   # [pc]
R0.sort()                       # [pc]
Rhalf = R0[len(R0)/2]           # [pc]
Rscale = Rhalf                   # or gpr.r_DM # [pc]

print('Rscale = ', Rscale)

# TODO: save Rscale in scale file

xnew /= Rscale; ynew /= Rscale    # [rscale]

# only for 0 (all) and 1 (first and only population)
for comp in range(gpr.ncomp):
    crscale = open(gpr.get_params_file(comp),'w')
    print('# Rscale in [pc],',' surfdens_central (=dens0) in [munit/rscale**2],',\
          ' and in [munit/pc**2],',' and totmass [munit],',\
          ' and max(v_LOS) in [km/s]', file=crscale)
    print(Rscale, file=crscale)
    crscale.close()

    print('grh_com: output: ', gpr.fileposcenter[comp])
    filepos = open(gpr.fileposcenter[comp],'w')
    print('# x [Rscale]','y [Rscale]','vLOS [km/s]', file=filepos)
    for k in range(ndm):
        print(xnew[k], ynew[k], vznew[k], file=filepos)
    filepos.close()
    print('')
Esempio n. 3
0
def run():
    xall, yall = np.loadtxt(gpr.get_com_file(0), skiprows=1, usecols=(0, 1), unpack=True)  # 2*[Rscale]
    # calculate 2D radius on the skyplane
    R = np.sqrt(xall ** 2 + yall ** 2)  # [Rscale]
    # set number and size of (linearly spaced) bins
    Rmin = 0.0  # [Rscale]
    Rmax = max(r) if gpr.rprior < 0 else 1.0 * gpr.rprior  # [Rscale]
    print("Rmax [Rscale] = ", Rmax)
    R = R[(R < Rmax)]

    # determine radius once and for all
    # this must not be changed between readout and gravlite run
    # if you wish to change: set gp.getnewdata = True in gl_params.py
    if gp.lograd:
        print(gpr.nbins, " bins in log spacings")
        Binmin, Binmax, Rbin = bin_r_log(Rmax / gpr.nbins, Rmax, gpr.nbins)
    elif gp.consttr:
        print(len(R) / gpr.nbins, " particles per bin")
        Binmin, Binmax, Rbin = bin_r_const_tracers(R, len(R) / gpr.nbins)
    else:
        print(gpr.nbins, " bins in linear spacings")
        Binmin, Binmax, Rbin = bin_r_linear(Rmin, Rmax, gpr.nbins)

    # volume of a circular ring from binmin to binmax
    vol = np.zeros(gpr.nbins)
    for k in range(gpr.nbins):
        vol[k] = 4.0 * np.pi / 3.0 * (Binmax[k] ** 3 - Binmin[k] ** 3)  # [Rscale^3]

    for comp in range(gpr.ncomp):
        print("#######  working on component ", comp)
        print("input: ", gpr.get_com_file(comp) + "_3D")
        # start from data centered on COM already:
        if gfile.bufcount(gpr.get_com_file(comp) + "_3D") < 2:
            continue
        x, y, z, v = np.loadtxt(
            gpr.get_com_file(comp) + "_3D", skiprows=1, usecols=(0, 1, 2, 3), unpack=True
        )  # 3*[Rscale], [km/s]

        # calculate 2D radius on the skyplane
        r = np.sqrt(x ** 2 + y ** 2)  # [Rscale]

        # set maximum radius (if gpr.rprior is set)
        rmax = max(r) if gpr.rprior < 0 else 1.0 * gpr.rprior  # [Rscale]
        print("rmax [Rscale] = ", rmax)
        sel = r <= rmax
        x = x[sel]
        y = y[sel]
        z = z[sel]
        v = v[sel]
        r = r[sel]  # [Rscale]
        totmass = 1.0 * len(x)  # [munit], munit = 1/star

        rs = r  # + possible starting offset, [Rscale]
        vlos = v  # + possible starting offset, [km/s]

        print("output density: ")
        print(gpr.get_ntracer_file(comp) + "_3D")
        tr = open(gpr.get_ntracer_file(comp) + "_3D", "w")
        print(totmass, file=tr)
        tr.close()

        print(gpr.get_dens_file(comp) + "_3D")
        de = open(gpr.get_dens_file(comp) + "_3D", "w")
        print("rbin", "binmin", "binmax", "nu(r)/nu(0)", "error", file=de)

        print(gpr.get_enc_mass_file(comp) + "_3D")
        em = open(gpr.get_enc_mass_file(comp) + "_3D", "w")
        print("rbin", "binmin", "binmax", "M(<r)", "error", file=em)

        # gpr.n=30 iterations for getting random picked radius values
        density = np.zeros((gpr.nbins, gpr.n))
        a = np.zeros((gpr.nbins, gpr.n))  # shared by density, siglos, kappa calcs
        for k in range(gpr.n):
            rsi = gpr.Rerror * np.random.randn(len(rs)) + rs  # [Rscale]
            vlosi = gpr.vrerror * np.random.randn(len(vlos)) + vlos  # [km/s]
            for i in range(gpr.nbins):
                ind1 = np.argwhere(np.logical_and(rsi >= Binmin[i], rsi < Binmax[i])).flatten()  # [1]
                density[i][k] = (1.0 * len(ind1)) / vol[i] * totmass  # [munit/Rscale^2]
                vlos1 = vlosi[ind1]  # [km/s]
                a[i][k] = 1.0 * len(ind1)  # [1]

        # output density
        dens0 = np.sum(density[0]) / (1.0 * gpr.n)  # [munit/Rscale^3]
        print("dens0 = ", dens0, " [munit/Rscale^3]")
        crscale = open(gpr.get_params_file(comp) + "_3D", "r")
        Rscale = np.loadtxt(crscale, comments="#", skiprows=1, unpack=False)
        crscale.close()

        cdens = open(gpr.get_params_file(comp) + "_3D", "a")
        print(dens0, file=cdens)  # [munit/Rscale^3]
        print(dens0 / Rscale ** 3, file=cdens)  # [munit/pc^3]
        print(totmass, file=cdens)  # [munit]
        cdens.close()

        ab0 = np.sum(a[0]) / (1.0 * gpr.n)  # [1]
        denserr0 = dens0 / np.sqrt(ab0)  # [munit/Rscale^3]
        p_dens = np.zeros(gpr.nbins)
        p_edens = np.zeros(gpr.nbins)
        for b in range(gpr.nbins):
            dens = np.sum(density[b]) / (1.0 * gpr.n)  # [munit/Rscale^3]
            ab = np.sum(a[b]) / (1.0 * gpr.n)  # [1]
            denserr = dens / np.sqrt(ab)  # [munit/Rscale^3]
            denserror = np.sqrt((denserr / dens0) ** 2 + (dens * denserr0 / (dens0 ** 2)) ** 2)  # [1]
            if math.isnan(denserror):
                denserror = 0.0  # [1]
                p_dens[b] = p_dens[b - 1]  # [1]
                p_edens[b] = p_edens[b - 1]  # [1]
            else:
                p_dens[b] = dens / dens0  # [1]
                p_edens[b] = denserror  # [1] #100/rbin would be artificial guess

            print(Rbin[b], Binmin[b], Binmax[b], p_dens[b], p_edens[b], file=de)  # [Rscale], 2*[dens0]
            indr = r < Binmax[b]
            menclosed = 1.0 * np.sum(indr) / totmass  # for normalization to 1  # [totmass]
            merror = menclosed / np.sqrt(ab)  # artificial menclosed/10 # [totmass]
            print(Rbin[b], Binmin[b], Binmax[b], menclosed, merror, file=em)  # [rscale], 2*[totmass]
            # TODO: check: take rbinmax for MCMC?
        de.close()
        em.close()

        if not gpr.showplots:
            continue
        # plot density
        ion()
        subplot(111)
        print("rbin = ", Rbin)
        print("p_dens = ", p_dens)
        print("p_edens = ", p_edens)

        plot(Rbin, p_dens, "b", lw=1)
        lbound = p_dens - p_edens
        lbound[lbound < 1e-6] = 1e-6
        ubound = p_dens + p_edens
        fill_between(Rbin, lbound, ubound, alpha=0.5, color="r")
        yscale("log")
        xlim([0, gpr.rprior])
        ylim([np.min(lbound), np.max(ubound)])
        xlabel(r"$r [r_c]$")
        ylabel(r"$\nu(r)/\nu(0)$")
        savefig(gpr.get_dens_png(i) + "_3D.png")
        ioff()
        show()
        clf()
Esempio n. 4
0
def run():
    print('input: ', gpr.fil)
    x0,y0,z0,vz0,vb0,Mg0,PM0,comp0 = np.genfromtxt(gpr.fil, skiprows = 0, unpack = True,\
                                                   usecols=(0,1,2,11,12,13,19,20),\
                                                   dtype="d17",\
                                                   converters={0:expDtofloat,  # x0  in pc \
                                                               1:expDtofloat,  # y0  in pc \
                                                               2:expDtofloat,  # z0  in pc \
                                                               11:expDtofloat, # vz0 in km/s\
                                                               12:expDtofloat, # vb0(LOS due binary), km/s\
                                                               13:expDtofloat, # Mg0 in Angstrom\
                                                               19:expDtofloat, # PM0 [1]\
                                                               20:expDtofloat}) # comp0 1,2,3(background)
    # TODO: use component 6-1 instead of 12-1 for z velocity, to include observational errors

    # only use stars which are members of the dwarf: exclude pop3 by construction
    pm = (PM0 >= gpr.pmsplit) # exclude foreground contamination, outliers
    PM0 = PM0[pm]
    comp0 = comp0[pm]; x0=x0[pm]; y0=y0[pm]; z0=z0[pm]; vz0=vz0[pm]; vb0=vb0[pm]; Mg0=Mg0[pm]
    pm1 = (comp0 == 1) # will be overwritten below if gp.metalpop
    pm2 = (comp0 == 2) # same same
    
    
    if gp.metalpop:
        # drawing of populations based on metallicity
        # get parameters from function in pymcmetal.py
        import pymcmetal as pmc
        p,mu1,sig1,mu2,sig2, M = pmc.bimodal_gauss(Mg0)
        pm1, pm2 = pmc.assign_pop(Mg0,p,mu1,sig1,mu2,sig2)
        # output: changed pm1, pm2

    # cutting pm_i to a maximum of ntracers particles:
    from random import shuffle
    ind = np.arange(len(x0))
    np.random.shuffle(ind)
    ind = ind[:gp.files.ntracer]
    x0=x0[ind]; y0=y0[ind]; z0=z0[ind]; comp0=comp0[ind]; vz0=vz0[ind]; vb0=vb0[ind]; Mg0=Mg0[ind]
    PM0 = PM0[ind]; pm1 = pm1[ind]; pm2 = pm2[ind]; pm = pm1+pm2
    
    # get center of mass with means
    #com_x, com_y,com_z = com_mean(x0,y0,z0,PM0) # [TODO], and TODO: z component included if available
    
    # get COM with shrinking sphere method
    com_x, com_y, com_z, com_vz = com_shrinkcircle_v(x0, y0, z0, vz0, PM0)
    print('COM [pc]: ', com_x, com_y, com_z)
    print('VOM [km/s]', com_vz)

    # from now on, work with 2D data only; z0 was only used to get center in (x,y) better
    x0 -= com_x; y0 -= com_y # [pc]
    vz0 -= com_vz #[km/s]
    
    R0 = np.sqrt(x0**2+y0**2) # [pc]
    Rc = R0                   # [pc]
    Rc.sort()                 # [pc]
    for i in range(len(Rc)-1):
        if Rc[i]>Rc[i+1]:               # [pc]
            print('sorting error!')
            exit(1)
    Rhalf = Rc[floor(len(Rc)/2)]        # [pc]
    Rscale = Rhalf                       # or gpr.r_DM # [pc]
    # Rscale = gpr.r_DM                    # deleted, we only work with data
    print('Rscale = ',Rscale,' pc')
    print('max(R) = ',max(Rc),' pc')
    print('last element of R : ',Rc[-1],' pc')
    print('total number of stars: ',len(Rc))
    
    x0 = x0/Rscale; y0 = y0/Rscale           # [Rscale]
    
    i = -1
    for pmn in [pm,pm1,pm2]:
        pmr = (R0<(gpr.rprior*Rscale))  # TODO: read from gl_class_file
        pmn = pmn*pmr                  # [1]
        print("fraction of members = ",1.0*sum(pmn)/len(pmn))
        i = i+1
        x=x0[pmn]; y=y0[pmn]; vz=vz0[pmn]; vb=vb0[pmn];  # [1], [km/s]
        Mg=Mg0[pmn]; comp=comp0[pmn]; PMN=PM0[pmn]   # [ang], [1], [1]
        m = np.ones(len(pmn))
        
        R = np.sqrt(x*x+y*y)            # [Rscale]
        
        # print("x y z" on first line, to interprete data later on)
        crscale = open(gpr.get_params_file(i),'w')
        print('# Rscale in [pc], surfdens_central (=dens0) in [munit/rscale**2], and in [munit/pc**2], and totmass [munit], and max(v_LOS) in [km/s]', file=crscale)
        print(Rscale, file=crscale)
        crscale.close()

        print('output: ',gpr.get_com_file(i))
        c = open(gpr.get_com_file(i),'w')
        print('# x [Rscale],','y [Rscale],','vLOS [km/s],','Rscale = ',Rscale,' pc', file=c)
        for k in range(len(x)):
            print(x[k],y[k],vz[k], file=c)      # [Rscale], [Rscale], [km/s]
        c.close()
        
        
        if not gpr.showplots: continue
        
        ion(); subplot(111)
        res = (abs(x)<3)*(abs(y)<3)
        x = x[res]; y = y[res]           # [Rscale]
        en = len(x)
        if en == 0: continue
        scatter(x[:en], y[:en], c=pmn[:en], s=35, vmin=0.95, vmax=1.0, lw=0.0, alpha=0.2)
        # xscale('log'); yscale('log')
        if i == 0: colorbar()
        circ_HL=Circle((0,0), radius=Rscale/Rscale, fc='None', ec='g', lw=1)
        circ_DM=Circle((0,0), radius=gpr.r_DM/Rscale, fc='None', ec='r', lw=1)
        gca().add_patch(circ_HL); gca().add_patch(circ_DM)
        
        # visible region
        maxr = max(np.abs(x));  mayr = max(np.abs(y)) #[rscale]
        width2 = max([maxr,mayr]) #[rscale]
        xlim([-width2,width2]); ylim([-width2,width2])
        axes().set_aspect('equal')
    
        xlabel(r'$x [R_s]$'); ylabel(r'$y [R_s]$')
        # title(gpr.fil)
        savefig(gpr.get_com_png(i))
        if gpr.showplots:
            ioff();show();clf()
Esempio n. 5
0
def run():
    print('input: ',gpr.get_com_file(0))
    # start from data centered on COM already:
    x,y,v = np.loadtxt(gpr.get_com_file(0),\
                       skiprows=1,usecols=(0,1,2),unpack=True) #[rscale], [rscale], [km/s]
    
    # calculate 2D radius on the skyplane
    r = np.sqrt(x**2+y**2) #[rscale]
    
    # set number and size of (linearly spaced) bins
    rmin = 0. #[rscale]
    rmax = max(r) if gpr.rprior<0 else 1.0*gpr.rprior #[rscale]
        
    print('rmax [rscale] = ', rmax)
    sel = (r<rmax)
    x = x[sel]; y = y[sel]; v = v[sel] #[rscale]
    totmass = 1.*len(x) #[munit], munit = 1/star
    
    if gp.lograd:
        # space logarithmically in radius
        binmin, binmax, rbin = bin_r_log(rmax/gpr.nbins, rmax, gpr.nbins)
    elif gp.consttr:
        binmin, binmax, rbin = bin_r_const_tracers(r, len(r)/gpr.nbins)
    else:
        binmin, binmax, rbin = bin_r_linear(rmin, rmax, gpr.nbins)
            
    #volume of a circular bin from binmin to binmax
    vol = np.zeros(gpr.nbins)
    for k in range(gpr.nbins):
        vol[k] = np.pi*(binmax[k]**2-binmin[k]**2) # [rscale**2]
            
    # rs = gpr.rerror*np.random.randn(len(r))+r
    rs = r  #[rscale] # if no initial offset is whished
    
    print('output: ')
    print(gpr.get_ntracer_file(0))
    tr = open(gpr.get_ntracer_file(0),'w')
    print(totmass, file=tr)
    tr.close()

    print(gpr.get_dens_file(0))
    de = open(gpr.get_dens_file(0),'w')
    print(gpr.get_enc_mass_file(0))
    em = open(gpr.get_enc_mass_file(0),'w')
    
    print('r','nu(r)/nu(0)','error', file=de)
    print('r','M(<r)','error', file=em)

    # 30 iterations for getting random picked radius values
    density = np.zeros((gpr.nbins,gpr.n))
    a       = np.zeros((gpr.nbins,gpr.n))
    for k in range(gpr.n):
        rsi = gpr.rerror * np.random.randn(len(rs)) + rs # [rscale]
        for j in range(gpr.nbins):
            ind1 = np.argwhere(np.logical_and(rsi>=binmin[j],rsi<binmax[j])).flatten() # [1]
            density[j][k] = (1.*len(ind1))/vol[j]*totmass # [munit/rscale**2]
            a[j][k] = 1.*len(ind1) #[1]
            
    dens0 = np.sum(density[0])/(1.*gpr.n) # [munit/rscale**2]
    print('dens0 = ',dens0,'[munit/rscale**2]')
    crscale = open(gpr.get_params_file(0),'r')
    rscale = np.loadtxt(crscale, comments='#', skiprows=1, unpack=False)
    crscale.close()

    cdens = open(gpr.get_params_file(0),'a')
    print(dens0, file=cdens)               # [munit/rscale**2]
    print(dens0/rscale**2, file=cdens)      # [munit/pc**2]
    print(totmass, file=cdens)             # [munit]
    cdens.close()
    
    ab0   = np.sum(a[0])/(1.*gpr.n)     # [1]
    denserr0 = dens0/np.sqrt(ab0)       # [munit/rscale**2]

    p_dens  = np.zeros(gpr.nbins);  p_edens = np.zeros(gpr.nbins)
    
    for b in range(gpr.nbins):
        dens = np.sum(density[b])/(1.*gpr.n) # [munit/rscale**2]
        ab   = np.sum(a[b])/(1.*gpr.n)       # [1]
        denserr = dens/np.sqrt(ab)       # [munit/rscale**2]
        denserror = np.sqrt((denserr/dens0)**2+(dens*denserr0/(dens0**2))**2) #[1]
        if(math.isnan(denserror)):
            denserror = 0. # [1]
            ## [PS]: TODO: change bin sizes to include same number of
            ##             stars in each bin, not assigning wrong density as below
            p_dens[b] = p_dens[b-1]  # [1]
            p_edens[b]= p_edens[b-1] # [1]
        else:
            p_dens[b] = dens/dens0   # [1]
            p_edens[b]= denserror    # [1] #100/rbin would be artificial guess

    for b in range(gpr.nbins):
        print(rbin[b],p_dens[b],p_edens[b], file=de) # [rscale], [dens0], [dens0]
        indr = (r<binmax[b])
        menclosed = 1.0*np.sum(indr)/totmass # /totmass for normalization to 1 at last bin #[totmass]
        merror = menclosed/np.sqrt(ab) # artificial menclosed/10 gives good approximation #[totmass]
        print(rbin[b],menclosed,merror, file=em) # [rscale], [totmass], [totmass]
        # TODO: check: take rbinmax for MCMC?
    de.close()
    em.close()


    if not gpr.showplots: return
    ion(); subplot(111)
    print('rbin = ',rbin)
    print('p_dens = ',p_dens)
    print('p_edens = ',p_edens)

    plot(rbin,p_dens,'b',linewidth=3)
    lbound = p_dens-p_edens; lbound[lbound<1e-6] = 1e-6
    ubound = p_dens+p_edens; 
    fill_between(rbin,lbound,ubound,alpha=0.5,color='r')
    # xscale('log'); 
    yscale('log')
    xlim([np.min(rbin),np.max(rbin)])
    ylim([np.min(lbound),np.max(ubound)])
    # ylim([1e-3,3.])#ylim([1e-6,2*np.max(p_dens)])
    # ylim([0,1])
    xlabel(r'$r [r_c]$')
    ylabel(r'$\nu(r)/\nu(0)$')
    # plt.legend(['\rho','\rho'],'lower left')
    # title(fil)
    # axes().set_aspect('equal')
    savefig(gpr.get_dens_png(0))
    if gpr.showplots:
        ioff(); show(); clf()
Esempio n. 6
0
x0 = x0/rscale; y0 = y0/rscale # [r_scale]

i = -1
for pmn in [pm,pm1,pm2,pm3]:
    pmr = (r0<(gpr.rprior*rscale)) # TODO: read from gl_class_file
    pmn = pmn*pmr # [1]
    print("fraction of members = ",1.0*sum(pmn)/len(pmn))
    i = i+1
    x=x0[pmn]; y=y0[pmn]; z=z0[pmn]; vz=vz0[pmn]; vb=vb0[pmn]; #[1], [km/s]
    Mg=Mg0[pmn]; comp=comp0[pmn]; PMN=PM0[pmn] # [ang], [1], [1]
    m = np.ones(len(pmn))
    
    r = np.sqrt(x*x+y*y) #[r_scale]

    # print "x y z" on first line, to interprete data later on
    crscale = open(gpr.get_params_file(i),'w')
    print('# rscale in [pc], surfdens_central (=dens0) in [munit/rscale**2], and in [munit/pc**2], and totmass [munit], and max(v_LOS) in [km/s]', file=crscale)
    print(rscale, file=crscale)
    crscale.close()

    print('output: ',gpr.get_com_file(i))
    c = open(gpr.get_com_file(i),'w')
    print('# x [rscale],','y [rscale],','vLOS [km/s],','rscale = ',rscale,' pc', file=c)
    for k in range(len(x)):
        print(x[k],y[k],vz[k], file=c) #[rscale], [rscale], [km/s]
    c.close()


    if not gpr.showplots: continue

    ion(); subplot(111)
Esempio n. 7
0
def run():
    # determine radius once and for all from all tracers
    R, Phi, vzall = np.loadtxt(gpr.fileposspherical[0],
                               comments='#',unpack=True) # 2*[Rscale], [km/s]
    # set number and size of (linearly spaced) bins
    Rmin = 0.                                         # [Rscale]
    Rmax = max(R) if gpr.rprior<0 else 1.0*gpr.rprior # [Rscale]
    print('Rmax [Rscale] = ', Rmax)                   # [Rscale]
    R = R[(R<=Rmax)]                                  # [Rscale]

    # this must not be changed between readout and gravlite run
    # if you wish to change: set gp.getnewdata = True in gl_params.py
    if gp.lograd:
        Binmin, Binmax, Rbin = bin_r_log(Rmax/gpr.nbins, Rmax, gpr.nbins)
        print(gpr.nbins,' bins in log spacings')
    elif gp.consttr:
        Binmin, Binmax, Rbin = bin_r_const_tracers(R, len(R)/gpr.nbins)
        print(len(R)/gpr.nbins,' particles per bin')
    else:
        Binmin, Binmax, Rbin = bin_r_linear(Rmin, Rmax, gpr.nbins)
        print(gpr.nbins, ' bins in linear spacings')


    # volume of a circular ring from binmin to binmax
    Vol = np.zeros(gpr.nbins)
    for k in range(gpr.nbins):
        Vol[k] = np.pi*(Binmax[k]**2-Binmin[k]**2) # [Rscale^2]


    for comp in range(gpr.ncomp):
        print('#######  working on component ',comp)
        print('grh_MCMCbin: input: ',gpr.fileposspherical[comp])
        # start from data centered on COM already:
        if gfile.bufcount(gpr.fileposspherical[comp])<2: continue
        R, Phi, v = np.loadtxt(gpr.fileposspherical[comp],\
                               comments='#',unpack=True)
                               # [Rscale], [1], [km/s]
        
        # set maximum radius (if gpr.rprior is set)
        Rmax = max(R) if gpr.rprior<0 else 1.0*gpr.rprior # [Rscale]
        print('Rmax [Rscale] = ', Rmax)
        sel = (R<=Rmax)
        R = R[sel]; v = v[sel] # [Rscale], [km/s]
        totmass = 1.*len(R) # [munit], munit = 1/star
            
        Rs = R                   # + possible starting offset, [Rscale]
        vlos = v                 # + possible starting offset, [km/s]
        
        print('grh_MCMCbin: output density: ')
        print(gpr.get_ntracer_file(comp))
        tr = open(gpr.get_ntracer_file(comp),'w')
        print(totmass, file=tr)
        tr.close()

        print(gpr.filedenfalloff[comp])
        de = open(gpr.filedenfalloff[comp],'w')
        print('Rbin [Rscale]','Binmin [Rscale]','Binmax [Rscale]',\
              'Nu(R)/Nu(0) [1]','error [1]', file=de)

        print(gpr.filemass[comp])
        em = open(gpr.filemass[comp],'w')
        print('R [Rscale]','Binmin [Rscale]','Binmax [Rscale]',\
              'M(<Binmax) [Msun]','error [Msun]', file=em)


        print('grh_MCMCbin: output siglos: ',gpr.filesig[comp])
        sigfil = open(gpr.filesig[comp],'w')
        print('R [Rscale]','Binmin [Rscale]','Binmax [Rscale]',\
              'sigma_r(R) [km/s]','error [km/s]', file=sigfil)


        print('grh_MCMCbin: output kurtosis: ',gpr.filekappa[comp])
        kappafil = open(gpr.filekappa[comp],'w')
        print('R [Rscale]','Binmin [Rscale]','Binmax [Rscale]',\
              'kappa_los(R) [1]','error [1]', file=kappafil)


        # gpr.n=30 iterations for getting random picked radius values
        Density = np.zeros((gpr.nbins,gpr.n))
        dispvelocity = np.zeros((gpr.nbins,gpr.n))
        mom4         = np.zeros((gpr.nbins,gpr.n))
        a            = np.zeros((gpr.nbins,gpr.n))
        # 'a' shared by density, siglos, kappa calcs
        for k in range(gpr.n):
            Rsi = gpr.Rerror * np.random.randn(len(Rs)) + Rs # [Rscale]
            vlosi = gpr.vrerror * np.random.randn(len(vlos)) + vlos # [km/s]
            for i in range(gpr.nbins):
                ind1 = np.argwhere(np.logical_and(Rsi >= Binmin[i],Rsi<Binmax[i])).flatten() # [1]
                Density[i][k] = (1.*len(ind1))/Vol[i]*totmass # [munit/rscale**2]
                vlos1 = vlosi[ind1] # [km/s]

                if(len(ind1)<=1):
                    dispvelocity[i][k] = dispvelocity[i-1][k]
                    mom4[i][k] = mom4[i-1][k]
                    # attention! should be 0, uses last value
                else:
                    dispvelocity[i][k] = meanbiweight(vlos1,ci_perc=68.4,ci_mean=True,ci_std=True)[1]
                                        # [km/s], see BiWeight.py
                    mom4[i][k] = kurtosis(vlos1, axis=0, fisher=False, bias=False) # [1]
                a[i][k] = 1.*len(ind1) #[1]

        # output density
        Dens0 = np.sum(Density[0])/(1.*gpr.n) # [munit/Rscale^2]
        print('Dens0 = ',Dens0,'[munit/Rscale^2]')
        crscale = open(gpr.get_params_file(comp),'r')
        Rscale = np.loadtxt(crscale, comments='#', unpack=False) # [pc]
        crscale.close()

        cdens = open(gpr.get_params_file(comp),'a')
        print(Dens0, file=cdens)               # [munit/Rscale^2]
        print(Dens0*Rscale**2, file=cdens)     # [munit/pc^2]
        print(totmass, file=cdens)             # [munit]
        cdens.close()

        ab0   = np.sum(a[0])/(1.*gpr.n)     # [1]
        Denserr0 = Dens0/np.sqrt(ab0)       # [munit/Rscale^2]
        P_dens  = np.zeros(gpr.nbins);  P_edens = np.zeros(gpr.nbins)
        for b in range(gpr.nbins):
            Dens = np.sum(Density[b])/(1.*gpr.n) # [munit/Rscale^2]
            ab   = np.sum(a[b])/(1.*gpr.n)       # [1]
            Denserr = Dens/np.sqrt(ab)       # [munit/Rscale^2]
            Denserror = np.sqrt((Denserr/Dens0)**2+(Dens*Denserr0/(Dens0**2))**2) # [1]
            if(math.isnan(Denserror)):
                Denserror = 0. # [1]
                P_dens[b] = P_dens[b-1]  # [1]
                P_edens[b]= P_edens[b-1] # [1]
            else:
                P_dens[b] = Dens/Dens0   # [1]
                P_edens[b]= Denserror    # [1] #100/rbin would be artificial guess

            print(Rbin[b],Binmin[b],Binmax[b],P_dens[b],P_edens[b], file=de)
            # [Rscale], [dens0], [dens0]
            indr = (R<Binmax[b])
            Menclosed = 1.0*np.sum(indr)/totmass # for normalization to 1  # [totmass]
            Merror = Menclosed/np.sqrt(ab) # or artificial Menclosed/10 # [totmass]
            print(Rbin[b], Binmin[b], Binmax[b], Menclosed, Merror, file=em)
            # [Rscale], 2* [totmass]
        de.close()
        em.close()


        # output siglos
        p_dvlos = np.zeros(gpr.nbins);        p_edvlos = np.zeros(gpr.nbins)
        for b in range(gpr.nbins):
            dispvel = np.sum(dispvelocity[b])/gpr.n # [km/s]
            ab = np.sum(a[b])/(1.*gpr.n)            # [1]
            if ab == 0:
                dispvelerror = p_edvlos[b-1] # [km/s]
                # attention! uses last error
            else:
                dispvelerror = dispvel/np.sqrt(ab) # [km/s]
            p_dvlos[b] = dispvel                   # [km/s]
            p_edvlos[b]= dispvelerror              # [km/s]

        maxvlos = max(p_dvlos)          # [km/s]
        print('maxvlos = ',maxvlos,'[km/s]')
        fpars = open(gpr.get_params_file(comp),'a')
        print(maxvlos, file=fpars)      # [km/s]
        fpars.close()
        
        for b in range(gpr.nbins):
            #     [Rscale] [Rscale]  [Rscale]   [maxvlos]                  [maxvlos]
            print(Rbin[b],Binmin[b],Binmax[b], np.abs(p_dvlos[b]/maxvlos),np.abs(p_edvlos[b]/maxvlos), file=sigfil)
            # TODO: check uncommented /np.sqrt(n))
        sigfil.close()



        # output kurtosis kappa
        p_kappa = np.zeros(gpr.nbins) # needed for plotting later
        p_ekappa = np.zeros(gpr.nbins)
        for b in range(gpr.nbins):
            kappavel = np.sum(mom4[b])/gpr.n # [1]
            ab = np.sum(a[b])/(1.*gpr.n)     # [1]
            if ab == 0:
                kappavelerror = p_edvlos[b-1] # [1]
                # attention! uses last error
            else:
                kappavelerror = np.abs(kappavel/np.sqrt(ab)) # [1]
            p_kappa[b] = kappavel
            p_ekappa[b] = kappavelerror
            
            print(Rbin[b],Binmin[b],Binmax[b],\
                  kappavel, kappavelerror, file=kappafil) # 3*[Rscale], 2*[1]
            # TODO: /np.sqrt(n))
        kappafil.close()


    


        if not gpr.showplots: continue
        # plot density
        ion(); subplot(111)
        print('Rbin = ',Rbin)
        print('P_dens = ',P_dens)
        print('P_edens = ',P_edens)


        plot(Rbin,P_dens,'b',lw=1)
        lbound = P_dens-P_edens; lbound[lbound<1e-6] = 1e-6
        ubound = P_dens+P_edens; 
        fill_between(Rbin, lbound, ubound, alpha=0.5, color='r')
        yscale('log')
        xlim([0,3.])
        ylim([np.min(lbound), np.max(ubound)])
        xlabel(r'$R [R_c]$')
        ylabel(r'$\nu_{2D}(R)/\nu_{2D}(0)$')
        savefig(gpr.get_dens_png(comp))
        # from gl_analytic import Sigma_anf
        # plot(Rbin, Sigma_anf(Rbin*Rscale))  # Sigma_anf argument in [pc] !

        ioff(); show(); clf()

        # plot siglos
        ion(); subplot(111)
        print('Rbin = ',Rbin,' Rscale')
        print('p_dvlos = ',p_dvlos,' km/s')
        print('p_edvlos = ',p_edvlos, 'km/s')
        plot(Rbin,p_dvlos,'b',lw=1)
        fill_between(Rbin,p_dvlos-p_edvlos,p_dvlos+p_edvlos,alpha=0.5,color='r') #[rscale],2*[km/s]

        xlabel(r'$R [\mathrm{Rscale}]$')
        ylabel(r'$\langle\sigma_{\mathrm{LOS}}\rangle [\mathrm{km/s}]$')
        ylim([0.,1.5*max(p_dvlos)])
        xlim([0,3])
        savefig(gpr.get_siglos_png(comp))
        # from gl_analytic import sig_los_anf
        # plot(Rbin,sig_los_anf(Rbin*Rscale)) # argument must be [pc] !

        ioff();show();clf()

        # plot kappa
        ion(); subplot(111)
        print('Rbin = ',Rbin,' Rscale')
        print('p_kappa = ',p_kappa)
        print('p_ekappa = ',p_ekappa)
        plot(Rbin,p_kappa,'b',lw=1)
        fill_between(Rbin,p_kappa-p_ekappa,p_kappa+p_ekappa,alpha=0.5,color='r') #[rscale],2*[1]
        xlabel(r'$R [\mathrm{Rscale}]$')
        ylabel(r'$\langle\kappa_{\mathrm{LOS}}\rangle [1]$')
        ylim([0,5])
        xlim([0,3])
        savefig(gpr.get_kurtosis_png(comp))
        ioff();show();clf()
Esempio n. 8
0
def run():
    for comp in range(gpr.ncomp):
        print('input:',gpr.fileposspherical[comp])
        R, Phi, vlos = np.loadtxt(gpr.fileposspherical[comp],\
                                  comments='#', unpack=True)
        Totmass = 1.*len(R) # [munit], munit = 1/star
        # Rs=gpr.Rerror*np.random.randn(len(r))+r
        # Rs not changed later on, ever: misplacement, for all realizations. wanted?
        # yes, we scatter radii in foo_pool
        Rs = R;    Rmin = min(Rs);     Rmax = max(Rs)
        if gp.lograd:
            print(gpr.nbins,' bins in log spacings')
            Binmin, Binmax, Rbin = bin_r_log(Rmax/gpr.nbins, Rmax, gpr.nbins)
        elif gp.consttr:
            Binmin, Binmax, Rbin = bin_r_const_tracers(Rs, len(Rs)/gpr.nbins)
            print(len(R)/gpr.nbins,' particles per bin')
        else:
            print(gpr.nbins, ' bins in linear spacings')
            Binmin, Binmax, Rbin = bin_r_linear(Rmin, Rmax, gpr.nbins)

        # volume of a bin with height binlength, 2D
        Vol = np.zeros(gpr.bins)
        for i in range(gpr.bins):
            Vol[i] = np.pi*(Binmax[i]**2-Binmin[i]**2)

        # gpr.n=30 iterations for getting random picked radius values
        Density = np.zeros((gpr.nbins,gpr.n))
        A       = np.zeros((gpr.nbins,gpr.n)) # shared by density, siglos, kappa calcs
        for k in range(gpr.n):
            Rsi = gpr.Rerror * np.random.randn(len(Rs)) + Rs # [Rscale]
            vlosi = gpr.vrerror * np.random.randn(len(vlos)) + vlos
            for i in range(gpr.nbins):
                ind1 = np.argwhere(np.logical_and(Rsi>=Binmin[i], Rsi<Binmax[i])).flatten() # [1]
                Density[i][k] = (1.*len(ind1))/Vol[i]*Totmass # [munit/Rscale^2]
                vlos1 = vlosi[ind1]                           # [km/s]
                A[i][k] = 1.*len(ind1)                        # [1]

        # output density
        Dens0 = np.sum(Density[0])/(1.*gpr.n) # [munit/Rscale^3]
        print('Dens0 = ',Dens0,' [munit/Rscale^2]')
        crscale = open(gpr.get_params_file(comp),'r')
        Rscale = np.loadtxt(cscale, comments='#', unpack=False)
        crscale.close()

        cdens = open(gpr.get_params_file(comp),'a')
        print(Dens0,file=cdens)               # [munit/Rscale^2]
        print(Dens0/Rscale**2,file=cdens)      # [munit/pc^2]
        print(Totmass,file=cdens)             # [munit]
        cdens.close()

        print(gpr.get_dens_file(comp))
        de = open(gpr.get_dens_file(comp),'w')
        print('# Rbin [Rscale]','Binmin [Rscale]','Binmax [Rscale]',
              'Nu(R)/Nu(0) [1]','error [1]', file=de)
    
        print(gpr.get_enc_mass_file(comp))
        em = open(gpr.get_enc_mass_file(comp),'w')
        print('# R [Rscale]','Binmin [Rscale]','Binmax [Rscale]',\
              'M(<Binmax) [Msun]','error [Msun]', file=em)

    
        AB0   = np.sum(A[0])/(1.*gpr.n)     # [1]
        Denserr0 = Dens0/np.sqrt(AB0)       # [munit/Rscale^3]
        P_dens  = np.zeros(gpr.nbins);  P_edens = np.zeros(gpr.nbins)
        for b in range(gpr.nbins):
            Dens = np.sum(Density[b])/(1.*gpr.n) # [munit/Rscale^3]
            AB   = np.sum(A[b])/(1.*gpr.n)       # [1]
            Denserr = Dens/np.sqrt(AB)       # [munit/Rscale^3]
            Denserror = np.sqrt((Denserr/Dens0)**2+(Dens*Denserr0/(Dens0**2))**2) #[1]
            if(math.isnan(Denserror)):
                Denserror = 0. # [1]
                P_dens[b] = P_dens[b-1]  # [1]
                P_edens[b]= P_edens[b-1] # [1]
            else:
                P_dens[b] = Dens/Dens0   # [1]
                P_edens[b]= Denserror    # [1] #100/rbin would be artificial guess

            print(Rbin[b], Binmin[b], Binmax[b], P_dens[b], P_edens[b], file=de)
            # [Rscale], 2*[dens0]

            # normalization to 1:
            indr = (R<Binmax[b])
            menclosed = 1.0*np.sum(indr)/Totmass  # [Totmass]
            
            merror = menclosed/np.sqrt(AB) # artificial menclosed/10 # [Totmass]
            print(Rbin[b], Binmin[b], Binmax[b], menclosed, merror, file=em)
            # [rscale], 2*[Totmass]
            # TODO: check: take rbinmax for MCMC?
        de.close()
        em.close()
        
        if not gpr.showplots:
            continue
        
        # plot density
        ion(); subplot(111)
        print('Rbin = ',Rbin)
        print('P_dens = ',P_dens)
        print('P_edens = ',P_edens)
        
        plot(Rbin,P_dens,'b',lw=1)
        lbound = P_dens-P_edens; lbound[lbound<1e-6] = 1e-6
        ubound = P_dens+P_edens; 
        fill_between(Rbin, lbound, ubound, alpha=0.5, color='r')
        yscale('log')
        # xlim([0,3.])
        # ylim([np.min(lbound),np.max(ubound)])
        xlabel(r'$R [R_c]$')
        ylabel(r'$\nu_{2D}(R)/\nu_{2D}(0)$')
        savefig(gpr.get_dens_png(i))
        if gpr.showplots:
            ioff(); show(); clf()
    return
Esempio n. 9
0
def run():
    xall,yall = np.loadtxt(gpr.get_com_file(0),skiprows=1,usecols=(0,1),unpack=True) # 2*[rcore]
    # calculate 2D radius on the skyplane
    r = np.sqrt(xall**2+yall**2) #[rcore]
    # set number and size of (linearly spaced) bins
    rmin = 0. #[rcore]
    rmax = max(r) if gpr.rprior<0 else 1.0*gpr.rprior #[rcore]
    print 'rmax [rcore] = ', rmax
    r = r[(r<rmax)]

    # determine radius once and for all
    if gp.lograd:
        print gpr.nbins,' bins in log spacings'
        binmin, binmax, rbin = bin_r_log(rmax/gpr.nbins, rmax, gpr.nbins)
    elif gp.consttr:
        print len(r)/gpr.nbins,' particles per bin'
        binmin, binmax, rbin = bin_r_const_tracers(r, len(r)/gpr.nbins)
    else:
        print gpr.nbins, ' bins in linear spacings'
        binmin, binmax, rbin = bin_r_linear(rmin, rmax, gpr.nbins)

    # volume of a circular ring from binmin to binmax
    vol = np.zeros(gpr.nbins)
    for k in range(gpr.nbins):
        vol[k] = np.pi*(binmax[k]**2-binmin[k]**2) # [rcore^2]


    for comp in range(gpr.ncomp):
        print 'comp = ',comp
        print 'input: ',gpr.get_com_file(comp)
        # start from data centered on COM already:
        if gfile.bufcount(gpr.get_com_file(comp))<2: continue
        x,y,vlos = np.loadtxt(gpr.get_com_file(comp),\
                              skiprows=1,usecols=(0,1,2),unpack=True) #[rcore], [rcore], [km/s]

        # calculate 2D radius on the skyplane
        r = np.sqrt(x**2+y**2) #[rcore]
        
        # set maximum radius (if gpr.rprior is set)
        rmax = max(r) if gpr.rprior<0 else 1.0*gpr.rprior #[rcore]
        print 'rmax [rcore] = ', rmax
        sel = (r<=rmax)
        x = x[sel]; y = y[sel]; vlos = vlos[sel]; r = r[sel] #[rcore]
        totmass = 1.*len(x) #[munit], munit = 1/star

        rs = r
        # no offset from the start!
        # rs = gpr.rerror*np.random.randn(len(r))+r #[rcore]
        # vlos = gpr.vrerror*np.random.randn(len(vlos))+vlos #[km/s]



        print 'output: ',gpr.get_siglos_file(comp)
        vfil = open(gpr.get_siglos_file(comp),'w')
        print >> vfil,'r','sigma_r(r)','error'

        # 30 iterations for drawing a given radius in bin
        dispvelocity = np.zeros((gpr.nbins,gpr.n))
        a = np.zeros((gpr.nbins,gpr.n))
        p_dvlos = np.zeros(gpr.nbins)
        p_edvlos = np.zeros(gpr.nbins)

        for k in range(gpr.n):
            rsi = gpr.rerror*np.random.randn(len(rs))+rs #[rcore]
            vlosi = gpr.vrerror*np.random.randn(len(vlos))+vlos #[km/s]
            for i in range(gpr.nbins):
                ind1 = np.argwhere(np.logical_and(rsi>binmin[i],rsi<binmax[i])).flatten()
                a[i][k] = len(ind1) #[1]
                vlos1 = vlosi[ind1] #[km/s]
                if(len(ind1)<=1):
                    dispvelocity[i][k] = dispvelocity[i-1][k]
                    # attention! should be 0, uses last value
                else:
                    dispvelocity[i][k] = meanbiweight(vlos1,ci_perc=68.4,\
                                                      ci_mean=True,ci_std=True)[1]
                    # [km/s], see BiWeight.py

        for i in range(gpr.nbins):
            dispvel = np.sum(dispvelocity[i])/gpr.n #[km/s]
            ab = np.sum(a[i])/(1.*gpr.n) #[1]
            if ab == 0:
                dispvelerror = p_edvlos[i-1] #[km/s]
                # attention! uses last error
            else:
                dispvelerror = dispvel/np.sqrt(ab) #[km/s]
            p_dvlos[i] = dispvel      #[km/s]
            p_edvlos[i]= dispvelerror #[km/s]

        maxvlos = max(p_dvlos) #[km/s]
        print 'maxvlos = ',maxvlos,'[km/s]'
        fpars = open(gpr.get_params_file(comp),'a')
        print >> fpars,maxvlos          #[km/s]
        fpars.close()

        for i in range(gpr.nbins):
            #             [rcore]  [maxvlos]                  [maxvlos]
            print >> vfil,rbin[i], np.abs(p_dvlos[i]/maxvlos),np.abs(p_edvlos[i]/maxvlos) #/np.sqrt(n))
        vfil.close()

        if not gp.testplot_read: continue

        ion(); subplot(111)
        print 'rbin = ',rbin,' rcore'
        print 'p_dvlos = ',p_dvlos,' km/s'
        print 'p_edvlos = ',p_edvlos, 'km/s'
        plot(rbin,p_dvlos,'b',lw=1)
        fill_between(rbin,p_dvlos-p_edvlos,p_dvlos+p_edvlos,alpha=0.5,color='r') #[rcore],[km/s],[km/s]

        xlabel(r'$r [\mathrm{rcore}]$')
        ylabel(r'$\langle\sigma_{\mathrm{LOS}}\rangle [\mathrm{km/s}]$')
        ylim([-5,30])
        # xscale('log')
        xlim([np.min(rbin),np.max(rbin)])
        #plt.legend(['\rho','\rho'],'lower left'); #title(dwarf)
        savefig(gpr.get_siglos_png(comp))
        if gpr.showplots:
            ioff();show();clf()
Esempio n. 10
0
def run():
    # get radius, used for all binning
    print('input:')
    print(gpr.get_com_file(0))
    if gfile.bufcount(gpr.get_com_file(0))<2: return
    x,y,vlos = np.loadtxt(gpr.get_com_file(0), skiprows=1, unpack=True) #2*[rscale], [km/s]
    totmass = 1.*len(x)  # [munit], [Msun], where each star is weighted with the same mass
    r = np.sqrt(x*x+y*y) # [rscale]
    
    #set binning
    #gpr.nbins = (max - min)*N^(1/3)/(2*(Q3-Q1)) #(method of wand)
    rmin = 0.                                       # [rscale]
    rmax = max(r) if gpr.rprior<0 else 1.0*gpr.rprior # [rscale]
    
    if gp.lograd:
        # space logarithmically in radius
        binmin, binmax, rbin = bin_r_log(rmax/gpr.nbins, rmax, gpr.nbins)
    elif gp.consttr:
        binmin, binmax, rbin = bin_r_const_tracers(r, len(r)/gpr.nbins)
    else:
        binmin, binmax, rbin = bin_r_linear(rmin, rmax, gpr.nbins)
        
    # offset from the start!
    rs = gpr.rerror*np.random.randn(len(r))+r #[rscale]
    vlos = gpr.vrerror*np.random.randn(len(vlos))+vlos #[km/s]
    print('output: ',gpr.get_siglos_file(0))
    vfil = open(gpr.get_siglos_file(0),'w')
    print('r','sigma_r(r)','error', file=vfil)

    # 30 iterations for drawing a given radius in bin
    dispvelocity = np.zeros((gpr.nbins,gpr.n))
    a = np.zeros((gpr.nbins,gpr.n))
    p_dvlos = np.zeros(gpr.nbins)
    p_edvlos = np.zeros(gpr.nbins)
    
    for k in range(gpr.n):
        rsi = gpr.rerror*np.random.randn(len(rs))+rs #[rscale]
        vlosi = gpr.vrerror*np.random.randn(len(vlos))+vlos #[km/s]
        for i in range(gpr.nbins):
            ind1 = np.argwhere(np.logical_and(rsi>binmin[i],rsi<binmax[i])).flatten()
            a[i][k] = len(ind1) #[1]
            vlos1 = vlosi[ind1] #[km/s]
            if(len(ind1)<=1):
                dispvelocity[i][k] = dispvelocity[i-1][k]
                # attention! should be 0, uses last value
            else:
                dispvelocity[i][k] = meanbiweight(vlos1,ci_perc=68.4,\
                                                  ci_mean=True,ci_std=True)[1]
                # [km/s], see BiWeight.py
                
    for i in range(gpr.nbins):
        dispvel = np.sum(dispvelocity[i])/gpr.n #[km/s]
        ab = np.sum(a[i])/(1.*gpr.n) #[1]
        if ab == 0:
            dispvelerror = p_edvlos[i-1] #[km/s]
            # attention! uses last error
        else:
            dispvelerror = dispvel/np.sqrt(ab) #[km/s]
        p_dvlos[i] = dispvel      #[km/s]
        p_edvlos[i]= dispvelerror #[km/s]

    maxvlos = max(p_dvlos) #[km/s]
    print('maxvlos = ',maxvlos,'[km/s]')
    fpars = open(gpr.get_params_file(0),'a')
    print(maxvlos, file=fpars)          #[km/s]
    fpars.close()
    import shutil
    shutil.copy2(gpr.get_params_file(0), gpr.get_params_file(1))


    for i in range(gpr.nbins):
        #             [rscale]  [maxvlos]                  [maxvlos]
        print(rbin[i], np.abs(p_dvlos[i]/maxvlos),np.abs(p_edvlos[i]/maxvlos), file=vfil) #/np.sqrt(n))
    vfil.close()

    if not gpr.showplots: return

    ion(); subplot(111)
    print('rbin = ',rbin,' rscale')
    print('p_dvlos = ',p_dvlos,' km/s')
    print('p_edvlos = ',p_edvlos, 'km/s')
    plot(rbin,p_dvlos,'b',linewidth=3)
    fill_between(rbin,p_dvlos-p_edvlos,p_dvlos+p_edvlos,alpha=0.5,color='r') #[rscale],[km/s],[km/s]

    xlabel(r'$r [rscale]$')
    ylabel(r'$\langle\sigma_{LOS}\rangle [km/s]$')
    ylim([-5,30])
    # xscale('log')
    xlim([np.min(rbin),np.max(rbin)])
    #plt.legend(['\rho','\rho'],'lower left'); #title(dwarf)
    savefig(gpr.get_siglos_png(0))
    if gpr.showplots:
        ioff();show();clf()
Esempio n. 11
0
def run():
    print('input:',gpr.fil)
    x0, y0, z0, vx, vy, vz = np.transpose(np.loadtxt(gpr.fil))
    
    # cutting pm_i to a maximum of ntracers particles:
    from random import shuffle
    ind = np.arange(len(x0))
    np.random.shuffle(ind)
    ind = ind[:gp.files.ntracer]
    x0 = x0[ind]; y0 = y0[ind]; z0 = z0[ind]
    vx = vx[ind]; vy = vy[ind]; vz = vz[ind]
    
    # get center of mass with means
    # com_x, com_y,com_z = com_mean(x0,y0,z0,PM0) 
    # [TODO], and TODO: z component included if available
    
    # get COM with shrinking sphere method
    PM = np.ones(len(x0)) # assign all particles the full probability of membership
    com_x, com_y, com_z, com_vz = com_shrinkcircle_v(x0,y0,z0,vz,PM)
    print('COM [pc]: ', com_x, com_y, com_z)
    print('VOM [km/s]', com_vz)

    # from now on, work with 2D data only; 
    # z0 was only used to get center in (x,y) better
    
    x0 -= com_x; y0 -= com_y # [pc]
    vz -= com_vz #[km/s]
    
    R0 = np.sqrt(x0**2+y0**2) # [pc]
    Rc = R0                   # [pc]
    Rc.sort()                 # [pc]
    for i in range(len(Rc)-1):
        if Rc[i]>Rc[i+1]:               # [pc]
            print('sorting error!')
            exit(1)
    Rhalf = Rc[floor(len(Rc)/2)]        # [pc]
    Rscale = Rhalf                       # or gpr.r_DM # [pc]
    print('Rscale = ',Rscale,' pc')
    print('max(R) = ',max(Rc),' pc')
    print('last element of R : ',Rc[-1],' pc')
    print('total number of stars: ',len(Rc))
    
    x0 = x0/Rscale; y0 = y0/Rscale           # [Rscale]
    
    i = -1
    for comp in range(gp.pops+1):      # gp.pops +1 for all components together
        pmr = (R0<(gpr.rprior*Rscale)) # TODO: read from gl_class_file
        i = i+1
        m = np.ones(len(R0))
        x = x0; y = y0
        R = np.sqrt(x*x+y*y)            # [Rscale]
        
        # print("x y z" on first line, to interprete data later on)
        crscale = open(gpr.get_params_file(i),'w')
        print('# Rscale in [pc], surfdens_central (=dens0) in [munit/rscale**2], and in [munit/pc**2], and totmass [munit], and max(v_LOS) in [km/s]', file=crscale)
        print(Rscale, file=crscale)
        crscale.close()

        print('output: ',gpr.get_com_file(i))
        c = open(gpr.get_com_file(i),'w')
        print('# x [Rscale],','y [Rscale],','vLOS [km/s],','Rscale = ',Rscale,' pc', file=c)
        for k in range(len(x)):
            print(x[k], y[k], vz[k], file=c)      # [Rscale], [Rscale], [km/s]
        c.close()
        
        
        if not gpr.showplots: continue
        figure(1)
        subplot(111)
        res = (abs(x)<3)*(abs(y)<3)
        x = x[res]; y = y[res]  # [Rscale]
        en = len(x)
        if en == 0: continue
        scatter(x[:en], y[:en],\
                s=35, vmin=0.95, vmax=1.0, lw=0.0, alpha=0.2)
        # xscale('log'); yscale('log')
        circ_HL=Circle((0,0), radius=Rscale/Rscale, fc='None', ec='g', lw=1)
        circ_DM=Circle((0,0), radius=gpr.r_DM/Rscale, fc='None', ec='r', lw=1)
        gca().add_patch(circ_HL); gca().add_patch(circ_DM)
        
        # visible region
        maxr = max(np.abs(x));  mayr = max(np.abs(y)) #[rscale]
        width2 = max([maxr,mayr]) #[rscale]
        xlim([-width2,width2]); ylim([-width2,width2])
        axes().set_aspect('equal')
    
        xlabel(r'$x [R_s]$'); ylabel(r'$y [R_s]$')
        # title(gpr.fil)
        savefig(gpr.get_com_png(i))
        show(block=True)