FlareLightCurve

class altaipony.flarelc.FlareLightCurve(time=None, flux=None, flux_err=None, time_format=None, time_scale=None, time_unit=None, centroid_col=None, centroid_row=None, quality=None, quality_bitmask=None, channel=None, campaign=None, quarter=None, sector=None, mission=None, cadenceno=None, targetid=None, ra=None, dec=None, label=None, meta={}, detrended_flux=None, detrended_flux_err=None, flux_trends=None, gaps=None, flares=None, flux_unit=None, primary_header=None, data_header=None, pos_corr1=None, pos_corr2=None, origin='FLC', fake_flares=None, it_med=None, pixel_flux=None, pixel_flux_err=None, pipeline_mask=None, camera=None, ccd=None, saturation=None)[source]

Bases: lightkurve.lightcurve.KeplerLightCurve, lightkurve.lightcurve.TessLightCurve

Flare light curve class that unifies properties of K2SC-de-trended and Kepler’s lightkurve.KeplerLightCurve.

Attributes:
time : array-like

Time measurements.

flux : array-like

Flux count for every time point.

flux_err : array-like

Uncertainty on each flux data point.

pixel_flux : multi-dimensional array

Flux in the target pixels from the KeplerTargetPixelFile.

pixel_flux_err : multi-dimensional array

Uncertainty on pixel_flux.

pipeline_mask : multi-dimensional boolean array

TargetPixelFile mask for aperture photometry.

time_format : str

String specifying how an instant of time is represented, e.g., ‘bkjd’ or ‘jd’.

time_scale : str

String that specifies how the time is measured, e.g., tdb’, ‘tt’, ‘ut1’, or ‘utc’.

time_unit : astropy.unit

Astropy unit object defining unit of time.

centroid_col : array-like

Centroid column coordinates as a function of time.

centroid_row : array-like

Centroid row coordinates as a function of time.

quality : array-like

Kepler quality flags.

quality_bitmask : str

Can be ‘none’, ‘default’, ‘hard’ or ‘hardest’.

channel : int

Channel number, where aperture is located on the CCD.

campaign : int

K2 campaign number.

quarter : int

Kepler Quarter number.

sector : int

TESS sector number

mission : string

Mission identifier, e.g., ‘TESS’, ‘K2’ or ‘Kepler’.

cadenceno : array-like

Cadence number - unique identifier.

targetid : int

EPIC ID number.

ra : float

RA in deg.

dec : float

Declination in deg.

label : string

‘EPIC xxxxxxxxx’.

meta : dict

Free-form metadata associated with the LightCurve. Not populated in general.

detrended_flux : array-like

K2SC detrend flux, same units as flux.

detrended_flux_err : array-like

K2SC detrend flux error, same units as flux.

flux_trends : array-like

Astrophysical variability as derived by K2SC.

gaps : list of tuples of ints

Each tuple contains the start and end indices of observation gaps. See find_gaps.

flares : DataFrame

Table of flares, their start and stop time, recovered equivalent duration (ED), and, if applicable, recovery probability, ratio of recovered ED to injected synthetic ED. Also information about quality flags may be stored here.

it_med : array-like

Iterative median, see the find_iterative_median method.

Attributes Summary

astropy_time Returns the time values as an Astropy ~astropy.time.Time object.
extra_columns
flux_quantity Returns the flux as an Astropy ~astropy.units.Quantity object.
flux_unit

Methods Summary

