Exemplo n.º 1
0
def make_table(field, targetSN, w1, w2):
    """ Joins tables of emission lines. """
    bins = halo_bins(field)
    data = []
    for i, bin in enumerate(bins):
        logfile = "logs_sn{0}_w{1}_{2}/emission_bin{3:04d}.txt".format(
                  targetSN, w1, w2, bin)
        with open(logfile) as f:
            content = f.readlines()
        header = [x.strip() for x in content if x.startswith("#")]
        data.append([x for x in content if not x.startswith("#")][0])
    with open("emission_sn{0}_w{1}_{2}.txt".format(targetSN,
                                                   w1, w2, bin), "w") as f:
        f.write("\n".join(header + data))
Exemplo n.º 2
0
            if j == 0:
                plt.ylabel("Flux ($10^{-20}$ erg / s / $\AA$)")
            ax.set_xlabel("$\lambda$ ($\AA$)")
            plt.legend(prop={"size":9})
            ylim =  ax.get_ylim()
            ax.set_ylim(ylim[0], 1.5*ylim[1])
            plt.locator_params(axis='x', nbins=5)
        plt.subplots_adjust(left=0.04, right=0.99, top=0.95)
        plt.savefig("logs_sn{0}_w{1}_{2}/emission_bin{3:04d}.png".format(
                     targetSN, w1, w2, bin))
###############################################################################

if __name__ == "__main__":
    targetSN = 70
    w1 = 4500
    w2 = 7000
    fwhm = 2.95
    sigma_res = fwhm / (2. * np.sqrt(2. * np.log(2.)))
    lines = (("Hbeta_4861", 4861.333), ("OIII_4959", 4958.91),
             ("OIII_5007", 5006.84), ("Halpha_6565", 6564.61),
             ("NI_5200", 5200.257), ("NII_6585", 6585.27),
             ("NII_6550", 6549.86), ("SII_6718", 6718.29),
             ("SII_6733", 6732.67))
    for field in fields:
        os.chdir(os.path.join(data_dir, "combined_{0}".format(field)))
        # prepare_residuals(field, w1, w2, targetSN, clobber=True)
        bins = halo_bins(field)
        # fit(field, targetSN, w1, w2, bins=bins, redo=False)
        # make_table(field, targetSN, w1, w2)
        prepare_table_for_map(field, targetSN, w1, w2)
        break
Exemplo n.º 3
0
def plot_rad_kinematics(targetSN, w1, w2, only_halo=False, fors2=True,
                        label="MUSE"):
    """ Plot LOSVD moments as a function of the radius. """
    ###########################################################################
    # Loading data into a single array
    cols = np.array((7,9, 11))
    for i, (sn, field) in enumerate(zip(targetSN, fields)):
        wdir = os.path.join(data_dir, "combined_{0}".format(field))
        os.chdir(wdir)
        table = "results_sn{0}_w{1}_{2}.dat".format(sn, w1, w2)
        specs = np.loadtxt(table, usecols=(0,), dtype=str)
        rr = np.loadtxt(table, usecols=(3,))
        dat = np.loadtxt(table, usecols=cols)
        err = np.loadtxt(table, usecols=cols+1)
        c = np.loadtxt(table, usecols=(4,))
        if only_halo:
            bins = np.array([int(x.split("bin")[1]) for x in specs])
            hbins = halo_bins(field)
            idx = np.in1d(bins, hbins)
            rr = rr[idx]
            dat = dat[idx]
            err = err[idx]
            c = c[idx]
        if i == 0:
            r = rr
            data = dat
            error = err
            colors = c
        else:
            r = np.hstack((r, rr))
            data = np.vstack((data, dat))
            error = np.vstack((error, err))
            colors = np.hstack((colors, c))
    ###########################################################################
    # Reading data from previous paper
    table = os.path.join(tables_dir, "Barbosa2016_lick_instr_res.dat")
    rb16 = np.loadtxt(table, usecols=(3,))
    datab16 = np.loadtxt(table, usecols=(7,9,11)).T
    errb16 = np.loadtxt(table, usecols=(8,10,12)).T
    ###########################################################################
    labels = ["$\sigma$ (km/s)", "$h_3$", "$h_4$"]
    data = data.T
    error = error.T
    os.chdir(plots_dir)
    lims = [[100, 500], [-.2, 0.2], [-.4, .4]]
    fig = plt.figure(1, figsize=(5,5))
    for i, (l, lerr, l2, l2err) in enumerate(zip(data, error, datab16, errb16)):
        ax = plt.subplot(len(cols), 1, i+1)
        ax.set_xscale("log")
        ax.errorbar(r, l, yerr=lerr, fmt="o", ecolor="0.8", zorder=0,
                    elinewidth=.5, capsize=0.5, mec="0.2", label=label,
                    markersize=5.5, c="lightskyblue", markeredgecolor="k",
                    mew=0.4)
        if fors2:
            ax.errorbar(rb16, l2, yerr=l2err, fmt="s", ecolor="0.8", zorder=0,
                        elinewidth=0.5, capsize=0.5, label="FORS2",
                        markersize=5, linewidth=0.6,
                        markeredgecolor="k", color="red", mew=0.4)
        q1, q2 = np.percentile(l, [5, 95])
        ymin = lims[i][0] if  lims[i][0] else q1 - 0.6 * np.abs(q2 - q1)
        ymax = lims[i][1] if lims[i][1] else q2 + 0.6 * np.abs(q2 - q1)
        ax.set_ylim(ymin, ymax)
        ax.set_xlim(0.1, 50)
        ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%.1f'))
        if i == len(cols)-1:
            ax.set_xlabel("R (kpc)")
        else:
            ax.xaxis.set_major_formatter(plt.NullFormatter())
        if i == 0:
            ax.legend(scatterpoints=1, prop={'size':10},
                      ncol=1, loc=2, frameon=False)
        ax.minorticks_on()
        ax.set_ylabel(labels[i])
        if i in [1,2]:
            ax.axhline(y=0, ls="--", c="k")
    plt.subplots_adjust(left=0.15, right=0.96, wspace=0.38, top=0.98,
                        hspace=0.1, bottom=0.1)
    name = "_halo" if only_halo else "all"
    forsstring = "_fors2" if fors2 else ""
    plt.savefig(os.path.join(plots_dir, "rad_losvd{0}{1}_w{2}_{3}.png".format(
        name, forsstring, w1, w2)), dpi=150)
    plt.clf()
    return
