Metadata-Version: 2.4
Name: quicklook-package
Version: 1.14.0
Author-email: jpdeleon <jpdeleon.bsap@gmail.com>
Project-URL: Homepage, https://github.com/jpdeleon/quicklook
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: POSIX :: Linux
Classifier: Topic :: Scientific/Engineering :: Astronomy
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: setuptools
Requires-Dist: matplotlib
Requires-Dist: lightkurve>=2.5
Requires-Dist: numpy>=2.0
Requires-Dist: transitleastsquares>=1.32
Requires-Dist: wotan>=1.10
Requires-Dist: h5py>=3.10
Requires-Dist: reproject>=0.13
Requires-Dist: astroplan>=0.10
Requires-Dist: loguru
Requires-Dist: flask
Requires-Dist: typer>=0.12
Requires-Dist: scipy>=1.10
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-benchmark; extra == "dev"
Requires-Dist: pytest-xdist; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Requires-Dist: pre-commit; extra == "dev"
Requires-Dist: tox>=4.0; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Requires-Dist: pytest-timeout>=2.4.0; extra == "dev"
Provides-Extra: precession
Requires-Dist: batman-package>=2.5; extra == "precession"
Provides-Extra: gui
Requires-Dist: flask; extra == "gui"
Requires-Dist: flask-sock; extra == "gui"
Requires-Dist: pytest-flask; extra == "gui"
Provides-Extra: gpu
Requires-Dist: gputls; extra == "gpu"
Requires-Dist: cupy-cuda12x[ctk]; extra == "gpu"
Provides-Extra: notebooks
Requires-Dist: ipykernel; extra == "notebooks"
Requires-Dist: jupyter; extra == "notebooks"
Requires-Dist: nbconvert; extra == "notebooks"
Dynamic: license-file

# QuickLook