append(others[, inplace]) Append one or more other LightCurve object(s) to this one.
bin([binsize, bins, method]) Bins a lightcurve in chunks defined by binsize or bins.
characterize_flares([flares_per_bin, …]) Use results from injection recovery to determine corrected flare characteristics.
copy() Returns a copy of this LightCurve object.
detrend(mode[, save, path, de_niter, …]) De-trends a FlareLightCurve using K2SC.
errorbar([linestyle]) Plots the light curve using Matplotlib’s ~matplotlib.pyplot.errorbar method.
estimate_cdpp([transit_duration, …]) Estimate the CDPP noise metric using the Savitzky-Golay (SG) method.
fill_gaps([method]) Fill in gaps in time.
find_flares([minsep, fake]) Find flares in a FlareLightCurve.
find_gaps([maxgap, minspan, splits]) Find gaps in light curve and stores them in the gaps attribute.
flatten([window_length, polyorder, …]) Removes the low frequency trend using scipy’s Savitzky-Golay filter.
fold(period[, t0, transit_midpoint]) Folds the lightcurve at a specified period and reference time t0.
from_stingray(lc) Create a new LightCurve from a stingray.Lightcurve.
from_timeseries(ts) Creates a new LightCurve from an AstroPy ~astropy.timeseries.TimeSeries object.
get_saturation([factor, return_level]) Goes back to the TPF and measures the maximum saturation level during a flare, averaged over the aperture mask.
inject_fake_flares([gapwindow, fakefreq, …]) Create a number of events, inject them in to data Use grid of amplitudes and durations, keep ampl in relative flux units Keep track of energy in Equiv Dur.
interact_bls([notebook_url, minimum_period, …]) Display an interactive Jupyter Notebook widget to find planets.
load_injrec_data(path, **kwargs) Fetch the injection-recovery table from a given path, and append it to any existing table.
mark_flagged_flares([explain]) Mark all flares that coincide with K2 flagged cadences.
normalize([unit]) Returns a normalized version of the light curve.
plot(**kwargs) Plot the light curve using Matplotlib’s ~matplotlib.pyplot.plot method.
plot_ed_ratio_heatmap([ampl_bins, dur_bins, …]) Plot recovered amplitude and recovered duration vs.
plot_recovery_probability_heatmap([…]) Plot injected amplitude and injected FWHM vs.
plot_river(period[, t0, ax, bin_points, …]) Plot the light curve as a river plot.
query_solar_system_objects([cadence_mask, …]) Returns a list of asteroids or comets which affected the light curve.
remove_nans() Removes cadences where the flux is NaN.
remove_outliers([sigma, sigma_lower, …]) Removes outlier data points using sigma-clipping.
sample_flare_recovery([iterations, …]) Runs a number of injection recovery cycles and characterizes the light curve by recovery probability and equivalent duration underestimation.
scatter([colorbar_label, show_colorbar]) Plots the light curve using Matplotlib’s ~matplotlib.pyplot.scatter method.
show_properties() Prints a description of all non-callable attributes.
to_corrector([method]) Returns a corrector object to remove instrument systematics.
to_csv([path_or_buf]) Writes the light curve to a CSV file.
to_fits(path) Write FlareLightCurve to a .fits file.
to_pandas([columns]) Converts the light curve to a Pandas ~pandas.DataFrame object.
to_periodogram([method]) Converts the light curve to a ~lightkurve.periodogram.Periodogram power spectrum object.
to_seismology(**kwargs) Returns a ~lightkurve.seismology.Seismology object for estimating quick-look asteroseismic quantities.
to_stingray() Returns a stingray.Lightcurve object.
to_table() Converts the light curve to an Astropy ~astropy.table.Table object.
to_timeseries() Converts the light curve to an AstroPy ~astropy.timeseries.TimeSeries object.

Attributes Documentation

astropy_time

Returns the time values as an Astropy ~astropy.time.Time object.

The Time object will be created based on the values of the light curve’s time, time_format, and time_scale attributes.

Raises:
ValueError

If the time_format attribute is not set or not one of the formats allowed by AstroPy.

Examples

The section below demonstrates working with time values using the TESS light curve of Pi Mensae as an example, which we obtained as follows:

>>> import lightkurve as lk
>>> lc = lk.search_lightcurvefile("Pi Mensae", mission="TESS", sector=1).download().PDCSAP_FLUX  
>>> lc  
TessLightCurve(TICID: 261136679)

Every LightCurve object has a time attribute, which provides access to the original array of time values given in the native format and scale used by the data product from which the light curve was obtained:

>>> lc.time  
array([1325.29698328, 1325.29837215, 1325.29976102, ..., 1353.17431099,
       1353.17569985, 1353.17708871])
>>> lc.time_format  
'btjd'
>>> lc.time_scale  
'tdb'

To enable users to convert these time values to different formats or scales, Lightkurve provides an easy way to access the time values as an AstroPy Time object:

>>> lc.astropy_time  
<Time object: scale='tdb' format='jd' value=[2458325.29698328 2458325.29837215 2458325.29976102 ... 2458353.17431099
2458353.17569985 2458353.17708871]>

This is convenient because AstroPy Time objects provide a lot of useful features. For example, we can now obtain the Julian Day or ISO values that correspond to the raw time values:

>>> lc.astropy_time.iso  
array(['2018-07-25 19:07:39.356', '2018-07-25 19:09:39.354',
       '2018-07-25 19:11:39.352', ..., '2018-08-22 16:11:00.470',
       '2018-08-22 16:13:00.467', '2018-08-22 16:15:00.464'], dtype='<U23')
>>> lc.astropy_time.jd   
array([2458325.29698328, 2458325.29837215, 2458325.29976102, ...,
       2458353.17431099, 2458353.17569985, 2458353.17708871])
extra_columns = ('quality', 'cadenceno', 'centroid_col', 'centroid_row')
flux_quantity

Returns the flux as an Astropy ~astropy.units.Quantity object.

flux_unit

Methods Documentation

append(others, inplace=False)

Append one or more other LightCurve object(s) to this one.

Parameters:
others : LightCurve, or list of LightCurve

Light curve(s) to be appended to the current one.

inplace : bool

If True, change the current LightCurve instance in place instead of creating and returning a new one. Defaults to False.

Returns:
new_lc : LightCurve

