Example #1
0
def test_to_corrector():
    """Does the tpf.to_corrector('pld') convenience method work?"""
    from lightkurve import KeplerTargetPixelFile
    from .test_targetpixelfile import TABBY_TPF

    tpf = KeplerTargetPixelFile(TABBY_TPF)
    lc = tpf.to_corrector("pld").correct()
    assert len(lc.flux) == len(tpf.time)
Example #2
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 #3
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"
Example #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
Example #5
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 #6
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"
Example #7
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
Example #8
0
def plot_lc(fname,index,verbose=True,show_all_lc=False,show_mask=True,sigma=None):
    hdulist = fits.open(fname)
    hdulen = len(hdulist)
    tpf = KeplerTargetPixelFile(fname, quality_bitmask='hardest')
    if verbose:
        print(hdulist.info())

    if index == 0: #primary
        data, hdr = read_tpf(fname,index,return_hdr=True)
        print('Plot of primary hdu currently unsupported. Try index=2\n')
        sys.exit()

    elif index == 1: #target tables
        data, hdr = read_tpf(fname,index,return_hdr=True)
        print('Plot of target table currently unsupported. Try index=2\n')
        sys.exit()

    nrows=hdulen-3 #remove first 3 indices
    fig, ax = pl.subplots(nrows=nrows,ncols=1,figsize=(10,10),sharex=True,squeeze=True)
    if index<hdulen and index>2:
        #read flux per r
        epic = str(tpf.keplerid)
        if show_all_lc:
            n=0
            for idx in np.arange(3,hdulen,1):
                df, hdr = read_tpf(fname,idx,return_hdr=True)
                t = df['time']
                f = df['flux']
                ferr = df['flux_err']
                rad = hdr['ap_rad']
                shape = hdr['ap_shape']

                if sigma is not None:
                    f_c=sigma_clip(f, sigma=sigma)
                    t = t[~f_c.mask]
                    f = f[~f_c.mask]
                    ferr = ferr[~f_c.mask]
                    print('removed {} outliers.\n'.format(np.sum(f_c.mask)))
                ax[n].errorbar(t,f,yerr=ferr,marker='o',label='r={}'.format(rad))
                ax[n].legend()
                n+=1
            pl.title('EPIC-'+epic)

        else:
            df, hdr = read_tpf(fname,index,return_hdr=True)
            t = df['time']
            f = df['flux']
            ferr = df['ferr']
            rad = hdr['ap_radius']
            shape = hdr['ap_shape']
            ax.errorbar(t,f,yerr=ferr,marker='o',label='r={}'.format(rad))
            ax.set_title(epic)
            pl.legend()

        if show_mask:
            mask = hdulist[2].data
            #fluxes = tpf.flux
            #plot_aper_mask(fluxes,rad,aper_shape=shape,contrast=0.1,epic=tpf.keplerid)
            ax = tpf.plot(aperture_mask=mask, mask_color='w', #frame=300,
                scale='linear', cmap='viridis', show_colorbar=True)
            pl.show()
    elif index>hdulen:
        print('hdulist has index until {} only. Exiting!\n'.format(hdulen))
        sys.exit()

    else:
        print('Incorrect index. Set verbose=True.\n')

    return fig
