Metadata-Version: 2.4
Name: costream
Version: 0.1.0
Summary: Streaming evaluation protocol for sparse-event detection on continuous signals
Author: Timilehin B. Aderinola
License-Expression: MIT
Project-URL: Repository, https://github.com/mlgig/costream
Project-URL: Issues, https://github.com/mlgig/costream/issues
Project-URL: Paper, https://arxiv.org/abs/2509.11789
Keywords: event detection,evaluation,time series,streaming,wearable sensors,fall detection
Classifier: Programming Language :: Python :: 3
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.25
Requires-Dist: pandas>=2.0
Requires-Dist: scikit-learn>=1.6
Requires-Dist: joblib
Requires-Dist: imbalanced-learn>=0.13
Requires-Dist: matplotlib>=3.10
Requires-Dist: seaborn>=0.13
Provides-Extra: models
Requires-Dist: aeon<2,>=1.2; extra == "models"
Requires-Dist: tensorflow>=2.15; extra == "models"
Requires-Dist: torch; extra == "models"
Dynamic: license-file

# costream: A Streaming Evaluation Protocol

**Evaluate sparse-event detectors on continuous signals the way they are deployed.**

Sparse-event detectors are commonly evaluated on presegmented windows: windows cut around annotated events, compared against windows sampled from event-free signal. A deployed detector has no such luxury. It must process an unsegmented signal continuously, find events whose locations are unknown, and avoid false alarms.

**costream** is a Python package that evaluates window-based detectors under those conditions. Overlapping window scores are aggregated into a temporal confidence map and thresholded into detection episodes. Each episode emits one timestamped event, which is scored against the annotation. This makes measurable what presegmented evaluation cannot: false alarms over elapsed monitoring time, detection delay and operating-point trade-offs. costream was developed and evaluated on wearable fall detection. Its defaults come from that application, and the protocol is not specific to it.