Light curve which has the other light curves appened to it.

bin(binsize=None, bins=None, method='mean')

Bins a lightcurve in chunks defined by binsize or bins.

The flux value of the bins will be computed by taking the mean (method='mean') or the median (method='median') of the flux. The default is mean.

Parameters:
binsize : int or None

Number of cadences to include in every bin. The default is 13 if neither bins nor binsize is assigned.

bins : int, list of int, str, or None

Requires Astropy version >3.1 and >2.10 Instruction for how to assign bin locations grouping by the time of samples rather than index; overrides the binsize= if given. If bins is an int, it is the number of bins. If it is a list it is taken to be the bin edges. If it is a string, it must be one of ‘blocks’, ‘knuth’, ‘scott’ or ‘freedman’. See ~astropy.stats.histogram for description of these algorithms.

method: str, one of ‘mean’ or ‘median’

The summary statistic to return for each bin. Default: ‘mean’.

Returns:
binned_lc : LightCurve

A new light curve which has been binned.

Notes

  • If the ratio between the lightcurve length and the binsize is not a whole number, then the remainder of the data points will be ignored.
  • If the original light curve contains flux uncertainties (flux_err), the binned lightcurve will report the root-mean-square error. If no uncertainties are included, the binned curve will return the standard deviation of the data.
  • If the original lightcurve contains a quality attribute, then the bitwise OR of the quality flags will be returned per bin.
characterize_flares(flares_per_bin=30, ampl_bins=None, dur_bins=None)[source]

Use results from injection recovery to determine corrected flare characteristics.

copy()

Returns a copy of this LightCurve object.

This method uses Python’s copy.deepcopy function to ensure that all objects stored within the LightCurve instance are fully copied.

Returns:
lc_copy : LightCurve

A new light curve object which is a copy of the original.

detrend(mode, save=False, path='detrended_lc.fits', de_niter=30, max_sigma=3, func=None, **kwargs)[source]

De-trends a FlareLightCurve using K2SC. Optionally saves the LightCurve in a fits file that can be read as K2SC file.

mode : str
“k2sc” or “savgol” or “custom”
de_niter : int
Differential Evolution global optimizer parameter. K2SC default is 150, here set to 30 as a safety net to avoid unintenional computational effort.
max_sigma: int
Default is 3, value is passed to iterative sigma clipping in K2SC
save : False or bool
If True, the light curve is saved as a fits file to a given folder.
path : str
Path to resulting fits file. As a default, the fits file will be stored in the working directory.
func : function
custom detrending function
kwargs : dict
Keyword arguments to pass to k2sc, detrend_savgol, or custom method
Returns:
FlareLightCurve
errorbar(linestyle='', **kwargs)

Plots the light curve using Matplotlib’s ~matplotlib.pyplot.errorbar method.

Parameters:
ax : ~matplotlib.axes.Axes

A matplotlib axes object to plot into. If no axes is provided, a new one will be generated.

normalize : bool

Normalize the lightcurve before plotting?

xlabel : str

Plot x axis label

ylabel : str

Plot y axis label

title : str

Plot set_title

style : str

Path or URL to a matplotlib style file, or name of one of matplotlib’s built-in stylesheets (e.g. ‘ggplot’). Lightkurve’s custom stylesheet is used by default.

linestyle : str

Connect the error bars using a line?

kwargs : dict

Dictionary of arguments to be passed to matplotlib.pyplot.scatter.

Returns:
ax : ~matplotlib.axes.Axes

The matplotlib axes object.

estimate_cdpp(transit_duration=13, savgol_window=101, savgol_polyorder=2, sigma=5.0)

Estimate the CDPP noise metric using the Savitzky-Golay (SG) method.

A common estimate of the noise in a lightcurve is the scatter that remains after all long term trends have been removed. This is the idea behind the Combined Differential Photometric Precision (CDPP) metric. The official Kepler Pipeline computes this metric using a wavelet-based algorithm to calculate the signal-to-noise of the specific waveform of transits of various durations. In this implementation, we use the simpler “sgCDPP proxy algorithm” discussed by Gilliland et al (2011ApJS..197….6G) and Van Cleve et al (2016PASP..128g5002V).

The steps of this algorithm are:
  1. Remove low frequency signals using a Savitzky-Golay filter with window length savgol_window and polynomial order savgol_polyorder.
  2. Remove outliers by rejecting data points which are separated from the mean by sigma times the standard deviation.
  3. Compute the standard deviation of a running mean with a configurable window length equal to transit_duration.

We use a running mean (as opposed to block averaging) to strongly attenuate the signal above 1/transit_duration whilst retaining the original frequency sampling. Block averaging would set the Nyquist limit to 1/transit_duration.

Parameters:
transit_duration : int, optional

The transit duration in units of number of cadences. This is the length of the window used to compute the running mean. The default is 13, which corresponds to a 6.5 hour transit in data sampled at 30-min cadence.

