Exemplo n.º 1
0
def get_max_prob_2(params,
                   parameters):  #should be combined with get_max_prob()
    mu_min, mu_max, mu_steps = params.mu_lim
    nu_min, nu_max, nu_steps = params.nu_lim
    r_min, r_max, r_steps = params.r_lim
    total_steps = ((mu_steps - 1) * (nu_steps - 1) * (r_steps - 1))
    Dmu = (mu_max - mu_min) / mu_steps
    Dnu = (nu_max - nu_min) / nu_steps
    Dr = (r_max - r_min) / r_steps
    print("Finding maximum probability of perturbation function,", total_steps,
          "steps")
    max_rho, count, progress = 0.0, 0, 0
    # Get value at center of each bin, so steps is one less than input number
    r = r_min + (Dr / 2.0)
    for i in range(r_steps - 1):
        mu = mu_min + (Dmu / 2.0)
        for j in range(mu_steps - 1):
            nu = nu_min + (Dnu / 2.0)
            for k in range(nu_steps - 1):
                x, y, z = co.GC2xyz(mu, nu, r, params.wedge)
                rho = perturb_density(x, y, z, parameters)  #Only change!!!
                if rho > max_rho:
                    max_rho = rho
                nu = nu + Dnu
                count = count + 1
                if count % (total_steps / 10) == 0:
                    print("Progress: ", progress, "percent searched")
                    progress = progress + 10
            mu = mu + Dmu
        r = r + Dr
    return max_rho
Exemplo n.º 2
0
def rough3d_integrator(params):  #q, r0, mu_lim, nu_lim, r_lim):
    """ lims are (min, max, N_steps) """
    mu_min, mu_max, mu_steps = params.mu_lim
    nu_min, nu_max, nu_steps = params.nu_lim
    r_min, r_max, r_steps = params.r_lim
    total_steps = ((mu_steps - 1) * (nu_steps - 1) * (r_steps - 1))
    Dmu = (mu_max - mu_min) / mu_steps
    Dnu = (nu_max - nu_min) / nu_steps
    Dr = (r_max - r_min) / r_steps
    print("Integrating function,", total_steps, "steps")
    integral, count, progress = 0.0, 0, 0
    # Integrate from value at center of each bin, so steps is one less than input number
    r = r_min + (Dr / 2.0)
    for i in range(r_steps - 1):
        mu = mu_min + (Dmu / 2.0)
        for j in range(mu_steps - 1):
            nu = nu_min + (Dnu / 2.0)
            for k in range(nu_steps - 1):
                #print mu, nu, r
                x, y, z = co.GC2xyz(mu, nu, r, params.wedge)
                rho = hernquist_profile(x, y, z, params.q, params.r0)
                dV = r * r * sc.cos(nu) * Dmu * Dnu * Dr
                integral = integral + rho * dV
                nu = nu + Dnu
                count = count + 1
                if count % (total_steps / 20) == 0:
                    print("Progress: ", progress, "percent complete")
                    progress = progress + 5
            mu = mu + Dmu
        r = r + Dr
    return integral
Exemplo n.º 3
0
def get_max_prob(params):
    print("Background Parameters:", params.q, params.r0)
    mu_min, mu_max, mu_steps = params.mu_lim
    nu_min, nu_max, nu_steps = params.nu_lim
    r_min, r_max, r_steps = params.r_lim
    total_steps = ((mu_steps - 1) * (nu_steps - 1) * (r_steps - 1))
    Dmu = (mu_max - mu_min) / mu_steps
    Dnu = (nu_max - nu_min) / nu_steps
    Dr = (r_max - r_min) / r_steps
    print("Integrating function,", total_steps, "steps")
    max_rho, count, progress = 0.0, 0, 0
    # Integrate from value at center of each bin, so steps is one less than input number
    r = r_min + (Dr / 2.0)
    for i in range(r_steps - 1):
        mu = mu_min + (Dmu / 2.0)
        for j in range(mu_steps - 1):
            nu = nu_min + (Dnu / 2.0)
            for k in range(nu_steps - 1):
                x, y, z = co.GC2xyz(mu, nu, r, params.wedge)
                rho = hernquist_profile(x, y, z, params.q, params.r0)
                if rho > max_rho:
                    max_rho = rho
                nu = nu + Dnu
                count = count + 1
                if count % (total_steps / 10) == 0:
                    print("Progress: ", progress, "percent searched")
                    progress = progress + 10
            mu = mu + Dmu
        r = r + Dr
    return max_rho
