FlareLightCurve

class altaipony.flarelc.FlareLightCurve(data=None, *args, time=None, flux=None, flux_err=None, **kwargs)[source]

Bases: KeplerLightCurve, TessLightCurve

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

Attributes:
timearray-like

Time values stored as an AstroPy ~astropy.time.Time object.

fluxarray-like

Brightness values stored as an AstroPy ~astropy.units.Quantity object.

flux_errarray-like

Brightness uncertainties stored as an AstroPy ~astropy.units.Quantity object.

pixel_fluxmulti-dimensional array

Flux in the target pixels from the KeplerTargetPixelFile.

pixel_flux_errmulti-dimensional array

Uncertainty on pixel_flux.

pipeline_maskmulti-dimensional boolean array

TargetPixelFile mask for aperture photometry.

time_formatstr

Deprecated since version 2.0.

time_scalestr

Deprecated since version 2.0.

time_unitastropy.unit

Astropy unit object defining unit of time.

centroid_colarray-like

Centroid column coordinates as a function of time.

centroid_rowarray-like

Centroid row coordinates as a function of time.

qualityarray-like

Kepler quality flags.

quality_bitmaskstr

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

channelint

Channel number, where aperture is located on the CCD.

campaignint

K2 campaign number.

quarterint

Kepler Quarter number.

sectorint

TESS sector number

missionstring

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

cadencenoarray-like

Cadence number - unique identifier.

objectstr

target ID.

rafloat

RA in deg.

decfloat

Declination in deg.

labelstring

‘EPIC xxxxxxxxx’.

metadict

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

detrended_fluxarray-like

K2SC detrend flux, same units as flux.

detrended_flux_errarray-like

K2SC detrend flux error, same units as flux.

flux_trendsarray-like

Astrophysical variability as derived by K2SC.

gapslist of tuples of ints

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

flaresDataFrame

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_medarray-like

Iterative median, see the find_iterative_median method.

Attributes Summary

ColumnClass

PDCSAP_FLUX

Deprecated since version 2.0.

SAP_FLUX

Deprecated since version 2.0.

astropy_time

Deprecated since version 2.0.

cadenceno

colnames

detrended_flux

detrended_flux_err

dtype

fake_flares

flares

flux

Brightness values stored as an AstroPy ~astropy.units.Quantity object.

flux_err

Brightness uncertainties stored as an AstroPy ~astropy.units.Quantity object.

flux_quantity

Deprecated since version 2.0.

flux_unit

Deprecated since version 2.0.

gaps

groups

has_masked_columns

True if table has any MaskedColumn columns.

has_masked_values

True if column in the table has values which are masked.

has_mixin_columns

True if table has any mixin columns (defined as columns that are not Column subclasses).

hdu

Deprecated since version 2.0.

iloc

Return a TableILoc object that can be used for retrieving indexed rows in the order they appear in the index.

indices

Return the indices associated with columns of the table as a TableIndices object.

info

it_med

loc

Return a TableLoc object that can be used for retrieving rows by index in a given data range.

loc_indices

Return a TableLocIndices object that can be used for retrieving the row indices corresponding to given table index key value or values.

mask

masked

meta

origin

pprint_exclude_names

Maintain tuple that controls table column visibility for print output.

pprint_include_names

Maintain tuple that controls table column visibility for print output.

saturation

time

Time values stored as an AstroPy ~astropy.time.Time object.

time_format

Deprecated since version 2.0.

time_scale

Deprecated since version 2.0.

write

Write this Table object out in the specified format.

Methods Summary

add_column(*args, **kwargs)

See add_column().

add_columns(*args, **kwargs)

See add_columns().

add_index(colnames[, engine, unique])

Insert a new index among one or more columns.

add_row([vals, mask])

Add a new row to the end of the table.

append(others[, inplace])

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

argsort([keys, kind, reverse])

Return the indices which would sort the table according to one or more key columns.

as_array([keep_byteorder, names])

Return a new copy of the table in the form of a structured np.ndarray or np.ma.MaskedArray object (as appropriate).

bin([time_bin_size, time_bin_start, ...])

Bins a lightcurve in equally-spaced bins in time.

characterize_flares([flares_per_bin, ...])

Use results from injection recovery to determine corrected flare characteristics.

convert_bytestring_to_unicode()

Convert bytestring columns (dtype.kind='S') to unicode (dtype.kind='U') using UTF-8 encoding.

convert_unicode_to_bytestring()

Convert unicode columns (dtype.kind='U') to bytestring (dtype.kind='S') using UTF-8 encoding.

copy([copy_data])

Return a copy of the table.

create_transit_mask(period, transit_time, ...)

Returns a boolean array that is True during transits and False elsewhere.

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.

field(item)

Return column[item] for recarray compatibility.

fill_gaps([method])

Fill in gaps in time.

filled([fill_value])

Return copy of self, with masked values filled.

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, epoch_time, epoch_phase, ...])

Returns a FoldedLightCurve object folded on a period and epoch.

from_pandas(df[, time_scale])

Convert a DataFrame to a astropy.timeseries.TimeSeries.

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.

group_by(keys)

Group this table by the specified keys.

head([n])

Return the first n rows.

index_column(name)

Return the positional index of column name.

index_mode(mode)

Return a context manager for an indexing mode.

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.

insert_row(index[, vals, mask])

Add a new row before the given index position in the table.

interact_bls([notebook_url, minimum_period, ...])

Display an interactive Jupyter Notebook widget to find planets.

items()

itercols()

Iterate over the columns of this table.

iterrows(*names)

Iterate over rows of table returning a tuple of values for each row.

keep_columns(names)

Keep only the columns specified (remove the others).

keys()

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.

more([max_lines, max_width, show_name, ...])

Interactively browse table with a paging interface.

normalize([unit])

Returns a normalized version of the light curve.

pformat([max_lines, max_width, show_name, ...])

Return a list of lines for the formatted string representation of

pformat_all([max_lines, max_width, ...])

Return a list of lines for the formatted string representation of

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[, epoch_time, ax, ...])

Plot the light curve as a river plot.

pprint([max_lines, max_width, show_name, ...])

Print a formatted string representation of the table.

pprint_all([max_lines, max_width, ...])

Print a formatted string representation of the entire table.

query_solar_system_objects([cadence_mask, ...])

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

read(*args, **kwargs)

Returns a KeplerLightCurve by reading the given file.

remove_column(name)

Remove a column from the table.

remove_columns(names)

Remove several columns from the table.

remove_indices(colname)

Remove all indices involving the given column.

remove_nans([column])

Removes cadences where column is a NaN.

remove_outliers([sigma, sigma_lower, ...])

Removes outlier data points using sigma-clipping.

remove_row(index)

Remove a row from the table.

remove_rows(row_specifier)

Remove rows from the table.

rename_column(name, new_name)

Rename a column.

rename_columns(names, new_names)

Rename multiple columns.

replace_column(name, col[, copy])

Replace column name with the new col object.

reverse()

Reverse the row order of table rows.

round([decimals])

Round numeric columns in-place to the specified number of decimals.

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.

search_neighbors([limit, radius])

Search the data archive at MAST for the most nearby light curves.

select_flux(flux_column[, flux_err_column])

Assign a different column to be the flux column.

show_in_browser([max_lines, jsviewer, ...])

Render the table in HTML and show it in a web browser.

show_in_notebook([tableid, css, ...])