savgol_window : int, optional

Width of Savitsky-Golay filter in cadences (odd number). Default value 101 (2.0 days in Kepler Long Cadence mode).

savgol_polyorder : int, optional

Polynomial order of the Savitsky-Golay filter. The recommended value is 2.

sigma : float, optional

The number of standard deviations to use for clipping outliers. The default is 5.

Returns:
cdpp : float

Savitzky-Golay CDPP noise metric in units parts-per-million (ppm).

Notes

This implementation is adapted from the Matlab version used by Jeff van Cleve but lacks the normalization factor used there: svn+ssh://murzim/repo/so/trunk/Develop/jvc/common/compute_SG_noise.m

fill_gaps(method='gaussian_noise')

Fill in gaps in time.

By default, the gaps will be filled with random white Gaussian noise distributed according to \(\mathcal{N} (\mu=\overline{\mathrm{flux}}, \sigma=\mathrm{CDPP})\). No other methods are supported at this time.

Parameters:
method : string {‘gaussian_noise’}

Method to use for gap filling. Fills with Gaussian noise by default.

Returns:
filled_lightcurve : LightCurve

A new light curve object in which all NaN values and gaps in time have been filled.

find_flares(minsep=3, fake=False, **kwargs)[source]

Find flares in a FlareLightCurve.

Parameters:
minsep : 3 or int

Minimum distance between two candidate start times in datapoints.

kwargs : dict

keyword arguments to pass to find_flares_in_cont_obs_period()

Returns:
FlareLightCurve
find_gaps(maxgap=0.09, minspan=10, splits=[])[source]

Find gaps in light curve and stores them in the gaps attribute. If required, adds additional splits in an arbitrary number of places. Caution: passing splits values means that you override the minspan and maxgap.

Parameters:
time : numpy array with floats

sorted array, in units of days

maxgap : 0.09 or float

maximum time gap between two datapoints in days, default equals approximately 2h

minspan : 10 or int

minimum number of datapoints in continuous observation, i.e., w/o gaps as defined by maxgap

splits : list of floats or ints

additional places in which to slice the time series

Returns:
FlareLightCurve
flatten(window_length=101, polyorder=2, return_trend=False, break_tolerance=5, niters=3, sigma=3, mask=None, **kwargs)

Removes the low frequency trend using scipy’s Savitzky-Golay filter.

This method wraps scipy.signal.savgol_filter.

Parameters:
window_length : int

The length of the filter window (i.e. the number of coefficients). window_length must be a positive odd integer.

polyorder : int

The order of the polynomial used to fit the samples. polyorder must be less than window_length.

return_trend : bool

If True, the method will return a tuple of two elements (flattened_lc, trend_lc) where trend_lc is the removed trend.

break_tolerance : int

If there are large gaps in time, flatten will split the flux into several sub-lightcurves and apply savgol_filter to each individually. A gap is defined as a period in time larger than break_tolerance times the median gap. To disable this feature, set break_tolerance to None.

niters : int

Number of iterations to iteratively sigma clip and flatten. If more than one, will perform the flatten several times, removing outliers each time.

sigma : int

Number of sigma above which to remove outliers from the flatten

mask : boolean array with length of self.time

Boolean array to mask data with before flattening. Flux values where mask is True will not be used to flatten the data. An interpolated result will be provided for these points. Use this mask to remove data you want to preserve, e.g. transits.

**kwargs : dict

Dictionary of arguments to be passed to scipy.signal.savgol_filter.

Returns:
flatten_lc : LightCurve

New light curve object with long-term trends removed.

If return_trend is set to True, this method will also return:
trend_lc : LightCurve

New light curve object containing the trend that was removed.

fold(period, t0=None, transit_midpoint=None)

Folds the lightcurve at a specified period and reference time t0.

This method returns a ~lightkurve.lightcurve.FoldedLightCurve object in which the time values range between -0.5 to +0.5 (i.e. the phase). Data points which occur exactly at t0 or an integer multiple of t0 + n*period will have phase value 0.0.

Parameters:
period : float

The period upon which to fold, in the same units as this LightCurve’s time attribute.

t0 : float, optional

Time corresponding to zero phase, in the same units as this LightCurve’s time attribute. Defaults to 0 if not set.

transit_midpoint : float, optional

Deprecated. Use t0 instead.

Returns:
folded_lightcurve : ~lightkurve.lightcurve.FoldedLightCurve

A new light curve object in which the data are folded and sorted by phase. The object contains an extra phase attribute.

Examples

The example below shows a light curve with a period dip which occurs near time value 1001 and has a period of 5 days. Calling the fold method will transform the light curve into a ~lightkurve.lightcurve.FoldedLightCurve object:

>>> import lightkurve as lk
>>> lc = lk.LightCurve(time=range(1001, 1012), flux=[0.5, 1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0, 1.0, 1.0, 0.5])
>>> folded_lc = lc.fold(period=5., t0=1006.)
>>> folded_lc   
<lightkurve.lightcurve.FoldedLightCurve>

