def test_kplr10417986():
    """Integration test"""
    filename = download_file(
        'https://archive.stsci.edu/missions/kepler/lightcurves/0104/010417986/kplr010417986-2010174085026_llc.fits',
        cache=True)  # noqa

    period = .0737309 * u.day
    epoch_mbjd = 55000.027476 * u.day
    duration = 1 * u.hour
    target_name = "KPLR 010417986"
    event_name = "False Positive"

    epoch_bkjd = epoch_mbjd - exo_const.mbjd + exo_const.bkjd
    tce = Tce(period=period,
              epoch=epoch_bkjd,
              epoch_offset=exo_const.bkjd,
              duration=duration,
              depth=0 * exo_const.frac_amp,
              target_name=target_name,
              event_name=event_name)

    lc = lightkurve.read(filename, flux_column="pdcsap_flux")
    sweet_vetter = Sweet()
    res = sweet_vetter.run(tce, lc)
    amp = res['amp']

    assert np.allclose(amp[0, 0], 637, atol=30)  # Amplitude
    assert np.allclose(amp[0, 2], 106.94, atol=10)  # SNR
Exemple #2
0
def test_contaminante():
    tpfc = lk.read(fname)
    period = 0.700606
    t0 = 131.59767
    duration = 0.993 / 24

    res = contaminante.calculate_contamination(tpfc,
                                               period,
                                               t0,
                                               duration,
                                               plot=False,
                                               cbvs=False)
    assert res[0]["delta_transit_depth[sigma]"] > 5
    assert res[0]["centroid_shift"][0].value > 5

    res = contaminante.calculate_contamination(tpfc,
                                               period,
                                               t0,
                                               duration,
                                               plot=False,
                                               cbvs=True)
    assert res[0]["delta_transit_depth[sigma]"] > 5
    assert res[0]["centroid_shift"][0].value > 5

    res = contaminante.calculate_contamination(tpfc,
                                               period,
                                               t0,
                                               duration,
                                               plot=False,
                                               cbvs=True,
                                               spline=False)
    assert res[0]["delta_transit_depth[sigma]"] > 5
    assert res[0]["centroid_shift"][0].value > 5

    res = contaminante.calculate_contamination(tpfc,
                                               period,
                                               t0,
                                               duration,
                                               plot=False,
                                               cbvs=True,
                                               sff=True)
    assert res[0]["delta_transit_depth[sigma]"] > 5
    assert res[0]["centroid_shift"][0].value > 5

    res = contaminante.calculate_contamination(tpfc,
                                               1000,
                                               t0,
                                               duration,
                                               plot=False,
                                               cbvs=True,
                                               sff=True)
    assert (res[0]["transit_depth"] == 0).all()
Exemple #3
0
def _from_path_AltaiPony(path):

    #    rhdul =  fits.open(path)
    #    attrs = dict()
    #    for k, v in rhdul[0].header.items():
    #        if str.lower(k) not in ['simple', 'bitpix', 'naxis', 'extend']:
    #            if str.lower(k) == "keplerid": #rename keplerid if it appears
    #                k = "targetid"
    #            attrs[str.lower(k)] = v
    #
    #    for k in ['time', 'flux', 'flux_err', 'centroid_col',
    #              'centroid_row', 'quality', 'cadenceno',
    #              'detrended_flux', 'detrended_flux_err',
    #              'quality_bitmask', 'saturation']:
    #        try:
    #            attrs[k] = rhdul[1].data[k].byteswap().newbyteorder()
    #        except KeyError:
    #            LOG.info("Warning: Keyword {} not in file.".format(k))
    #            continue
    lc = read(path)
    lc = lc[np.isfinite(lc.time.value) & np.isfinite(lc.flux.value)
            & np.isfinite(lc.cadenceno.value)]
    # keys = dict([(key, lc[key].value) for key in lc.colnames[:3]])
    # print(keys)
    # flc = lc.FlareLightCurve(**keys, time_format=lc.time.format, meta=lc.meta)
    #    flc = FlareLightCurve(time=lc.time.value,
    #                          flux=lc.flux.value,
    #                          flux_err=lc.flux_err.value,
    #                          pos_corr1=
    #                          meta=lc.meta)

    lc["detrended_flux"] = np.nan
    lc["detrended_flux_err"] = np.nan

    lc.__class__ = FlareLightCurve
    lc._init_flare_table()
    return lc