Render the table in HTML and show it in the IPython notebook.

show_properties()

Prints a description of all non-callable attributes.

sort([keys, kind, reverse])

Sort the table according to one or more keys.

tail([n])

Return the last n rows.

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_excel(path_or_buf, **kwargs)

Shorthand for to_pandas().to_excel().

to_fits(*args, **kwargs)

Writes the KeplerLightCurve to a FITS file.

to_pandas(**kwargs)

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()

to_timeseries()

Deprecated since version 2.0.

truncate([before, after, column])

Truncates the light curve before and after some time value.

update(other[, copy])

Perform a dictionary-style update and merge metadata.

values()

values_equal(other)

Element-wise comparison of table with another table, list, or scalar.

Attributes Documentation

ColumnClass
PDCSAP_FLUX

Deprecated since version 2.0: The PDCSAP_FLUX function is deprecated and may be removed in a future version.

A copy of the light curve in which lc.flux = lc.pdcsap_flux

and lc.flux_err = lc.pdcsap_flux_err. It is provided for backwards- compatibility with Lightkurve v1.x and will be removed soon.

SAP_FLUX

Deprecated since version 2.0: The SAP_FLUX function is deprecated and may be removed in a future version.

A copy of the light curve in which lc.flux = lc.sap_flux

and lc.flux_err = lc.sap_flux_err. It is provided for backwards- compatibility with Lightkurve v1.x and will be removed soon.

astropy_time

Deprecated since version 2.0: The astropy_time function is deprecated and may be removed in a future version. Use time instead.

cadenceno
colnames
detrended_flux
detrended_flux_err
dtype
fake_flares
flares
flux

Brightness values stored as an AstroPy ~astropy.units.Quantity object.

flux_err

Brightness uncertainties stored as an AstroPy ~astropy.units.Quantity object.

flux_quantity

Deprecated since version 2.0: The flux_quantity function is deprecated and may be removed in a future version. Use flux instead.

flux_unit

Deprecated since version 2.0: The flux_unit function is deprecated and may be removed in a future version. Use flux.unit instead.

gaps
groups
has_masked_columns

True if table has any MaskedColumn columns.

This does not check for mixin columns that may have masked values, use the has_masked_values property in that case.

has_masked_values

True if column in the table has values which are masked.

This may be relatively slow for large tables as it requires checking the mask values of each column.

has_mixin_columns

True if table has any mixin columns (defined as columns that are not Column subclasses).

hdu

Deprecated since version 2.0: The hdu function is deprecated and may be removed in a future version. Use fits.open(lc.filename) instead.

iloc

Return a TableILoc object that can be used for retrieving indexed rows in the order they appear in the index.

indices

Return the indices associated with columns of the table as a TableIndices object.

info
it_med
loc

Return a TableLoc object that can be used for retrieving rows by index in a given data range. Note that both loc and iloc work only with single-column indices.

loc_indices

Return a TableLocIndices object that can be used for retrieving the row indices corresponding to given table index key value or values.

mask
masked
meta
origin
pprint_exclude_names

Maintain tuple that controls table column visibility for print output.

This is a descriptor that inherits from MetaAttribute so that the attribute value is stored in the table meta[‘__attributes__’].

This gets used for the pprint_include_names and pprint_exclude_names Table attributes.

pprint_include_names

Maintain tuple that controls table column visibility for print output.

This is a descriptor that inherits from MetaAttribute so that the attribute value is stored in the table meta[‘__attributes__’].

This gets used for the pprint_include_names and pprint_exclude_names Table attributes.

saturation
time

Time values stored as an AstroPy ~astropy.time.Time object.

time_format

Deprecated since version 2.0: The time_format function is deprecated and may be removed in a future version. Use time.format instead.

time_scale

Deprecated since version 2.0: The time_scale function is deprecated and may be removed in a future version. Use time.scale instead.

write

Write this Table object out in the specified format.

This function provides the Table interface to the astropy unified I/O layer. This allows easily writing a file in many supported data formats using syntax such as:

>>> from astropy.table import Table
>>> dat = Table([[1, 2], [3, 4]], names=('a', 'b'))
>>> dat.write('table.dat', format='ascii')

Get help on the available writers for Table using the``help()`` method:

>>> Table.write.help()  # Get help writing Table and list supported formats
>>> Table.write.help('fits')  # Get detailed help on Table FITS writer
>>> Table.write.list_formats()  # Print list of available formats

The serialize_method argument is explained in the section on Table serialization methods.

See also: https://docs.astropy.org/en/stable/io/unified.html

Parameters:
*argstuple, optional

Positional arguments passed through to data writer. If supplied the first argument is the output filename.

formatstr

File format specifier.

serialize_methodstr, dict, optional

Serialization method specifier for columns.

**kwargsdict, optional

Keyword arguments passed through to data writer.

Methods Documentation

add_column(*args, **kwargs)

See add_column().

add_columns(*args, **kwargs)

See add_columns().

add_index(colnames, engine=None, unique=False)

Insert a new index among one or more columns. If there are no indices, make this index the primary table index.

Parameters:
colnamesstr or list

List of column names (or a single column name) to index

enginetype or None

Indexing engine class to use, either ~astropy.table.SortedArray, ~astropy.table.BST, or ~astropy.table.SCEngine. If the supplied argument is None (by default), use ~astropy.table.SortedArray.

uniquebool

Whether the values of the index must be unique. Default is False.

add_row(vals=None, mask=None)

Add a new row to the end of the table.

The vals argument can be:

sequence (e.g. tuple or list)

Column values in the same order as table columns.

mapping (e.g. dict)

Keys corresponding to column names. Missing values will be filled with np.zeros for the column dtype.

None

All values filled with np.zeros for the column dtype.

This method requires that the Table object “owns” the underlying array data. In particular one cannot add a row to a Table that was initialized with copy=False from an existing array.

The mask attribute should give (if desired) the mask for the values. The type of the mask should match that of the values, i.e. if vals is an iterable, then mask should also be an iterable with the same length, and if vals is a mapping, then mask should be a dictionary.

Parameters:
valstuple, list, dict or None

Use the specified values in the new row

masktuple, list, dict or None

Use the specified mask values in the new row

Examples

Create a table with three columns ‘a’, ‘b’ and ‘c’:

>>> t = Table([[1,2],[4,5],[7,8]], names=('a','b','c'))
>>> print(t)
 a   b   c
--- --- ---
  1   4   7
  2   5   8

Adding a new row with entries ‘3’ in ‘a’, ‘6’ in ‘b’ and ‘9’ in ‘c’:

>>> t.add_row([3,6,9])
>>> print(t)
  a   b   c
  --- --- ---
  1   4   7
  2   5   8
  3   6   9
append(others, inplace=False)

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

Parameters:
othersLightCurve, or list of LightCurve

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

inplacebool

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

Returns:
new_lcLightCurve

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

argsort(keys=None, kind=None, reverse=False)

Return the indices which would sort the table according to one or more key columns. This simply calls the numpy.argsort function on the table with the order parameter set to keys.

Parameters:
keysstr or list of str

The column name(s) to order the table by

kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional

Sorting algorithm used by numpy.argsort.

reversebool

Sort in reverse order (default=False)

Returns:
index_arrayndarray, int

Array of indices that sorts the table by the specified key column(s).

as_array(keep_byteorder=False, names=None)