An object of type ~lightkurve.lightcurve.FoldedLightCurve is useful because it provides convenient access to the phase values and the phase-folded fluxes:

>>> folded_lc.phase
array([-0.4, -0.4, -0.2, -0.2,  0. ,  0. ,  0. ,  0.2,  0.2,  0.4,  0.4])
>>> folded_lc.flux
array([1. , 1. , 1. , 1. , 0.5, 0.5, 0.5, 1. , 1. , 1. , 1. ])

We can still access the original time values as well:

>>> folded_lc.time_original
array([1004, 1009, 1005, 1010, 1001, 1006, 1011, 1002, 1007, 1003, 1008])

A ~lightkurve.lightcurve.FoldedLightCurve inherits all the features of a standard LightCurve object. For example, we can very quickly obtain a phase-folded plot using:

>>> folded_lc.plot()    # doctest: +SKIP
static from_stingray(lc)

Create a new LightCurve from a stingray.Lightcurve.

Parameters:
lc : stingray.Lightcurve

A stingray Lightcurve object.

static from_timeseries(ts)

Creates a new LightCurve from an AstroPy ~astropy.timeseries.TimeSeries object.

Parameters:
ts : ~astropy.timeseries.TimeSeries

The AstroPy TimeSeries object. The object must contain columns named ‘time’, ‘flux’, and ‘flux_err’.

get_saturation(factor=10, return_level=False)[source]

Goes back to the TPF and measures the maximum saturation level during a flare, averaged over the aperture mask.

Parameters:
factor : 10 or float

Saturation level in full well depths.

Returns:
FlareLightCurve with modified ‘flares’ attribute.
inject_fake_flares(gapwindow=0.1, fakefreq=0.005, inject_before_detrending=False, d=False, seed=None, **kwargs)[source]

Create a number of events, inject them in to data Use grid of amplitudes and durations, keep ampl in relative flux units Keep track of energy in Equiv Dur. Duration defined in minutes Amplitude defined multiples of the median error

interact_bls(notebook_url='localhost:8888', minimum_period=None, maximum_period=None, resolution=2000)

Display an interactive Jupyter Notebook widget to find planets.

The Box Least Squares (BLS) periodogram is a statistical tool used for detecting transiting exoplanets and eclipsing binaries in light curves. This method will display a Jupyter Notebook Widget which enables the BLS algorithm to be used interactively. Behind the scenes, the widget uses the AstroPy implementation of BLS [1].

This feature only works inside an active Jupyter Notebook. It requires Bokeh v1.0 (or later) and AstroPy v3.1 (or later), which are optional dependencies. An error message will be shown if these dependencies are not available.

Parameters:
notebook_url: str

Location of the Jupyter notebook page (default: “localhost:8888”) When showing Bokeh applications, the Bokeh server must be explicitly configured to allow connections originating from different URLs. This parameter defaults to the standard notebook host and port. If you are running on a different location, you will need to supply this value for the application to display properly. If no protocol is supplied in the URL, e.g. if it is of the form “localhost:8888”, then “http” will be used.

minimum_period : float or None

Minimum period to assess the BLS to. If None, default value of 0.3 days will be used.

maximum_period : float or None

Maximum period to evaluate the BLS to. If None, the time coverage of the lightcurve / 4 will be used.

resolution : int

Number of points to use in the BLS panel. Lower this value for faster but less accurate performance. You can also vary this value using the widget’s Resolution Slider.

References

[1]http://docs.astropy.org/en/latest/stats/bls.html

Examples

Load the light curve for Kepler-10, remove long-term trends, and display the BLS tool as follows:

>>> import lightkurve as lk
>>> lc = lk.search_lightcurvefile('kepler-10', quarter=3).download()  # doctest: +SKIP
>>> lc = lc.PDCSAP_FLUX.normalize().flatten()  # doctest: +SKIP
>>> lc.interact_bls()  # doctest: +SKIP
load_injrec_data(path, **kwargs)[source]

Fetch the injection-recovery table from a given path, and append it to any existing table.

mark_flagged_flares(explain=False)[source]

Mark all flares that coincide with K2 flagged cadences. Explain the flags if needed.

Parameters:
explain : False or bool

If True, an explanation column will be added to the flares table explaining the flags that were raised during the flare duration.

Returns:
FlareLightCurve with the flares table supplemented with an integer
quality and, if applicable, a string explanation column.
normalize(unit='unscaled')

Returns a normalized version of the light curve.

The normalized light curve is obtained by dividing the flux and flux_err object attributes by the by the median flux. Optionally, the result will be multiplied by 1e2 (if unit=’percent’), 1e3 (unit=’ppt’), or 1e6 (unit=’ppm’).

