Metadata-Version: 2.4
Name: gpimg
Version: 0.2.0
Summary: Exact O(n) two-dimensional Gaussian-process fits and images of multi-band light curves
Author-email: Francisco Förster <francisco.forster@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/fforster/gpimg
Project-URL: Documentation, https://gpimg.readthedocs.io
Project-URL: Source, https://github.com/fforster/gpimg
Keywords: gaussian process,light curves,state space,kalman filter,astronomy,LSST,transients
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: C
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Topic :: Scientific/Engineering :: Astronomy
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.23
Provides-Extra: test
Requires-Dist: pytest>=7; extra == "test"
Requires-Dist: scipy>=1.9; extra == "test"
Provides-Extra: docs
Requires-Dist: sphinx>=7; extra == "docs"
Requires-Dist: furo>=2024.1; extra == "docs"
Requires-Dist: numpydoc>=1.6; extra == "docs"
Requires-Dist: sphinx-copybutton>=0.5; extra == "docs"
Requires-Dist: matplotlib>=3.7; extra == "docs"
Requires-Dist: myst-parser>=2; extra == "docs"
Provides-Extra: plot
Requires-Dist: matplotlib>=3.7; extra == "plot"
Dynamic: license-file

# gpimg

**Exact O(n) two-dimensional Gaussian processes for multi-band light curves.**