Example #9
0
def tpf2lc(fname, radii, aper_shape='round', outlier_sigma=5,
        flat_window=301, corr_window=51, cutoff_limit=1.0, polyorder=4,
        break_tolerance=5,save_as_tpf=False, verbose=False, outdir='reduced'):
    '''
    Do aperture photometry with multiple apertures and a mask.
    The light curve with a given aperture is appended with the original data and saved
    as separate fits. The best light curve/aperture (determined with cdpp) is saved in index=1. 
    '''
    fname_new = os.path.join(outdir,epic+'_'+aper_shape+'.fits')
    if 

    print('\nAperture photometry with r={} and {} mask...\n'.format(radii,aper_shape))
    if verbose:
        print("""sigma cut for outliers: {}\nwindow length (flatten): {}\nwindow length (sff): {}\ncutoff limit (if mask=irregular): {}\n
            """.format(outlier_sigma,flat_window,corr_window,cutoff_limit))
    hdr = fits.getheader(fname)
    hdulist = fits.open(fname)
    tpf = KeplerTargetPixelFile(fname, quality_bitmask='hardest')
    epic=str(tpf.keplerid)

    if epic not in hdulist.filename():
        raise ValueError('Kepler ID in header doesn\'t match the filename')

    flux_per_r = {}
    cdpps = {}
    for r in radii:
        mask = make_mask(tpf.flux, rad=r, shape=aper_shape, epic=epic)
        lc = tpf.to_lightcurve(aperture_mask=mask);
        lc2 = lc.remove_nans().remove_outliers(sigma=outlier_sigma)
        flat_lc2, trend = lc2.flatten(window_length=flat_window,
                                    polyorder=polyorder,
                                    break_tolerance=break_tolerance,
                                    return_trend=True)
        corr_lc = flat_lc2.correct(method='sff',windows=corr_window)

        flux_per_r[r]=(corr_lc.time,corr_lc.flux,corr_lc.flux_err)
        cdpps[r] = corr_lc.cdpp()

    ###TO DO: add lc generated with irregular mask
    mask = make_mask(tpf.flux, rad=r, shape='irregular', epic=epic)
    lc = tpf.to_lightcurve(aperture_mask=mask);
    lc2 = lc.remove_nans().remove_outliers(sigma=outlier_sigma)
    flat_lc2, trend = lc2.flatten(window_length=flat_window,
                                polyorder=polyorder,
                                break_tolerance=break_tolerance,
                                return_trend=True)
    corr_lc = flat_lc2.correct(method='sff',windows=corr_window)
    flux_per_r['irreg']=(corr_lc.time,corr_lc.flux,corr_lc.flux_err)
    cdpps['irreg'] = corr_lc.cdpp()

    if save_as_tpf:
        cdpp_list=[]
        #append to hdulist photometry of each aperture and save
        for num,r in enumerate(flux_per_r):
            comment_num = 'COMMENT{}'.format(num)
            aper_name = '{}_APER{}'.format(aper_shape,num)
            hdr['ap_rad'] = r
            hdr['ap_shape'] = aper_shape
            hdr['cdpp'] = cdpps[r]
            cdpp_list.append(cdpps[r])

            tab = table.Table(flux_per_r[r], names=['time','flux','flux_err'])
            bintab=fits.BinTableHDU(tab,name=aper_name,header=hdr)
            #append bin table to original hdulist
            hdulist.append(bintab)

        #find smallest cdpp
        best_r=min(cdpps.items(), key=operator.itemgetter(1))[0]

        #re-create bin table
        #tab = table.Table(flux_per_r[best_r], names=['time','flux','flux_err'])
        #bintab=fits.BinTableHDU(tab,name=aper_name,header=hdr)
        #move to index 3 (0: primary; 1: table; 2: aperture)
        #hdulist.insert(3, bintab)

        #alternatively, move hdu into last index of hdulist
        hdulist += [hdulist.pop(3+np.argmin(cdpp_list))]

        #make hdu for best mask
        if best_r == 'irreg':
            mask = make_mask(tpf.flux, rad=r, shape='irreg', epic=epic)
        else:
            mask = make_mask(tpf.flux, rad=best_r, shape=aper_shape, epic=epic)
        hdu=fits.hdu.ImageHDU(np.array(mask,dtype=float), name='APERTURE', header=hdr) #problem with bool
        #replace aperture
        hdulist[2] = hdu

        #save fits
        #fname_new = os.path.join(outdir,fname.split('/')[-1].split('-')[0][4:]+'_'+aper_shape+'.fits')
        if not os.path.exists(outdir):
            os.makedirs(outdir)
        hdulist.writeto(fname_new)
        print('Saved: {}\n'.format(fname_new))

    return flux_per_r, mask


def read_tpf(fname,index,return_hdr=True):
    '''
    fname: str, filename
    index: int, hdulist index
            [0,1,2] = primary, target table, aperture mask
            [4,...] = photometry using specified aperture
    return_hdr: bool
    '''
    hdulist = fits.open(fname)
    if index == 0: #primary
        data = hdulist[index].data
        hdr = hdulist[index].header
        if return_hdr:
            return data, hdr
        else:
            return data
    elif index == 1: #target tables
        data = hdulist[index].data
        hdr = hdulist[index].header
        if return_hdr:
            return data, hdr
        else:
            return data
    elif index == 2: #aperture mask
        data = hdulist[index].data
        hdr = hdulist[index].header
        if return_hdr:
            return data, hdr
        else:
            return data
    else:
        df=table.Table(hdulist[index].data).to_pandas()
        hdr = hdulist[index].header
        if return_hdr:
            return df, hdr
        else:
            return df

