Exemplo n.º 1
0
def test_pld_corrector():
    # download tpf data for a target
    k2_target = "EPIC247887989"
    k2_tpf = search_targetpixelfile(k2_target).download()
    # instantiate PLD corrector object
    pld = PLDCorrector(k2_tpf[:500], aperture_mask="threshold")
    # produce a PLD-corrected light curve with a default aperture mask
    corrected_lc = pld.correct()
    # ensure the CDPP was reduced by the corrector
    pld_cdpp = corrected_lc.estimate_cdpp()
    raw_cdpp = k2_tpf.to_lightcurve().estimate_cdpp()
    assert pld_cdpp < raw_cdpp
    # make sure the returned object is the correct type (`KeplerLightCurve`)
    assert isinstance(corrected_lc, KeplerLightCurve)
    # try detrending using a threshold mask
    corrected_lc = pld.correct()
    # reduce using fewer principle components
    corrected_lc = pld.correct(pca_components=20)
    # try PLD on a TESS observation
    from lightkurve import TessTargetPixelFile
    from ..test_targetpixelfile import TESS_SIM

    tess_tpf = TessTargetPixelFile(TESS_SIM)
    # instantiate PLD corrector object
    pld = PLDCorrector(tess_tpf[:500], aperture_mask="pipeline")
    # produce a PLD-corrected light curve with a pipeline aperture mask
    raw_lc = tess_tpf.to_lightcurve(aperture_mask="pipeline")
    corrected_lc = pld.correct(pca_components=20)
    # the corrected light curve should have higher precision
    assert corrected_lc.estimate_cdpp() < raw_lc.estimate_cdpp()
    # make sure the returned object is the correct type (`TessLightCurve`)
    assert isinstance(corrected_lc, TessLightCurve)
Exemplo n.º 2
0
def test_open():
    """Does the deprecated `open` function still work?"""
    from lightkurve.io import open

    with warnings.catch_warnings():  # lk.open is deprecated
        warnings.simplefilter("ignore", LightkurveDeprecationWarning)
        # define paths to k2 and tess data
        k2_path = os.path.join(TESTDATA, "test-tpf-star.fits")
        tess_path = os.path.join(TESTDATA,
                                 "tess25155310-s01-first-cadences.fits.gz")
        # Ensure files are read in as the correct object
        k2tpf = open(k2_path)
        assert isinstance(k2tpf, KeplerTargetPixelFile)
        tesstpf = open(tess_path)
        assert isinstance(tesstpf, TessTargetPixelFile)
        # Open should fail if the filetype is not recognized
        try:
            open(os.path.join(PACKAGEDIR, "data", "lightkurve.mplstyle"))
        except LightkurveError:
            pass
        # Can you instantiate with a path?
        assert isinstance(KeplerTargetPixelFile(k2_path),
                          KeplerTargetPixelFile)
        assert isinstance(TessTargetPixelFile(tess_path), TessTargetPixelFile)
        # Can open take a quality_bitmask argument?
        assert open(k2_path, quality_bitmask="hard").quality_bitmask == "hard"
def plot_frame(tpf: TessTargetPixelFile, aperture=None, ax=None, savefn=None, frame=200, show_colorbar=True, **kwargs):
    """
    Function to plot TPF frame
    (optional) If aperture is 'threshold' string, a mask will be generated from
    the TPF native create_threshold_mask() function.

    :param tpf: target pixel file
    :param aperture: array-like, 'pipeline', 'all', 'threshold', or None
        A boolean array describing the aperture such that `True` means
        that the pixel will be used.
        If None or 'all' are passed, all pixels will be used.
        If 'pipeline' is passed, the mask suggested by the official pipeline
        will be returned.
        If 'threshold' is passed, all pixels brighter than 3-sigma above
        the median flux will be used.
    :param ax: if given, the frame will plot on this axis
    :param savefn: safe filename if want to save file
    :param frame: frame # of TPF which to plot
    :param show_colorbar: whether to show color bar
    :param kwargs: keyword arguments to pass to tpf.plot function
    """
    if not ax:
        ax = plt.subplot(projection=tpf.wcs)
    # Set default plotting args
    kwargs['interpolation'] = 'nearest'
    kwargs['cmap'] = 'hot'
    kwargs['scale'] = 'sqrt'

    with warnings.catch_warnings():
        warnings.simplefilter("ignore", RuntimeWarning)
        tpf.plot(ax=ax, frame=frame, show_colorbar=show_colorbar, aperture_mask=aperture, **kwargs)
    with plt.style.context(MPLSTYLE):
        ax.coords[0].set_axislabel('Right Ascension')
        ax.coords[1].set_axislabel('Declination')
    # IF want to save
    if savefn:
        plt.gcf().savefig(savefn)
    return ax
