Example #1
0
def GetLClightkurve(file='', **kwargs):
    '''
    Construct a light curve from either
    - a local KeplerTargetPixelFile, or
    - a random K2 KeplerTargetPixelFile from the archive
    using the lightkurve built-in correct function.

    Parameters
    ----------
    file : '' or str
        light curve file path. Default will download random file from archive.
    **kwargs : dict
        Keyword arguments to that will be passed to the KeplerTargetPixelFile
        constructor.

    Returns
    -------
    lc: pandas DataFrame
        light curve with columns ['time', 'flux_raw', 'error']
    '''
    if file == '':
        print('Choose a random LC from the archives...')
        idlist = pd.read_csv(
            'stars_shortlist/share/helpers/GO_all_campaigns_to_date.csv',
            usecols=['EPIC ID'])

        ID = choose_random_item(idlist['EPIC ID'].values)
        tpf = None
        try:
            tpf = KeplerTargetPixelFile.from_archive(ID, cadence='long')
        except ArchiveError:
            print('EPIC {} was observed during several campaigns.'
                  '\nChoose the earliest available.'.format(ID))
            C = 0
            while C < 20:
                print(C)
                try:
                    tpf = KeplerTargetPixelFile.from_archive(ID,
                                                             cadence='long',
                                                             campaign=C)
                except ArchiveError:
                    C += 1
                    pass
                if tpf != None:
                    break
    else:
        tpf = KeplerTargetPixelFile(file, quality_bitmask='default')

    lc = tpf.to_lightcurve(method='aperture')
    lc = lc.correct(windows=20)
    LC = pd.DataFrame({
        'flux_raw': lc.flux,
        'time': np.copy(lc.time).byteswap().newbyteorder(),
        'error': lc.flux_err,
        'flags': np.copy(lc.quality).byteswap().newbyteorder(),
    })

    return LC
Example #2
0
def from_TargetPixel_source(target, **kwargs):
    """
    Accepts paths and EPIC IDs as targets. Either fetches a ``KeplerTargetPixelFile``
    from MAST via ID or directly from a path, then creates a lightcurve with
    default Kepler/K2 pixel mask.

    Parameters
    ------------
    target : str or int
        EPIC ID (e.g., 211119999) or path to zipped ``KeplerTargetPixelFile``
    kwargs : dict
        Keyword arguments to pass to `KeplerTargetPixelFile.from_archive()
        <https://lightkurve.keplerscience.org/api/lightkurve.targetpixelfile.KeplerTargetPixelFile.html#lightkurve.targetpixelfile.KeplerTargetPixelFile.from_archive>`_
    """
    tpf = KeplerTargetPixelFile.from_archive(target, **kwargs)
    lc = tpf.to_lightcurve()
    return from_KeplerLightCurve(lc)
Example #3
0
    def detrend(self):
        """
        De-trends a FlareLightCurve using ``K2SC``.
        """
        #make sure there is no detrended_flux already
        # = make sure you only pass KeplerLightCurve derived FLCs
        tpf = KeplerTargetPixelFile.from_archive(self.targetid)
        new_lc = copy.copy(self)
        new_lc.keplerid = self.targetid
        new_lc.primary_header = tpf.hdu[0].header
        new_lc.data_header = tpf.hdu[1].header
        new_lc.pos_corr1 = tpf.hdu[1].data['POS_CORR1'][tpf.quality_mask]
        new_lc.pos_corr2 = tpf.hdu[1].data['POS_CORR2'][tpf.quality_mask]
        del tpf

        #K2SC MAGIC
        new_lc.__class__ = k2sc_lc
        new_lc.k2sc(de_niter=3) #de_niter set low for testing purpose
        # something like assert new_lc.time == self.time is needed here
        self.detrended_flux = (new_lc.corr_flux - new_lc.tr_time
                              + np.nanmedian(new_lc.tr_time))
        return