Exemplo n.º 4
0
def merge_tables(targetSN, w1, w2):
    """ Make single table containing kinematics and stellar populations. """
    for sn, field in zip(targetSN, fields):
        print "Merging {0}".format(field)
        wdir = os.path.join(data_dir, "combined_{0}".format(field))
        os.chdir(wdir)
        ######################################################################
        # Calculating geometric parameters of bins
        geom = calc_geom(sn, field)
        ######################################################################
        # Selecting tables
        kintable = "ppxf_results_sn{0}_w{1}_{2}.txt".format(sn, w1, w2)
        licktab = "lick_corr_sn{0}_w{1}_{2}.txt".format(sn, 4500, 7000)
        lickerrtab = "lick_mcerr_sn{0}_w{1}_{2}.txt".format(sn, 4500, 7000)
        magtab = "magab_w5000_6000.dat"
        # poptable = os.path.join(data_dir, "populations_chain1.txt")
        tables = [kintable, licktab, lickerrtab, magtab]
        # #####################################################################
        # Loading data in tables
        data = [np.loadtxt(x, dtype=str) for x in tables]
        # Concatenating data from geometric calculations
        data = [geom] + data
        ######################################################################
        # Aligning tables
        specs = [np.array([int(y.split("bin")[1]) for y in x[:,0]]) for x in
                 data]
        ref = intersect_n_arrays(specs)
        idx = [np.searchsorted(x, ref) for x in specs]
        data = [d[i] for (i,d) in zip(idx,data)]
        #######################################################################
        # Interwine Lick indices and errors
        lick = np.insert(data[3], np.arange(len(data[2][0])), data[2], axis=1)
        data[2] = lick[:,1:]
        del data[3]
        #######################################################################
        combined = []
        for i in range(len(data)):
            if i == 0:
                combined = data[i]
            else:
                combined = np.column_stack((combined, data[i][:,1:]))
        ####################################################################
        # Including boolean indication if bin is part of halo or not
        inhalo = np.in1d(ref, halo_bins(field)).astype(int)
        combined = np.column_stack((combined, inhalo))
        # Making headers
        header = ["Spectrum", "X(kpc)", "Y(kpc)", "R(kpc)", "PA(degree)", 'V',
                  'V_err', 'Sigma', 'Sigma_err', 'h3',
                  'h3_err', 'h4', 'h4_err', 'chi/DOF', 'S/N/Angstrom',
                  'adegree', 'mdegree']
        indices = np.loadtxt(os.path.join(tables_dir, "bands.txt"),
                             usecols=(0,), dtype=str)
        err = ["{0}_err".format(x) for x in indices]
        indices = np.insert(err, np.arange(25), indices)

        header += indices.tolist()
        header += ["mag_ab", "mag_V"]
        header += ["is_halo"]
        # header += ["Age", "LERR", "UERR", "[Z/H]", "LERR", "UERR", "[alpha]/Fe",
        #           "LERR", "UERR"]
        # header += ["RAJ2000", "DECJ2000"]
        header = ["# ({0}) {1}".format(i,h) for i,h in enumerate(header)]
        # #####################################################################
        filename = os.path.join(wdir, "results_sn{0}_w{1}_{2}.dat".format(
                   sn, w1, w2))
        with open(filename, "w") as f:
            f.write("\n".join(header) + "\n")
            np.savetxt(f, combined, fmt="%s")
    return