Exemplo n.º 4
0
def _from_path_TPF(path, mission, aperture_mask="default"):

    origins = {"Kepler": "KLC", "K2": "KLC", "TESS": "TLC"}

    if ((mission == "Kepler") | (mission == "K2")):
        tpf = KeplerTargetPixelFile(path)

    elif mission == "TESS":
        tpf = TessTargetPixelFile(path)

    if aperture_mask == "default":
        aperture_mask = tpf.pipeline_mask

    lc = tpf.to_lightcurve(aperture_mask=aperture_mask)

    flc = _convert_TPF_to_FLC(tpf, lc)

    return flc
Exemplo n.º 5
0
def test_read():
    # define paths to k2 and tess data
    k2_path = os.path.join(TESTDATA, "test-tpf-star.fits")
    tess_path = os.path.join(TESTDATA,
                             "tess25155310-s01-first-cadences.fits.gz")
    # Ensure files are read in as the correct object
    k2tpf = read(k2_path)
    assert isinstance(k2tpf, KeplerTargetPixelFile)
    tesstpf = read(tess_path)
    assert isinstance(tesstpf, TessTargetPixelFile)
    # Open should fail if the filetype is not recognized
    try:
        read(os.path.join(PACKAGEDIR, "data", "lightkurve.mplstyle"))
    except LightkurveError:
        pass
    # Can you instantiate with a path?
    assert isinstance(KeplerTargetPixelFile(k2_path), KeplerTargetPixelFile)
    assert isinstance(TessTargetPixelFile(tess_path), TessTargetPixelFile)
    # Can open take a quality_bitmask argument?
    assert read(k2_path, quality_bitmask="hard").quality_bitmask == "hard"
def extract_lightcurve(tpf: TessTargetPixelFile, aperture_mask, background_mask=None, sigma=3.0,
                       remove_outlier=True, background_sub=False, return_mask=False):
    """
    Extract Background Subtracted Light Curve
    Remove outliers (Optional)

    :param tpf: TargetPixelFile containing all the target data
    :param aperture_mask: A boolean array describing the aperture; `True` pixels are those inside aperture
    :param background_mask: A boolean array describing the bkg aperture: `True` pixels are background pixels
    :param sigma: The number of standard deviations to use for clipping limits
    :param remove_outlier: Whether to remove outliers in returned Light Curve
    :param background_sub: Whether to background subtract the light curve
    :param return_mask: Whether to return a mask indicating which data points were removed
    :return: TessLightCurve object with the processed data
    """

    lc_final = tpf.extract_aperture_photometry(aperture_mask=aperture_mask)

    if background_sub:
        if background_mask is None:
            # If no background mask was given, at least mask the given source
            background_mask = aperture_mask
        else:
            background_mask = ~background_mask

        pix_num = aperture_mask.sum()
        # Get sigma clipped statistics per timestamp for each aperture type; masks source target
        mean_orig, median_orig, std_orig = sigma_clipped_stats(tpf.flux, sigma=sigma,
                                                               mask=np.broadcast_to(background_mask, tpf.shape),
                                                               axis=(1, 2), maxiters=3)

        # Background subtract and propagate error (ONLY USING MEAN)
        lc_final.flux -= pix_num * mean_orig
        lc_final.flux_err = np.sqrt(lc_final.flux_err ** 2 + (std_orig * pix_num) ** 2)

    if remove_outlier:
        lc_final, mask = lc_final.remove_outliers(sigma=sigma, return_mask=True)
        if return_mask:
            return lc_final, mask
    return lc_final
Exemplo n.º 7
0
def download_tess_tpf(star=261136679, **kw):
    '''
    This function is a wrapper a "Target Pixel Files" (TPF) for TESS data, as
    accessed through the MAST archive. Each TPF is basically a movie; it
    contains a time series of images in a tiny little area around a
    particular TESS target.

    This has been tested only on data from TESS Sector 1. The available
    data are described here:

    https://archive.stsci.edu/prepds/tess-data-alerts/

    Parameters
    ----------

    star: str, int
        The TESS Input Catalog ID of the star whose light curve
        you want to download. (We should make a more flexible interface
        for this in the future, once more data are available).

    Returns
    -------

    tpf: TessTargetPixelFile object
        This is a `lightkurve`-style TargetPixelFile object, which contains
        the attributes `tpf.time` (times in JD) and `tpf.flux` (the brightness
        of each pixel as a function of time), as well as lots of methods for
        analysis and plotting.
    '''

    # download a TessTargetPixelFile from the MAST archive
    url = "https://archive.stsci.edu/hlsps/tess-data-alerts/hlsp_tess-data-alerts_tess_phot_{:011}-s01_tess_v1_tp.fits".format(
        int(star))
    tpf = TessTargetPixelFile(url, **kw)

    # return the tpf
    return tpf
