Beispiel #1
0
def main():

    # commandline parser
    parser = initialize_parser()
    args = parser.parse_args()

    # read an observed spectrum
    # read in the observed spectrum
    # assumed to be astropy table compatibile and include units
    specfile = args.spectrumfile
    outputname = specfile.split(".")[0]
    if not os.path.isfile(specfile):
        pack_path = pkg_resources.resource_filename("pahfit", "data/")
        test_specfile = "{}/{}".format(pack_path, specfile)
        if os.path.isfile(test_specfile):
            specfile = test_specfile
        else:
            raise ValueError("Input spectrumfile {} not found".format(specfile))

    # get the table format (from extension of filename)
    tformat = specfile.split(".")[-1]
    if tformat == "ecsv":
        tformat = "ascii.ecsv"
    obs_spectrum = Table.read(specfile, format=tformat)
    obs_x = obs_spectrum["wavelength"].to(u.micron, equivalencies=u.spectral())
    obs_y = obs_spectrum["flux"].to(u.Jy, equivalencies=u.spectral_density(obs_x))
    obs_unc = obs_spectrum["sigma"].to(u.Jy, equivalencies=u.spectral_density(obs_x))

    # strip units as the observed spectrum is in the internal units
    obs_x = obs_x.value
    obs_y = obs_y.value

    # read in the PAHFIT results
    pmodel = PAHFITBase(obs_x, obs_y, filename=args.fitfilename)

    # plot result
    fontsize = 18
    font = {"size": fontsize}
    mpl.rc("font", **font)
    mpl.rc("lines", linewidth=2)
    mpl.rc("axes", linewidth=2)
    mpl.rc("xtick.major", size=5, width=1)
    mpl.rc("ytick.major", size=5, width=1)
    mpl.rc("xtick.minor", size=3, width=1)
    mpl.rc("ytick.minor", size=3, width=1)

    fig, axs = plt.subplots(ncols=1, nrows=2, figsize=(15, 10),
                            gridspec_kw={'height_ratios': [3, 1]},
                            sharex=True)

    pmodel.plot(axs, obs_x, obs_y, obs_unc.value, pmodel.model, scalefac_resid=args.scalefac_resid)

    # use the whitespace better
    fig.subplots_adjust(hspace=0)

    # show or save
    if args.savefig:
        fig.savefig("{}.{}".format(outputname, args.savefig))
    else:
        plt.show()
Beispiel #2
0
def initialize_trimmed_model(packfile, obsdata):
    """
    Initialize a model based on the packfile, ignoring components outside of the wavelength range.

    Parameters
    ----------
    packfile : string
        file with the PAHFIT pack information

    obsdata : dict
        observed data where x = wavelength, y = SED, and unc = uncertainties

    Returns
    -------
    pmodel: PAHFITBase model
        PAHFIT model based on trimmed science pack table

    """
    # read in and edit the table before we parse it
    packfile_found = find_packfile(packfile)
    t = Table.read(packfile_found, format="ipac")

    # determine wavelength range
    w = obsdata["x"].value
    wmin = np.amin(w)
    wmax = np.amax(w)

    # decide which rows we are going to keep
    keep_row = np.full(len(t), True)

    # Only keep drudes and gauss with center within 1 FWHM
    is_drude_or_gauss = np.logical_or(t["Form"] == "Drude1D",
                                      t["Form"] == "Gaussian1D")
    x0 = t[is_drude_or_gauss]["x_0"]
    fwhm = t[is_drude_or_gauss]["fwhm"]
    keep_row[is_drude_or_gauss] = np.logical_and(wmin < x0 + fwhm,
                                                 x0 - fwhm < wmax)

    # now parse the trimmed table
    print("Keeping these rows")
    print(t[keep_row])
    param_info = PAHFITBase.parse_table(t[keep_row])

    # and create a new model (and don't pass a file name, so that the
    # current contents of param_info are used)
    trimmed_model = PAHFITBase(
        obsdata["x"].value,
        obsdata["y"].value,
        estimate_start=True,
        param_info=param_info,
    )
    return trimmed_model