Parameters:
unit : ‘unscaled’, ‘percent’, ‘ppt’, ‘ppm’

The desired relative units of the normalized light curve; ‘ppt’ means ‘parts per thousand’, ‘ppm’ means ‘parts per million’.

Returns:
normalized_lightcurve : LightCurve

A new light curve object in which flux and flux_err have been divided by the median flux.

Warns:
LightkurveWarning

If the median flux is negative or within half a standard deviation from zero.

Examples

>>> import lightkurve as lk
>>> lc = lk.LightCurve(time=[1, 2, 3], flux=[25945.7, 25901.5, 25931.2], flux_err=[6.8, 4.6, 6.2])
>>> normalized_lc = lc.normalize()
>>> normalized_lc.flux
array([1.00055917, 0.99885466, 1.        ])
>>> normalized_lc.flux_err
array([0.00026223, 0.00017739, 0.00023909])
plot(**kwargs)

Plot the light curve using Matplotlib’s ~matplotlib.pyplot.plot method.

Parameters:
ax : ~matplotlib.axes.Axes

A matplotlib axes object to plot into. If no axes is provided, a new one will be created.

normalize : bool

Normalize the lightcurve before plotting?

xlabel : str

Plot x axis label

ylabel : str

Plot y axis label

title : str

Plot set_title

style : str

Path or URL to a matplotlib style file, or name of one of matplotlib’s built-in stylesheets (e.g. ‘ggplot’). Lightkurve’s custom stylesheet is used by default.

kwargs : dict

Dictionary of arguments to be passed to matplotlib.pyplot.plot.

Returns:
ax : ~matplotlib.axes.Axes

The matplotlib axes object.

plot_ed_ratio_heatmap(ampl_bins=None, dur_bins=None, flares_per_bin=20)[source]

Plot recovered amplitude and recovered duration vs. the ratio of recovered ED to injected ED.

plot_recovery_probability_heatmap(ampl_bins=None, dur_bins=None, flares_per_bin=20)[source]

Plot injected amplitude and injected FWHM vs. the fraction of recovered flares.

plot_river(period, t0=0, ax=None, bin_points=1, minimum_phase=-0.5, maximum_phase=0.5, method='mean', **kwargs)

Plot the light curve as a river plot.

A river plot uses colors to represent the light curve values in chronological order, relative to the period of an interesting signal. Each row in the plot represents a full period cycle, and each column represents a fixed phase. This type of plot is often used to visualize Transit Timing Variations (TTVs) in the light curves of exoplanets.

All extra keywords supplied are passed on to Matplotlib’s ~matplotlib.pyplot.pcolormesh function.

Parameters:
ax : ~matplotlib.axes.Axes

The matplotlib axes object.

period: float

Period at which to fold the light curve

t0 : float

Phase mid point for plotting

bin_points : int

How many points should be in each bin.

minimum_phase : float

The minimum phase to plot.

maximum_phase : float

The maximum phase to plot.

method : str

The river method. Choose from ‘mean’ or ‘median’ or ‘sigma’. If ‘mean’ or ‘median’, the plot will display the average value in each bin. If ‘sigma’, the plot will display the average in the bin divided by the error in each bin, in order to show the data in terms of standard deviation.

kwargs : dict

Dictionary of arguments to be passed on to Matplotlib’s ~matplotlib.pyplot.pcolormesh function.

Returns:
ax : ~matplotlib.axes.Axes

The matplotlib axes object.

query_solar_system_objects(cadence_mask='outliers', radius=None, sigma=3, location=None, cache=True, return_mask=False)

Returns a list of asteroids or comets which affected the light curve.

Light curves of stars or galaxies are frequently affected by solar system bodies (e.g. asteroids, comets, planets). These objects can move across a target’s photometric aperture mask on time scales of hours to days. When they pass through a mask, they tend to cause a brief spike in the brightness of the target. They can also cause dips by moving through a local background aperture mask (if any is used).

The artifical spikes and dips introduced by asteroids are frequently confused with stellar flares, planet transits, etc. This method helps to identify false signals injects by asteroids by providing a list of the solar system objects (name, brightness, time) that passed in the vicinity of the target during the span of the light curve.

This method queries the SkyBot API, which returns a list of asteroids/comets/planets given a location, time, and search cone.

Notes: * This method will use the ra and dec properties of the LightCurve

object to determine the position of the search cone.
  • The size of the search cone is 15 spacecraft pixels by default. You can change this by passing the radius parameter (unit: degrees).
  • This method will only search points in time during which he light curve showed 3-sigma outliers in flux. You can override this behavior and search all times by passing the cadence_mask=’all’ argument, but this will be much slower.
Parameters:
cadence_mask : str or bool

mask in time to select which frames or points should be searched for SSOs. Default “outliers” will search for SSOs at points that are sigma from the mean. “all” will search all cadences. Pass a boolean array with values of “True” for times to search for SSOs.

radius : optional, float