Exemplo n.º 8
0
 def load(self):
     '''
     Load the hard-to-download data (special for TESS TPF).
     '''
     self._downloaded = TessTargetPixelFile(self.filename)
     print(f'loaded file from {self.filename}')
    def load_candidate_single_transits(self, training_data_dir, inner_dir):
        single_transits_dir = training_data_dir + "/single_transits/"
        single_transits_inner_dir = single_transits_dir + inner_dir
        if not os.path.exists(single_transits_dir):
            os.mkdir(single_transits_dir)
        if not os.path.exists(single_transits_inner_dir):
            os.mkdir(single_transits_inner_dir)
        files = os.listdir(single_transits_inner_dir)
        files_to_process = os.listdir(training_data_dir + "/" + inner_dir)
        files_to_process.sort()
        if len(files) > 0:
            files.sort()
            last_file = files[-1]
            file_name_matches = re.search("(TIC [0-9]+)", last_file)
            target = file_name_matches[1]
            target_index = files_to_process.index(target) + 1
        else:
            target_index = 0
        files_to_process = files_to_process[target_index:]
        for file in files_to_process:
            target_dir = training_data_dir + "/" + inner_dir + "/" + file
            tpfs_short_dir = target_dir + "/tpfs_short/"
            if not os.path.exists(tpfs_short_dir):
                continue
            ts_short = pd.read_csv(target_dir + "/time_series_short.csv")
            ois = pd.read_csv(target_dir + "/ois.csv")
            tpfs_short = []
            for tpf_file in os.listdir(tpfs_short_dir):
                tpfs_short.append(TessTargetPixelFile(tpfs_short_dir + "/" + tpf_file))
            for oi in ois.iterrows():
                initial_t0 = oi[1]["t0"]
                duration = oi[1]["duration"] / 24 * 2
                period = oi[1]["period"]
                transit = 0
                for t0 in np.arange(initial_t0, ts_short["time"].max(), period):
                    fig, axs = plt.subplots(1, 1, figsize=(16, 16), constrained_layout=True)
                    tpf_short_framed = None
                    for tpf in tpfs_short:
                        if tpf.time[0].value < t0 and tpf.time[-1].value > t0:
                            tpf_short_framed = tpf[(tpf.time.value > t0 - duration) & (tpf.time.value < t0 + duration)]
                            if len(tpf_short_framed) == 0:
                                break
                            tpf_short_framed.plot_pixels(axs, aperture_mask=tpf_short_framed.pipeline_mask)
                            break
                    if tpf_short_framed is None or len(tpf_short_framed) == 0:
                        continue
                    fig.suptitle("Single Transit Analysis")
                    plt.show()
                    fig, axs = plt.subplots(4, 1, figsize=(16, 16), constrained_layout=True)
                    ts_short_framed = ts_short[(ts_short["time"] > t0 - duration) & (ts_short["time"] < t0 + duration)]
                    axs[0].scatter(ts_short_framed["time"], ts_short_framed["centroids_x"].to_numpy(), color="black")
                    axs[0].scatter(ts_short_framed["time"], ts_short_framed["motion_x"].to_numpy(), color="red")
                    axs[1].scatter(ts_short_framed["time"], ts_short_framed["centroids_y"].to_numpy(), color="black")
                    axs[1].scatter(ts_short_framed["time"], ts_short_framed["motion_y"].to_numpy(), color="red")
                    axs[2].scatter(ts_short_framed["time"], ts_short_framed["background_flux"].to_numpy(), color="blue")
                    axs[3].scatter(ts_short_framed["time"], ts_short_framed["flux"].to_numpy(), color="blue")
                    fig.suptitle("Single Transit Analysis")
                    plt.show()
                    selection = None

                    def press(key):
                        print(f"'{key}' pressed")
                        global selection
                        if key == "0":
                            selection = 0.0
                        elif key == "1":
                            selection = 0.25
                        elif key == "2":
                            selection = 0.5
                        elif key == "3":
                            selection = 0.75
                        elif key == "4":
                            selection = 1.0
                        if selection is not None:
                            single_transit_path = single_transits_inner_dir + "/" + file + "/S" + str(
                                transit) + "_" + str(
                                selection)
                            pathlib.Path(single_transit_path).mkdir(parents=True, exist_ok=True)
                            ts_short_framed.to_csv(single_transit_path + "/ts_short_framed.csv")
                            tpf_short_framed.to_fits(single_transit_path + "/tpf_short_framed.fits", True)
                            stop_listening()

                    listen_keyboard(on_press=press)
                    transit = transit + 1