[![Documentation](https://readthedocs.org/projects/quicklook/badge/?version=latest)](https://quicklook.readthedocs.io/en/latest/)
[![CI](https://github.com/jpdeleon/quicklook/actions/workflows/build-and-test.yml/badge.svg)](https://github.com/jpdeleon/quicklook/actions/workflows/build-and-test.yml)
[![PyPI](https://img.shields.io/pypi/v/quicklook-package)](https://pypi.org/project/quicklook-package/)
[![Python](https://img.shields.io/pypi/pyversions/quicklook-package)](https://pypi.org/project/quicklook-package/)
[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/jpdeleon/quicklook)

`quicklook` is a Python pipeline that searches for transit signals in [TESS](https://tess.mit.edu/) light curves. Given a target name, it downloads the light curve, estimates the stellar rotation period, searches for transiting companions using the [Transit Least Squares](https://ui.adsabs.harvard.edu/abs/2019A%26A...623A..39H/abstract) (TLS) algorithm, and produces a publication-ready 9-panel diagnostic figure.

Although `quicklook` is optimized to find transiting exoplanets, it can also detect eclipsing binaries, variable stars, and other periodic signals.

## Features

- **Multi-pipeline support** -- SPOC, TESS-SPOC, QLP, CDIPS, PATHOS, TGLC, TASOC, T16
- **Flux / light-curve type** -- PDCSAP or SAP for SPOC; aperture or PSF photometry for TGLC, with an automatic best-quality default
- **Automated detrending** -- biweight, cosine, median, GP, and other [wotan](https://github.com/hippke/wotan) methods with dynamic rotation-aware ($P_{\text{rot}}$) window tuning and adaptive spline density, plus a built-in **Notch** and **LOCoR** filter (Rizzuto et al. 2017) that preserve transit shape via a windowed BIC test / rotation-cycle combination instead of dividing it out
- **Stellar rotation** -- Generalized Lomb-Scargle (GLS) periodogram
- **Transit detection & vetting** -- Transit Least Squares (TLS) periodogram with advanced vetting flags (depth variance ratio, duration consistency, secondary eclipse SDE, and iterative multi-planet search)
- **Single-transit search** -- optional search for individual transits that TLS cannot find, with a red-noise-aware box search, a BIC test against step/ramp systematics, its own wider detrending window that is re-fitted with detected events masked, a period lower limit, duotransit pairing with ranked period aliases, and a `none`/`mono`/`duo`/`periodic` classification ([docs](docs/single-transit.md))
- **TTV search** -- optional per-transit timing fits (free mid-time, depth and duration), an O−C diagram with a robust χ² test against a linear ephemeris, masking at the fitted times in the iterative search, red-noise (β) inflation of the timing errors, vetting against catalogue periods and the stellar rotation period, cycle-count alternatives across sector gaps, chaining of three or more single events, and diagnostic figures (`*_ttv.png`, `*_ttv_transits.png`) from local-baseline timing on the raw flux with injection-calibrated errors, which still work on spotted young stars where TLS fails ([docs](docs/ttv-search.md))
- **Precession search** -- optional per-sector transit-shape fits (joint `batman` fit with shared a/Rs and limb darkening, free b, Rp/Rs, mid-time and baseline per sector), static/linear/quadratic b(t) models compared by BIC, a candidate test (|db/dt| >= 3σ, ΔBIC >= 2, T14 trend opposite to b), flags for dilution changes (CROWDSAP), mixed cadence, per-sector T0 shifts, the b–Rp/Rs grazing degeneracy (blocking when Rp/Rs also trends) and short baselines, derived di/dt and years until the transit disappears, and a `*_precession.png` figure. An eclipsing-binary branch (`--precession-mode eb`, or auto from SIMBAD) fits the inner-binary inclination per sector with a two-star eclipse model, checks it against the measured depth trend, and gives an upper limit on the triple's nodal precession period ([docs](docs/precession-search.md))
- **Broken time axes** -- in every layout (periodic, TTV, mono, duo), light-curve panels of multi-sector data are split at gaps longer than 10 d into one equal-width sub-axes per sector, so each sector stays readable
- **Neighbor check** -- Gaia source overlay on cached archival sky images, with optional nearby SIMBAD object labels
- **Batch processing** -- `--each-sector` mode, GNU parallel support, and candidate ranking tools
- **Fast CLI startup** -- lazy imports keep `ql --help` under 200 ms
- **Headless friendly** -- detects missing display and aborts early, or works fully offline with `--save`
- **Web GUI** -- Flask-based interface with live progress, job queue, and gallery
- **HDF5 output** -- full TLS results saved for downstream filtering

## Installation

Requires Python 3.10+. Choose either `uv` (recommended) or `pip` below.

<details open>
<summary><strong>uv (recommended)</strong></summary>

```bash
# Command-line application
uv tool install quicklook-package

# Or install this repository, including development dependencies
uv sync --extra dev

# Optional extras for a repository installation
uv sync --extra gui        # Web GUI
uv sync --extra gpu        # GPU transit search (CUDA 12)
uv sync --extra notebooks  # Jupyter notebooks
```

Run commands from a repository installation with `uv run`, for example
`uv run quicklook --help`.

</details>

<details>
<summary><strong>pip</strong></summary>

```bash
# Command-line application
python -m pip install -U quicklook-package

# Optional extras
python -m pip install -U "quicklook-package[gui]"       # Web GUI
python -m pip install -U "quicklook-package[gpu]"       # GPU transit search (CUDA 12)
python -m pip install -U "quicklook-package[notebooks]" # Jupyter notebooks
python -m pip install -U "quicklook-package[dev]"       # Development tools
```

Once installed, run commands directly, for example `quicklook --help` or
`ql --help`.

</details>

With the `gpu` extra installed, QuickLook uses GTLS when a CUDA device is
visible and automatically falls back to the standard CPU TLS implementation
when GTLS or a GPU is unavailable, or when GPU execution fails to initialize.

## Try it on Google Colab

Each notebook installs `quicklook` when opened in Colab.

| Notebook | Topic | |
|---|---|---|
| [`examples.ipynb`](https://github.com/jpdeleon/quicklook/blob/main/notebook/examples.ipynb) | Quick-look basics: a planet, an eclipsing binary and more | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jpdeleon/quicklook/blob/main/notebook/examples.ipynb) |
| [`single_transit_search.ipynb`](https://github.com/jpdeleon/quicklook/blob/main/notebook/single_transit_search.ipynb) | Mono- and duotransit search (TOI-2180 b) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jpdeleon/quicklook/blob/main/notebook/single_transit_search.ipynb) |
| [`ttv_search.ipynb`](https://github.com/jpdeleon/quicklook/blob/main/notebook/ttv_search.ipynb) | TTV search (TOI-216 c, TOI-6109 b) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jpdeleon/quicklook/blob/main/notebook/ttv_search.ipynb) |
| [`precession_search.ipynb`](https://github.com/jpdeleon/quicklook/blob/main/notebook/precession_search.ipynb) | Precession search (TOI-1355 b, V907 Sco) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jpdeleon/quicklook/blob/main/notebook/precession_search.ipynb) |

## Usage

### Command line

A single `quicklook` command groups every subcommand (the shorter `ql` alias
is equivalent):

```bash
uv run quicklook --help       # show commands: run, read-tls, rank-tls, gui
uv run quicklook run --help   # full analysis options
uv run quicklook read-tls --help  # extract TLS results to CSV
uv run quicklook rank-tls --help  # filter and rank candidates
uv run quicklook gui --help   # launch the web GUI
```

Drop the `uv run` prefix once the package is installed on your `PATH`
(e.g. `quicklook run ...` or `ql run ...`).

```bash
# Basic run on the latest TESS sector
ql run --name WASP-21 --save --verbose

# Specific sector and pipeline
ql run --name TOI-125.01 --sector 2 --pipeline qlp

# Custom detrending
ql run --name TOI-125.01 --flatten-method cosine --window-length 0.3

# Notch filter (window length in days) or LOCoR (window-length is the
# rotation period in days; leave it unset to estimate it via GLS)
ql run --name TOI-125.01 --flatten-method notch --window-length 0.5
ql run --name TOI-125.01 --flatten-method locor

# Restrict TLS period search range
ql run --name TOI-125.01 --period-limits 1 5

# By default the TLS period ceiling is ~0.98x the baseline (so a 20 d planet with
# 2 transits in one ~27 d sector is in range); a winner with <2 transits falls back
# to the standard half-baseline search. Restore the old half-baseline ceiling with:
ql run --name TOI-125.01 --no-extend-period-ceiling
# When the target has a catalogue ephemeris, the log and the saved HDF5 also carry an
# "epoch check": the stacked dip SNR at the predicted transit times (epoch_snr,
# epoch_n_covered, epoch_control_snr_p95, epoch_detected), independent of TLS.

# Iteratively mask detected transits and re-run TLS to find additional planets.
# Stops when SDE drops below --min-sde-iterative (default 5) or --max-planets
# is reached; saves one periodogram + odd-even PNG and one TLS HDF5 per planet.
ql run --name TOI-125.01 --iterative --min-sde-iterative 6 --max-planets 3 --save

# Also search for single transits (mono-transits). The target is classified as
# none/mono/duo/periodic; a mono result swaps panels 5, 7 and 8 for the event SNR,
# an event zoom with systematics models, and the periods allowed by the data.
ql run --name TOI-2180 --sector 48 --single-event-search --save
# Stitch sectors to pair two transits into a duotransit; panels 7 and 8 then show
# both events overlaid and the allowed periods dT/n with their probabilities.
ql run --name TOI-2180 --sectors 19,48 --exptime 120 --single-event-search --save

# Fit each transit separately and test for transit-timing variations (needs >=3
# transits); panels 7 and 8 become the aligned transits and the O-C diagram.
ql run --name TOI-216 --sectors 1,2,3,4,5,6 --exptime 120 --ttv-search --save

# Active star: time the transits of a known ephemeris. --custom-ephem takes
# priority over TLS, which on spotted stars locks onto the rotation period
# (also writes *_ttv.png and *_ttv_transits.png from the raw flux)
ql run --name TOI-6109 --sectors 18,58,85 --exptime 120 --ttv-search \
  --custom-ephem 2458798.0657 0.001 8.538878 0.00001 3.25 0.3 --save

# Fit the transit shape per sector and test for a secular drift in the impact
# parameter b (nodal precession); needs >=2 stitched sectors spanning >=1 yr.
# ExoFOP R*, M* (when available) constrain a/Rs, which matters at moderate b.
pip install 'quicklook-package[precession]'
ql run --name TOI-1355 --sector all --exptime 120 --precession-search --save
# Eclipsing binary in a triple: fit the inner inclination per sector
# (give the binary period with T0 at the primary eclipse).
ql run --name <EB> --sector all --exptime 120 --precession-search --precession-mode eb \
  --custom-ephem <T0> <T0err> <P> <Perr> <T14 [h]> <T14err> --save
# See docs/precession-search.md for the TOI-1355 and V907 Sco examples and validation.

# Run on every available sector
ql run --name TOI-125.01 --each-sector --save

# Run all sectors with 4 parallel workers
ql run --name TOI-125.01 --each-sector -j 4 --save

# Run every available pipeline on the latest sector
ql run --name TOI-125.01 --each-pipeline --save

# TGLC PSF photometry with nearby SIMBAD objects overlaid
ql run --name TOI-125.01 --pipeline tglc --fluxtype psf --show-simbad --save
```

> **Note:** Old-style `-save` / `-verbose` flags and the standalone
> `read_tls` / `rank_tls` commands still work via automatic redirect.
> Underscore flags (`--flatten_method`) are interchangeable with hyphens
> (`--flatten-method`). On headless Linux systems, `--save` is required
> (the CLI detects missing `$DISPLAY` and exits early unless `--save` is set).

### Python API

```python
from quicklook import TessQuickLook

ql = TessQuickLook(
    target_name="WASP-21",
    sector=56,
    pipeline="SPOC",
    flux_type="pdcsap",
    verbose=True,
)

fig = ql.plot_tql()

# Access results
print(f"Rotation period: {ql.Prot_ls:.2f} days")
print(f"TLS period: {ql.tls_results.period:.4f} days")
print(f"TLS SDE: {ql.tls_results.SDE:.1f}")
```

For **SPOC**, `flux_type` selects `"pdcsap"` or `"sap"`. For **TGLC**, the same
argument selects the photometry method -- `"aperture"` or `"psf"`; any other
value (including the default) uses automatic selection of the less-contaminated,
lower-scatter light curve. TGLC light curves absent from MAST are extracted
locally via effective-PSF (ePSF) photometry. Locally extracted light curves carry the same
`tess_flags` / `tglc_flags` columns as the MAST HLSP, and quicklook drops
flagged cadences using `--quality-bitmask` plus TGLC's background-outlier flag
(which catches scattered-light ramps that carry no TESS flag); pass
`--quality-bitmask none` to keep every cadence. MAST TGLC HLSP files get the
same treatment: they are downloaded unmasked and quicklook applies the bitmask
itself, so `--quality-bitmask hardest` works despite lightkurve's int16
overflow in its TGLC reader (see `LIGHTKURVE_TGLC_BUG_REPORT.txt`).

#### Benchmarking local TGLC against MAST

`scripts/benchmark_tglc.py` checks that the local ePSF pipeline
(`quicklook.tglc.get_tglc_lc`) reproduces the TGLC HLSP light curve hosted at
MAST (downloaded with `lightkurve`). It matches the two light curves cadence by
cadence, compares `cal_aper_flux`, `cal_psf_flux`, `aperture_flux` and
`psf_flux`, and exits with status 3 if the calibrated fluxes disagree (Pearson
r < 0.9 or robust residual > 0.5x the MAST point-to-point scatter). A crash
exits 1, so batch runs can separate disagreements from failures:

```bash
uv run scripts/benchmark_tglc.py                         # defaults: TOI-270 s3, TOI-519 s7-8, TOI-674 s9-10
uv run scripts/benchmark_tglc.py "TIC 12345" --sector 10 --size 99 --outdir bench/
```

`--prior none` fits field stars without the Gaia-brightness prior, matching
how the MAST HLSP v1 files were made (their headers carry no `PRIOR` keyword);
the default `0.1` is what `get_tglc_lc` uses.

It writes a JSON report and an overlay plot to `--outdir`. Columns that are
all-NaN in the MAST file (some HLSPs have no PSF flux) are reported as
unavailable rather than failed.

### Web GUI

```bash
uv run quicklook gui                       # http://127.0.0.1:5000
uv run quicklook gui --host 0.0.0.0 --port 8080
```

Open http://127.0.0.1:5000 in your browser. Enter a target, adjust parameters, and click **Run QuickLook**. Progress is streamed live via WebSocket. Supports single targets, batch submission, and each-sector mode.

Each running job streams its output log live. Finished jobs (done, error, or cancelled) keep a **Log** button in the queue that reloads their captured output from disk — so you can review what happened even after the job left the live queue or the server restarted.

![Per-job output log](docs/img/ql-gui-joblog.png)

![QuickLook Web GUI](docs/img/ql-gui.png)

Search options such as **Single-transit search**, **TTV search** and **Precession search** live under **Period Search**:

![Period Search options](docs/img/ql-gui-period-search.png)

The **TLS Summary** page tabulates every `*_tls.h5` result in a folder. The
values it shows are cached in `static/outputs/jobs.db` by path, modification
time and size, so only new or changed files are opened on each visit: the
first visit to a large folder takes a while, and later visits load in well
under a second. Deleting `jobs.db` simply rebuilds the cache (and clears job
history). Opening the GUI upgrades `jobs.db` to a newer schema, which older
QuickLook versions will refuse to open.

The Flask debugger is off by default. Pass `--debug` (or set `QUICKLOOK_DEBUG=1`)
to enable it and the auto-reloader while developing:

```bash
uv run quicklook gui --debug
QUICKLOOK_DEBUG=1 uv run quicklook gui
```

Leave it off on any host other users can reach — the Werkzeug debugger
exposes an interactive console to whoever can open the port. The standalone
`ql-gui` command remains available as an alias for `quicklook gui`.

## Output figure

```bash
ql run --name WASP-21 --save --verbose
```

![Example output](tests/WASP-21_s83_pdcsap_sc.png)

The 9-panel figure shows:

| Panel | Content |
|-------|---------|
| 1 | Raw light curve + trend line |
| 2 | GLS periodogram (stellar rotation period) |
| 3 | Phase-folded light curve at rotation period |
| 4 | Flattened light curve + detected transits |
| 5 | TLS periodogram (orbital period) |
| 6 | TESS aperture + Gaia sources (and optional SIMBAD objects) on archival image |
| 7 | Phase-folded transit (odd/even comparison) |
| 8 | Secondary eclipse check at phase 0.5 |
| 9 | Summary of stellar and companion parameters |

## CLI tools

All subcommands are available under either `quicklook` or the shorter `ql` alias.

| Command | Description |
|---------|-------------|
| `quicklook run` | Run the full QuickLook pipeline on a target |
| `quicklook read-tls` | Extract TLS results from a directory of `.h5` files into a CSV |
| `quicklook rank-tls` | Filter and rank candidates by SDE from the CSV output |
| `quicklook shared-epochs` | Flag single events that several stars in a batch share (scattered light, momentum dumps) |
| `quicklook gui` | Launch the web GUI (requires `[gui]` extra); also available as `ql-gui` |

## Batch processing

Process a list of TIC IDs:

```bash
# Generate batch script
cat tic_ids.txt | while read tic; do
  echo "ql run --name TIC$tic --save --outdir results | tee TIC$tic.log"
done > run_batch.sh

# Run in parallel with GNU parallel
cat run_batch.sh | parallel -j 4

# Extract and rank results
ql read-tls results/
# With --single-event-search: events at the same time on >=3 stars (within
# --tol 0.25 d) are systematics. Writes results_shared_{events,targets}.csv;
# mono/duo targets whose events are all shared get event_class_vetted=systematic.
ql shared-epochs results/
ql rank-tls results/ --output-dir ranked

# Combine ranked plots into a PDF
pip install img2pdf
img2pdf ranked/*.png --output ranked.pdf
```

## Documentation

Full documentation is available at [quicklook.readthedocs.io](https://quicklook.readthedocs.io/en/latest/).

## License

See [LICENSE](LICENSE) for details.