Return a new copy of the table in the form of a structured np.ndarray or np.ma.MaskedArray object (as appropriate).

Parameters:
keep_byteorderbool, optional

By default the returned array has all columns in native byte order. However, if this option is True this preserves the byte order of all columns (if any are non-native).

nameslist, optional:

List of column names to include for returned structured array. Default is to include all table columns.

Returns:
table_arrayarray or ~numpy.ma.MaskedArray

Copy of table as a numpy structured array. ndarray for unmasked or ~numpy.ma.MaskedArray for masked.

bin(time_bin_size=None, time_bin_start=None, time_bin_end=None, n_bins=None, aggregate_func=None, bins=None, binsize=None)

Bins a lightcurve in equally-spaced bins in time.

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.

Parameters:
time_bin_size~astropy.units.Quantity or ~astropy.time.TimeDelta, optional

The time interval for the binned time series - this is either a scalar value (in which case all time bins will be assumed to have the same duration) or as an array of values (in which case each time bin can have a different duration). If this argument is provided, time_bin_end should not be provided. (Default: 0.5 days; default unit: days.)

time_bin_start~astropy.time.Time or iterable, optional

The start time for the binned time series - this can be either given directly as a ~astropy.time.Time array or as any iterable that initializes the ~astropy.time.Time class. This can also be a scalar value if time_bin_size is provided. Defaults to the first time in the sampled time series.

time_bin_end~astropy.time.Time or iterable, optional

The times of the end of each bin - this can be either given directly as a ~astropy.time.Time array or as any iterable that initializes the ~astropy.time.Time class. This can only be given if time_bin_start is an array of values. If time_bin_end is a scalar, time bins are assumed to be contiguous, such that the end of each bin is the start of the next one, and time_bin_end gives the end time for the last bin. If time_bin_end is an array, the time bins do not need to be contiguous. If this argument is provided, time_bin_size should not be provided. This option, like the iterable form of time_bin_start, requires Astropy 5.0.

n_binsint, optional

The number of bins to use. Defaults to the number needed to fit all the original points. Note that this will create this number of bins of length time_bin_size independent of the lightkurve length.

aggregate_funccallable, optional

The function to use for combining points in the same bin. Defaults to np.nanmean.

binsint, iterable or str, optional

If an int, this gives the number of bins to divide the lightkurve into. In contrast to n_bins this adjusts the length of time_bin_size to accommodate the input time series length. If it is an iterable of ints, it specifies the indices of the bin edges. If a string, it must be one of ‘blocks’, ‘knuth’, ‘scott’ or ‘freedman’ defining a method of automatically determining an optimal bin size. See ~astropy.stats.histogram for a description of each method. Note that ‘blocks’ is not a useful method for regularly sampled data.

binsizeint

In Lightkurve v1.x, the default behavior of bin() was to create bins which contained an equal number data points in each bin. This type of binning is discouraged because it usually makes more sense to create equally-sized bins in time duration, which is the new default behavior in Lightkurve v2.x. Nevertheless, this binsize parameter allows users to simulate the old behavior of Lightkurve v1.x. For ease of implementation, setting this parameter is identical to passing time_bin_size = lc.time[binsize] - time[0], which means that the bins are not guaranteed to contain an identical number of data points.

Returns:
binned_lcLightCurve

A new light curve which has been binned.

characterize_flares(flares_per_bin=30, ampl_bins=None, dur_bins=None)[source]

Use results from injection recovery to determine corrected flare characteristics.

convert_bytestring_to_unicode()

Convert bytestring columns (dtype.kind=’S’) to unicode (dtype.kind=’U’) using UTF-8 encoding.

Internally this changes string columns to represent each character in the string with a 4-byte UCS-4 equivalent, so it is inefficient for memory but allows scripts to manipulate string arrays with natural syntax.

convert_unicode_to_bytestring()

Convert unicode columns (dtype.kind=’U’) to bytestring (dtype.kind=’S’) using UTF-8 encoding.

When exporting a unicode string array to a file, it may be desirable to encode unicode columns as bytestrings.

copy(copy_data=True)

Return a copy of the table.

Parameters:
copy_databool

If True (the default), copy the underlying data array. Otherwise, use the same data array. The meta is always deepcopied regardless of the value for copy_data.

create_transit_mask(period, transit_time, duration)

Returns a boolean array that is True during transits and False elsewhere.

This method supports multi-planet systems by allowing period, transit_time, and duration to be array-like lists of parameters.

Parameters:
period~astropy.units.Quantity, float, or array-like

Period(s) of the transits.

duration~astropy.units.Quantity, float, or array-like

Duration(s) of the transits.

transit_time~astropy.time.Time, float, or array-like

Transit midpoint(s) of the transits.

Returns:
transit_masknp.array of bool

Mask that flags transits. Mask is True where there are transits.

Examples

You can create a transit mask for a single-planet system as follows:

>>> import lightkurve as lk
>>> lc = lk.LightCurve({'time': [1, 2, 3, 4, 5], 'flux': [1, 1, 1, 1, 1]})
>>> lc.create_transit_mask(transit_time=2., period=2., duration=0.1)
array([False,  True, False,  True, False])

The method accepts lists of parameters to support multi-planet systems:

>>> lc.create_transit_mask(transit_time=[2., 3.], period=[2., 10.], duration=[0.1, 0.1])
array([False,  True,  True,  True, False])
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.

Parameters:

modestr

“k2sc” or “savgol” or “custom”

de_niterint

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

saveFalse or bool

If True, the light curve is saved as a fits file to a given folder.

pathstr

Path to resulting fits file. As a default, the fits file will be stored in the working directory.

funcfunction

custom detrending function

kwargsdict

Keyword arguments to pass to k2sc, detrend_savgol, or custom method

Returns:
FlareLightCurve
errorbar(linestyle='', **kwargs) Axes

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

Parameters:
linestylestr

Connect the error bars using a line?

columnstr

Name of data column to plot. Default flux.

ax~matplotlib.axes.Axes

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

normalizebool

Normalize the lightcurve before plotting?

xlabelstr

X axis label.

ylabelstr

Y axis label.

titlestr

Title shown at the top using matplotlib set_title.

stylestr

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.

show_colorbarboolean

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

colorbar_labelstr

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

offsetfloat

Offset value to apply to the Y axis values before plotting. Use this to avoid light curves from overlapping on the same plot. By default, no offset is applied.

kwargsdict

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

Returns:
ax~matplotlib.axes.Axes

The matplotlib axes object.

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

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_durationint, 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_windowint, optional

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

savgol_polyorderint, optional

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

sigmafloat, optional

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

Returns:
cdppfloat

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

field(item)

Return column[item] for recarray compatibility.