def retreive_data(num_periods=4,
                  KIC=4570949,
                  drop_outliers=False,
                  downloaded=True,
                  base_dir="../mastDownload/Kepler/",
                  params=None,
                  which_quarters=None):
    """
    Retreives and conditions data for the given KIC object

    Args:
        num_periods (int, optional) - window size for median filter
        KIC (optional, int) - KIC number
        drop_outliers (optional, boolean) - drop outliers?
        downloaded (optional, boolean) - whether data are DLed
        base_dir (optional, str) - directory under which to find data files
        params (optional, dict) - if not None, the routine masks
            points in transit (as indicated by the params values)
            while conditioning the data
        which_quarters (optional, list) - which quarters to return

    Returns:
        time (float array) - observational times
        flux (float array) - unconditioned light curve data
        filtered_time (float array) - observational times, conditioned
        filtered_flux (float array) - observational data, conditioned

    """

    if (not downloaded):
        for q in range(0, 18):
            try:
                lc = KeplerLightCurveFile.from_archive(
                    str(KIC), quarter=q, verbose=False).PDCSAP_FLUX
                tpf = KeplerTargetPixelFile.from_archive(str(KIC), quarter=q)

            except:
                pass

    time = np.array([])
    flux = np.array([])

    filtered_time = np.array([])
    filtered_flux = np.array([])

    # Return the filter
    returned_filter = np.array([])

    # Collect all data files
    ls = glob(base_dir + "kplr*" + str(KIC) + "_lc_Q*/*.fits")
    tpfs = glob(base_dir + "kplr*" + str(KIC) + "_lc_Q*/*targ.fits.gz")

    if (which_quarters is None):
        which_quarters = range(len(ls))

    for i in which_quarters:
        # PDCSAP_FLUX supposedly takes care of the flux fraction -
        # _Data Processing Handbook_, p. 129
        # https://archive.stsci.edu/kepler/manuals/KSCI-19081-002-KDPH.pdf
        lc = KeplerLightCurveFile(ls[i]).PDCSAP_FLUX
        lc.remove_nans()

        cur_time = lc.time
        cur_flux = lc.flux

        # Remove nans since remove_nans above doesn't seem to work.
        ind = ~np.isnan(cur_flux)
        cur_time = cur_time[ind]
        cur_flux = cur_flux[ind]

        time = np.append(time, cur_time)
        flux = np.append(flux, cur_flux)

        cur_filtered_time, cur_filtered_flux, cur_filter =\
                filter_data(cur_time, cur_flux, num_periods=num_periods,
                        drop_outliers=drop_outliers, params=params)

        filtered_time = np.append(filtered_time, cur_filtered_time)
        filtered_flux = np.append(filtered_flux, cur_filtered_flux)
        returned_filter = np.append(returned_filter, cur_filter)

    # Finally remove any NaNs that snuck through
    ind = ~np.isnan(filtered_flux)
    filtered_time = filtered_time[ind]
    filtered_flux = filtered_flux[ind]

    return time, flux, filtered_time, filtered_flux, returned_filter
Example #5
0
param_values = np.zeros((1, 5))
for i in range(sheet.nrows):
    i = int(i)
    row = 5  # Which system in the excel file do you want to look at? Remember to -1 because excel is not 0 indexed. So, if I want to look at the system in row 3 of the excel file, I need to type in '2' here
    stellarsystem = sheet.cell_value(row, 0)
    quarter = sheet.cell_value(row, 1)
    starmass = sheet.cell_value(row, 2)
    starradius = sheet.cell_value(row, 3)
    startemp = sheet.cell_value(row, 4)
print('Stellar System: ', int(stellarsystem), '\nQuarter of Observation: ',
      int(quarter), '\nHost Star Mass in Solar Masses: ', starmass,
      '\nRadius of Host Star in Solar Radii: ', starradius,
      '\nTemperature of Host Star in Kelvin: ', startemp)

# Importing our data (target pixel file)
tpf = KeplerTargetPixelFile.from_archive(int(stellarsystem),
                                         quarter=int(quarter))
tpf.plot(aperture_mask=tpf.pipeline_mask)

# Convert the target pixel file into a light curve using the pipeline-defined aperture mask
lc = tpf.to_lightcurve(aperture_mask=tpf.pipeline_mask)
lc.plot()
plt.title("Light Curve from TPF")

# Use Kepler Light Curve File now (rather than being generated by us using a Target Pixel File, these files have been pregenerated using NASA’s Kepler Data Processing Pipeline - contains SAP and PDCSAP flux)
lcf = KeplerLightCurveFile.from_archive(
    int(stellarsystem), quarter=int(quarter)).PDCSAP_FLUX.remove_nans()
lcf.plot()
plt.title('PDCSAP Flux Light Curve From Archive of Kepler ' +
          str(stellarsystem))
# lcf.scatter()