Exemplo n.º 4
0
def generate_perturbation(num_stars,
                          params,
                          parameters,
                          batch=1000,
                          fail_quit=100,
                          fileout="Pertgen82.txt",
                          detection=1,
                          convolve=1,
                          append=0,
                          primary=0):
    """Density of perturbation added to background, as a function of position"""
    # Initialize file
    if append == 0:
        out = open(fileout, 'w')
        out.write("# " + str(num_stars) + " stars, l,b,r \n")
        out.close()
    # Get integral
    tot_prob = get_max_prob_2(params, parameters)
    N_out, fails = 0, 0
    g_min, g_max = params.stripe[2][0], params.stripe[2][1]
    while N_out < num_stars:
        # Generate Points
        mu, nu, r = get_stripe_points(params.mu_lim, params.nu_lim,
                                      params.r_lim, batch)
        # Test points for inclusion
        x, y, z = co.GC2xyz(mu, nu, r, params.wedge)
        holder = []
        for i in range(len(mu)):
            rho = perturb_density(x[i], y[i], z[i], parameters)
            #print (rho / tot_prob), rho, tot_prob
            if (rho / tot_prob) > np.random.uniform():
                l, b, r1 = co.xyz2lbr(x[i], y[i], z[i])
                # Convolve
                if convolve == 1:
                    r1 = star_convolution(r1, params.modfit)
                # Detection
                if detection == 1:
                    m_g = co.getg(r1)
                    if np.random.uniform() > sigmoid_error(m_g, params.modfit):
                        continue
                if (co.getg(r1) < g_min) or (co.getg(r1) > g_max): continue
                if primary == 1:
                    if co.SDSS_primary(l, b, wedge, fmt='lb', low=9,
                                       high=25) == 0:
                        continue
                # Add to keepers
                holder.append([round(l, 6), round(b, 6), round(r1, 6)])
                N_out = N_out + 1
        # Failure code
        if len(holder) == 0: fails = fails + 1
        if fails >= fail_quit: break
        # Remove possible excess stars
        if N_out > num_stars:
            slice = -1 * (N_out - num_stars)
            holder = holder[:slice]
            print("#---Sliced {0} stars to make quota".format(str(-1 * slice)))
            N_out = N_out + slice  #Slice is negative
        # Add to dataset
        if len(holder) != 0:
            if fi.append_data(sc.array(holder), fileout, delimiter=" ") == 1:
                print(
                    "#---Perturbation Progress: {0} stars of {1} total stars generated"
                    .format(N_out, num_stars))
    if fails >= fail_quit:
        print(
            "!!! Perturbation generation FAILED due to overstepping empty batch limit: {0}"
            .format(fail_quit))
    else:
        print(
            "#---Perturbation generation succeeded, written as {0}, with {1} empty batches"
            .format(fileout, fails))
    return fileout
