Ejemplo n.º 1
0
def plot_shift_data(target_unshifted,
                    target_shifted,
                    reference,
                    shift_data,
                    pdf,
                    order,
                    wavlim='all',
                    singleorder=False):
    """Create shift plots from shift data

    Args:
        target_unshifted (HiresSpectrum): Unshifted target spectrum
        target_shifted (Spectrum): Shifted target spectrum
        reference (Spectrum): Reference spectrum
        shift_data (dict): Shift data object
        pdf: Pdf file object
        order (int): HIRES order to plot
        wavlim: A specific wavelength range to plot spectrum
    """
    # Create temp specmatch object
    sm = specmatch.SpecMatch(target_unshifted)
    sm.target = target_shifted
    sm.shift_ref = reference
    sm.shift_data = shift_data

    plot_shifts(sm, pdf, order, wavlim, singleorder)
def main(libpath, targ_name, outpath):
    lib = library.read_hdf(libpath)
    targ_idx = lib.get_index(targ_name)
    targ_param, targ_spec = lib[targ_idx]

    results = lib.library_params.copy()

    for wl in range(WAVLIM[0], WAVLIM[1], WAVSTEP):
        print("Matching region {0:d} - {1:d}".format(wl, wl + 100))
        sm = specmatch.SpecMatch(targ_spec, lib, (wl, wl + WAVSTEP))
        sm.match(ignore=targ_idx)

        cs_col = 'chi_squared_{0:d}'.format(wl)
        results[cs_col] = sm.match_results['chi_squared']
        fit_col = 'fit_params_{0:d}'.format(wl)
        results[fit_col] = sm.match_results['fit_params']

    results.to_csv(outpath)
Ejemplo n.º 3
0
def main(libpath, targ_name, respath, outpath, num_best):
    lib = library.read_hdf(libpath)
    targ_idx = lib.get_index(targ_name)
    targ_param, targ_spec = lib[targ_idx]

    res_match = pd.read_csv(respath, index_col=0)
    res_lincomb = targ_param.to_frame().transpose()

    for wl in range(WAVLIM[0], WAVLIM[1], WAVSTEP):
        matchcs_col = 'chi_squared_{0:d}'.format(wl)
        res_match.sort_values(by=matchcs_col, inplace=True)
        matchfit_col = 'fit_params_{0:d}'.format(wl)

        sm = specmatch.SpecMatch(targ_spec, lib, (wl,wl+100), num_best)
        sm.match(match_results=res_match.rename(\
            columns={matchcs_col:'chi_squared', matchfit_col:'fit_params'}))

        bestcs_col = 'best_cs_lincomb{0:d}_{1:d}'.format(num_best, wl)
        bestcs = np.array(res_match.head(num_best)[matchcs_col])
        res_lincomb[bestcs_col] = json.dumps(bestcs.tolist())

        refidxs_col = 'ref_idxs_lincomb{0:d}_{1:d}'.format(num_best, wl)
        ref_idxs = np.array(res_match.head(num_best).index)
        res_lincomb[refidxs_col] = json.dumps(ref_idxs.tolist())

        coeffs_col = 'coeffs_lincomb{0:d}_{1:d}'.format(num_best, wl)
        coeffs = np.array(match.get_lincomb_coeffs(sm.mt_lincomb.best_params))
        res_lincomb[coeffs_col] = json.dumps(coeffs.tolist())

        cs_col = 'chi_squared_lincomb{0:d}_{1:d}'.format(num_best, wl)
        res_lincomb[cs_col] = sm.mt_lincomb.best_chisq

        fit_col = 'fit_params_lincomb{0:d}_{1:d}'.format(num_best, wl)
        res_lincomb[fit_col] = sm.mt_lincomb.best_params.dumps()

    res_lincomb.to_csv(outpath)
Ejemplo n.º 4
0
def match_spectrum(specpath,
                   indir="./",
                   plot_level=0,
                   inlib=False,
                   outdir="./",
                   suffix=""):
    """Match a spectrum given its observation ID

    Args:
        specpath (str): Path to spectrum or its CPS observation id jXX.XXXX
        indir (str): Directory to look in for target spectrum
        plot_level (int, 0-2): Level of plotting to save
        inlib (str or False): String to search within library for to exclude
            from matching process
        outdir (str): Output file directory
        suffix (str): String to append to output file names

    Returns:
        specmatch.SpecMatch object
    """
    # Check if specpath is a path or an observation ID
    if os.path.exists(specpath):
        targ_path = specpath
        targid = os.path.splitext(os.path.basename(specpath))[0]
    else:
        targ_path = os.path.join(indir,
                                 'r' + specpath + '_adj' + suffix + '.fits')
        if not os.path.exists(targ_path):
            raise ValueError(specpath + " does not exist!")
        targid = 'r' + specpath

    # Load shifted spectrum
    target = spectrum.read_fits(targ_path)

    lib = library.read_hdf()
    sm = specmatch.SpecMatch(target, lib)

    if inlib:
        name = inlib
        sm.target.name = inlib
        sm.target.attrs['obs'] = targid
        targ_idx = lib.get_index(inlib)
        targ_param, targ_spec = lib[targ_idx]
        sm.match(ignore=targ_idx)
    else:
        name = targid
        targ_param = None
        sm.match()

    # Save results
    outdir = os.path.join(outdir, name)
    if not os.path.exists(outdir):
        os.mkdir(outdir)
    outpath = os.path.join(outdir, name + suffix + '_match.csv')
    sm.match_results.to_csv(outpath)

    # Save SpecMatch object
    outpath = os.path.join(outdir, name + suffix + '_sm.hdf')
    sm.to_hdf(outpath)

    # Generate representative plots
    if plot_level == 1:
        plotspath = os.path.join(outdir, name + suffix + '_match_plots.pdf')
        with PdfPages(plotspath) as pdf:
            region = (5100, 5200)
            wavlim = (5160, 5190)
            plot_match(sm, pdf, region, wavlim, targ_param)

    # Generate full plots
    if plot_level == 2:
        plotspath = os.path.join(outdir, name + suffix + '_match_plots.pdf')
        with PdfPages(plotspath) as pdf:
            for reg in sm.regions:
                plot_match(sm, pdf, reg, wavlim='all', targ_param=targ_param)

    return sm