fill_gaps(method: str = '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:
methodstring {‘gaussian_noise’}

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

Returns:
filled_lightcurveLightCurve

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

filled(fill_value=None)

Return copy of self, with masked values filled.

If input fill_value supplied then that value is used for all masked entries in the table. Otherwise the individual fill_value defined for each table column is used.

Parameters:
fill_valuestr

If supplied, this fill_value is used for all masked entries in the entire table.

Returns:
filled_table~astropy.table.Table

New table with masked values filled

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

Find flares in a FlareLightCurve.

Parameters:
minsep3 or int

Minimum distance between two candidate start times in datapoints.

kwargsdict

keyword arguments to pass to find_flares_in_cont_obs_period()

Possible keyword arguments:
sigmanumpy array

local scatter of the flux. Array should be the same length as the detrended flux array. If sigma=None, error is used instead.

N1int (default is 3)

How many times above sigma is required.

N2int (Default is 2)

How many times above sigma and detrended_flux_err is required

N3int (Default is 3)

The number of consecutive points required to flag as a flare.

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:
timenumpy array with floats

sorted array, in units of days

maxgap0.09 or float

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

minspan10 or int

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

splitslist 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_lengthint

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

polyorderint

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

return_trendbool

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

break_toleranceint

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.

nitersint

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

sigmaint

Number of sigma above which to remove outliers from the flatten

maskboolean 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.

**kwargsdict

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

Returns:
flatten_lcLightCurve

New light curve object with long-term trends removed.

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

New light curve object containing the trend that was removed.

fold(period=None, epoch_time=None, epoch_phase=0, wrap_phase=None, normalize_phase=False)

Returns a FoldedLightCurve object folded on a period and epoch.

This method is identical to AstroPy’s ~astropy.timeseries.TimeSeries.fold() method, except it returns a FoldedLightCurve object which offers convenient plotting methods.

Parameters:
periodfloat ~astropy.units.Quantity

The period to use for folding. If a float is passed we’ll assume it is in units of days.

epoch_time~astropy.time.Time

The time to use as the reference epoch, at which the relative time offset / phase will be epoch_phase. Defaults to the first time in the time series.

epoch_phasefloat or ~astropy.units.Quantity

Phase of epoch_time. If normalize_phase is True, this should be a dimensionless value, while if normalize_phase is False, this should be a ~astropy.units.Quantity with time units. Defaults to 0.

wrap_phasefloat or ~astropy.units.Quantity

The value of the phase above which values are wrapped back by one period. If normalize_phase is True, this should be a dimensionless value, while if normalize_phase is False, this should be a ~astropy.units.Quantity with time units. Defaults to half the period, so that the resulting time series goes from -period / 2 to period / 2 (if normalize_phase is False) or -0.5 to 0.5 (if normalize_phase is True).

normalize_phasebool

If False phase is returned as ~astropy.time.TimeDelta, otherwise as a dimensionless ~astropy.units.Quantity.

Returns:
folded_lightcurveFoldedLightCurve

The folded light curve object in which the time column holds the phase values.

classmethod from_pandas(df, time_scale='utc')

Convert a DataFrame to a astropy.timeseries.TimeSeries.

Parameters:
dfpandas.DataFrame

A pandas pandas.DataFrame instance.

time_scalestr

The time scale to pass into astropy.time.Time. Defaults to UTC.

static from_stingray(lc)

Create a new LightCurve from a stingray.Lightcurve.

Parameters:
lcstingray.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:
factor10 or float

Saturation level in full well depths.

Returns:
FlareLightCurve with modified ‘flares’ attribute.
group_by(keys)

Group this table by the specified keys.

This effectively splits the table into groups which correspond to unique values of the keys grouping object. The output is a new ~astropy.table.TableGroups which contains a copy of this table but sorted by row according to keys.

The keys input to group_by can be specified in different ways:

  • String or list of strings corresponding to table column name(s)

  • Numpy array (homogeneous or structured) with same length as this table

  • ~astropy.table.Table with same length as this table

Parameters:
keysstr, list of str, numpy array, or ~astropy.table.Table

Key grouping object

Returns:
out~astropy.table.Table

New table with groups set

head(n: int = 5)

Return the first n rows.

Parameters:
nint

Number of rows to return.

Returns:
lcLightCurve

Light curve containing the first n rows.

index_column(name)

Return the positional index of column name.

Parameters:
namestr

column name

Returns:
indexint

Positional index of column name.

Examples

Create a table with three columns ‘a’, ‘b’ and ‘c’:

>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']],
...           names=('a', 'b', 'c'))
>>> print(t)
 a   b   c
--- --- ---
  1 0.1   x
  2 0.2   y
  3 0.3   z

Get index of column ‘b’ of the table:

>>> t.index_column('b')
1
index_mode(mode)

Return a context manager for an indexing mode.

Parameters:
modestr

Either ‘freeze’, ‘copy_on_getitem’, or ‘discard_on_copy’. In ‘discard_on_copy’ mode, indices are not copied whenever columns or tables are copied. In ‘freeze’ mode, indices are not modified whenever columns are modified; at the exit of the context, indices refresh themselves based on column values. This mode is intended for scenarios in which one intends to make many additions or modifications in an indexed column. In ‘copy_on_getitem’ mode, indices are copied when taking column slices as well as table slices, so col[i0:i1] will preserve indices.

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

insert_row(index, vals=None, mask=None)

Add a new row before the given index position in the table.

The vals argument can be:

sequence (e.g. tuple or list)

Column values in the same order as table columns.

mapping (e.g. dict)

Keys corresponding to column names. Missing values will be filled with np.zeros for the column dtype.

None

All values filled with np.zeros for the column dtype.

The mask attribute should give (if desired) the mask for the values. The type of the mask should match that of the values, i.e. if vals is an iterable, then mask should also be an iterable with the same length, and if vals is a mapping, then mask should be a dictionary.

Parameters:
valstuple, list, dict or None

Use the specified values in the new row

masktuple, list, dict or None

Use the specified mask values in the new row

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). 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_periodfloat or None

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

maximum_periodfloat or None

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

resolutionint

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

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_lightcurve('kepler-10', quarter=3).download()  
>>> lc = lc.normalize().flatten()  
>>> lc.interact_bls()  
items()
itercols()

Iterate over the columns of this table.

Examples

To iterate over the columns of a table:

>>> t = Table([[1], [2]])
>>> for col in t.itercols():
...     print(col)
col0
----
   1
col1
----
   2

Using itercols() is similar to for col in t.columns.values() but is syntactically preferred.

iterrows(*names)

Iterate over rows of table returning a tuple of values for each row.

This method is especially useful when only a subset of columns are needed.

The iterrows method can be substantially faster than using the standard Table row iteration (e.g. for row in tbl:), since that returns a new ~astropy.table.Row object for each row and accessing a column in that row (e.g. row['col0']) is slower than tuple access.

Parameters:
nameslist

List of column names (default to all columns if no names provided)

Returns:
rowsiterable

Iterator returns tuples of row values

Examples

Create a table with three columns ‘a’, ‘b’ and ‘c’:

>>> t = Table({'a': [1, 2, 3],
...            'b': [1.0, 2.5, 3.0],
...            'c': ['x', 'y', 'z']})

To iterate row-wise using column names:

>>> for a, c in t.iterrows('a', 'c'):
...     print(a, c)
1 x
2 y
3 z
keep_columns(names)

Keep only the columns specified (remove the others).

Parameters:
namesstr or iterable of str

The columns to keep. All other columns will be removed.

Examples

Create a table with three columns ‘a’, ‘b’ and ‘c’:

>>> t = Table([[1, 2, 3],[0.1, 0.2, 0.3],['x', 'y', 'z']],
...           names=('a', 'b', 'c'))
>>> print(t)
 a   b   c
--- --- ---
  1 0.1   x
  2 0.2   y
  3 0.3   z

Keep only column ‘a’ of the table:

>>> t.keep_columns('a')
>>> print(t)
 a
---
  1
  2
  3

Keep columns ‘a’ and ‘c’ of the table:

>>> t = Table([[1, 2, 3],[0.1, 0.2, 0.3],['x', 'y', 'z']],
...           names=('a', 'b', 'c'))
>>> t.keep_columns(['a', 'c'])
>>> print(t)
 a   c
--- ---
  1   x
  2   y
  3   z
keys()
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:
explainFalse 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.
more(max_lines=None, max_width=None, show_name=True, show_unit=None, show_dtype=False)

Interactively browse table with a paging interface.

Supported keys:

f, <space> : forward one page
b : back one page
r : refresh same page
n : next row
p : previous row
< : go to beginning
> : go to end
q : quit browsing
h : print this help
Parameters:
max_linesint

Maximum number of lines in table output

max_widthint or None

Maximum character width of output

show_namebool

Include a header row for column names. Default is True.

show_unitbool

Include a header row for unit. Default is to show a row for units only if one or more columns has a defined value for the unit.

show_dtypebool

Include a header row for column dtypes. Default is False.

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 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_lightcurveLightCurve

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
<Quantity [1.00055917, 0.99885466, 1.        ]>
>>> normalized_lc.flux_err
<Quantity [0.00026223, 0.00017739, 0.00023909]>
pformat(max_lines=None, max_width=None, show_name=True, show_unit=None, show_dtype=False, html=False, tableid=None, align=None, tableclass=None)
Return a list of lines for the formatted string representation of

the table.

If no value of max_lines is supplied then the height of the screen terminal is used to set max_lines. If the terminal height cannot be determined then the default is taken from the configuration item astropy.conf.max_lines. If a negative value of max_lines is supplied then there is no line limit applied.

The same applies for max_width except the configuration item is astropy.conf.max_width.

Parameters:
max_linesint or None

Maximum number of rows to output

max_widthint or None

Maximum character width of output

show_namebool

Include a header row for column names. Default is True.

show_unitbool

Include a header row for unit. Default is to show a row for units only if one or more columns has a defined value for the unit.

show_dtypebool

Include a header row for column dtypes. Default is True.

htmlbool

Format the output as an HTML table. Default is False.

tableidstr or None

An ID tag for the table; only used if html is set. Default is “table{id}”, where id is the unique integer id of the table object, id(self)

alignstr or list or tuple or None

Left/right alignment of columns. Default is right (None) for all columns. Other allowed values are ‘>’, ‘<’, ‘^’, and ‘0=’ for right, left, centered, and 0-padded, respectively. A list of strings can be provided for alignment of tables with multiple columns.

tableclassstr or list of str or None

CSS classes for the table; only used if html is set. Default is None.

Returns:
lineslist

Formatted table as a list of strings.

pformat_all(max_lines=-1, max_width=-1, show_name=True, show_unit=None, show_dtype=False, html=False, tableid=None, align=None, tableclass=None)
Return a list of lines for the formatted string representation of

the entire table.

If no value of max_lines is supplied then the height of the screen terminal is used to set max_lines. If the terminal height cannot be determined then the default is taken from the configuration item astropy.conf.max_lines. If a negative value of max_lines is supplied then there is no line limit applied.

The same applies for max_width except the configuration item is astropy.conf.max_width.

Parameters:
max_linesint or None

Maximum number of rows to output

max_widthint or None

Maximum character width of output

show_namebool

Include a header row for column names. Default is True.

show_unitbool

Include a header row for unit. Default is to show a row for units only if one or more columns has a defined value for the unit.

show_dtypebool

Include a header row for column dtypes. Default is True.

htmlbool

Format the output as an HTML table. Default is False.

tableidstr or None

An ID tag for the table; only used if html is set. Default is “table{id}”, where id is the unique integer id of the table object, id(self)

alignstr or list or tuple or None

Left/right alignment of columns. Default is right (None) for all columns. Other allowed values are ‘>’, ‘<’, ‘^’, and ‘0=’ for right, left, centered, and 0-padded, respectively. A list of strings can be provided for alignment of tables with multiple columns.

tableclassstr or list of str or None

CSS classes for the table; only used if html is set. Default is None.

Returns:
lineslist

Formatted table as a list of strings.

plot(**kwargs) Axes

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

Parameters:
columnstr

Name of data column to plot. Default flux.

ax~matplotlib.axes.Axes

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

normalizebool

Normalize the lightcurve before plotting?

xlabelstr

X axis label.

ylabelstr

Y axis label.

titlestr

Title shown at the top using matplotlib set_title.

stylestr

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.

show_colorbarboolean

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

colorbar_labelstr

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

offsetfloat

Offset value to apply to the Y axis values before plotting. Use this to avoid light curves from overlapping on the same plot. By default, no offset is applied.

kwargsdict

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, **kwargs)[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, **kwargs)[source]

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

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

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, but it can be used to visualize periodic signals of any origin.

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

epoch_timefloat

Phase mid point for plotting. Defaults to the first time value.

bin_pointsint

How many points should be in each bin.

minimum_phasefloat

The minimum phase to plot.

maximum_phasefloat

The maximum phase to plot.

methodstr

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.

kwargsdict

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

Returns:
ax~matplotlib.axes.Axes

The matplotlib axes object.

pprint(max_lines=None, max_width=None, show_name=True, show_unit=None, show_dtype=False, align=None)

Print a formatted string representation of the table.

If no value of max_lines is supplied then the height of the screen terminal is used to set max_lines. If the terminal height cannot be determined then the default is taken from the configuration item astropy.conf.max_lines. If a negative value of max_lines is supplied then there is no line limit applied.

The same applies for max_width except the configuration item is astropy.conf.max_width.

Parameters:
max_linesint or None

Maximum number of lines in table output.

max_widthint or None

Maximum character width of output.

show_namebool

Include a header row for column names. Default is True.

show_unitbool

Include a header row for unit. Default is to show a row for units only if one or more columns has a defined value for the unit.

show_dtypebool

Include a header row for column dtypes. Default is False.

alignstr or list or tuple or None

Left/right alignment of columns. Default is right (None) for all columns. Other allowed values are ‘>’, ‘<’, ‘^’, and ‘0=’ for right, left, centered, and 0-padded, respectively. A list of strings can be provided for alignment of tables with multiple columns.

pprint_all(max_lines=-1, max_width=-1, show_name=True, show_unit=None, show_dtype=False, align=None)

Print a formatted string representation of the entire table.

This method is the same as astropy.table.Table.pprint except that the default max_lines and max_width are both -1 so that by default the entire table is printed instead of restricting to the size of the screen terminal.

Parameters:
max_linesint or None

Maximum number of lines in table output.

max_widthint or None

Maximum character width of output.

show_namebool

Include a header row for column names. Default is True.

show_unitbool

Include a header row for unit. Default is to show a row for units only if one or more columns has a defined value for the unit.

show_dtypebool

Include a header row for column dtypes. Default is False.

alignstr or list or tuple or None

Left/right alignment of columns. Default is right (None) for all columns. Other allowed values are ‘>’, ‘<’, ‘^’, and ‘0=’ for right, left, centered, and 0-padded, respectively. A list of strings can be provided for alignment of tables with multiple columns.

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

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.

Parameters:
cadence_maskstr, or boolean array with length of self.time

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. Alternatively, pass a boolean array with values of “True” for times to search for SSOs.

radiusoptional, float

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

sigmaoptional, float

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

locationoptional, str

Spacecraft location. Options include ‘kepler’ and ‘tess’. Default: self.mission

cacheoptional, bool

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