**Paper:** *costream: A Streaming Evaluation Protocol for Wearable Fall Detection* (AICS 2026). [arXiv:2509.11789](https://arxiv.org/abs/2509.11789)

## How it works

1. **Window scoring.** A trained classifier scores successive overlapping windows of a continuous signal.
2. **Temporal aggregation.** Scores are combined by pointwise maximum into a temporal confidence map.
3. **Detection episodes.** Thresholding gives contiguous episodes, and episodes closer than `debounce_secs` merge into one.
4. **Event evaluation.** Each episode emits one detection, scored against the annotated event.

![costream streaming evaluation workflow](https://raw.githubusercontent.com/mlgig/costream/main/figures/streaming-evaluation.png)

## Install

```bash
pip install costream
```

This installs numpy, pandas, scikit-learn, imbalanced-learn, joblib, matplotlib and seaborn. The aeon models used in the paper (Catch22, MiniRocket, QUANT, ResNet) are optional. The `models` extra installs aeon, TensorFlow and PyTorch, which are large downloads:

```bash
pip install "costream[models]"
```

Python 3.10 or newer. The package is tested on 3.10.

## Quickstart

### 1. Prepare your data

costream needs, for each recording, a signal and event labels, grouped by subject so that cross-validation can split on subjects. You need at least as many subjects as folds.

**Signal and labels.** `make_csv_loader` reads one CSV per recording. `feature_cols` names the signal column or columns, and `label_col` (default `"label"`) names the label column: 0 for background, non-zero from the annotated event. The first sample of each contiguous non-zero block is taken as the event position `f`. Use `new_features={"mag": fn}` to derive a column such as a magnitude from raw axes, and any `pandas.read_csv` option (`header`, `names`, and so on) is passed through. If your files carry no label column, supply a `label_extractor(df, path) -> df` that adds one, for example from the file name.

**Grouping by subject.** `group_files_by_subject(directory)` returns `{subject_id: [paths]}`. By default the subject id is the part of the file name before the first underscore or hyphen, so `s01_rec2.csv` belongs to subject `s01`. For other naming schemes, pass an `id_extractor` that takes a `pathlib.Path` and returns the id, and use `file_pattern` to select files.

```python
# Files named like "rec2_P01.csv": the subject id is the last token.
groups = group_files_by_subject(
    "data/", id_extractor=lambda p: p.stem.split("_")[-1]
)

# Illustration: the event sample is encoded in the file name, "P01_rec2_f120000.csv".
def label_from_name(df, path):
    f = int(path.stem.split("_f")[-1])
    df["label"] = 0
    df.loc[f, "label"] = 1
    return df

load = make_csv_loader(feature_cols=["mag"], label_col="label",
                       label_extractor=label_from_name)
```

### 2. Run an evaluation

```python
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

from costream.data import group_files_by_subject, make_csv_loader
from costream.evaluation import ModelSpec, run_subject_cv

groups = group_files_by_subject("data/")  # {subject_id: [csv paths]}
load = make_csv_loader(feature_cols=["mag"], label_col="label")
subject_map = {sid: load(paths) for sid, paths in groups.items()}

specs = [ModelSpec(name="ExtraTrees", estimator=make_pipeline(
    StandardScaler(), ExtraTreesClassifier(n_estimators=150, random_state=0)))]

results = run_subject_cv(
    subject_map, specs,
    feature_cols=["mag"], label_col="label",
    cv=5, window_size=10.0, step=1.0, freq=100,
    activity_threshold=1.4, spacing="multiphase",
    tolerance=20.0, debounce_secs=60.0, resample=False,
)
print(results[["model", "protocol", "fold", "tp", "fp", "fn", "f1-score"]])
```

Any scikit-learn-style classifier with `fit` and `predict_proba` works. [`scripts/smoke_test.py`](https://github.com/mlgig/costream/blob/main/scripts/smoke_test.py) runs the same pipeline end to end on synthetic data.

## What it computes

`run_subject_cv` evaluates every model under both protocols in the same folds. Each row of `results` is one model, fold and protocol, at threshold 0.5, with the protocol in the `protocol` column. See `results.columns` for the full list.

- **Protocol B (streaming)** is costream's protocol. The detector scores every window of the continuous recording, scores are aggregated into a confidence map, and each detection episode is scored against the annotation.
- **Protocol A (presegmented)** is the conventional baseline: a window at the annotated event against windows from event-free signal. It is included so you can see whether the two ways of evaluating lead to the same conclusions.

The protocols measure different quantities, so compare rankings across them, not absolute scores.

`costream.evaluation.evaluate_recording` scores a single recording, and threshold sweeps from cached window scores are in `scripts/run_tau_sweep.py` (see the paper for the cost-sensitive threshold analysis).

## Configuration

| Parameter               | Meaning                                                                                                                                    | Default                               |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------- |
| `window_size`         | window length in seconds                                                                                                                   | 7.0 (the paper uses 3, 10, 30 and 60) |
| `step`                | window step in seconds                                                                                                                     | 1.0                                   |
| `freq`                | sampling rate in Hz                                                                                                                        | 100                                   |
| `activity_threshold`  | admissibility gate, in the units of `mag`: a window is admissible only if its peak between one and two seconds from its start exceeds it | 1.4                                   |
| `tolerance`           | `t` in the reference interval `[f - 1, f + t)` seconds, where `f` is the annotated event                                             | 20                                    |
| `debounce_secs`       | detections closer than this merge into one episode                                                                                         | 60                                    |
| `exclusion_tolerance` | negative windows are drawn outside `[f - (window_size + t), f + t)`                                                                      | 20                                    |

Inadmissible windows are excluded from the negative training set and score zero at inference. The defaults come from wearable fall detection, and 1.4 assumes acceleration in g. For other signals or events, set `activity_threshold`, `tolerance` and `debounce_secs` to suit the signal and the expected event duration. If the gate drops every negative window, training fails with a single-class error.

## Reproducing the paper

[`reproduce_paper.ipynb`](https://github.com/mlgig/costream/blob/main/reproduce_paper.ipynb) shows every table and figure from the paper, rendered on the page, without running anything and without access to FARSEEING. To rerun it, which reads only the CSVs under [`results/`](https://github.com/mlgig/costream/tree/main/results) and needs no model refitting:

```bash
pip install -r requirements.txt
pip install -e .
jupyter notebook reproduce_paper.ipynb
```

To regenerate the results from scratch, place FARSEEING at `data/farseeing.feather` and run:

```bash
python scripts/run_sweep.py
```

FARSEEING is available from its maintainers on request. Its loader is `scripts/farseeing_loader.py`. To check an installation without FARSEEING:

```bash
python scripts/smoke_test.py
```

This runs the full pipeline on fabricated data, not real falls, to confirm that the install works. The exact versions used for the paper are pinned in `requirements.txt` (Python 3.10.18).

## Citation

```bibtex
@inproceedings{aderinola2026costream,
  title     = {costream: A Streaming Evaluation Protocol for Wearable Fall Detection},
  author    = {Aderinola, Timilehin B. and D'Ascanio, Ilaria and Palmerini, Luca and Chiari, Lorenzo and Klenk, Jochen and Becker, Clemens and Caulfield, Brian and Ifrim, Georgiana},
  booktitle = {Proceedings of the Irish Conference on Artificial Intelligence and Cognitive Science (AICS 2026)},
  series    = {Proceedings of Machine Learning Research},
  year      = {2026}
}
```

The proceedings volume and pages will be added when published.

## Licence

MIT. See [`LICENSE`](https://github.com/mlgig/costream/blob/main/LICENSE).

## Acknowledgements

This work was supported by Research Ireland under the Government of Ireland Postdoctoral Fellowship Programme (Grant Number: GOIPD/2025/1434).