def xmkpy3_finder_chart_tpf_overlay_v6():
    import matplotlib.pyplot as plt
    import astropy.units as u
    import sys
    import os
    import ntpath
    import argparse
    import ast

    import lightkurve as lk  # ignore PEP8 warning of redefinition
    lk.log.setLevel('INFO')

    import mkpy3

    #
    # argparse: BEGIN =========================================================
    #
    parser = argparse.ArgumentParser()
    #
    parser.add_argument(
        '--tpf_filename',
        action="store",
        type=str,
        default=None,
        help="Filename of the Target Pixel File (TPF) [default: None]")
    parser.add_argument('--frame',
                        action="store",
                        type=int,
                        default=0,
                        help='Frame number (integer) [default: 0]')
    parser.add_argument('--survey',
                        action="store",
                        type=str,
                        default='2MASS-J',
                        help="Survey name (str) [default: '2MASS-J']")
    parser.add_argument(
        '--width_height_arcmin',
        action="store",
        type=float,
        default=2.0,
        help='Width and height size in arcmin (float) [default: 2.0]')
    parser.add_argument('--show_plot',
                        type=mkpy3.mkpy3_util_str2bool,
                        default=True,
                        help='If True, show the plot [default=True]')
    parser.add_argument(
        '--plotfile',
        action="store",
        type=str,
        default='mkpy3_plot.png',
        help="Filename of the output plotfile [default: 'mkpy3_plot.png']")
    parser.add_argument(
        '--overwrite',
        type=mkpy3.mkpy3_util_str2bool,
        default=False,
        help='If True, overwrite ("clobber") an existing output file '
        '[default: False.')
    parser.add_argument(
        '--figsize',
        action="store",
        type=ast.literal_eval,
        default="[9,9]",
        help="2-item list of figure width and height [Matplotlib] (str) "
        "[default: \"[9,9]\"")
    parser.add_argument('--title',
                        action="store",
                        type=str,
                        default=None,
                        help='Title of the finder chart (str) [default: None]')
    parser.add_argument(
        '--percentile',
        action="store",
        type=float,
        default=99.0,
        help='Percentile [percentage of pixels to keep: 0.0 to 100.0] '
        '(float) [default: 99.0]')
    parser.add_argument(
        '--cmap',
        action="store",
        type=str,
        default=None,
        help="Colormap name [Matplotlib] (str) [default: 'gray']")
    parser.add_argument(
        '--colors',
        action="store",
        type=ast.literal_eval,
        default="[None,'cornflowerblue','red']",
        help="3-item list of overlay color names [Matplotlib] (str) "
        "[default: \"['None','cornflowerblue','red']\"")
    parser.add_argument(
        '--lws',
        action="store",
        type=ast.literal_eval,
        default="[0,3,4]",
        help="3-item list of overlay line widths [Matplotlib] (str) "
        "[default: \"[0,3,4]\"")
    parser.add_argument(
        '--zorders',
        action="store",
        type=ast.literal_eval,
        default="[0,1,2]",
        help="3-item list of overlay zorder values [Matplotlib] (str) "
        "[default: \"[0,1,2]\"")
    parser.add_argument(
        '--marker_dict',
        action="store",
        type=ast.literal_eval,
        default="{'edgecolor':'yellow', 's':600, 'facecolor':'None', 'lw':3, "
        "'zorder':10}",
        help="marker kwargs (dictonary string) for ax.scatter() [Matplotlib] "
        "(str) [default: \"{'edgecolor':'yellow', 's':600, 'facecolor':'None',"
        " 'lw':3, 'zorder':10}\"")
    parser.add_argument(
        '--verbose',
        type=mkpy3.mkpy3_util_str2bool,
        default=False,
        help='Print extra information if True (bool) [default=False]')
    #
    args = parser.parse_args()

    tpf_filename = args.tpf_filename
    frame = args.frame
    survey = args.survey
    width_height_arcmin = args.width_height_arcmin
    show_plot = args.show_plot
    plotfile = args.plotfile
    overwrite = args.overwrite
    figsize = args.figsize
    title_ = args.title
    percentile = args.percentile
    cmap = args.cmap
    colors = args.colors
    lws = args.lws
    zorders = args.zorders
    marker_dict = args.marker_dict
    verbose = args.verbose
    #
    if (verbose):
        print('%s =args.tpf_filename' % (args.tpf_filename))
        print('%s =args.frame' % (args.frame))
        print("'%s' =args.survey" % (args.survey))
        print('%s =args.width_height_arcmin' % (args.width_height_arcmin))
        print('%s =args.show_plot' % (args.show_plot))
        print("'%s' =args.plotfile" % (args.plotfile))
        print('%s =args.overwrite' % (args.overwrite))
        print('%s =args.figsize' % (args.figsize))
        print('%s =args.title' % (args.title))
        print('%s =args.percentile' % (args.percentile))
        print('%s =args.cmap' % (args.cmap))
        print('%s =args.colors' % (args.colors))
        print('%s =args.lws' % (args.lws))
        print('%s =args.zorders' % (args.zorders))
        print('%s =args.marker_dict' % (args.marker_dict))
        print('%s =args.verbose' % (args.verbose))
        print()
    # pass:if
    #
    # argparse: END ===========================================================
    #

    ok = (type(marker_dict) is dict) or (marker_dict is None)
    if (not ok):
        print()
        print('**** ERROR ***** BAD ARGUMENT VALUE *****')
        print()
        print('marker_dict must be a dictionary or None:')
        print(marker_dict, '=marker_dict')
        print()
        sys.exit(1)
    # pass:if

    if (tpf_filename is not None):
        mkpy3.mkpy3_util_check_file_exists(tpf_filename, True)
        tpf = lk.read(tpf_filename)
    else:
        tpf = lk.search_targetpixelfile(target='kepler-138b',
                                        mission='kepler',
                                        cadence='long',
                                        quarter=10).download(quality_bitmask=0)
        #   6--- exoplanet Kelper-138b is "KIC 7603200"
        print()
        print('No TargetPixelFile (TPF) filename given.')
        print()
        print('Using default TPF [Kepler Q10 observations of exoplanet Kepler-'
              '138b (KIC 760320)]:')
    # pass#if
    print()
    print('TPF filename:', ntpath.basename(tpf.path))
    print('TPF dirname: ', os.path.dirname(tpf.path))
    print()

    ra_deg = tpf.ra
    dec_deg = tpf.dec
    if (verbose):
        print()
        print(ra_deg, '=ra_deg')
        print(dec_deg, '=dec_deg')
    # pass#if

    print()

    # get survey image data
    # survey = '2MASS-J'  # hard-wired option
    survey_hdu, survey_hdr, survey_data, survey_wcs, survey_cframe = \
        mkpy3.mkpy3_finder_chart_survey_fits_image_get_v1(
            ra_deg, dec_deg, radius_arcmin=width_height_arcmin,
            survey=survey, verbose=verbose)

    # create a matplotlib figure object
    fig = plt.figure(figsize=figsize)

    # create a matplotlib axis object with right ascension and declination axes
    ax = plt.subplot(projection=survey_wcs)

    # show the survey image
    mkpy3.mkpy3_finder_chart_image_show_v1(ax=ax,
                                           image_data=survey_data,
                                           percentile=percentile,
                                           cmap=cmap,
                                           verbose=verbose)

    # show the TPF overlay
    mkpy3_finder_chart_tpf_overlay_v6(ax=ax,
                                      survey_wcs=survey_wcs,
                                      tpf=tpf,
                                      frame=frame,
                                      colors=colors,
                                      lws=lws,
                                      zorders=zorders,
                                      verbose=verbose)

    # add title
    if (title_ is None):
        title_ = tpf.hdu[0].header['object']
    # pass:if
    plt.suptitle(title_, size=25)

    # put a yellow circle at the target position
    if (type(marker_dict) is dict):
        ax.scatter(ra_deg * u.deg,
                   dec_deg * u.deg,
                   transform=ax.get_transform(survey_cframe),
                   **marker_dict)

    # adjust the plot margins
    plt.subplots_adjust(left=0.2, right=0.9, top=0.9, bottom=0.2)

    if (plotfile != ''):
        if (plotfile != 'mkpy3_plot.png'):
            mkpy3.mkpy3_util_check_file_exists(plotfile, overwrite)
        plt.savefig(plotfile, dpi=300)  # , bbox_inches = "tight")
        print('\n%s <--- plotfile written  :-)\n' % (plotfile))
    # pass:if

    if (show_plot):
        plt.ioff()
        plt.show()
    # pass:if

    plt.close()