return_mask: optional, bool

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

show_progress: optional, bool

If True will display a progress bar during the download

Returns:
resultpandas.DataFrame

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

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).

  • By default, this method will only search points in time during which the light curve showed 3-sigma outliers in flux. You can override this behavior and search for specific times by passing cadence_mask. See examples for details.

Examples

Find if there are SSOs affecting the lightcurve for the given time frame:

>>> df_sso = lc.query_solar_system_objects(cadence_mask=(lc.time.value >= 2014.1) & (lc.time.value <= 2014.9))  

Find if there are SSOs affecting the lightcurve for all times, but it will be much slower:

>>> df_sso = lc.query_solar_system_objects(cadence_mask='all')  
classmethod read(*args, **kwargs)

Returns a KeplerLightCurve by reading the given file.

Parameters:
filenamestr

Local path or remote url of a Kepler light curve FITS file.

flux_columnstr, optional

The column in the FITS file to be read as flux. Defaults to ‘pdcsap_flux’. Typically ‘pdcsap_flux’ or ‘sap_flux’.

quality_bitmaskstr or int, optional

Bitmask (integer) which identifies the quality flag bitmask that should be used to mask out bad cadences. If a string is passed, it has the following meaning:

  • “none”: no cadences will be ignored

  • “default”: cadences with severe quality issues will be ignored

  • “hard”: more conservative choice of flags to ignore This is known to remove good data.

  • “hardest”: removes all data that has been flagged This mask is not recommended.

See the KeplerQualityFlags class for details on the bitmasks.

formatstr, optional

The format of the Kepler FITS file. Should be one of ‘kepler’, ‘k2sff’, ‘everest’. Defaults to ‘kepler’.

remove_column(name)

Remove a column from the table.

This can also be done with:

del table[name]
Parameters:
namestr

Name of column to remove

Examples

Create a table with three columns ‘a’, ‘b’ and ‘c’:

>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']],
...           names=('a', 'b', 'c'))
>>> print(t)
 a   b   c
--- --- ---
  1 0.1   x
  2 0.2   y
  3 0.3   z

Remove column ‘b’ from the table:

>>> t.remove_column('b')
>>> print(t)
 a   c
--- ---
  1   x
  2   y
  3   z

To remove several columns at the same time use remove_columns.

remove_columns(names)

Remove several columns from the table.

Parameters:
namesstr or iterable of str

Names of the columns to remove

Examples

Create a table with three columns ‘a’, ‘b’ and ‘c’:

>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']],
...     names=('a', 'b', 'c'))
>>> print(t)
 a   b   c
--- --- ---
  1 0.1   x
  2 0.2   y
  3 0.3   z

Remove columns ‘b’ and ‘c’ from the table:

>>> t.remove_columns(['b', 'c'])
>>> print(t)
 a
---
  1
  2
  3

Specifying only a single column also works. Remove column ‘b’ from the table:

>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']],
...     names=('a', 'b', 'c'))
>>> t.remove_columns('b')
>>> print(t)
 a   c
--- ---
  1   x
  2   y
  3   z

This gives the same as using remove_column.

remove_indices(colname)

Remove all indices involving the given column. If the primary index is removed, the new primary index will be the most recently added remaining index.

Parameters:
colnamestr

Name of column

remove_nans(column: str = 'flux')

Removes cadences where column is a NaN.

Parameters:
columnstr

Column to check for NaNs. Defaults to 'flux'.

Returns:
clean_lightcurveLightCurve

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

Examples

>>> import lightkurve as lk
>>> import numpy as np
>>> lc = lk.LightCurve({'time': [1, 2, 3], 'flux': [1., np.nan, 1.]})
>>> lc.remove_nans()
<LightCurve length=2>
time   flux  flux_err

Time float64 float64
---- ------- --------
1.0     1.0      nan
3.0     1.0      nan
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:
sigmafloat

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_lowerfloat 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_upperfloat 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_maskbool

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.

**kwargsdict

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

Returns:
clean_lcLightCurve

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

outlier_maskNumPy 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
<Time object: scale='tdb' format='jd' value=[1. 3. 5.]>
>>> lc_clean.flux
<Quantity [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
<Time object: scale='tdb' format='jd' value=[1. 3. 4. 5.]>
>>> lc_clean.flux
<Quantity [    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])
remove_row(index)

Remove a row from the table.

Parameters:
indexint

Index of row to remove

Examples

Create a table with three columns ‘a’, ‘b’ and ‘c’:

>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']],
...           names=('a', 'b', 'c'))
>>> print(t)
 a   b   c
--- --- ---
  1 0.1   x
  2 0.2   y
  3 0.3   z

Remove row 1 from the table:

>>> t.remove_row(1)
>>> print(t)
 a   b   c
--- --- ---
  1 0.1   x
  3 0.3   z

To remove several rows at the same time use remove_rows.

remove_rows(row_specifier)

Remove rows from the table.

Parameters:
row_specifierslice or int or array of int

Specification for rows to remove

Examples

Create a table with three columns ‘a’, ‘b’ and ‘c’:

>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']],
...           names=('a', 'b', 'c'))
>>> print(t)
 a   b   c
--- --- ---
  1 0.1   x
  2 0.2   y
  3 0.3   z

Remove rows 0 and 2 from the table:

>>> t.remove_rows([0, 2])
>>> print(t)
 a   b   c
--- --- ---
  2 0.2   y

Note that there are no warnings if the slice operator extends outside the data:

>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']],
...           names=('a', 'b', 'c'))
>>> t.remove_rows(slice(10, 20, 1))
>>> print(t)
 a   b   c
--- --- ---
  1 0.1   x
  2 0.2   y
  3 0.3   z
rename_column(name, new_name)

Rename a column.

This can also be done directly by setting the name attribute of the info property of the column:

table[name].info.name = new_name
Parameters:
namestr

The current name of the column.

new_namestr

The new name for the column

Examples

Create a table with three columns ‘a’, ‘b’ and ‘c’:

>>> t = Table([[1,2],[3,4],[5,6]], names=('a','b','c'))
>>> print(t)
 a   b   c
--- --- ---
  1   3   5
  2   4   6

Renaming column ‘a’ to ‘aa’:

>>> t.rename_column('a' , 'aa')
>>> print(t)
 aa  b   c
--- --- ---
  1   3   5
  2   4   6
rename_columns(names, new_names)

Rename multiple columns.

Parameters:
nameslist, tuple

A list or tuple of existing column names.

new_nameslist, tuple

A list or tuple of new column names.

Examples

Create a table with three columns ‘a’, ‘b’, ‘c’:

>>> t = Table([[1,2],[3,4],[5,6]], names=('a','b','c'))
>>> print(t)
  a   b   c
 --- --- ---
  1   3   5
  2   4   6

Renaming columns ‘a’ to ‘aa’ and ‘b’ to ‘bb’:

>>> names = ('a','b')
>>> new_names = ('aa','bb')
>>> t.rename_columns(names, new_names)
>>> print(t)
 aa  bb   c
--- --- ---
  1   3   5
  2   4   6
replace_column(name, col, copy=True)

Replace column name with the new col object.

The behavior of copy for Column objects is: - copy=True: new class instance with a copy of data and deep copy of meta - copy=False: new class instance with same data and a key-only copy of meta

For mixin columns: - copy=True: new class instance with copy of data and deep copy of meta - copy=False: original instance (no copy at all)