def plot_lc(fname,index,verbose=True,show_all_lc=False,show_mask=True,sigma=None):
    hdulist = fits.open(fname)
    hdulen = len(hdulist)
    tpf = KeplerTargetPixelFile(fname, quality_bitmask='hardest')
    if verbose:
        print(hdulist.info())

    if index == 0: #primary
        data, hdr = read_tpf(fname,index,return_hdr=True)
        print('Plot of primary hdu currently unsupported. Try index=2\n')
        sys.exit()

    elif index == 1: #target tables
        data, hdr = read_tpf(fname,index,return_hdr=True)
        print('Plot of target table currently unsupported. Try index=2\n')
        sys.exit()

    nrows=hdulen-3 #remove first 3 indices
    fig, ax = pl.subplots(nrows=nrows,ncols=1,figsize=(10,10),sharex=True,squeeze=True)
    if index<hdulen and index>2:
        #read flux per r
        epic = str(tpf.keplerid)
        if show_all_lc:
            n=0
            for idx in np.arange(3,hdulen,1):
                df, hdr = read_tpf(fname,idx,return_hdr=True)
                t = df['time']
                f = df['flux']
                ferr = df['flux_err']
                rad = hdr['ap_rad']
                shape = hdr['ap_shape']

                if sigma is not None:
                    f_c=sigma_clip(f, sigma=sigma)
                    t = t[~f_c.mask]
                    f = f[~f_c.mask]
                    ferr = ferr[~f_c.mask]
                    print('removed {} outliers.\n'.format(np.sum(f_c.mask)))
                ax[n].errorbar(t,f,yerr=ferr,marker='o',label='r={}'.format(rad))
                ax[n].legend()
                n+=1
            pl.title('EPIC-'+epic)

        else:
            df, hdr = read_tpf(fname,index,return_hdr=True)
            t = df['time']
            f = df['flux']
            ferr = df['ferr']
            rad = hdr['ap_radius']
            shape = hdr['ap_shape']
            ax.errorbar(t,f,yerr=ferr,marker='o',label='r={}'.format(rad))
            ax.set_title(epic)
            pl.legend()

        if show_mask:
            mask = hdulist[2].data
            #fluxes = tpf.flux
            #plot_aper_mask(fluxes,rad,aper_shape=shape,contrast=0.1,epic=tpf.keplerid)
            ax = tpf.plot(aperture_mask=mask, mask_color='w', #frame=300,
                scale='linear', cmap='viridis', show_colorbar=True)
            pl.show()
    elif index>hdulen:
        print('hdulist has index until {} only. Exiting!\n'.format(hdulen))
        sys.exit()

    else:
        print('Incorrect index. Set verbose=True.\n')

    return fig
#---------------------------STATS---------------------------#


def noise_statistic(t, f, timescale=0.25, verbose=False):
    '''
    c.f. lightkurve.cdpp()
    '''
    nchunks = int((t[-1]-t[0])/timescale)+1
    idx = [(t > t[0] + n * timescale) & (t < t[0] + (n + 1) * timescale) for n in range(nchunks)]
    chunks = [f[ix] for ix in idx if ix.sum() > 1]

    cdpp = np.std([np.nanmedian(ch) for ch in chunks])

    if verbose:
        print('cdpp = {:.4f}'.format(cdpp))

    return cdpp
Example #10
0
    lcNorm = lc.flux / np.nanmedian(lc.flux)


#    lines.append(ax.scatter(lc.time[i], custLCC[i], s=20, c='r'))
#    lines.append(ax.scatter(lc.time[i], custLCR[i], s=20, c='k'))

#    circleShape = patches.Circle((x[i],y[i]), 1.5, fill=False, alpha=0.4)
#    rectanShape = patches.Rectangle((x[i]-1.5,y[i]-1.5), 3.0, 3.0, fill=False)
#    p = PatchCollection([rectanShape, circleShape], alpha=0.4)
#    colors = np.linspace(0,1,2)
#    p.set_array(np.array(colors))
#    p.set_edgecolor('face')
#    ps.append(ax1.add_collection(p))

id = str(sys.argv[1])
tpf = ktpf.from_fits('./figures/{}_tpf.fits'.format(id))
lc = tpf.to_lightcurve()

pointing = 'pointingModel_{}-{}.txt'.format(3, 3)