Exemplo n.º 5
0
def do_compare_wedges(file1="stars-82.txt",
                      file2="Stripe82_coadd.csv",
                      stripe=82,
                      hern=0):
    """ Modify if size is not 1.0 """
    one_run = fi.read_data(file1)
    or_l = len(one_run[:, 0])
    or_hist = plot_wedge_density(one_run,
                                 stripe,
                                 q=0.458,
                                 r0=19.4,
                                 streams=None,
                                 perturb=None,
                                 name="_rho1",
                                 mag=0,
                                 plot=0)
    coadd = fi.read_data(file2)
    ca_l = len(coadd[:, 0])
    ca_hist = plot_wedge_density(coadd,
                                 stripe,
                                 q=0.458,
                                 r0=19.4,
                                 streams=None,
                                 perturb=None,
                                 name="_rho2",
                                 mag=0,
                                 plot=0)
    # Separate into heights
    #print or_hist[:,0]
    #print ca_hist[:,0]
    or_h = or_hist[:, 1]
    ca_h = ca_hist[:, 1]
    if hern == 1:
        # Get Hernquist profile
        mu_avg = ((419.0 - 310.0) / 2.0) + 310.0
        nu_avg = 0.0
        sol_r = sc.arange((np.ma.min(ca_hist[:, 0]) + 0.5),
                          (np.ma.max(ca_hist[:, 0]) + 1.5), (1.0))
        x, y, z = coor.GC2xyz(mu_avg, nu_avg, sol_r, 82)
        Hern_rho = twg.hernquist_profile(x, y, z, q=0.458, r0=19.4)
        H_scale = sc.ma.max(Hern_rho)
        for i in range(len(Hern_rho)):
            Hern_rho[i] = Hern_rho[i] / H_scale
        for i in range(len(or_h)):
            or_h[i] = or_h[i] / Hern_rho[i]
        norm = sc.ma.max(ca_h)
        for i in range(len(ca_h)):
            ca_h[i] = ca_h[i] / Hern_rho[i]
        # Differentiate the bins
        if len(or_h) > len(ca_h): l = len(or_h)
        else: l = len(ca_h)
        diff_h = sc.zeros(l)
        for i in range(len(or_h)):
            diff_h[i] = diff_h[i] + or_h[i]
        for i in range(len(ca_h)):
            diff_h[i] = diff_h[i] - ca_h[i]
    else:
        # Divide the first data set by the second
        if len(or_h) < len(ca_h):
            l = len(or_h)
            extra_h = -0.1 * sc.ones((len(ca_h) - l))
        else:
            l = len(ca_h)
            extra_h = 0.1 * sc.ones((len(or_h) - l))
        diff_h = sc.zeros(l)
        for i in range(l):
            #diff_h[i] = ( (or_h[i]/or_l) / (ca_h[i]/ca_l) ) - 1.0
            diff_h[i] = (or_h[i] / ca_h[i]) - 1.0
    #Make plot
    fig = plt.figure()
    #plt.bar(ca_hist[:,0], ca_hist[:,1], 1.0, fill=None, ec="b")
    #plt.bar(or_hist[:,0], or_hist[:,1], 1.0, fill=None, ec="r")
    #plt.ylabel(r'$\rho$ (stars/kpc)')
    plt.bar(ca_hist[:l, 0], diff_h, 1.0)
    if hern != 1:
        #plt.bar(ca_hist[l:,0], extra_h, 1.0, ec="r", fill=None)
        plt.plot([np.ma.min(ca_hist[:, 0]),
                  np.ma.max(ca_hist[:, 0])], [0.0, 0.0], "k:")
    plt.xlabel(r'Sun-centered $r$ (kpc)')
    plt.ylabel(r'$(\rho_{unmatched} / \rho_{matched}) - 1.0$ (stars/kpc)')
    #plt.savefig(("diff.ps"), papertype='letter')
    plt.show()
    plt.close('all')
Exemplo n.º 6
0
def plot_wedge_density(data,
                       wedge=82,
                       q=0.458,
                       r0=19.5,
                       mu_min=310.0,
                       mu_max=419.0,
                       streams=None,
                       perturb=None,
                       name="out",
                       mag=0,
                       plot=1,
                       size=1.0):
    """Plots the average density of a wedge versus radius
    stream coords. should be a list of streams, with each sub-list being a
    standard 6-parameter set of stream parameters; perturb is weight of
    perturbation, if any;  mag is whether data is in g magnitudes or not.
    CURRENTLY ONLY WORKS (WELL) FOR STRIPE 82!!!"""
    #Get Average Density with r
    x, y, z = coor.lbr2xyz(data[:, 0], data[:, 1], data[:, 2])
    if mag == 1: r = coor.getr(data[:, 2])
    else: r = data[:, 2]
    max, min = np.ma.max(r), np.ma.min(r)
    bins = int((max - min + 1.0) / size)
    rho_raw = sc.zeros(bins, int)
    for i in range(len(r)):
        index = int((r[i] - min) / size)
        rho_raw[index] = rho_raw[index] + 1
    # get volume at each distance
    #mu_min, mu_max = 310.0, 419.0  #Defined in def inputs
    nu_min, nu_max = (-1.25 * ma.pi / 180.0), (1.25 * ma.pi / 180.0)
    mu_bit = mu_max - mu_min
    nu_bit = sc.sin(nu_max) - sc.sin(nu_min)
    V = sc.zeros(bins, float)
    for i in range(bins):
        r_bit = (min + (i + 1) * size)**3 - (min + i * size)**3
        V[i] = r_bit * (1. / 3.) * mu_bit * nu_bit
    # make the histogram of rho(r)
    rho_hist = sc.zeros((bins, 3), float)
    for i in range(bins):
        rho_hist[i, 0] = min + (i * size)
        rho_hist[i, 1] = rho_raw[i] / V[i]
        rho_hist[i, 2] = (ma.sqrt(rho_raw[i] + 1.0) + 1.0) / V[i]
    """Plot Herquist, stream, perturbation functions over histogram"""
    #get gal-centered herquist distribution for r points in wedge
    mu_avg = ((mu_max - mu_min) / 2.0) + mu_min
    nu_avg = 0.0
    sol_r = sc.arange(min, max, size)
    x, y, z = coor.GC2xyz(mu_avg, nu_avg, sol_r, wedge)
    Hern_rho = twg.hernquist_profile(x, y, z, q, r0)
    H_scale = sc.sum(rho_hist[:, 1]) / sc.sum(
        Hern_rho)  #multiply a factor of 2 to account for different # of bins
    for i in range(len(Hern_rho)):
        Hern_rho[i] = Hern_rho[i] * H_scale
    # DO STREAM!!!
    ################
    #get gal-centered perturbation distribution for r points in wedge
    if perturb != None:
        perturb_rho = twg.perturb_density(x, y, z, (0.0, 0.79, -19.9))
        p_scale = 1.0
        for i in range(len(perturb_rho)):
            perturb_rho[i] = perturb_rho[i] * p_scale
    #Plot it all
    if plot == 1:
        fig = plt.figure()
        plt.bar(rho_hist[:, 0], (rho_hist[:, 1] / Hern_rho) - 1.0, size)
        #plt.plot(sol_r, Hern_rho, c='r')
        if perturb != None:
            plt.plot(sol_r, perturb_rho, c='r')
        plt.xlabel(r'Sun-centered $r$ (kpc)')
        plt.ylabel(r'$\rho$ (stars/kpc)')
        #plt.savefig((name+".ps"), papertype='letter')
        plt.show()
        plt.close('all')
    return rho_hist
