Пример #1
0
    async def get_targetpixelfile(self, mission, target, sector=None, campaign=None, quarter=None, aperture_mask="ALL"):

        result = None

        if mission == "TESS":
            result = search_targetpixelfile(mission=mission, target=target,sector=sector)
        elif mission == "Kepler":
            result = search_targetpixelfile(mission=mission, target=target, quarter=quarter)
        elif mission == "K2":
            result = search_targetpixelfile(mission=mission, target=target, campaign=campaign)
        else:
            raise ValueError("Unknown mission, must be TESS, Kepler, or K2")

        return result.download()
def FoldTarget(target, targetquarter, targetexp, targetperiod):
    pixelfile = search_targetpixelfile(target, quarter=targetquarter, exptime=targetexp).download();
    #print("\nDownloaded")

    pixelfile.plot(frame=1);

    lc = pixelfile.to_lightcurve(aperture_mask=pixelfile.pipeline_mask);
    #plt.title("Scatter Plot");
    lc.scatter();
    

    lc.plot();
    plt.title("Light Curve")
    #print("\nMask Done!")

    """lc = pixelfile.to_lightcurve(aperture_mask='all');
    lc.plot();
    print("\nAll Done!")"""

    flat_lc = lc.flatten(window_length=401);
    flat_lc.plot();
    plt.title("Flat")
    #print("\nFlat Done!")

    folded_lc = flat_lc.fold(period=targetperiod);
    folded_lc.plot();
    plt.title("Folded")
    #print("\nFold Done!")

    binned_lc = folded_lc.bin(time_bin_size=0.01);
    binned_lc.plot();
    plt.title("Binned")
Пример #3
0
def _from_mast_K2(targetid,
                  mode,
                  c,
                  flux_type="PDCSAP_FLUX",
                  cadence="long",
                  aperture_mask="default",
                  download_dir=None):

    if mode == "TPF":

        tpffilelist = search_targetpixelfile(targetid,
                                             mission="K2",
                                             campaign=c,
                                             cadence=cadence)
        tpf = tpffilelist.download(download_dir=download_dir)

        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

    elif mode == "LC":

        flcfilelist = search_lightcurvefile(targetid,
                                            mission="K2",
                                            campaign=c,
                                            cadence=cadence)
        flcfile = flcfilelist.download(download_dir=download_dir)
        lc = flcfile.get_lightcurve(flux_type)
        flc = _convert_LC_to_FLC(lc, origin="KLC")
        return flc