Ejemplo n.º 5
0
def specmatch_spectrum(specpath,
                       plot_level=0,
                       inlib=False,
                       outdir="./",
                       num_best=5,
                       suffix="",
                       wavlim='all',
                       lib_subset=None,
                       name=None,
                       n_lib_subset=None):
    """Perform the specmatch on a given spectrum

    Args:
        specpath (str): Path to target spectrum
        plot_level (int, 0-2): Level of plots
            0 - No plots saved, 1 - Representative plots, 2 - All plots
        inlib (str or False): String to search within library for to exclude
            from matching process
        outdir (str): Output file directory
        num_best (int): Number of best matches to use at lincomb stage
        suffix (str): String to append to output file names

    Returns:
        specmatch.SpecMatch object
    """
    if not os.path.exists(specpath):
        raise ValueError(specpath + " does not exist!")

    if wavlim == 'all':
        target = spectrum.read_hires_fits(specpath)
    else:
        target = spectrum.read_hires_fits(specpath).cut(*wavlim)

    # Determine the name of the target
    if inlib:
        name = inlib
    elif name is None:
        name = os.path.basename(specpath)[:-5]

    if n_lib_subset is not None:
        lib = library.read_hdf(wavlim='none')
        lib_subset = lib.library_params.lib_index
        lib_subset = np.random.choice(lib_subset,
                                      size=n_lib_subset,
                                      replace=False)

    lib = library.read_hdf(wavlim=wavlim, lib_index_subset=lib_subset)
    sm = specmatch.SpecMatch(target, lib)
    sm.shift()

    if inlib:
        targ_idx = lib.get_index(inlib)
        targ_param, targ_spec = lib[targ_idx]
        sm.match(ignore=targ_idx, wavlim=wavlim)
    else:
        targ_param = None
        sm.match(wavlim=wavlim)

    sm.target.name = name  # attach target name

    sm.lincomb(num_best)

    # Print results
    print("SpecMatch Results for {0}".format(name))
    sm.results_to_txt(sys.stdout)

    outdir = os.path.join(outdir, name)
    if not os.path.exists(outdir):
        os.makedirs(outdir)

    # Save final results
    outpath = os.path.join(outdir, name + suffix + '_results.txt')
    with open(outpath, 'w') as f:
        if inlib:
            f.write('Library Parameters\n')
            f.write('------------------\n')
            f.write('Teff: {0:.0f} +/- {1:.0f} K\n'.format(
                targ_param['Teff'], targ_param['u_Teff']))
            f.write('Radius: {0:.3f} +/- {1:.3f} Rsun\n'.format(
                targ_param['radius'], targ_param['u_radius']))
            f.write('[Fe/H]: {0:.2f} +/- {1:.2f} dex\n'.format(
                targ_param['feh'], targ_param['u_feh']))
        f.write('\n')
        sm.results_to_txt(f, verbose=True)
        print("created {}".format(outpath))

    # Save full results
    outpath = os.path.join(outdir, name + suffix + '_sm.hdf')
    sm.to_hdf(outpath)
    print("created {}".format(outpath))

    # Create representative plots
    if plot_level is not None and plot_level > 0:
        plotspath = os.path.join(outdir, name + suffix + '_plots.pdf')
        with PdfPages(plotspath) as pdf:
            region = (5100, 5200)
            wavlim = (5160, 5190)
            order = 2

            plot_shifts(sm, pdf, order, wavlim)
            plot_match(sm, pdf, region, wavlim, targ_param)
            plot_lincomb(sm, pdf, region, wavlim, targ_param)
            print("created {}".format(plotspath))

    # Create full plots
    if plot_level == 2:
        shiftplotspath = os.path.join(outdir,
                                      name + suffix + '_shift_plots.pdf')
        with PdfPages(shiftplotspath) as pdf:
            for order in range(np.shape(sm.target_unshifted.w)[0]):
                plot_shifts(sm, pdf, order, wavlim='all')

        matchplotspath = os.path.join(outdir,
                                      name + suffix + '_match_plots.pdf')
        with PdfPages(matchplotspath) as pdf:
            for reg in sm.regions:
                plot_match(sm, pdf, reg, wavlim='all', targ_param=targ_param)

        lincombplotspath = os.path.join(outdir,
                                        name + suffix + '_lincomb_plots.pdf')
        with PdfPages(lincombplotspath) as pdf:
            for reg in sm.lincomb_regions:
                plot_lincomb(sm, pdf, reg, wavlim='all', targ_param=targ_param)

        print("created {}".format(plotspath))

    return sm