Radius in degrees to search for bodies. If None, will search for SSOs within 15 pixels.

sigma : optional, float

If cadence_mask is set to “outlier”, sigma will be used to identify outliers.

cache : optional, bool

If True will cache the search result in the astropy cache. Set to False to request the search again.

return_mask: bool

If True will return a boolean mask in time alongside the result

Returns:
result : pandas.DataFrame

DataFrame object which lists the Solar System objects in frames that were identified to contain SSOs. Returns None if no objects were found.

remove_nans()

Removes cadences where the flux is NaN.

Returns:
clean_lightcurve : LightCurve

A new light curve object from which NaNs fluxes have been removed.

remove_outliers(sigma=5.0, sigma_lower=None, sigma_upper=None, return_mask=False, **kwargs)

Removes outlier data points using sigma-clipping.

This method returns a new LightCurve object from which data points are removed if their flux values are greater or smaller than the median flux by at least sigma times the standard deviation.

Sigma-clipping works by iterating over data points, each time rejecting values that are discrepant by more than a specified number of standard deviations from a center value. If the data contains invalid values (NaNs or infs), they are automatically masked before performing the sigma clipping.

Note

This function is a convenience wrapper around astropy.stats.sigma_clip() and provides the same functionality. Any extra arguments passed to this method will be passed on to sigma_clip.

Parameters:
sigma : float

The number of standard deviations to use for both the lower and upper clipping limit. These limits are overridden by sigma_lower and sigma_upper, if input. Defaults to 5.

sigma_lower : float or None

The number of standard deviations to use as the lower bound for the clipping limit. Can be set to float(‘inf’) in order to avoid clipping outliers below the median at all. If None then the value of sigma is used. Defaults to None.

sigma_upper : float or None

The number of standard deviations to use as the upper bound for the clipping limit. Can be set to float(‘inf’) in order to avoid clipping outliers above the median at all. If None then the value of sigma is used. Defaults to None.

return_mask : bool

Whether or not to return a mask (i.e. a boolean array) indicating which data points were removed. Entries marked as True in the mask are considered outliers. This mask is not returned by default.

**kwargs : dict

Dictionary of arguments to be passed to astropy.stats.sigma_clip.

Returns:
clean_lc : LightCurve

A new light curve object from which outlier data points have been removed.

outlier_mask : NumPy array, optional

Boolean array flagging which cadences were removed. Only returned if return_mask=True.

Examples

This example generates a new light curve in which all points that are more than 1 standard deviation from the median are removed:

>>> lc = LightCurve(time=[1, 2, 3, 4, 5], flux=[1, 1000, 1, -1000, 1])
>>> lc_clean = lc.remove_outliers(sigma=1)
>>> lc_clean.time
array([1, 3, 5])
>>> lc_clean.flux
array([1, 1, 1])

Instead of specifying sigma, you may specify separate sigma_lower and sigma_upper parameters to remove only outliers above or below the median. For example:

>>> lc = LightCurve(time=[1, 2, 3, 4, 5], flux=[1, 1000, 1, -1000, 1])
>>> lc_clean = lc.remove_outliers(sigma_lower=float('inf'), sigma_upper=1)
>>> lc_clean.time
array([1, 3, 4, 5])
>>> lc_clean.flux
array([    1,     1, -1000,     1])

Optionally, you may use the return_mask parameter to return a boolean array which flags the outliers identified by the method. For example:

>>> lc_clean, mask = lc.remove_outliers(sigma=1, return_mask=True)
>>> mask
array([False,  True, False,  True, False])
sample_flare_recovery(iterations=2000, inject_before_detrending=False, mode=None, func=None, save_lc_to_file=False, folder='', fakefreq=0.05, save=False, path=None, detrend_kwargs={}, **kwargs)[source]

Runs a number of injection recovery cycles and characterizes the light curve by recovery probability and equivalent duration underestimation. Inject one flare per light curve.

Parameters:
iterations : 2000 or int

Number of injection/recovery cycles

inject_before_detrending : False or bool

If True, fake flare are injected directly into raw data.

mode : str

“savgol” or “k2sc”. Required if inject_before_detrending is True.

fakefreq : 0.05 or float

number of flares per day, but at least one per continuous observation period will be injected

detrend_kwargs : dict

Keyword arguments to pass to FlareLightCurve.detrend

kwargs : dict

Keyword arguments to pass to inject_fake_flares

Returns:
lc : FlareLightCurve

Detrended LC with all fake_flares listed in the attribute

fake_lc : FlareLightCurve

Light curve with the last iteration of synthetic flares injected.

scatter(colorbar_label='', show_colorbar=True, **kwargs)

Plots the light curve using Matplotlib’s ~matplotlib.pyplot.scatter method.

Parameters:
ax : ~matplotlib.axes.Axes

A matplotlib axes object to plot into. If no axes is provided, a new one will be generated.