gpimg fits a Gaussian process jointly in time and wavelength to a multi-band light curve and returns the posterior
flux on any time × wavelength grid. The kernel is a Matérn-3/2 in time times a squared exponential in ln λ:

    k((t,λ),(t',λ')) = A² (1 + √3|t−t'|/ℓt) exp(−√3|t−t'|/ℓt) · exp(−(ln λ − ln λ')² / 2ℓλ²)

Because the time kernel is a linear stochastic differential equation and the kernel is separable, a light curve
observed in up to six bands is *exactly* a small linear Gaussian state-space model. gpimg evaluates the likelihood,
its analytic gradient, maximum-likelihood fits and posterior images with Kalman filters and smoothers in **O(n)**,
with no approximation.

- Exact: likelihoods agree with a dense Cholesky GP to ~1e-11 (relative).
- Fast: one likelihood + gradient of an 18 668-point light curve in 4.7 ms on one core; a fit of a typical
  deep-drilling LSST light curve (~660 points) in ~19 ms with five starts — 279× faster than PISCOLA's GP fit, and
  1 100× faster for wide-fast-deep light curves (~64 points).
- Compiled C core, no JIT and no warm-up; AVX2 + FMA code selected at run time; OpenMP batches.
- Posteriors at any wavelength, smoothed or causal (real time), with an optional numerically stable
  Rauch–Tung–Striebel smoother, and exact band–band covariances for colors.
- Optional fitted jitter for scatter the quoted errors do not describe; off by default, and off costs nothing.
- Optional Matérn-5/2 time kernel (`kernel="matern52"`), also exact: fits cost the same with one band and about
  1.5x with six.
- Python package and plain C library (Makefile, CMake, pkg-config).

Documentation: the Sphinx sources under `docs/` (guide, Python API, C API, theory). A hosted build is not up yet.

## Installation

```console
$ pip install gpimg
```

gpimg ships as a source distribution, so this compiles the C core for your machine: you need a C compiler (gcc or
clang). OpenMP is optional — without it `gpimg.batch` runs serially and everything else is unaffected. An AVX2 +
FMA copy is built alongside the portable one and chosen at import when the CPU supports it.

From a source checkout, which also gets you the plain C library:

```console
$ pip install .                        # the Python package
$ pytest                               # optional: pip install ".[test]" first
$ make -C c && make -C c test          # the C library: build/libgpimg.so, build/libgpimg.a
$ sudo make -C c install               # or: cmake -S c -B build && cmake --build build
```

## Python quick start

```python
import numpy as np
import gpimg

# t [days], band ('u','g','r','i','z','y' or 0..5; LSST by default), flux and flux_err in any flux unit
gp = gpimg.GP(t, band, flux, flux_err)
res = gp.fit()                                     # maximum likelihood, 5 starting points
print(res.amplitude, res.length_time, res.length_wave, res.message)
res = gp.fit(jitter=True)                          # + a white jitter for extra scatter; res.jitter

img = gp.predict(np.linspace(-30, 120, 300),       # times [d]
                 np.geomspace(3200, 10200, 200))   # wavelengths [Å]
img.mean.shape, img.std.shape                      # (200, 300): wavelengths x times

curves = gp.predict_bands(np.linspace(-30, 120, 300))     # {'u': (mean, std), ...}
curves, covs = gp.predict_bands(t_grid, cov=True)         # + {('g','r'): cov, ...} for color errors
live = gp.predict(t_grid, causal=True)                    # filtered: data up to each time only
stable = gp.predict(t_grid, wave_grid, smoother="rts")    # numerically stable smoother
```

Many light curves from one long table (pandas, astropy, dict of arrays), fitted and imaged in parallel:

```python
lcs = gpimg.LightCurves.from_table(table, id="oid", t="t", band="band", flux="flux", flux_err="flux_err")
res = gpimg.batch(lcs, np.linspace(-30, 120, 300), np.geomspace(3200, 10200, 200))
res.mean.shape        # (n_objects, 200, 300), float32
```

Other surveys: `gpimg.GP(t, band, flux, err, wavelengths={"g": 4800.0, "r": 6400.0, "i": 7900.0})`.

Runnable examples are in `examples/` (`quickstart.py`, `batch_table.py`, `causal_vs_smoothed.py`,
`other_survey.py`).

## C quick start

```c
#include "gpimg.h"

double lnwave[6];                               /* ln of the band wavelengths */
gp_fit_opts opts;
gp_fit_default_opts(&opts);
opts.nstart = 5;
gp_fit_result res;
gp_fit(n, t, band, y, err, lnwave, theta0, &opts, &res);                  /* res.theta = (ln A, ln lt, ln ll) */
/* 3 = ntheta, the length of res.theta (4 with opts.ntheta = 4, which also fits a white jitter) */
gp_image(n, t, band, y, err, 6, lnwave, 3, res.theta, nt, tg, nl, lng, mean, var, GPIMG_SMOOTH(GPIMG_RTS));
/* gp_image_cov(...) additionally fills cov[npair][nt] for pairs (pa[p], pb[p]) of grid wavelengths */
```

See `c/examples/example.c` and the C API reference in `docs/c_api.rst`.

## Performance and accuracy

Single core, Intel Core Ultra 7 255U; simulated LSST light curves (details in `docs/guide/performance.rst` and
`docs/guide/accuracy.rst`).

| likelihood + gradient | gpimg | dense GP (tinygp, warm) | smolgp, same model (warm) |
|---|---|---|---|
| 1 000 points | 0.20 ms | 165 ms | 12 ms |
| 12 000 points | 2.8 ms | 242 s | 0.27 s |
| 18 668 points | 4.7 ms | — | 0.41 s |

| median per fit | DDF (~660 points) | WFD (~64 points) |
|---|---|---|
| gpimg, 5 starts | 18.7 ms | 1.7 ms |
| PISCOLA as shipped | 4.95 s | 2.17 s |

Against a dense double-precision GP with the same hyperparameters: likelihood ≤ 3.5e-11, gradient ≤ 8.4e-9 and
posterior mean ≤ 1.1e-10 (relative). With `smoother="rts"` the posterior variance agrees with a 200-bit reference
to 7e-10 at the grid points where the default smoother is worst (4.8e-3).

## Citing

A paper describing gpimg is in preparation. Until then please cite the software and the works in the
references (`docs/references.rst`), in particular Hartikainen & Särkkä (2010) for
the state-space formulation of temporal Gaussian processes.

## License

MIT — see [LICENSE](LICENSE).