Beispiel #3
0
def test_classic_pack():
    # first use the static code to generate the feature dictonaries
    # instrument pack
    spitzer_sl_ll_pack = InstPackSpitzerIRSSLLL()
    # science pack
    sci_pack = SciPackExGal(spitzer_sl_ll_pack)
    oparam_info = (sci_pack.bb_info, sci_pack.dust_features,
                   sci_pack.h2_features, sci_pack.ion_features,
                   sci_pack.att_info)

    # now read in the equivalent info from a file
    path_packs = pkg_resources.resource_filename('pahfit', 'packs/')
    packfilename = '{}/scipack_ExGal_SpitzerIRSSLLL.ipac'.format(path_packs)
    path_data = pkg_resources.resource_filename('pahfit', 'data/')
    datafilename = '{}/M101_Nucleus_irs.ipac'.format(path_data)

    obs_spectrum = Table.read(datafilename, format='ipac')
    obs_x = obs_spectrum['wavelength'].to(u.micron,
                                          equivalencies=u.spectral())
    obs_y = obs_spectrum['flux'].to(u.Jy,
                                    equivalencies=u.spectral_density(obs_x))

    pmodel = PAHFITBase(obs_x.value, obs_y.value, filename=packfilename, tformat='ipac')
    # read in the file and get the param_info
    nparam_info = pmodel.read(packfilename, tformat='ipac')

    # check the different dictonaries are equivalent
    for k in range(len(oparam_info)):
        for ckey in oparam_info[k].keys():
            if isinstance(oparam_info[k][ckey][0], tuple):
                # loop over each tuple and test
                # complicated as tuple and has None values
                assert len(oparam_info[k][ckey]) == len(nparam_info[k][ckey])
                for i in range(len(oparam_info[k][ckey])):
                    o1, o2 = oparam_info[k][ckey][i]
                    n1, n2 = nparam_info[k][ckey][i]
                    if (o1 is not None) and (n1 is not None):
                        np.testing.assert_allclose(o1, n1)
                    else:
                        assert o1 == n1
                    if (o2 is not None) and (n2 is not None):
                        np.testing.assert_allclose(o2, n2)
                    else:
                        assert o2 == n2
            elif isinstance(oparam_info[k][ckey][0], float):
                np.testing.assert_allclose(oparam_info[k][ckey],
                                           nparam_info[k][ckey])
            else:
                np.testing.assert_equal(oparam_info[k][ckey],
                                        nparam_info[k][ckey])
Beispiel #4
0
def initialize_model(packfile, obsdata, estimate_start=False):
    """
    Initialize a model based on the packfile

    Parameters
    ----------
    packfile : string
        file with the PAHFIT pack information

    obsdata : dict
        observed data where x = wavelength, y = SED, and unc = uncertainties

    estimate_start : boolean
        estimate the starting parameters based on the observed data

    Returns
    -------
    pmodel : PAHFITBase model
        PAHFIT model
    """

    packfile_found = find_packfile(packfile)

    pmodel = PAHFITBase(
        obsdata["x"].value,
        obsdata["y"].value,
        estimate_start=estimate_start,
        filename=packfile_found,
    )

    return pmodel
Beispiel #5
0
def initialize_model(packfile, obsdata, estimate_start=False):
    """
    Initialize a model based on the packfile

    Parameters
    ----------
    packfile : string
        file with the PAHFIT pack information

    obsdata : dict
        observed data where x = wavelength, y = SED, and unc = uncertainties

    estimate_start : boolean
        estimate the starting parameters based on the observed data

    Returns
    -------
    pmodel : PAHFITBase model
        PAHFIT model
    """

    # read in the pack file
    if not os.path.isfile(packfile):
        pack_path = pkg_resources.resource_filename("pahfit", "packs/")
        test_packfile = "{}/{}".format(pack_path, packfile)
        if os.path.isfile(test_packfile):
            packfile = test_packfile
        else:
            raise ValueError("Input packfile {} not found".format(packfile))

    pmodel = PAHFITBase(
        obsdata["x"].value,
        obsdata["y"].value,
        estimate_start=estimate_start,
        filename=packfile,
    )

    return pmodel
Beispiel #6
0
def main():

    # setup and parse the command line
    parser = initialize_parser()
    args = parser.parse_args()

    # read in the observed spectrum
    # assumed to be astropy table compatibile and include units
    specfile = args.spectrumfile
    outputname = specfile.split(".")[0]
    if not os.path.isfile(specfile):
        pack_path = pkg_resources.resource_filename("pahfit", "data/")
        test_specfile = "{}/{}".format(pack_path, specfile)
        if os.path.isfile(test_specfile):
            specfile = test_specfile
        else:
            raise ValueError(
                "Input spectrumfile {} not found".format(specfile))

    # get the table format (from extension of filename)
    tformat = specfile.split(".")[-1]
    if tformat == "ecsv":
        tformat = "ascii.ecsv"
    obs_spectrum = Table.read(specfile, format=tformat)
    obs_x = obs_spectrum["wavelength"].to(u.micron, equivalencies=u.spectral())
    obs_y = obs_spectrum["flux"].to(u.Jy,
                                    equivalencies=u.spectral_density(obs_x))
    obs_unc = obs_spectrum["sigma"].to(u.Jy,
                                       equivalencies=u.spectral_density(obs_x))

    # strip units as the observed spectrum is in the internal units
    obs_x = obs_x.value
    obs_y = obs_y.value
    weights = 1.0 / obs_unc.value

    # read in the pack file
    packfile = args.packfile
    if not os.path.isfile(packfile):
        pack_path = pkg_resources.resource_filename("pahfit", "packs/")
        test_packfile = "{}/{}".format(pack_path, packfile)
        if os.path.isfile(test_packfile):
            packfile = test_packfile
        else:
            raise ValueError("Input packfile {} not found".format(packfile))

    pmodel = PAHFITBase(obs_x,
                        obs_y,
                        estimate_start=args.estimate_start,
                        filename=packfile)

    # pick the fitter
    fit = LevMarLSQFitter()

    # fit
    obs_fit = fit(
        pmodel.model,
        obs_x,
        obs_y,
        weights=weights,
        maxiter=200,
        epsilon=1e-10,
        acc=1e-10,
    )
    print(fit.fit_info["message"])

    # save results to fits file
    pmodel.save(obs_fit, outputname, args.saveoutput)

    # plot result
    fontsize = 18
    font = {"size": fontsize}
    mpl.rc("font", **font)
    mpl.rc("lines", linewidth=2)
    mpl.rc("axes", linewidth=2)
    mpl.rc("xtick.major", width=2)
    mpl.rc("ytick.major", width=2)

    fig, ax = plt.subplots(figsize=(15, 10))

    pmodel.plot(ax, obs_x, obs_y, obs_fit)

    ax.set_yscale("linear")
    ax.set_xscale("log")

    # use the whitespace better
    fig.tight_layout()

    # show
    if args.showplot:
        plt.show()
    # save (always)
    fig.savefig("{}.{}".format(outputname, args.savefig))
