Metadata-Version: 2.4
Name: lunapi
Version: 1.8.0
Summary: Python interface to the Luna toolset for sleep signal analysis
Keywords: Sleep,EEG,PSG,Luna,Signal processing
Author-Email: Shaun Purcell <shaun.purcell@nyspi.columbia.edu>, Tejas Karkera <tkarkera@mgh.harvard.edu>, Senthil Palanivelu <spalanivelu@mgh.harvard.edu>, Nataliia Kozhemiako <nkozhemiako@bwh.harvard.edu>
Maintainer-Email: Tejas Karkera <tkarkera@mgh.harvard.edu>
License-Expression: GPL-3.0-or-later
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Topic :: Scientific/Engineering
Classifier: Framework :: Jupyter :: JupyterLab
Classifier: Natural Language :: English
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Project-URL: Homepage, https://zzz.nyspi.org/luna/
Project-URL: Documentation, https://zzz.nyspi.org/luna/
Project-URL: Repository, https://github.com/remnrem/luna-api
Requires-Python: <3.15,>=3.9
Requires-Dist: pandas<3,>=2.2
Requires-Dist: numpy<3,>=2.0
Requires-Dist: matplotlib<4,>=3.8
Requires-Dist: scipy<1.17,>=1.13; python_version < "3.11"
Requires-Dist: scipy<2,>=1.17; python_version >= "3.11"
Requires-Dist: plotly<6,>=5
Requires-Dist: nbformat<6,>=5
Requires-Dist: ipywidgets<9,>=8
Requires-Dist: tqdm<5,>=4
Requires-Dist: requests<3,>=2
Requires-Dist: IPython<9,>=8
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Description-Content-Type: text/markdown

# lunapi

**Python interface to the [Luna](https://zzz.nyspi.org/luna/) C/C++ sleep-signal analysis engine.**

`lunapi` exposes the full Luna command set to Python, enabling scripted and notebook-based workflows for polysomnographic (PSG) data — using the same analytical core as the Luna command-line tool and the [Lunascope](https://github.com/Lorcan7274/lunascope) desktop application.

---

## Statement of Need

Large-scale sleep research increasingly requires processing thousands of PSG recordings programmatically, while maintaining the ability to inspect individual records interactively. Existing Python EEG libraries are general-purpose frameworks that lack dedicated sleep-analysis primitives. `lunapi` provides direct Python access to Luna's domain-specific command set — covering spectral analysis, sleep staging, annotation handling, artifact detection, connectivity, and more — without requiring users to leave the Python/notebook environment or learn the Luna command-line interface.

---

## Features

- **Full Luna command set** — run any Luna command (PSD, SPINDLES, SOAP, POPS, …) directly from Python and receive structured results as DataFrames
- **Project-level workflows** — load a sample list and execute commands across an entire cohort in a few lines
- **Per-recording access** — attach EDF and annotation files, extract raw signals and annotation events, insert or modify signals in memory
- **Structured output** — results returned as `pandas` DataFrames keyed by command and stratum
- **SQLite result stores** — write output to `.db` files that can be queried as virtual TSV-like tables
- **Sleep staging** — SOAP and POPS automated staging models accessible directly from Python
- **Visualization helpers** — hypnogram, PSD, spectrogram, and topographic map plotting for notebooks
- **NSRR Moonbeam** — download and attach recordings directly from the National Sleep Research Resource
- **GPA association modeling** — linear association analysis on cohort-level result matrices
- **Docker containers** — pre-built images with Luna, `lunapi`, and all dependencies

---

## Installation

`lunapi` is distributed as a binary wheel via PyPI (no compiler required):

```bash
pip install lunapi
```

Supported platforms: macOS (Intel & Apple Silicon), Linux (x86_64), Windows 10/11 (x86_64), Python 3.9–3.14.

Using a virtual environment is recommended:

```bash
python3 -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install lunapi
```

---

## Worked Example

### Single-recording workflow

```python
import lunapi as lp

# Create a project and attach a recording
p = lp.proj(verbose=False)
rec = p.inst("my_subject")
rec.attach_edf("/path/to/recording.edf")
rec.attach_annot("/path/to/recording.annot")

# List available channels
print(rec.chs())

# Run a Luna command and retrieve results as a DataFrame
rec.eval("PSD sig=EEG dB spectrum")
df = rec.table("PSD", "CH_F")
print(df.head())
```

### Cohort workflow

```python
import lunapi as lp

p = lp.proj(verbose=False)
p.sample_list("study.lst")        # three-column file: ID, EDF path, annot path

# Run PSD across all recordings (returns dict of DataFrames)
results = p.proc("PSD sig=EEG dB spectrum")
df = results["PSD"]["CH_F"]
print(df.groupby("CH")["PSD"].mean())
```

### Python destrat command

The package also installs `destrat.py`, a Python/SQLite reader for Luna
output databases.  It accepts the common native `destrat` query options,
including row and column stratifiers and level restrictions:

```bash
destrat.py out.db
destrat.py out.db +PSD -r CH F -v PSD
destrat.py out.db +PSD -r F/11,15 CH -c B -v PSD
```

Multiple databases and glob patterns are accepted.  Extracted tables are
written as tab-delimited output to standard output, so they can be redirected
or piped to another program.  The same reader is available from Python as
`lp.destrat(...)`.

### Automated sleep staging

```python
rec.eval("RUN-POPS sig=C3 ref=M2 path=~/dropbox/pops")   # point to downloaded POPS models
stages = rec.table("RUN_POPS", "E")   # per-epoch predictions
print(stages["PRED"].value_counts())
```

Full documentation, command reference, and interactive notebooks are at [zzz.nyspi.org/luna/](https://zzz.nyspi.org/luna/).

---

## Native macOS builds

ONNX Runtime (ORT) support is disabled by default. The build skips ORT
compilation, linking, and wheel bundling; ORT-dependent commands are unavailable.
After switching from an ORT-enabled cache, rebuild Luna once:

```bash
NATIVE_DEPS_MODE=luna bash build-macos.sh
pip install .
```

To enable ORT, use `LUNAPI_ORT=1` for both the native build and `pip install`.
Use `NATIVE_DEPS_MODE=all` to build ORT if it is not already cached.

## Testing

```bash
pip install -e ".[dev]"
pytest
```

This runs 59 tests covering the core workflow (load instance, run commands, retrieve tables, extract signals, annotation handling, sample-list workflow), visualization helpers, GPA utilities, and package smoke tests. No real EDF files are required — a synthetic in-memory recording is generated by the test fixtures.

---

## Documentation

| Resource | URL |
|---|---|
| Luna ecosystem | https://zzz.nyspi.org/luna/ |
| lunapi notebooks | https://github.com/remnrem/luna-api/tree/main/notebooks |
| Lunascope desktop app | https://github.com/Lorcan7274/lunascope |
| NSRR | https://sleepdata.org |


---

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on bug reports, feature requests, and pull requests.

## Questions / Support

Open an issue on GitHub or write to `luna.remnrem@gmail.com`.