Parameters:
namestr

Name of column to replace

col~astropy.table.Column or ~numpy.ndarray or sequence

New column object to replace the existing column.

copybool

Make copy of the input col, default=True

See also

add_columns, astropy.table.hstack, update

Examples

Replace column ‘a’ with a float version of itself:

>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3]], names=('a', 'b'))
>>> float_a = t['a'].astype(float)
>>> t.replace_column('a', float_a)
reverse()

Reverse the row order of table rows. The table is reversed in place and there are no function arguments.

Examples

Create a table with three columns:

>>> t = Table([['Max', 'Jo', 'John'], ['Miller','Miller','Jackson'],
...         [12,15,18]], names=('firstname','name','tel'))
>>> print(t)
firstname   name  tel
--------- ------- ---
      Max  Miller  12
       Jo  Miller  15
     John Jackson  18

Reversing order:

>>> t.reverse()
>>> print(t)
firstname   name  tel
--------- ------- ---
     John Jackson  18
       Jo  Miller  15
      Max  Miller  12
round(decimals=0)

Round numeric columns in-place to the specified number of decimals. Non-numeric columns will be ignored.

Parameters:
decimals: int, dict

Number of decimals to round the columns to. If a dict is given, the columns will be rounded to the number specified as the value. If a certain column is not in the dict given, it will remain the same.

Examples

Create three columns with different types:

>>> t = Table([[1, 4, 5], [-25.55, 12.123, 85],
...     ['a', 'b', 'c']], names=('a', 'b', 'c'))
>>> print(t)
 a    b     c
--- ------ ---
  1 -25.55   a
  4 12.123   b
  5   85.0   c

Round them all to 0:

>>> t.round(0)
>>> print(t)
 a    b    c
--- ----- ---
  1 -26.0   a
  4  12.0   b
  5  85.0   c

Round column ‘a’ to -1 decimal:

>>> t.round({'a':-1})
>>> print(t)
 a    b    c
--- ----- ---
  0 -26.0   a
  0  12.0   b
  0  85.0   c
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:
iterations2000 or int

Number of injection/recovery cycles

inject_before_detrendingFalse or bool

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

modestr

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

fakefreq0.05 or float

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

detrend_kwargsdict

Keyword arguments to pass to FlareLightCurve.detrend

kwargsdict

Keyword arguments to pass to inject_fake_flares

Returns:
lcFlareLightCurve

Detrended LC with all fake_flares listed in the attribute

fake_lcFlareLightCurve

Light curve with the last iteration of synthetic flares injected.

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

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

Parameters:
columnstr

Name of data column to plot. Default flux.

ax~matplotlib.axes.Axes

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

normalizebool

Normalize the lightcurve before plotting?

xlabelstr

X axis label.

ylabelstr

Y axis label.

titlestr

Title shown at the top using matplotlib set_title.

stylestr

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.

show_colorbarboolean

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

colorbar_labelstr

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

offsetfloat

Offset value to apply to the Y axis values before plotting. Use this to avoid light curves from overlapping on the same plot. By default, no offset is applied.

kwargsdict

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

Returns:
ax~matplotlib.axes.Axes

The matplotlib axes object.

search_neighbors(limit: int = 10, radius: float = 3600.0, **search_criteria)

Search the data archive at MAST for the most nearby light curves.

By default, the 10 nearest neighbors located within 3600 arcseconds are returned. You can override these defaults by changing the limit and radius parameters.

If the LightCurve object is a Kepler, K2, or TESS light curve, the default behavior of this method is to only return light curves obtained during the exact same quarter, campaign, or sector. This is useful to enable coeval light curves to be inspected for spurious noise signals in common between multiple neighboring targets. You can override this default behavior by passing a mission, quarter, campaign, or sector argument yourself.

Please refer to the docstring of search_lightcurve for a complete list of search parameters accepted.

Parameters:
limitint

Maximum number of results to return.

radiusfloat or astropy.units.Quantity object

Conesearch radius. If a float is given it will be assumed to be in units of arcseconds.

**search_criteriakwargs

Extra criteria to be passed to search_lightcurve.

Returns:
resultSearchResult object

Object detailing the neighbor light curves found, sorted by distance from the current light curve.

select_flux(flux_column, flux_err_column=None)

Assign a different column to be the flux column.

This method returns a copy of the LightCurve in which the flux and flux_err columns have been replaced by the values contained in a different column.

Parameters:
flux_columnstr

Name of the column that should become the ‘flux’ column.

flux_err_columnstr or None

Name of the column that should become the ‘flux_err’ column. By default, the column will be used that is obtained by adding the suffix “_err” to the value of flux_column. If such a column does not exist, flux_err will be populated with NaN values.

Returns:
lcLightCurve

Copy of the LightCurve object with the new flux values assigned.

Examples

You can use this function to change the flux data on which most Lightkurve features operate. For example, to view a periodogram based on the “sap_flux” column in a TESS light curve, use:

>>> lc.select_flux("sap_flux").to_periodogram("lombscargle").plot()  
show_in_browser(max_lines=5000, jsviewer=False, browser='default', jskwargs={'use_local_files': True}, tableid=None, table_class='display compact', css=None, show_row_index='idx')

Render the table in HTML and show it in a web browser.

Parameters:
max_linesint

Maximum number of rows to export to the table (set low by default to avoid memory issues, since the browser view requires duplicating the table in memory). A negative value of max_lines indicates no row limit.

jsviewerbool

If True, prepends some javascript headers so that the table is rendered as a DataTables data table. This allows in-browser searching & sorting.

browserstr

Any legal browser name, e.g. 'firefox', 'chrome', 'safari' (for mac, you may need to use 'open -a "/Applications/Google Chrome.app" {}' for Chrome). If 'default', will use the system default browser.

jskwargsdict

Passed to the astropy.table.JSViewer init. Defaults to {'use_local_files': True} which means that the JavaScript libraries will be served from local copies.

tableidstr or None

An html ID tag for the table. Default is table{id}, where id is the unique integer id of the table object, id(self).

table_classstr or None

A string with a list of HTML classes used to style the table. Default is “display compact”, and other possible values can be found in https://www.datatables.net/manual/styling/classes

cssstr

A valid CSS string declaring the formatting for the table. Defaults to astropy.table.jsviewer.DEFAULT_CSS.

show_row_indexstr or False

If this does not evaluate to False, a column with the given name will be added to the version of the table that gets displayed. This new column shows the index of the row in the table itself, even when the displayed table is re-sorted by another column. Note that if a column with this name already exists, this option will be ignored. Defaults to “idx”.

show_in_notebook(tableid=None, css=None, display_length=50, table_class='astropy-default', show_row_index='idx')

Render the table in HTML and show it in the IPython notebook.

Parameters:
tableidstr or None

An html ID tag for the table. Default is table{id}-XXX, where id is the unique integer id of the table object, id(self), and XXX is a random number to avoid conflicts when printing the same table multiple times.

table_classstr or None

A string with a list of HTML classes used to style the table. The special default string (‘astropy-default’) means that the string will be retrieved from the configuration item astropy.table.default_notebook_table_class. Note that these table classes may make use of bootstrap, as this is loaded with the notebook. See this page for the list of classes.

cssstr

A valid CSS string declaring the formatting for the table. Defaults to astropy.table.jsviewer.DEFAULT_CSS_NB.

display_lengthint, optional

Number or rows to show. Defaults to 50.