Exemplo n.º 7
0
def sgr_xyz_plots(stripes, params):
    """ Plots stream positions & directions in galactic XYZ"""
    positions = sc.zeros((len(stripes), 3))
    vectors = sc.zeros((len(stripes), 3))
    for i, stripe in enumerate(stripes):
        positions[i, 0], positions[i, 1], positions[i, 2] = coor.GC2xyz(
            eval(params[i][4]), 0.0, eval(params[i][5]), stripe)
        if stripe == 9 or stripe == 22 or stripe == 82:
            theta, phi = (ma.pi - eval(params[i][6])), (eval(params[i][7]) +
                                                        ma.pi)
        else:
            theta, phi = eval(params[i][6]), eval(params[i][7])
        theta, phi = coor.angle_bounds3(theta * deg, phi * deg, phi_max=180.0)
        theta, phi = theta * rad, phi * rad
        print stripe, theta, phi
        vectors[i, 0] = ma.sin(theta) * ma.cos(phi)
        vectors[i, 1] = ma.sin(theta) * ma.sin(phi)
        vectors[i, 2] = ma.cos(theta)
    off = 1.0
    """ Plot xy """
    plt.figure(1)
    #ax = plt.subplot(111)
    plt.scatter(GC[0],
                GC[1],
                s=40,
                edgecolor="k",
                marker="o",
                facecolor="black")
    plt.text(GC[0] + off, GC[1] + off, "GC", fontsize=10)
    plt.scatter(sun[0],
                sun[1],
                s=20,
                edgecolor="k",
                marker=(8, 2, 0),
                facecolor="white")
    plt.text(sun[0] + off, sun[1] + off, "Sun", fontsize=10)
    plt.scatter(Sgr[0],
                Sgr[1],
                s=20,
                edgecolor="k",
                marker="o",
                facecolor="black")
    plt.text(Sgr[0] + off, Sgr[1] + off, "Sgr Core", fontsize=10)
    t = sc.arange(0.0, 2.0 * ma.pi, 0.01)
    plt.plot(30.0 * sc.cos(t), 30.0 * sc.sin(t), "k:")
    offset_x = [
        0.0, 0.0, 0.0, -1.0, -2.0, -1.0, -1.0, 0.0, 0.0, 0.0, -1.0, -2.0, -3.2,
        -3.0, 0.5, 0.0, 0.0, -1.0
    ]
    offset_y = [
        0.0, 0.0, -1.0, -1.9, 0.2, 0.5, 0.5, -1.0, -2.0, -3.0, -3.0, -2.9,
        -2.5, 0.5, 0.5, -2.0, -2.0, -2.25
    ]
    for i in range(len(stripes)):
        #plt.annotate(str(stripes[i]), xy=(positions[i,0], positions[i,1]),
        #            xytext=( (positions[i,0]+(vectors[i,0]*100.0)), (positions[i,1]+(vectors[i,1]*100.0)) ),
        #            arrowprops=dict(facecolor='black', arrowstyle="->") )
        if stripes[i] < 75: color = 'white'
        else: color = 'black'
        plt.arrow(positions[i, 0],
                  positions[i, 1],
                  vectors[i, 0] * 10.0,
                  vectors[i, 1] * 10.0,
                  width=0.20,
                  head_width=1.5,
                  facecolor=color)
        if stripes[i] < 20 or stripes[i] > 19:
            plt.text(positions[i, 0] + offset_x[i],
                     positions[i, 1] + offset_y[i],
                     r"$" + str(stripes[i]) + r"$",
                     fontsize=10)
    plt.xlabel(r"$X_{GC}$ (kpc)")
    plt.ylabel(r"$Y_{GC}$ (kpc)")
    plt.axis('equal')
    plt.ylim(-30, 30)
    plt.xlim(-30, 30)
    locs, labels = plt.xticks()
    for i in range(len(labels)):
        labels[i] = r"$" + str(locs[i]) + r"$"
    plt.xticks(locs, labels, fontsize=12)
    locs, labels = plt.yticks()
    for i in range(len(labels)):
        labels[i] = r"$" + str(locs[i]) + r"$"
    plt.yticks(locs, labels, fontsize=12)
    """ Plot xz """
    plt.figure(2)
    #ax = plt.subplot(111)
    plt.scatter(GC[0],
                GC[2],
                s=40,
                edgecolor="k",
                marker="o",
                facecolor="black")
    plt.text(GC[0] + off, GC[2] + off, r"GC", fontsize=10)
    plt.scatter(sun[0],
                sun[2],
                s=20,
                edgecolor="k",
                marker=(8, 2, 0),
                facecolor="white")
    plt.text(sun[0] + off, sun[2] + off, "Sun", fontsize=10)
    plt.scatter(Sgr[0],
                Sgr[2],
                s=20,
                edgecolor="k",
                marker="o",
                facecolor="black")
    plt.text(Sgr[0] + off, Sgr[2] + off, "Sgr Core", fontsize=10)
    plt.plot([-30.0, 30.0], [0.0, 0.0], "k:")
    offset_x = [
        0.2, 0.0, 0.0, -0.2, 0.0, 0.0, 0.0, -0.5, 1.0, 1.0, 0.5, 0.75, 0.0,
        0.0, 0.5, 0.0, 0.0, 0.0
    ]
    offset_z = [
        0.0, 0.0, 0.0, -2.5, 0.0, 0.0, -2.0, 0.5, -1.0, -1.0, 0.25, -1.0, -0.5,
        0.0, -0.5, 0.0, 0.5, 0.5
    ]
    for i in range(len(stripes)):
        #plt.annotate(str(stripes[i]), xytext=(positions[i,0], positions[i,2]),
        #            xy=( (positions[i,0]+(vectors[i,0]*10.0)), (positions[i,2]+(vectors[i,2]*10.0)) ),
        #            arrowprops=dict(facecolor='black', arrowstyle="->") )
        if stripes[i] < 75: color = 'white'
        else: color = 'black'
        plt.arrow(positions[i, 0],
                  positions[i, 2],
                  vectors[i, 0] * 10.0,
                  vectors[i, 2] * 10.0,
                  width=0.25,
                  head_width=2.0,
                  facecolor=color)
        if stripes[i] < 20 or stripes[i] > 19:
            plt.text(positions[i, 0] + offset_x[i],
                     positions[i, 2] + offset_z[i],
                     r"$" + str(stripes[i]) + r"$",
                     fontsize=10)
    plt.xlabel(r"$X_{GC}$ (kpc)")
    plt.ylabel(r"$Z_{GC}$ (kpc)")
    plt.axis('equal')
    plt.xlim(-45, 45)
    plt.ylim(-40, 50)
    locs, labels = plt.xticks()
    for i in range(len(labels)):
        labels[i] = r"$" + str(locs[i]) + r"$"
    plt.xticks(locs, labels, fontsize=12)
    locs, labels = sc.arange(-40.0, 50.0, 20.0), []
    for i in range(len(locs)):
        labels.append(r"$" + str(locs[i]) + r"$")
    plt.yticks(locs, labels, fontsize=12)
    # done
    plt.show()