theta, delX, delY = np.loadtxt(pointing,
                               usecols=(1, 2, 3),
                               skiprows=1,
                               unpack=True)

new_id, pos, tmag = ticID(int(id))
x, y, scats, lines = [], [], [], []
ps = []

for i in range(len(tpf.flux) - 1):
    if i == 0:
Example #11
0
def generate_tweet(tpf_fn=None, movie_length=60, step=49):
    """Generate a status message and animated gif.

    Parameters
    ----------
    tpf_fn : str (optional)
        Path or url to a TPF file. If `None`, a random file will be downloaded.

    movie_length : int (optional)
        Number of frames in the animation.

    Returns
    -------
    (status, gif, plot, tpf) : (str, str, str, `TargetPixelFile`)
    """
    # Open the Target Pixel File
    if tpf_fn is None:  # Get a random url
        db = KeplerArchiveCrawlerDB('tpf-urls/latest-tpf-urls.txt')
        tpf_fn = db.random_url()
    log.info('Opening {0}'.format(tpf_fn))
    tpf = TargetPixelFile(tpf_fn, cache=False)
    log.info('KEPMAG = {0}, DIM = {1}'.format(tpf.hdulist[0].header['KEPMAG'],
                                              tpf.hdulist[1].header['TDIM5']))
    # Don't tweet tiny strips
    if (tpf.hdulist[2].header['NAXIS1'] <
            3) or (tpf.hdulist[2].header['NAXIS2'] < 3):
        raise Exception('Tiny strip')
    # Files contain occasional bad frames, so we make multiple attempts
    # with random starting points
    attempt_no = 0
    while attempt_no < 7:
        attempt_no += 1
        try:
            start = random.randint(0, tpf.no_frames - step * movie_length)
            try:
                kepmag = '🔆 Kp {:.1f}\n'.format(
                    float(tpf.hdulist[0].header['KEPMAG']))
            except Exception:
                kepmag = ''
            timestr = tpf.timestamp(start).split(' ')[0]
            campaign = tpf.hdulist[0].header['CAMPAIGN']
            url = "https://archive.stsci.edu/k2/data_search/search.php?ktc_k2_id={}&action=Search".format(
                tpf.objectname.split(' ')[1])
            status = ('New Kepler data were recently released!\n'
                      '🔎 {}\n'
                      '🗓 {} (C{})\n'
                      '{}'
                      '🔗 {}'.format(tpf.objectname, timestr, campaign,
                                       kepmag, url))
            log.info(status)
            # Create the animated gif
            gif_fn = '/tmp/keplerbot.gif'
            tpf.save_movie(gif_fn,
                           start=start,
                           stop=start + step * movie_length,
                           step=step,
                           fps=3,
                           min_percent=0.,
                           max_percent=93.,
                           ignore_bad_frames=True)
            # Create the lightcurve plot
            plot_fn = '/tmp/keplerbot-lightcurve.png'
            ktpf = KeplerTargetPixelFile(tpf_fn)
            ktpf.to_lightcurve(aperture_mask='all').correct(
                restore_trend=True).remove_outliers().scatter(normalize=False)
            pl.tight_layout()
            print('Writing {}'.format(plot_fn))
            pl.savefig(plot_fn)
            pl.close()

            return status, gif_fn, plot_fn, tpf
        except Exception as e:
            log.error(e)
    raise Exception('Tweet failed')
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 #13
0
matplotlib.use("Agg")
import matplotlib.gridspec as gridspec
from scipy.misc import imread


def animate(i):
    global scats, lines, lc
    ax1.imshow(tpf.flux[i], origin='lower', vmin=cbmin, vmax=cbmax)
    for line in lines:
        line.remove()
    lines = []
    lines.append(ax.scatter(lc.time[i], lcNorm[i], s=16, c='r'))


file = '219870537.fits'
tpf = ktpf.from_fits(file)
lc = tpf.to_lightcurve()
lcNorm = lc.flux / np.nanmedian(lc.flux)

cbmin = np.max(tpf.flux[0]) * 0.05
cbmax = np.max(tpf.flux[0]) * 0.85

lines = []
img = imread('ellie_logo.png')
fig = plt.figure(figsize=(10, 5))

plt.imshow(img)
plt.axis('off')
plt.tight_layout()

ax = fig.add_axes([0.685, 0.1335, 0.165, 0.176])
Example #14
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()