def pahfit(input_dir, output, max_iter, error, packfile, exclude_bf):

    try:
        os.mkdir(output)
    except:
        pass

    for subdir, dirs, files in os.walk(fr'./{input_dir}'):
        for specfile in files:
            try:
                if specfile.split('.')[-1] == 'txt' or specfile.split(
                        '.')[-1] == 'ipac':

                    filepath = subdir + os.sep + specfile

                    outputname = specfile.split('.')[0]
                    typer.echo(
                        f'Performing PAHFit for {typer.style(outputname, bold=True, fg=typer.colors.MAGENTA)}'
                    )

                    obs_spectrum = Table.read(filepath, format='ipac')
                    obs_x = obs_spectrum['wavelength'].to(
                        u.micron, equivalencies=u.spectral())
                    obs_y = obs_spectrum['flux'].to(
                        u.Jy, equivalencies=u.spectral_density(obs_x))
                    obs_unc = obs_spectrum['sigma'].to(
                        u.Jy, equivalencies=u.spectral_density(obs_x))

                    obs_x = obs_x.value
                    obs_y = obs_y.value
                    weights = 1. / obs_unc.value

                    # packfile = fr'C:\Users\bpart\OneDrive\Desktop\astro\MASSIVE\data\packFile.ipac'

                    pmodel = PAHFITBase(obs_x, obs_y, filename=packfile)

                    # pick the fitter
                    fit = LevMarLSQFitter()

                    # fit
                    obs_fit = fit(pmodel.model,
                                  obs_x,
                                  obs_y,
                                  weights=weights,
                                  maxiter=max_iter,
                                  epsilon=1e-10,
                                  acc=error)

                    pmodel.save(obs_fit, fr'{output}\{outputname}', 'ipac')

                    # plot result
                    fontsize = 18
                    font = {'size': fontsize}
                    mpl.rc('font', **font)
                    mpl.rc('lines', linewidth=2)
                    mpl.rc('axes', linewidth=2)
                    mpl.rc('xtick.major', width=2)
                    mpl.rc('ytick.major', width=2)

                    fig, ax = plt.subplots(figsize=(15, 10))

                    # modelfig, modelax = plt.subplots(figsize=(15, 10))

                    # modelax.plot(obs_x, obs_fit(obs_x) /obs_x, "g-")

                    # modelfig.tight_layout()

                    modelcsv = open(fr'{output}\{outputname}_model.csv', 'w')

                    modelcsv.write(
                        'observed wavelength (microns), observed flux (Jy), model flux (Jy)\n'
                    )
                    ys = obs_fit(obs_x)
                    for i in range(len(obs_x)):

                        modelcsv.write(
                            f'{str(obs_x[i])}, {str(obs_y[i])}, {str(ys[i])}\n'
                        )
                    modelcsv.close()

                    pmodel.plot(ax, obs_x, obs_y, obs_fit)
                    ax.plot(obs_x, obs_y / obs_x, "ks", fillstyle="full")

                    ax.set_yscale('linear')
                    ax.set_xscale('log')

                    # use the whitespace better
                    fig.tight_layout()

                    fig.savefig(fr'{output}\{outputname}.png')

                    # chiSquared = calc_reduced_chi_square(obs_fit(obs_x), obs_x, obs_y, obs_unc, len(obs_x), 139)

                    print("SUCCESS", outputname)
            except:
                print('PAHFIT FAILED FOR', specfile)