show_row_indexstr or False

If this does not evaluate to False, a column with the given name will be added to the version of the table that gets displayed. This new column shows the index of the row in the table itself, even when the displayed table is re-sorted by another column. Note that if a column with this name already exists, this option will be ignored. Defaults to “idx”.

Notes

Currently, unlike show_in_browser (with jsviewer=True), this method needs to access online javascript code repositories. This is due to modern browsers’ limitations on accessing local files. Hence, if you call this method while offline (and don’t have a cached version of jquery and jquery.dataTables), you will not get the jsviewer features.

show_properties()

Prints a description of all non-callable attributes.

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

sort(keys=None, *, kind=None, reverse=False)

Sort the table according to one or more keys. This operates on the existing table and does not return a new table.

Parameters:
keysstr or list of str

The key(s) to order the table by. If None, use the primary index of the Table.

kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional

Sorting algorithm used by numpy.argsort.

reversebool

Sort in reverse order (default=False)

Examples

Create a table with 3 columns:

>>> t = Table([['Max', 'Jo', 'John'], ['Miller', 'Miller', 'Jackson'],
...            [12, 15, 18]], names=('firstname', 'name', 'tel'))
>>> print(t)
firstname   name  tel
--------- ------- ---
      Max  Miller  12
       Jo  Miller  15
     John Jackson  18

Sorting according to standard sorting rules, first ‘name’ then ‘firstname’:

>>> t.sort(['name', 'firstname'])
>>> print(t)
firstname   name  tel
--------- ------- ---
     John Jackson  18
       Jo  Miller  15
      Max  Miller  12

Sorting according to standard sorting rules, first ‘firstname’ then ‘tel’, in reverse order:

>>> t.sort(['firstname', 'tel'], reverse=True)
>>> print(t)
firstname   name  tel
--------- ------- ---
      Max  Miller  12
     John Jackson  18
       Jo  Miller  15
tail(n: int = 5)

Return the last n rows.

Parameters:
nint

Number of rows to return.

Returns:
lcLightCurve

Light curve containing the last n rows.

to_corrector(method='sff', **kwargs)

Returns a corrector object to remove instrument systematics.

Parameters:
methodsstring

Currently, “sff” and “cbv” are supported. This will return a ~correctors.SFFCorrector and ~correctors.CBVCorrector class instance respectively.

**kwargsdict

Extra keyword arguments to be passed to the corrector class.

Returns:
correcter~correctors.corrector.Corrector

Instance of a Corrector class, which typically provides ~correctors.corrector.Corrector.correct() and ~correctors.corrector.Corrector.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_bufstring or file handle

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

**kwargsdict

Dictionary of arguments to be passed to TimeSeries.write().

Returns:
csvstr or None

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

to_excel(path_or_buf, **kwargs) None

Shorthand for to_pandas().to_excel().

Parameters:
path_or_bufstring or file handle

File path or object.

**kwargsdict

Dictionary of arguments to be passed to to_pandas().to_excel(**kwargs).

to_fits(*args, **kwargs)[source]

Writes the KeplerLightCurve to a FITS file.

Parameters:
pathstring, default None

File path, if None returns an astropy.io.fits.HDUList object.

overwritebool

Whether or not to overwrite the file

flux_column_namestr

The name of the label for the FITS extension, e.g. SAP_FLUX or FLUX

aperture_maskarray-like

Optional 2D aperture mask to save with this lightcurve object, if defined. The mask can be either a boolean mask or an integer mask mimicking the Kepler/TESS convention; boolean masks are automatically converted to the Kepler/TESS conventions

extra_datadict

Extra keywords or columns to include in the FITS file. Arguments of type str, int, float, or bool will be stored as keywords in the primary header. Arguments of type np.array or list will be stored as columns in the first extension.

Returns:
hduastropy.io.fits

Returns an astropy.io.fits object if path is None

to_pandas(**kwargs)

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

The data frame will be indexed by time using values corresponding to the light curve’s time format. This is different from the default behavior of Table.to_pandas() in AstroPy, which converts time values into ISO timestamps.

Returns:
dataframepandas.DataFrame

A data frame indexed by time.

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

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

This method will call either LombScarglePeriodogram.from_lightcurve() <lightkurve.periodogram.LombScarglePeriodogram.from_lightcurve> or BoxLeastSquaresPeriodogram.from_lightcurve() <lightkurve.periodogram.BoxLeastSquaresPeriodogram.from_lightcurve>, which in turn wrap astropy’s ~astropy.timeseries.LombScargle and ~astropy.timeseries.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'.

kwargsdict

Keyword arguments passed to either LombScarglePeriodogram <lightkurve.periodogram.LombScarglePeriodogram.from_lightcurve> or BoxLeastSquaresPeriodogram <lightkurve.periodogram.BoxLeastSquaresPeriodogram.from_lightcurve>.

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:
lightcurvestingray.Lightcurve

An stingray Lightcurve object.

to_table() Table
to_timeseries()

Deprecated since version 2.0: to_timeseries() has been deprecated. LightCurve is a sub-class of Astropy TimeSeries as of Lightkurve v2.0 and no longer needs to be converted.

truncate(before: float | None = None, after: float | None = None, column: str = 'time')

Truncates the light curve before and after some time value.

Parameters:
beforefloat

Truncate all rows before this time value.

afterfloat

Truncate all rows after this time value.

columnstr, optional

The name of the column on which the truncation is based. Defaults to ‘time’.

Returns:
truncated_lcLightCurve

The truncated light curve.

update(other, copy=True)

Perform a dictionary-style update and merge metadata.

The argument other must be a |Table|, or something that can be used to initialize a table. Columns from (possibly converted) other are added to this table. In case of matching column names the column from this table is replaced with the one from other. If other is a |Table| instance then |= is available as alternate syntax for in-place update and | can be used merge data to a new table.

Parameters:
othertable-like

Data to update this table with.

copybool

Whether the updated columns should be copies of or references to the originals.

See also

add_columns, astropy.table.hstack, replace_column

Examples

Update a table with another table:

>>> t1 = Table({'a': ['foo', 'bar'], 'b': [0., 0.]}, meta={'i': 0})
>>> t2 = Table({'b': [1., 2.], 'c': [7., 11.]}, meta={'n': 2})
>>> t1.update(t2)
>>> t1
<Table length=2>
 a      b       c
str3 float64 float64
---- ------- -------
 foo     1.0     7.0
 bar     2.0    11.0
>>> t1.meta
{'i': 0, 'n': 2}

Update a table with a dictionary:

>>> t = Table({'a': ['foo', 'bar'], 'b': [0., 0.]})
>>> t.update({'b': [1., 2.]})
>>> t
<Table length=2>
 a      b
str3 float64
---- -------
 foo     1.0
 bar     2.0
values()
values_equal(other)

Element-wise comparison of table with another table, list, or scalar.

Returns a Table with the same columns containing boolean values showing result of comparison.

Parameters:
othertable-like object or list or scalar

Object to compare with table

Examples

Compare one Table with other:

>>> t1 = Table([[1, 2], [4, 5], [-7, 8]], names=('a', 'b', 'c'))
>>> t2 = Table([[1, 2], [-4, 5], [7, 8]], names=('a', 'b', 'c'))
>>> t1.values_equal(t2)
<Table length=2>
 a     b     c
bool  bool  bool
---- ----- -----
True False False
True  True  True