Exemplo n.º 5
0
def plot_rad_lick(targetSN, w1, w2, only_halo=True, fors2=True):
    """ Plot Lick indices as a function of the radius. """
    ###########################################################################
    # Loading data into a single array
    for i, (sn, field) in enumerate(zip(targetSN, fields)):
        wdir = os.path.join(data_dir, "combined_{0}".format(field))
        os.chdir(wdir)
        table = "results_sn{0}_w{1}_{2}.dat".format(sn, w1, w2)
        specs = np.loadtxt(table, usecols=(0,), dtype=str)
        rr = np.loadtxt(table, usecols=(3,))
        l = np.loadtxt(table, usecols=np.arange(41,64,2))
        le = np.loadtxt(table, usecols=np.arange(42,65,2))
        c = np.ones_like(rr) * i
        if only_halo:
            bins = np.array([int(x.split("bin")[1]) for x in specs])
            hbins = halo_bins(field)
            idx = np.in1d(bins, hbins)
            rr = rr[idx]
            l = l[idx]
            le = le[idx]
            c = np.ones_like(rr) * i
        if i == 0:
            r = rr
            lick = l
            lickerr = le
            colors = c
        else:
            r = np.hstack((r, rr))
            lick = np.vstack((lick, l))
            lickerr = np.vstack((lickerr, le))
            colors = np.hstack((colors, c))
    ###########################################################################
    # Reading data from previous paper
    table = os.path.join(tables_dir, "Barbosa2016_lick_instr_res.dat")
    rb16 = np.loadtxt(table, usecols=(3,))
    lb16 = np.loadtxt(table, usecols=np.arange(39,62,2)).T
    lb16err = np.loadtxt(table, usecols=np.arange(40,63,2)).T
    ###########################################################################
    indices = np.loadtxt(os.path.join(tables_dir, "bands.txt"), usecols=(0,),
                         dtype="S16")
    for i, index in enumerate(indices):
        if "_" in index:
            indices[i] = index.replace("_", "$_").replace("_beta", r"\beta") \
                         + "$"
    mag = "(mag)"
    ang = "($\AA$)"
    units = np.array([ang, ang, mag, mag, ang, ang, ang, ang, ang, ang, ang,
            ang, ang, ang, mag, mag, ang, ang, ang, ang, ang, ang, ang, mag,
            mag])
    indices = ["{0} {1}".format(x,y) for x,y in zip(indices, units)]
    indices = indices[12:]
    lick = lick.T
    lickerr = lickerr.T
    os.chdir(plots_dir)
    fig = plt.figure(1, figsize=(10,6))
    cmap = "YlGnBu_r"
    for i, (l, lerr, l2, l2err) in enumerate(zip(lick, lickerr, lb16, lb16err)):
        ax = plt.subplot(4, 3, i+1)
        ax.set_xscale("log")
        ax.errorbar(r, l, yerr=lerr, fmt=None, ecolor="0.8", zorder=0,
                    elinewidth=.5, capsize=0.5)
        if not only_halo:
            ax.errorbar(rb16, l2, yerr=l2err, fmt=None, ecolor="0.8", zorder=0,
                        elinewidth=0.5, capsize=0.5)
        ax.scatter(r, l, c=colors, s=15, zorder=1, cmap=cmap, vmin=-0.5,
                   linewidths=0.2)
        if fors2:
            ax.scatter(rb16, l2, c="r", s=10, zorder=1, marker="s",
                        linewidths=0.2)
        q1, q2 = np.percentile(l, [2, 98])
        ax.set_ylim(q1 - 1.2 * np.abs(q2 - q1), q2 + 1.2 * np.abs(q2 - q1) )
        ax.set_xlim(0.1, 50)
        if i > 8:
            ax.set_xlabel("R (kpc)")
        else:
            ax.xaxis.set_major_formatter(plt.NullFormatter())
        if i == 0:
            for c, field in zip([0, 0.33, 0.66, 1.], fields):
                ax.scatter(1000, 1000, c=cm.get_cmap(cmap)(c), s=15, zorder=1,
                           cmap=cmap, vmin=-0.5, linewidths=0.2,
                           label="Field {0}".format(field[-1]))
            ax.legend(scatterpoints=1, prop={'size':6},
                      ncol=2, loc=2)
        ax.minorticks_on()
        ax.set_ylabel(indices[i])
    plt.subplots_adjust(left=0.08, right=0.98, wspace=0.38, top=0.98,
                        hspace=0.13)
    name = "halo" if only_halo else "all"
    forsstr = "_fors2" if fors2 else ""
    plt.savefig(os.path.join(plots_dir, "rlick_{0}{1}.png".format(name,
                                                                  forsstr)),
                dpi=200)
    return