Metadata-Version: 2.4
Name: star_toffee
Version: 1.6.1
Summary: Package for finding flares in TESS and Kepler lightcurves
Author-email: Jason Reeves <jasonree702@gmail.com>, Andy Zhang <Andy.Zhang649964@tufts.edu>, "David V. Martin" <david.martin@tufts.edu>
License-Expression: MIT
Project-URL: Homepage, https://github.com/JasonReeves702/TOFFEE/blob/main/README.md
Project-URL: Issues, https://github.com/JasonReeves702/TOFFEE/issues
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: astropy>=7.0.0
Requires-Dist: astroquery>=0.4.11
Requires-Dist: lightkurve>=2.5.1
Requires-Dist: matplotlib>=3.10.7
Requires-Dist: numpy>=1.25.2
Requires-Dist: pandas>=2.3.3
Requires-Dist: pytest
Requires-Dist: requests>=2.32.5
Requires-Dist: scikit_learn>=1.7.2
Requires-Dist: scipy>=1.16.3
Requires-Dist: wotan>=1.10
Dynamic: license-file

<p align="center">
  <img src="https://raw.githubusercontent.com/JasonReeves702/TOFFEE/main/TOFFEE_Logo.png" width="385" height="223" alt="TOFFEE logo" />
</p>

# TOFFEE

**T**ESS **O**verlapping **F**lare **F**inder and **E**nergy **E**valuator — a Python
package for detrending TESS and Kepler light curves, detecting stellar flares, and
measuring their energies.

TOFFEE's distinguishing feature is that it resolves **overlapping and sympathetic
flares**: where most threshold-based finders return one event, TOFFEE models the
decay of the brightest flare and searches the residuals for the fainter ones hidden
inside it. That makes flare samples complete down to short waiting times, which is
what the waiting-time statistics of magnetic reconnection actually depend on.

## Statement of need

Threshold-based flare finders (following Chang, Byun & Hartman 2015) scan a detrended
light curve for runs of points above some multiple of the photometric scatter. They
work well on isolated events, but two problems limit the samples they produce:

1. **Overlapping flares are counted once.** A flare that begins during the decay of a
   brighter one is absorbed into its parent. Any measurement of flare waiting times is
   biased precisely in the regime that distinguishes between models of sympathetic
   flaring.
2. **Detrending artefacts and instrumental noise masquerade as flares.** Residual red
   noise left by the detrending step creeps over the detection threshold and inflates
   the sample at low amplitudes, where most flares live.

TOFFEE addresses the first with a top-down search: it starts at the brightest point,
fits a rise and a decay model, and re-runs detection on the residuals to find
secondaries. It addresses the second with two complementary purity methods (below).
It also derives stellar parameters — spot modulation and rotation — with the flares
masked out, so those estimates are not biased by the flares themselves.

## Installation

```bash
pip install star_toffee
```

Requires Python 3.8 or newer. Dependencies (numpy, scipy, astropy, astroquery,
lightkurve, wotan, pandas, matplotlib, scikit-learn) are installed automatically.

## Quickstart

```python
import numpy as np
import toffee
import lightkurve as lk

#grab a TESS 2-minute light curve
lc = lk.search_lightcurve('TIC 441420236', mission = 'TESS', cadence = 120)[0].download()

#detrend first. detect_flares expects a normalised, detrended light curve --
#it does not detrend for you. load_and_flatten also applies the quality filter.
time, flux, flux_err = toffee.load_and_flatten(lc.time.value, lc.flux.value,
                                               lc.flux_err.value, lc.quality.value)

#then detect. the flags were handled above, so switch that step off here
flares = toffee.detect_flares(time, flux, flux_err, np.zeros(len(time)),
                              flag_values = None)
print(flares)
```

`detect_flares` returns a pandas DataFrame, one row per flare:

| Column | Meaning |
| --- | --- |
| `T_peak` | time of the flare peak, in days (same scale as the input time) |
| `T_start`, `T_end` | flare start and end, in days |
| `Amplitude` | peak flux above the normalised baseline |
| `ED` | equivalent duration, in **seconds** |
| `Primary_or_Secondary` | whether the flare was found directly, or inside another flare's residuals |
| `Num_Points` | cadences spanned by the flare |
| `Num_Abv_Threshold` | cadences above the detection threshold |
| `Amp_Sigma` | amplitude in units of the photometric scatter |

Most of `detect_flares`' arguments are tuned defaults. In practice only
`primary_threshold`, `secondary_threshold`, `num_consec` and `num_consec_sec` are
worth adjusting.

## Sample purity

Two independent methods, designed to be used in that order:

**Red noise smoothing.** Mask the large flares found in a first detection pass, then
re-detrend on a short window (~0.075–0.1 d) so the detrending fits around the flares
rather than through them. This strips the low-amplitude residual noise that would
otherwise clear the threshold.

```python
result = toffee.flatten_detect_smooth(time, flux, flux_err, quality, window = 0.1)
result['first']      #flares before smoothing
result['second']     #flares after
result['dropped']    #first-pass flares the smoothing removed
result['new']        #flares the smoothing revealed
```

**Square index cutting.** The square index is flare duration over amplitude. Boxy,
high-SI shapes are usually artefacts rather than flares, so cutting `log(SI) >~ 0.6`
raises purity.

```python
flares = toffee.add_square_index(flares, cadence = 120)   #cadence in SECONDS
clean  = toffee.select_by_square_index(flares, log_si_max = 0.6)
```

## Other features

```python
#detrending on its own. flatten's return arity depends on which stages you ask
#for: 3 values with no short_window, 4 with no periodogram, 5 with both
orbit_t, lc_quad, lc_wotan, lc_flat, periodic = toffee.flatten(
    time, flux, flux_err, short_window = 0.25, periodogram = [0.1, 10])

#rotation period with the flares masked out, and its false-alarm probability
period, false_alarm = toffee.get_rot_period(time, flux, flux_err)

#plot a detection. takes the same detrended inputs as detect_flares
toffee.visualizer(time, flux, flux_err, np.zeros(len(time)), flag_values = None)
```

## Documentation and tutorials

- Tutorials: TODO — link the rendered notebook series
- API reference: TODO — link the Sphinx site once it is published

## Tests

```bash
pytest src/toffee/tests/test_toffee.py -q
```

The suite is hermetic: every light curve is synthetic and seeded, and the detrending
tests monkeypatch the FFI-times download, so no network access or TESS data is needed.

## Citation

If TOFFEE is useful in your work, please cite TODO — add the JOSS paper once it has
a DOI, and the methods paper.

## License

MIT. See [LICENSE](LICENSE).