Пример #4
0
def download_k2_tpf(star='WASP-47', **kw):
    '''
    This function is a wrapper a "Target Pixel Files" (TPF) for Kepler/K2 data.
    Each TPF is basically a movie; it contains a time series of images in a tiny
    little area around a particular Kepler/K2 target.

    This has been tested only on data from the main Kepler mission and K2.

    Parameters
    ----------

    star: str, int
        The name of the star whose light curve you want to download.
        This can be a name ("K2-18", "TRAPPIST-1") or an EPIC number
        (246199087).

    Returns
    -------

    tpf: KeplerTargetPixelFile 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 KeplerLightCurveFile from the MAST archive
    tpf = search_targetpixelfile(star, **kw).download()
    return tpf
Пример #5
0
def data_K2(fitspath):

    targetname = fitspath[43:]
    targetname = targetname[:-18]

    print('TARGET ' + str(targetname))

    campaign_no = 18

    try:
        tpf = lk.search_targetpixelfile(str(targetname), campaign=18).download()
    except IOError:
        return 0, 0, 0, 0

    lc = tpf.to_lightcurve().normalize().flatten()
    time = lc.time
    flux = lc.flux

    flux_count = len(flux)
    sumflux = sum(flux)
    flux_avg = sumflux/flux_count

    flux = [i/flux_avg for i in flux]

    #normalize to 0.0
    flux = [i-1 for i in flux]

    flux = np.asarray(flux)
    time = np.asarray(time)

    #SIGMA CLIPPING
    flux = sigma_clip(flux, sigma=3, iters=1)
    flux = flux.filled(fill_value=0)

    return time, flux, targetname, campaign_no
Пример #6
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)
Пример #7
0
def _from_mast_K2(targetid,
                  mode,
                  c,
                  flux_type="PDCSAP_FLUX",
                  cadence="long",
                  aperture_mask="default",
                  download_dir=None):
    mission = "K2"
    if mode == "TPF":

        tpffilelist = search_targetpixelfile(targetid,
                                             mission=mission,
                                             campaign=c,
                                             cadence=cadence)
        tpf = tpffilelist.download(download_dir=download_dir)

        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

    elif mode == "LC":

        flcfilelist = search_lightcurve(targetid,
                                        mission=mission,
                                        campaign=c,
                                        cadence=cadence,
                                        author="K2")

        return _handle_missions(flcfilelist, mission, flux_type, cadence,
                                download_dir, targetid, c)
Пример #8
0
def download_all_short_cadence_observations_for_targets_in_flare_catalog():
    """Downloads and saves all the short cadence observations for the stars which appear in the flare catalog."""
    flare_catalog = np.genfromtxt(catalog_path, delimiter=',', skip_header=1)
    kepler_input_catalog_numbers = list(
        map(int, [target[0] for target in flare_catalog]))
    observations_skipped = 0
    targets_skipped = 0
    for kepler_input_catalog_number in kepler_input_catalog_numbers:
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", category=LightkurveWarning
                                    )  # Ignore warnings about empty downloads.
            current_target_skipped = False
            short_cadence_observations = search_targetpixelfile(
                kepler_input_catalog_number, cadence='short')
            for observation_index, observation in enumerate(
                    short_cadence_observations):
                observation_file_name = f'{kepler_input_catalog_number}_{observation_index}.fits'
                try:
                    observation.download().to_fits(os.path.join(
                        data_directory, observation_file_name),
                                                   overwrite=True)
                except OSError:
                    observations_skipped += 1
                    if not current_target_skipped:
                        current_target_skipped = True
                        targets_skipped += 1
    print(f'{targets_skipped} targets skipped.')
    print(f'{observations_skipped} observations skipped.')
Пример #9
0
def tpf_grabber(tic_id, sectors):
    '''Authors:
		Patrick Tamburo, Boston University, July 2020
	Purpose:
        Given a target's position when it was observed with TESS, returns the column and row of the pixel that the target fell on. 
	Inputs:
        tic_id (str): The target's TIC ID (e.g., 'TIC 326109505')
        sector (array of ints): Sectors during which the target was observed
    Outputs:
        tpfs (list): List of target pixel files. 
	TODO:
    '''

    tpfs = []
    for i in range(len(sectors)):
        tpf = lk.search_targetpixelfile(tic_id, sector=sectors[i]).download()
        if tpf is not None:
            tpfs.append(tpf)
        else:
            #Sometimes, tpf files don't exist for certain sectors, even though the target may have been observed in them...don't know why.
            #But if that is the case, just skip that sector.
            print('ERROR: no data found for {} in sector {:2d}, skipping.'.
                  format(tic_id, sectors[i]))
            continue
    return tpfs
Пример #10
0
def find_campaigns(s):
    '''Find campaigns and EPIC IDs
    for a given RA and Dec pair
    using lightkurve query function.

    Parameters:
    ------------
    s : str
        "RA Dec" in deg

    Return:
    -------
    list, int : list of campaigns, EPIC ID
    '''
    res = search_targetpixelfile(s, radius=2)
    pdf = res.table.to_pandas()

    if pdf.shape[0] > 0:
        pdf['Campaign'] = pdf.obs_id.str[-5:-3].astype(int)
        pdf['EPIC'] = pdf.target_name.str[4:]
        try:
            assert (pdf.EPIC.values == pdf.EPIC.iloc[0]).all()
        except:
            print("Something went wrong here\n")
            print(pdf.EPIC.values)
            return [np.nan], np.nan

        return pdf.Campaign.tolist(), pdf.EPIC.iloc[0]
    else:
        return [np.nan], np.nan
def xmkpy3_plot_add_compass_rose_v5():
    import matplotlib.pyplot as plt
    import lightkurve as lk
    #
    obj = 3  # USER CUSTOMIZE
    #
    tpf = None
    if (obj == 1):
        north_arm_arcsec = 8
        tpf = lk.search_targetpixelfile(
          target='Kepler-138b', mission='Kepler', quarter=10)\
          .download(quality_bitmask=0)
        #         ^--- Exoplanet Kelper-138b is "KIC 7603200"
    elif (obj == 2):
        north_arm_arcsec = 42
        search_results = lk.search_tesscut(target='CD Ind', sector=1)
        tpf = search_results[0].download(cutout_size=(11, 11),
                                         quality_bitmask=0)
    elif (obj == 3):
        north_arm_arcsec = 42
        tpf = lk.search_targetpixelfile(target='CD Ind',
                                        mission='TESS',
                                        sector=1).download(quality_bitmask=0)
    else:
        print('***ERROR*** BAD OBJECT NUMBER:', obj)
    # pass:if
    assert (tpf is not None)
    #
    # Plot the 2nd frame of the TPF
    ax = tpf.plot(frame=1, cmap='gray_r')
    #
    # add a compass rose using the WCS from the TargetPixelFile
    mkpy3_plot_add_compass_rose_v5(ax=ax,
                                   wcs=tpf.wcs,
                                   north_arm_arcsec=north_arm_arcsec,
                                   verbose=True)
    #
    print(tpf.path, '\n^--- tpf.path\n')
    print(tpf.ra, '=tpf.ra')
    print(tpf.dec, '=tpf.dec')
    print(obj, '=obj')
    #
    plot_file = 'mkpy3_plot1.png'
    plt.savefig(plot_file, bbox_inches="tight")
    plt.close()
    print('\n', plot_file, ' <--- new PNG file written')
Пример #12
0
def makeLCQ(ID, q):
    """
    Generates a Kepler lightcurve file for a given target ID and quarter.
    1 <= q <= 17
    """
    tpf = lk.search_targetpixelfile(ID, quarter=q).download()
    lightcurve = tpf.to_lightcurve()
    lightcurve = remove_anomalies(lightcurve)
    return lightcurve
def FlatTarget(target, targetquarter, targetexp):
    pixelfile = search_targetpixelfile(target, quarter=targetquarter, exptime=targetexp).download();
    
    lc = pixelfile.to_lightcurve(aperture_mask=pixelfile.pipeline_mask);
    lc.scatter();

    flat_lc = lc.flatten(window_length=401);
    flat_lc.plot();
    plt.title("Flat")
Пример #14
0
def test_FPs():
    """Produce some figures that show centroid offsets"""
    names = [
        "KIC 5391911",
        "KIC 5866724",
        "EPIC 220256496",
        "EPIC 210957318",
        "TIC 293435336",
        "TIC 13023738",
    ]
    kwargs = [
        {"quarter": 3},
        {"quarter": 3},
        {"campaign": 8},
        {"campaign": 4},
        {},
        {"sector": 2},
    ]

    periods = [0.782068488, 2.154911236, 0.669558, 4.098503000, 1.809886, 8.0635]
    t0s = [
        131.8940201,
        133.498613,
        2457393.81364 - 2454833,
        2457063.80710000 - 2454833,
        2456107.85507 - 2457000,
        2459104.87232 - 2457000,
    ]
    durs = np.asarray([1.239, 3.1341, 1, 2.3208, 3.694, 3.396]) / 24
    depths = [
        0.01157 * 0.01,
        0.00850 * 0.01,
        0.015450 ** 2,
        1.603 * 0.01,
        1.189 * 0.01,
        5180 * 1e-6,
    ]

    for name, period, t0, dur, kwarg, depth in zip(
        names, periods, t0s, durs, kwargs, depths
    ):
        tpf = lk.search_targetpixelfile(name, **kwarg).download()
        r = centroid_test(
            tpf,
            period,
            t0,
            dur,
            aperture_mask="pipeline",
            plot=True,
            transit_depths=depth,
        )
        r["figs"][0].savefig(
            f"{testdir}/docs/{name.replace(' ','').lower()}.png",
            dpi=200,
            bbox_inches="tight",
        )
Пример #15
0
 def get_tpf(self):
     """
     FIXME: refactor to tpf.py?
     """
     res = lk.search_targetpixelfile(f"EPIC {self.epicid}",
                                     campaign=self.campaign,
                                     mission="K2")
     tpf = res.download()
     self.tpf = tpf
     return tpf
Пример #16
0
def get_count_stars_in_flare_catalog_with_short_cadence_data():
    """Returns the number of targets in the flare catalog with short cadence data."""
    flare_catalog = np.genfromtxt(catalog_path, delimiter=',', skip_header=1)
    kepler_input_catalog_numbers = [target[0] for target in flare_catalog]
    count_with_short_cadence = 0
    for kepler_input_catalog_number in kepler_input_catalog_numbers:
        short_cadence_observations = search_targetpixelfile(
            kepler_input_catalog_number, cadence='short')
        if len(short_cadence_observations) is not 0:
            count_with_short_cadence += 1
    return count_with_short_cadence
Пример #17
0
 def test_cyclic_conversion(self):
     tpfs = lightkurve.search_targetpixelfile(target="TIC 251848941", cadence=120, author="SPOC") \
         .download_all(cutout_size=CUTOUT_SIZE)
     for tpf in tpfs:
         self.assertTrue((tpf.pipeline_mask ==
                          ApertureExtractor.from_pixels_to_boolean_mask(
                              ApertureExtractor.from_boolean_mask(
                                  tpf.pipeline_mask, tpf.column,
                                  tpf.row), tpf.column, tpf.row,
                              len(tpf.pipeline_mask[1]),
                              len(tpf.pipeline_mask[0]))).all())
Пример #18
0
def test_pld_aperture_mask():
    """Test for #523: does PLDCorrector.correct() accept separate apertures for
    PLD pixels?"""
    tpf = search_targetpixelfile("K2-205")[0].download()
    # use only the pixels in the pipeline mask
    lc_pipeline = tpf.to_corrector("pld").correct(pld_aperture_mask="pipeline",
                                                  restore_trend=False)
    # use all pixels in the tpf
    lc_all = tpf.to_corrector("pld").correct(pld_aperture_mask="all",
                                             restore_trend=False)
    # does this improve the correction?
    assert lc_all.estimate_cdpp() < lc_pipeline.estimate_cdpp()
Пример #19
0
 def get_tpf(self, campaign=None):
     """
     FIXME: refactor to tpf.py?
     """
     if campaign is None:
         campaign = self.campaign
     assert campaign in self.all_campaigns
     res = lk.search_targetpixelfile(f"EPIC {self.epicid}",
                                     campaign=campaign,
                                     mission="K2")
     tpf = res.download()
     self.tpf = tpf
     return tpf
Пример #20
0
def plot_EPIC_ID(epic, sigma_value = 5):
    search = lk.search_targetpixelfile(epic, mission='K2')
    print(search)
    pixelfile = search.download(quality_bitmask='hard' ) #gets the data about the EPIC ID
    print('*********Quarter :' ,pixelfile.quarter, 'Mission : ',pixelfile.mission )
    #pixelfile.interact(notebook_url='localhost:8893')
    fname = str(epic)+'.fits'
               
    lc = pixelfile.to_lightcurve(aperture_mask='all') #gets the light curve information
    lc = outlier_removal(lc, sigma_value) #calls the function that removes outliers
    lc.to_fits(path=fname, overwrite=True)
    # files.download(fname)    
    return lc #returns the light curve information
def xmkpy3_finder_chart_survey_fits_image_get_v1():
    import lightkurve as lk
    lk.log.setLevel('INFO')
    import matplotlib.pyplot as plt
    import astropy.units as u
    from astropy.visualization import ImageNormalize, PercentileInterval, SqrtStretch
    import os
    import ntpath

    # Exoplanet Kelper-138b is "KIC 7603200":
    tpf = lk.search_targetpixelfile(target='kepler-138b', mission='kepler',
      cadence='long', quarter=10).download(quality_bitmask=0)
    print('TPF filename:', ntpath.basename(tpf.path))
    print('TPF dirname: ', os.path.dirname(tpf.path))

    target = 'Kepler-138b'
    ra_deg = tpf.ra
    dec_deg = tpf.dec

    # get survey image data
    width_height_arcmin = 3.00
    survey = '2MASS-J'
    survey_hdu, survey_hdr, survey_data, survey_wcs, survey_cframe = \
      mkpy3_finder_chart_survey_fits_image_get_v1(ra_deg, dec_deg,
      radius_arcmin=width_height_arcmin, survey=survey, verbose=True)

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

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

    norm = ImageNormalize(survey_data, interval=PercentileInterval(99.0),
      stretch=SqrtStretch())
    ax.imshow(survey_data, origin='lower', norm=norm, cmap='gray_r')

    ax.set_xlabel('Right Ascension (J2000)')
    ax.set_ylabel('Declination (J2000)')
    ax.set_title('')
    plt.suptitle(target)

    # put a yellow circle at the target position
    ax.scatter(ra_deg * u.deg, dec_deg * u.deg,
      transform=ax.get_transform(survey_cframe),
      s=600, edgecolor='yellow', facecolor='None', lw=3, zorder=100)

    pname = 'mkpy3_plot.png'
    if (pname != ''):
        plt.savefig(pname, bbox_inches="tight")
        print(pname, ' <--- plot filename has been written!  :-)\n')
Пример #22
0
def tpf_sap(tic):

    #search targetpixelfiles for given TIC ID
    search_res = lk.search_targetpixelfile('TIC ' + str(tic))
    #initialize SPOC found,first found
    spoc_found = False
    spoc_first = False

    lc_holder = []
    for i in range(len(search_res)):
        #select search result object
        search_i = search_res[i]
        #skip if not SPOC, 120 s exposure
        if (search_i.author.data[0] == 'SPOC') & (search_i.exptime.data[0]
                                                  == 120):
            print("Found SPOC " + str(search_i.mission[0]) + " data for TIC " +
                  str(tic) + "!")
            spoc_found = True
            if (spoc_first == False) & (spoc_first is not None):
                spoc_first = True
        else:
            continue
        tpf = search_res[i].download()
        if spoc_first == True:
            # get apertures, median image, and  WCS data for contamination plot
            pipeline_mask = tpf.pipeline_mask
            threshold_mask = tpf.create_threshold_mask(
                threshold=10, reference_pixel='center')
            median_im = np.nanmedian(tpf.hdu[1].data['FLUX'], axis=0)
            im_header = tpf.hdu[2].header  #used for later WCS projection
            #reset spoc_first to None
            spoc_first = None

        # get lightcurve with pipeline mask
        lc = tpf.to_lightcurve(aperture_mask=tpf.pipeline_mask)
        lc = lc.remove_outliers(sigma=5.0)
        lc['sector'] = np.repeat(
            a=lc.sector,
            repeats=len(lc))  #add sector label for my plotting functions
        lc_holder.append(
            lc.to_pandas().reset_index(drop=False))  #store in lc_holder

    if spoc_found == False:
        print("No SPOC data found for TIC " + str(tic) + ".")
        spoc_lc = pd.DataFrame()
        pipeline_mask = np.array([])
    else:
        spoc_lc = pd.concat(lc_holder)  #combine lc into 1 pandas dataframe

    return (spoc_lc, pipeline_mask, threshold_mask, median_im, im_header)
Пример #23
0
def make_lc(tic=None,epic=None,hostname=None,mission='tess',verbose=True):
    """Return a LightCurve object from TESS or K2 planet.

    Keyword arguments:
    Need one of:
        tic -- TIC ID # of the host star
        epic -- EPIC ID # of the host star
        hostname -- host star name
    mission -- which mission to get the data from (default 'tess')
    verbose -- whether to print status updates (default False)
    """
    if tic == None:
        if epic:
            tic = get_tic_from_epic(epic)
        elif hostname:
            tic = get_tic_from_name(hostname)

    if verbose: print('Fetching TPF...')
    if mission.lower() == 'tess':
        tpf = lk.search_targetpixelfile(tic,mission='tess').download()
    elif mission.lower() == 'k2':
        epic = get_epic_from_tic(tic)
        tpf = lk.search_targetpixelfile(epic,mission='k2').download()
    else:
        raise ValueError('Mission must be \'tess\' or \'k2\'.')

    if verbose: print('Detrending...')
    if mission.lower() == 'tess':
        corrector = lk.PLDCorrector(tpf)
        lc = corrector.correct()
    elif mission.lower() == 'k2':
        lc = tpf.to_lightcurve(aperture_mask=tpf.pipeline_mask)
        lc.remove_outliers(sigma=6).flatten()    


    if verbose: print('Success')    
    return lc
Пример #24
0
def extract_sectors(object_info, cache_dir):
    mission, mission_prefix, id_int = LcBuilder().parse_object_info(
        object_info.mission_id())
    object_sectors = None
    if mission == "Kepler":
        lcf_search_results = lightkurve.search_targetpixelfile(
            object_info.mission_id(),
            mission=object_info.mission_id(),
            cadence="long")
        object_sectors = lcf_search_results.download_all(
            download_dir=cache_dir).quarter
    elif mission == "K2":
        lcf_search_results = lightkurve.search_targetpixelfile(
            object_info.mission_id(),
            mission=object_info.mission_id(),
            cadence="long")
        object_sectors = lcf_search_results.download_all(
            download_dir=cache_dir).campaign
    elif mission == "TESS":
        lcf_search_results = lightkurve.search_tesscut(
            object_info.mission_id())
        object_sectors = lcf_search_results.download_all(
            download_dir=cache_dir).sector
    return object_sectors
Пример #25
0
def test_tess_pld_corrector():
    tpf = search_targetpixelfile("TOI 700")[0].download()
    pld = PLDCorrector(tpf)
    # Is the correct filetype returned?
    clc = pld.correct()
    assert isinstance(clc, TessLightCurve)
    # Do the diagnostic plots run?
    pld.diagnose()
    plt.close()
    pld.diagnose_masks()
    plt.close()
    # Does sparse correction work?
    pld.correct(sparse=True)
    # Did the correction with default values help?
    raw_lc = tpf.to_lightcurve(aperture_mask="threshold")
    assert clc.estimate_cdpp() < raw_lc.estimate_cdpp()
def ProcessTarget(target, targetquarter, targetexp):
    pixelfile = search_targetpixelfile(target, quarter=targetquarter, exptime=targetexp).download();
    print("\nDownloaded")

    pixelfile.plot(frame=1);

    lc = pixelfile.to_lightcurve(aperture_mask=pixelfile.pipeline_mask);
    lc.plot();
    print("\nMask Done!")

    """lc = pixelfile.to_lightcurve(aperture_mask='all');
    lc.plot();
    print("\nAll Done!")"""

    flat_lc = lc.flatten(window_length=401);
    flat_lc.plot();
    print("\nFlat Done!")
Пример #27
0
def find_planet_iter_per(star, quarter):
    tpf = lk.search_targetpixelfile(star, quarter=quarter).download()
    #tpf.plot(frame=100, scale='log', show_colorbar=True)
    #plt.show()

    lc = tpf.to_lightcurve(aperture_mask=tpf.pipeline_mask)
    #lc.plot()
    #plt.show();

    flat, trend = lc.flatten(window_length=301, return_trend=True)
    #ax = lc.errorbar(label=args.star)                   # plot() returns a matplotlib axes ...
    #trend.plot(ax=ax, color='red', lw=2, label='Trend');  # which we can pass to the next plot() to use the same axes
    #plt.show();

    #flat.errorbar(label=args.star);
    #plt.show();

    best_planet_score = None
    best_folded = None
    best_result = None
    best_interpolations = None
    for best_fit_period_start in np.arange(0.5, 30.1, 0.5): 
        periodogram = flat.to_periodogram(method="bls", period=np.arange(best_fit_period_start, best_fit_period_start + 0.5, 0.0001))
        best_fit_period = periodogram.period_at_max_power
        transit_time_at_max_power = periodogram.transit_time_at_max_power
        folded = flat.fold(period=best_fit_period, t0=transit_time_at_max_power)

        interpolations = process_folded_lc(folded)
        if is_there_a_planet(*interpolations):
            score = planet_score(*interpolations)
            # print(best_fit_period, transit_time_at_max_power, interpolations, score)
            if best_planet_score is None or score < best_planet_score:
                best_planet_score = score
                best_folded = folded
                best_result = (best_fit_period, transit_time_at_max_power)
                best_interpolations = interpolations
                # print(interpolations)
    #best_folded.bin().scatter() # .errorbar();
    #plt.show();
    #best_folded.plot_river()
    #plt.show();
    if best_result is not None:
        print(star, best_result[0], best_result[1])
    else:
        print(star, "No planet found")
Пример #28
0
 def test_from_boolean_mask(self):
     tpfs = lightkurve.search_targetpixelfile(target="TIC 251848941", cadence=120, author="SPOC")\
         .download_all()
     apertures = {}
     for tpf in tpfs:
         apertures[tpf.sector] = ApertureExtractor.from_boolean_mask(
             tpf.pipeline_mask, tpf.column, tpf.row)
     self.assertEquals(19, len(apertures[2]))
     self.assertTrue(any(([649, 171] == x).all() for x in apertures[2]))
     self.assertTrue(any(([649, 172] == x).all() for x in apertures[2]))
     self.assertTrue(any(([650, 170] == x).all() for x in apertures[2]))
     self.assertTrue(any(([650, 171] == x).all() for x in apertures[2]))
     self.assertTrue(any(([650, 172] == x).all() for x in apertures[2]))
     self.assertTrue(any(([650, 173] == x).all() for x in apertures[2]))
     self.assertTrue(any(([650, 174] == x).all() for x in apertures[2]))
     self.assertTrue(any(([651, 170] == x).all() for x in apertures[2]))
     self.assertTrue(any(([651, 171] == x).all() for x in apertures[2]))
     self.assertTrue(any(([651, 172] == x).all() for x in apertures[2]))
     self.assertTrue(any(([651, 173] == x).all() for x in apertures[2]))
     self.assertTrue(any(([651, 174] == x).all() for x in apertures[2]))
     self.assertTrue(any(([652, 170] == x).all() for x in apertures[2]))
     self.assertTrue(any(([652, 171] == x).all() for x in apertures[2]))
     self.assertTrue(any(([652, 172] == x).all() for x in apertures[2]))
     self.assertTrue(any(([652, 173] == x).all() for x in apertures[2]))
     self.assertTrue(any(([653, 171] == x).all() for x in apertures[2]))
     self.assertTrue(any(([653, 172] == x).all() for x in apertures[2]))
     self.assertTrue(any(([653, 173] == x).all() for x in apertures[2]))
     self.assertEquals(15, len(apertures[29]))
     self.assertTrue(any(([1133, 142] == x).all() for x in apertures[29]))
     self.assertTrue(any(([1133, 143] == x).all() for x in apertures[29]))
     self.assertTrue(any(([1133, 144] == x).all() for x in apertures[29]))
     self.assertTrue(any(([1133, 145] == x).all() for x in apertures[29]))
     self.assertTrue(any(([1134, 141] == x).all() for x in apertures[29]))
     self.assertTrue(any(([1134, 142] == x).all() for x in apertures[29]))
     self.assertTrue(any(([1134, 143] == x).all() for x in apertures[29]))
     self.assertTrue(any(([1134, 144] == x).all() for x in apertures[29]))
     self.assertTrue(any(([1134, 145] == x).all() for x in apertures[29]))
     self.assertTrue(any(([1135, 142] == x).all() for x in apertures[29]))
     self.assertTrue(any(([1135, 143] == x).all() for x in apertures[29]))
     self.assertTrue(any(([1135, 144] == x).all() for x in apertures[29]))
     self.assertTrue(any(([1135, 145] == x).all() for x in apertures[29]))
     self.assertTrue(any(([1136, 143] == x).all() for x in apertures[29]))
     self.assertTrue(any(([1136, 144] == x).all() for x in apertures[29]))
Пример #29
0
def test_tpf():
    """
    """
    t = Tpf(
        ticid=TICID,
        sector=SECTOR,
        quality_bitmask="default",
        apply_data_quality_mask=False,
    )
    tpf1 = t.get_tpf()
    assert tpf1.targetid == TICID
    assert tpf1.sector == SECTOR

    res = lk.search_targetpixelfile(f"TIC {t.ticid}",
                                    mission="TESS",
                                    cadence="short",
                                    sector=SECTOR)
    tpf2 = res.download()
    assert tpf1.targetid == tpf2.targetid
    assert tpf1.sector == tpf2.sector
    assert tpf1.quality_bitmask == tpf2.quality_bitmask
Пример #30
0
def plot_EPIC_ID(epic, sigma_value=5):
    #gets the pixelfile data
    pixelfile = lk.search_targetpixelfile(epic).download(
        quality_bitmask="hardest")  #gets the pixel data
    lc = pixelfile.to_lightcurve(aperture_mask='all')  #masks the noisy data
    lc = outlier_removal(lc, sigma_value)  #removes remaining outliers
    lc = outlier_removal(lc, sigma_value)  #removes remaining outliers

    #creates the file path and exports the fits file
    path = pathlib.Path(
        "EPIC ID Analysis" + str(epic)
    )  #creates the path for the EPIC ID; the name of the folder is the EPIC ID
    if path.exists() == False:
        os.mkdir("EPIC ID Analysis\\" + str(epic))
    file = "EPIC ID Analysis\\" + str(epic) + "\\" + str(
        epic
    ) + "_Info.fits"  #path for the fits file; e.g. EPIC ID Analysis/205008727/205008727_Info.fits
    print("Fits directory: ", file)
    lc.to_fits(path=file)  #exports the fits file
    lc.plot()  #plots the graph
    return lc  #returns the lightcurve data