Exemple #5
0
    #

    ok = (type(marker_dict) is dict) or (marker_dict is None)
    if (not ok):
        print()
        print('**** ERROR ***** BAD ARGUMENT VALUE *****')
        print()
        print('marker_dict must be a dictionary or None:')
        print(marker_dict, '=marker_dict')
        print()
        sys.exit(1)
    # pass:if

    if (tpf_filename is not None):
        check_file_exists(tpf_filename, True)
        tpf = lk.read(tpf_filename)
    else:
        tpf = lk.search_targetpixelfile(target='kepler-138b',
                                        mission='kepler',
                                        quarter=10).download(quality_bitmask=0)
        #   6--- exoplanet Kelper-138b is "KIC 7603200"
        print()
        print('No TargetPixelFile (TPF) filename given.')
        print()
        print('Using default TPF [Kepler Q10 observations of exoplanet Kepler-'
              '138b (KIC 760320)]:')
    # pass#if
    print()
    print('TPF filename:', ntpath.basename(tpf.path))
    print('TPF dirname: ', os.path.dirname(tpf.path))
    print()
Exemple #6
0
"""
This contains a collection of functions to test the Machine API
"""
import numpy as np
from scipy import sparse
import pytest
import lightkurve as lk
from astropy.utils.data import get_pkg_data_filename

from psfmachine import TPFMachine

tpfs = []
for idx in range(10):
    tpfs.append(lk.read(get_pkg_data_filename(f"data/tpf_test_{idx:02}.fits")))
tpfs = lk.collections.TargetPixelFileCollection(tpfs)


@pytest.mark.remote_data
def test_create_delta_sparse_arrays():
    machine = TPFMachine.from_TPFs(tpfs)
    # create numpy arrays
    machine._create_delta_arrays()
    non_sparse_arr = machine.__dict__.copy()

    # check for main attrs shape
    assert non_sparse_arr["time"].shape == (10, )
    assert non_sparse_arr["flux"].shape == (10, 285)
    assert non_sparse_arr["flux_err"].shape == (10, 285)
    assert non_sparse_arr["column"].shape == (285, )
    assert non_sparse_arr["row"].shape == (285, )
    assert non_sparse_arr["ra"].shape == (285, )