normalize : bool

Normalize the lightcurve before plotting?

xlabel : str

Plot x axis label

ylabel : str

Plot y axis label

title : str

Plot set_title

style : str

Path or URL to a matplotlib style file, or name of one of matplotlib’s built-in stylesheets (e.g. ‘ggplot’). Lightkurve’s custom stylesheet is used by default.

colorbar_label : str

Label to show next to the colorbar (if c is given).

show_colorbar : boolean

Show the colorbar if colors are given using the c argument?

kwargs : dict

Dictionary of arguments to be passed to matplotlib.pyplot.scatter.

Returns:
ax : ~matplotlib.axes.Axes

The matplotlib axes object.

show_properties()

Prints a description of all non-callable attributes.

Prints in order of type (ints, strings, lists, arrays, others).

to_corrector(method='sff')

Returns a corrector object to remove instrument systematics.

Parameters:
methods : string

Currently, only “sff” is supported. This will return a SFFCorrector class instance.

Returns:
correcter : lightkurve.Correcter

Instance of a Corrector class, which typically provides correct() and diagnose() methods.

to_csv(path_or_buf=None, **kwargs)

Writes the light curve to a CSV file.

This method will convert the light curve into the Comma-Separated Values (CSV) text format. By default this method will return the result as a string, but you can also write the string directly to disk by providing a file name or handle via the path_or_buf parameter.

Parameters:
path_or_buf : string or file handle

File path or object. By default, the result is returned as a string.

**kwargs : dict

Dictionary of arguments to be passed to pandas.DataFrame.to_csv().

Returns:
csv : str or None

Returns a csv-formatted string if path_or_buf=None. Returns None otherwise.

to_fits(path)[source]

Write FlareLightCurve to a .fits file. Read it in again using from_path().

to_pandas(columns=('time', 'flux', 'flux_err', 'quality', 'centroid_col', 'centroid_row'))

Converts the light curve to a Pandas ~pandas.DataFrame object.

By default, the object returned will contain the columns ‘time’, ‘flux’, ‘flux_err’, ‘quality’, ‘centroid_col’, and ‘centroid_row’. This can be changed using the columns parameter.

Parameters:
columns : list of str

List of columns to include in the DataFrame. The names must match attributes of the LightCurve object (e.g. time, flux).

Returns:
dataframe : pandas.DataFrame object

A dataframe indexed by time and containing the columns flux and flux_err.

to_periodogram(method='lombscargle', **kwargs)

Converts the light curve to a ~lightkurve.periodogram.Periodogram power spectrum object.

This method will call either lightkurve.periodogram.LombScarglePeriodogram.from_lightcurve() or lightkurve.periodogram.BoxLeastSquaresPeriodogram.from_lightcurve(), which in turn wrap astropy.stats.LombScargle and astropy.stats.BoxLeastSquares.

Optional keywords accepted if method='lombscargle' are: minimum_frequency, maximum_frequency, mininum_period, maximum_period, frequency, period, nterms, nyquist_factor, oversample_factor, freq_unit, normalization, ls_method.

Optional keywords accepted if method='bls' are minimum_period, maximum_period, period, frequency_factor, duration.

Parameters:
method : {‘lombscargle’, ‘boxleastsquares’, ‘ls’, ‘bls’}

Use the Lomb Scargle or Box Least Squares (BLS) method to extract the power spectrum. Defaults to 'lombscargle'. 'ls' and 'bls' are shorthands for 'lombscargle' and 'boxleastsquares'.

kwargs : dict

Keyword arguments passed to either ~lightkurve.periodogram.LombScarglePeriodogram or ~lightkurve.periodogram.BoxLeastSquaresPeriodogram.

Returns:
Periodogram : ~lightkurve.periodogram.Periodogram object

The power spectrum object extracted from the light curve.

to_seismology(**kwargs)

Returns a ~lightkurve.seismology.Seismology object for estimating quick-look asteroseismic quantities.

All **kwargs will be passed to the to_periodogram() method.

Returns:
seismology : ~lightkurve.seismology.Seismology object

Object which can be used to estimate quick-look asteroseismic quantities.

to_stingray()

Returns a stingray.Lightcurve object.

This feature requires Stingray to be installed (e.g. pip install stingray). An ImportError will be raised if this package is not available.

Returns:
lightcurve : stingray.Lightcurve

An stingray Lightcurve object.

to_table()

Converts the light curve to an Astropy ~astropy.table.Table object.

Returns:
table : astropy.table.Table

An AstroPy Table with columns ‘time’, ‘flux’, and ‘flux_err’.

to_timeseries()

Converts the light curve to an AstroPy ~astropy.timeseries.TimeSeries object.

This feature requires AstroPy v3.2 or later (released in 2019). An ImportError will be raised if this version is not available.

Returns:
timeseries : ~astropy.timeseries.TimeSeries

An AstroPy TimeSeries object.