costream 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- costream-0.1.0/LICENSE +21 -0
- costream-0.1.0/PKG-INFO +188 -0
- costream-0.1.0/README.md +159 -0
- costream-0.1.0/costream/__init__.py +1 -0
- costream-0.1.0/costream/data/__init__.py +9 -0
- costream-0.1.0/costream/data/loader.py +131 -0
- costream-0.1.0/costream/data/utils.py +91 -0
- costream-0.1.0/costream/evaluation/__init__.py +39 -0
- costream-0.1.0/costream/evaluation/checks.py +107 -0
- costream-0.1.0/costream/evaluation/cross_validation.py +241 -0
- costream-0.1.0/costream/evaluation/event_detection.py +187 -0
- costream-0.1.0/costream/evaluation/presegmented.py +91 -0
- costream-0.1.0/costream/evaluation/probability_cache.py +167 -0
- costream-0.1.0/costream/evaluation/tester.py +202 -0
- costream-0.1.0/costream/evaluation/visualization.py +695 -0
- costream-0.1.0/costream/model/__init__.py +5 -0
- costream-0.1.0/costream/model/cost_classifier_cv.py +224 -0
- costream-0.1.0/costream/model/metrics.py +171 -0
- costream-0.1.0/costream/model/specs.py +132 -0
- costream-0.1.0/costream/segmentation/__init__.py +17 -0
- costream-0.1.0/costream/segmentation/gate.py +38 -0
- costream-0.1.0/costream/segmentation/streaming_segmenter.py +259 -0
- costream-0.1.0/costream/segmentation/training_segmenter.py +229 -0
- costream-0.1.0/costream.egg-info/PKG-INFO +188 -0
- costream-0.1.0/costream.egg-info/SOURCES.txt +28 -0
- costream-0.1.0/costream.egg-info/dependency_links.txt +1 -0
- costream-0.1.0/costream.egg-info/requires.txt +12 -0
- costream-0.1.0/costream.egg-info/top_level.txt +1 -0
- costream-0.1.0/pyproject.toml +42 -0
- costream-0.1.0/setup.cfg +4 -0
costream-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Timilehin Aderinola
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
costream-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: costream
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Streaming evaluation protocol for sparse-event detection on continuous signals
|
|
5
|
+
Author: Timilehin B. Aderinola
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/mlgig/costream
|
|
8
|
+
Project-URL: Issues, https://github.com/mlgig/costream/issues
|
|
9
|
+
Project-URL: Paper, https://arxiv.org/abs/2509.11789
|
|
10
|
+
Keywords: event detection,evaluation,time series,streaming,wearable sensors,fall detection
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: numpy>=1.25
|
|
18
|
+
Requires-Dist: pandas>=2.0
|
|
19
|
+
Requires-Dist: scikit-learn>=1.6
|
|
20
|
+
Requires-Dist: joblib
|
|
21
|
+
Requires-Dist: imbalanced-learn>=0.13
|
|
22
|
+
Requires-Dist: matplotlib>=3.10
|
|
23
|
+
Requires-Dist: seaborn>=0.13
|
|
24
|
+
Provides-Extra: models
|
|
25
|
+
Requires-Dist: aeon<2,>=1.2; extra == "models"
|
|
26
|
+
Requires-Dist: tensorflow>=2.15; extra == "models"
|
|
27
|
+
Requires-Dist: torch; extra == "models"
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# costream: A Streaming Evaluation Protocol
|
|
31
|
+
|
|
32
|
+
**Evaluate sparse-event detectors on continuous signals the way they are deployed.**
|
|
33
|
+
|
|
34
|
+
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.
|
|
35
|
+
|
|
36
|
+
**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.
|
|
37
|
+
|
|
38
|
+
**Paper:** *costream: A Streaming Evaluation Protocol for Wearable Fall Detection* (AICS 2026). [arXiv:2509.11789](https://arxiv.org/abs/2509.11789)
|
|
39
|
+
|
|
40
|
+
## How it works
|
|
41
|
+
|
|
42
|
+
1. **Window scoring.** A trained classifier scores successive overlapping windows of a continuous signal.
|
|
43
|
+
2. **Temporal aggregation.** Scores are combined by pointwise maximum into a temporal confidence map.
|
|
44
|
+
3. **Detection episodes.** Thresholding gives contiguous episodes, and episodes closer than `debounce_secs` merge into one.
|
|
45
|
+
4. **Event evaluation.** Each episode emits one detection, scored against the annotated event.
|
|
46
|
+
|
|
47
|
+

|
|
48
|
+
|
|
49
|
+
## Install
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install costream
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
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:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
pip install "costream[models]"
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Python 3.10 or newer. The package is tested on 3.10.
|
|
62
|
+
|
|
63
|
+
## Quickstart
|
|
64
|
+
|
|
65
|
+
### 1. Prepare your data
|
|
66
|
+
|
|
67
|
+
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.
|
|
68
|
+
|
|
69
|
+
**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.
|
|
70
|
+
|
|
71
|
+
**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.
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
# Files named like "rec2_P01.csv": the subject id is the last token.
|
|
75
|
+
groups = group_files_by_subject(
|
|
76
|
+
"data/", id_extractor=lambda p: p.stem.split("_")[-1]
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
# Illustration: the event sample is encoded in the file name, "P01_rec2_f120000.csv".
|
|
80
|
+
def label_from_name(df, path):
|
|
81
|
+
f = int(path.stem.split("_f")[-1])
|
|
82
|
+
df["label"] = 0
|
|
83
|
+
df.loc[f, "label"] = 1
|
|
84
|
+
return df
|
|
85
|
+
|
|
86
|
+
load = make_csv_loader(feature_cols=["mag"], label_col="label",
|
|
87
|
+
label_extractor=label_from_name)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### 2. Run an evaluation
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
from sklearn.ensemble import ExtraTreesClassifier
|
|
94
|
+
from sklearn.pipeline import make_pipeline
|
|
95
|
+
from sklearn.preprocessing import StandardScaler
|
|
96
|
+
|
|
97
|
+
from costream.data import group_files_by_subject, make_csv_loader
|
|
98
|
+
from costream.evaluation import ModelSpec, run_subject_cv
|
|
99
|
+
|
|
100
|
+
groups = group_files_by_subject("data/") # {subject_id: [csv paths]}
|
|
101
|
+
load = make_csv_loader(feature_cols=["mag"], label_col="label")
|
|
102
|
+
subject_map = {sid: load(paths) for sid, paths in groups.items()}
|
|
103
|
+
|
|
104
|
+
specs = [ModelSpec(name="ExtraTrees", estimator=make_pipeline(
|
|
105
|
+
StandardScaler(), ExtraTreesClassifier(n_estimators=150, random_state=0)))]
|
|
106
|
+
|
|
107
|
+
results = run_subject_cv(
|
|
108
|
+
subject_map, specs,
|
|
109
|
+
feature_cols=["mag"], label_col="label",
|
|
110
|
+
cv=5, window_size=10.0, step=1.0, freq=100,
|
|
111
|
+
activity_threshold=1.4, spacing="multiphase",
|
|
112
|
+
tolerance=20.0, debounce_secs=60.0, resample=False,
|
|
113
|
+
)
|
|
114
|
+
print(results[["model", "protocol", "fold", "tp", "fp", "fn", "f1-score"]])
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
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.
|
|
118
|
+
|
|
119
|
+
## What it computes
|
|
120
|
+
|
|
121
|
+
`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.
|
|
122
|
+
|
|
123
|
+
- **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.
|
|
124
|
+
- **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.
|
|
125
|
+
|
|
126
|
+
The protocols measure different quantities, so compare rankings across them, not absolute scores.
|
|
127
|
+
|
|
128
|
+
`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).
|
|
129
|
+
|
|
130
|
+
## Configuration
|
|
131
|
+
|
|
132
|
+
| Parameter | Meaning | Default |
|
|
133
|
+
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------- |
|
|
134
|
+
| `window_size` | window length in seconds | 7.0 (the paper uses 3, 10, 30 and 60) |
|
|
135
|
+
| `step` | window step in seconds | 1.0 |
|
|
136
|
+
| `freq` | sampling rate in Hz | 100 |
|
|
137
|
+
| `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 |
|
|
138
|
+
| `tolerance` | `t` in the reference interval `[f - 1, f + t)` seconds, where `f` is the annotated event | 20 |
|
|
139
|
+
| `debounce_secs` | detections closer than this merge into one episode | 60 |
|
|
140
|
+
| `exclusion_tolerance` | negative windows are drawn outside `[f - (window_size + t), f + t)` | 20 |
|
|
141
|
+
|
|
142
|
+
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.
|
|
143
|
+
|
|
144
|
+
## Reproducing the paper
|
|
145
|
+
|
|
146
|
+
[`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:
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
pip install -r requirements.txt
|
|
150
|
+
pip install -e .
|
|
151
|
+
jupyter notebook reproduce_paper.ipynb
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
To regenerate the results from scratch, place FARSEEING at `data/farseeing.feather` and run:
|
|
155
|
+
|
|
156
|
+
```bash
|
|
157
|
+
python scripts/run_sweep.py
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
FARSEEING is available from its maintainers on request. Its loader is `scripts/farseeing_loader.py`. To check an installation without FARSEEING:
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
python scripts/smoke_test.py
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
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).
|
|
167
|
+
|
|
168
|
+
## Citation
|
|
169
|
+
|
|
170
|
+
```bibtex
|
|
171
|
+
@inproceedings{aderinola2026costream,
|
|
172
|
+
title = {costream: A Streaming Evaluation Protocol for Wearable Fall Detection},
|
|
173
|
+
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},
|
|
174
|
+
booktitle = {Proceedings of the Irish Conference on Artificial Intelligence and Cognitive Science (AICS 2026)},
|
|
175
|
+
series = {Proceedings of Machine Learning Research},
|
|
176
|
+
year = {2026}
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
The proceedings volume and pages will be added when published.
|
|
181
|
+
|
|
182
|
+
## Licence
|
|
183
|
+
|
|
184
|
+
MIT. See [`LICENSE`](https://github.com/mlgig/costream/blob/main/LICENSE).
|
|
185
|
+
|
|
186
|
+
## Acknowledgements
|
|
187
|
+
|
|
188
|
+
This work was supported by Research Ireland under the Government of Ireland Postdoctoral Fellowship Programme (Grant Number: GOIPD/2025/1434).
|
costream-0.1.0/README.md
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# costream: A Streaming Evaluation Protocol
|
|
2
|
+
|
|
3
|
+
**Evaluate sparse-event detectors on continuous signals the way they are deployed.**
|
|
4
|
+
|
|
5
|
+
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.
|
|
6
|
+
|
|
7
|
+
**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.
|
|
8
|
+
|
|
9
|
+
**Paper:** *costream: A Streaming Evaluation Protocol for Wearable Fall Detection* (AICS 2026). [arXiv:2509.11789](https://arxiv.org/abs/2509.11789)
|
|
10
|
+
|
|
11
|
+
## How it works
|
|
12
|
+
|
|
13
|
+
1. **Window scoring.** A trained classifier scores successive overlapping windows of a continuous signal.
|
|
14
|
+
2. **Temporal aggregation.** Scores are combined by pointwise maximum into a temporal confidence map.
|
|
15
|
+
3. **Detection episodes.** Thresholding gives contiguous episodes, and episodes closer than `debounce_secs` merge into one.
|
|
16
|
+
4. **Event evaluation.** Each episode emits one detection, scored against the annotated event.
|
|
17
|
+
|
|
18
|
+

|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install costream
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
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:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install "costream[models]"
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Python 3.10 or newer. The package is tested on 3.10.
|
|
33
|
+
|
|
34
|
+
## Quickstart
|
|
35
|
+
|
|
36
|
+
### 1. Prepare your data
|
|
37
|
+
|
|
38
|
+
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.
|
|
39
|
+
|
|
40
|
+
**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.
|
|
41
|
+
|
|
42
|
+
**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.
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
# Files named like "rec2_P01.csv": the subject id is the last token.
|
|
46
|
+
groups = group_files_by_subject(
|
|
47
|
+
"data/", id_extractor=lambda p: p.stem.split("_")[-1]
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# Illustration: the event sample is encoded in the file name, "P01_rec2_f120000.csv".
|
|
51
|
+
def label_from_name(df, path):
|
|
52
|
+
f = int(path.stem.split("_f")[-1])
|
|
53
|
+
df["label"] = 0
|
|
54
|
+
df.loc[f, "label"] = 1
|
|
55
|
+
return df
|
|
56
|
+
|
|
57
|
+
load = make_csv_loader(feature_cols=["mag"], label_col="label",
|
|
58
|
+
label_extractor=label_from_name)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### 2. Run an evaluation
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from sklearn.ensemble import ExtraTreesClassifier
|
|
65
|
+
from sklearn.pipeline import make_pipeline
|
|
66
|
+
from sklearn.preprocessing import StandardScaler
|
|
67
|
+
|
|
68
|
+
from costream.data import group_files_by_subject, make_csv_loader
|
|
69
|
+
from costream.evaluation import ModelSpec, run_subject_cv
|
|
70
|
+
|
|
71
|
+
groups = group_files_by_subject("data/") # {subject_id: [csv paths]}
|
|
72
|
+
load = make_csv_loader(feature_cols=["mag"], label_col="label")
|
|
73
|
+
subject_map = {sid: load(paths) for sid, paths in groups.items()}
|
|
74
|
+
|
|
75
|
+
specs = [ModelSpec(name="ExtraTrees", estimator=make_pipeline(
|
|
76
|
+
StandardScaler(), ExtraTreesClassifier(n_estimators=150, random_state=0)))]
|
|
77
|
+
|
|
78
|
+
results = run_subject_cv(
|
|
79
|
+
subject_map, specs,
|
|
80
|
+
feature_cols=["mag"], label_col="label",
|
|
81
|
+
cv=5, window_size=10.0, step=1.0, freq=100,
|
|
82
|
+
activity_threshold=1.4, spacing="multiphase",
|
|
83
|
+
tolerance=20.0, debounce_secs=60.0, resample=False,
|
|
84
|
+
)
|
|
85
|
+
print(results[["model", "protocol", "fold", "tp", "fp", "fn", "f1-score"]])
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
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.
|
|
89
|
+
|
|
90
|
+
## What it computes
|
|
91
|
+
|
|
92
|
+
`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.
|
|
93
|
+
|
|
94
|
+
- **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.
|
|
95
|
+
- **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.
|
|
96
|
+
|
|
97
|
+
The protocols measure different quantities, so compare rankings across them, not absolute scores.
|
|
98
|
+
|
|
99
|
+
`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).
|
|
100
|
+
|
|
101
|
+
## Configuration
|
|
102
|
+
|
|
103
|
+
| Parameter | Meaning | Default |
|
|
104
|
+
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------- |
|
|
105
|
+
| `window_size` | window length in seconds | 7.0 (the paper uses 3, 10, 30 and 60) |
|
|
106
|
+
| `step` | window step in seconds | 1.0 |
|
|
107
|
+
| `freq` | sampling rate in Hz | 100 |
|
|
108
|
+
| `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 |
|
|
109
|
+
| `tolerance` | `t` in the reference interval `[f - 1, f + t)` seconds, where `f` is the annotated event | 20 |
|
|
110
|
+
| `debounce_secs` | detections closer than this merge into one episode | 60 |
|
|
111
|
+
| `exclusion_tolerance` | negative windows are drawn outside `[f - (window_size + t), f + t)` | 20 |
|
|
112
|
+
|
|
113
|
+
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.
|
|
114
|
+
|
|
115
|
+
## Reproducing the paper
|
|
116
|
+
|
|
117
|
+
[`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:
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
pip install -r requirements.txt
|
|
121
|
+
pip install -e .
|
|
122
|
+
jupyter notebook reproduce_paper.ipynb
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
To regenerate the results from scratch, place FARSEEING at `data/farseeing.feather` and run:
|
|
126
|
+
|
|
127
|
+
```bash
|
|
128
|
+
python scripts/run_sweep.py
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
FARSEEING is available from its maintainers on request. Its loader is `scripts/farseeing_loader.py`. To check an installation without FARSEEING:
|
|
132
|
+
|
|
133
|
+
```bash
|
|
134
|
+
python scripts/smoke_test.py
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
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).
|
|
138
|
+
|
|
139
|
+
## Citation
|
|
140
|
+
|
|
141
|
+
```bibtex
|
|
142
|
+
@inproceedings{aderinola2026costream,
|
|
143
|
+
title = {costream: A Streaming Evaluation Protocol for Wearable Fall Detection},
|
|
144
|
+
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},
|
|
145
|
+
booktitle = {Proceedings of the Irish Conference on Artificial Intelligence and Cognitive Science (AICS 2026)},
|
|
146
|
+
series = {Proceedings of Machine Learning Research},
|
|
147
|
+
year = {2026}
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
The proceedings volume and pages will be added when published.
|
|
152
|
+
|
|
153
|
+
## Licence
|
|
154
|
+
|
|
155
|
+
MIT. See [`LICENSE`](https://github.com/mlgig/costream/blob/main/LICENSE).
|
|
156
|
+
|
|
157
|
+
## Acknowledgements
|
|
158
|
+
|
|
159
|
+
This work was supported by Research Ireland under the Government of Ireland Postdoctoral Fellowship Programme (Grant Number: GOIPD/2025/1434).
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Callable, Dict, List, Optional, Sequence, Union
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
__all__ = ["group_files_by_subject", "make_csv_loader"]
|
|
12
|
+
|
|
13
|
+
def group_files_by_subject(
|
|
14
|
+
data_dir: Union[str, Path],
|
|
15
|
+
id_extractor: Optional[Callable[[str], str]] = None,
|
|
16
|
+
file_pattern: str = "*.csv"
|
|
17
|
+
) -> Dict[str, List[Path]]:
|
|
18
|
+
"""
|
|
19
|
+
Group files in a directory into a mapping of {subject_id: [file_paths]}.
|
|
20
|
+
"""
|
|
21
|
+
base_dir = Path(data_dir)
|
|
22
|
+
if not base_dir.is_dir():
|
|
23
|
+
raise FileNotFoundError(f"Directory not found: {base_dir}")
|
|
24
|
+
|
|
25
|
+
if id_extractor is None:
|
|
26
|
+
def _default_extractor(p: Path) -> str:
|
|
27
|
+
name = p.stem
|
|
28
|
+
m = re.match(r"^([^_-]+)", name)
|
|
29
|
+
return m.group(1) if m else name
|
|
30
|
+
id_extractor = _default_extractor
|
|
31
|
+
|
|
32
|
+
mapping = defaultdict(list)
|
|
33
|
+
files = list(base_dir.glob(file_pattern))
|
|
34
|
+
|
|
35
|
+
if not files:
|
|
36
|
+
# Try recursive if flat search fails
|
|
37
|
+
files = list(base_dir.rglob(file_pattern))
|
|
38
|
+
|
|
39
|
+
for path in files:
|
|
40
|
+
sid = id_extractor(path)
|
|
41
|
+
mapping[sid].append(path)
|
|
42
|
+
|
|
43
|
+
for sid in mapping:
|
|
44
|
+
mapping[sid].sort()
|
|
45
|
+
|
|
46
|
+
return dict(mapping)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def make_csv_loader(
|
|
50
|
+
feature_cols: Optional[Sequence[str]] = None,
|
|
51
|
+
label_col: str = "label",
|
|
52
|
+
timestamp_col: Optional[str] = None,
|
|
53
|
+
parse_dates: bool = False,
|
|
54
|
+
new_features: Optional[Dict[str, Callable[[pd.DataFrame], pd.Series]]] = None,
|
|
55
|
+
label_extractor: Optional[Callable[[pd.DataFrame, Path], pd.DataFrame]] = None,
|
|
56
|
+
**read_csv_kwargs
|
|
57
|
+
) -> Callable[[Sequence[Union[str, Path]]], List[pd.DataFrame]]:
|
|
58
|
+
"""
|
|
59
|
+
Creates a factory function to load CSV files into standardized DataFrames.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
feature_cols: List of columns to keep as input features.
|
|
63
|
+
label_col: Name of the target column (0=normal, 1=event).
|
|
64
|
+
timestamp_col: Optional name of the timestamp column.
|
|
65
|
+
parse_dates: If True, parses the timestamp column as datetime.
|
|
66
|
+
new_features: Dictionary of {new_col_name: function(df) -> series}.
|
|
67
|
+
label_extractor: Optional function(df, path) -> df.
|
|
68
|
+
Used to inject labels based on filename/path (e.g. for SisFall).
|
|
69
|
+
Must ensure the dataframe has a column named `label_col` after execution.
|
|
70
|
+
**read_csv_kwargs: Arguments for pd.read_csv (e.g. header=None, names=['x','y','z']).
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
A function `load_signals(files)` that returns a list of DataFrames.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
def load_signals(files: Sequence[Union[str, Path]]) -> List[pd.DataFrame]:
|
|
77
|
+
dfs: List[pd.DataFrame] = []
|
|
78
|
+
|
|
79
|
+
for f in files:
|
|
80
|
+
path = Path(f)
|
|
81
|
+
if not path.exists():
|
|
82
|
+
raise FileNotFoundError(f"File not found: {path}")
|
|
83
|
+
|
|
84
|
+
# Prepare date parsing args
|
|
85
|
+
parse_arg = read_csv_kwargs.pop('parse_dates', None)
|
|
86
|
+
if parse_dates and timestamp_col:
|
|
87
|
+
parse_arg = [timestamp_col]
|
|
88
|
+
|
|
89
|
+
# Load Raw
|
|
90
|
+
df = pd.read_csv(path, parse_dates=parse_arg, **read_csv_kwargs)
|
|
91
|
+
|
|
92
|
+
# Generate derived features (e.g., Magnitude)
|
|
93
|
+
if new_features:
|
|
94
|
+
for new_col_name, func in new_features.items():
|
|
95
|
+
df[new_col_name] = func(df)
|
|
96
|
+
|
|
97
|
+
# Inject Labels (for simulated datasets without label columns)
|
|
98
|
+
if label_extractor:
|
|
99
|
+
df = label_extractor(df, path)
|
|
100
|
+
|
|
101
|
+
# Check label column existence
|
|
102
|
+
if label_col not in df.columns:
|
|
103
|
+
raise ValueError(
|
|
104
|
+
f"Label column '{label_col}' not found in {path.name}. "
|
|
105
|
+
f"If the file has no label column, provide a `label_extractor`."
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
# 3. Determine which columns to keep
|
|
109
|
+
if feature_cols is None:
|
|
110
|
+
exclude = {c for c in (timestamp_col, label_col) if c}
|
|
111
|
+
selected_features = [c for c in df.columns if c not in exclude]
|
|
112
|
+
else:
|
|
113
|
+
selected_features = list(feature_cols)
|
|
114
|
+
missing = [c for c in selected_features if c not in df.columns]
|
|
115
|
+
if missing:
|
|
116
|
+
raise KeyError(f"Missing feature columns in {path.name}: {missing}")
|
|
117
|
+
|
|
118
|
+
# 4. Filter and Type Cast
|
|
119
|
+
cols_to_keep = selected_features + [label_col]
|
|
120
|
+
if timestamp_col and timestamp_col in df.columns:
|
|
121
|
+
cols_to_keep.append(timestamp_col)
|
|
122
|
+
|
|
123
|
+
df = df[cols_to_keep].copy()
|
|
124
|
+
df[selected_features] = df[selected_features].astype("float32")
|
|
125
|
+
df[label_col] = df[label_col].astype("int8")
|
|
126
|
+
|
|
127
|
+
dfs.append(df)
|
|
128
|
+
|
|
129
|
+
return dfs
|
|
130
|
+
|
|
131
|
+
return load_signals
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Data utility functions for processing signals and labels.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from typing import Dict, List, Sequence, Tuple, Union, Optional
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
|
|
12
|
+
__all__ = ["get_event_starts", "extract_streaming_data"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def get_event_starts(labels: np.ndarray) -> Union[int, np.ndarray]:
|
|
16
|
+
"""
|
|
17
|
+
Identify the start indices of distinct events from a label array.
|
|
18
|
+
|
|
19
|
+
Handles contiguous blocks of non-zero labels.
|
|
20
|
+
Example: [0, 0, 1, 1, 1, 0, 2, 2] -> Returns [2, 6]
|
|
21
|
+
|
|
22
|
+
Parameters
|
|
23
|
+
----------
|
|
24
|
+
labels : np.ndarray
|
|
25
|
+
Array of integer labels (0=Background, >0=Event).
|
|
26
|
+
|
|
27
|
+
Returns
|
|
28
|
+
-------
|
|
29
|
+
int or np.ndarray
|
|
30
|
+
-1 if no events found.
|
|
31
|
+
Array of start indices if events exist.
|
|
32
|
+
"""
|
|
33
|
+
labels = np.asarray(labels)
|
|
34
|
+
non_zero_indices = np.flatnonzero(labels)
|
|
35
|
+
|
|
36
|
+
if non_zero_indices.size == 0:
|
|
37
|
+
return -1
|
|
38
|
+
|
|
39
|
+
# Find gaps > 1 sample to identify distinct event blocks
|
|
40
|
+
gaps = np.diff(non_zero_indices) > 1
|
|
41
|
+
|
|
42
|
+
# The starts are: the very first non-zero index...
|
|
43
|
+
# ...PLUS the indices immediately following any gap.
|
|
44
|
+
starts = np.insert(non_zero_indices[1:][gaps], 0, non_zero_indices[0])
|
|
45
|
+
|
|
46
|
+
return starts
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def extract_streaming_data(
|
|
50
|
+
subject_map: Dict[str, List[pd.DataFrame]],
|
|
51
|
+
subjects: Sequence[str],
|
|
52
|
+
feature_col: str,
|
|
53
|
+
label_col: str = "label"
|
|
54
|
+
) -> Tuple[List[np.ndarray], List[Union[int, np.ndarray]]]:
|
|
55
|
+
"""
|
|
56
|
+
Extract raw signals and robust event start indices for a list of subjects.
|
|
57
|
+
|
|
58
|
+
Parameters
|
|
59
|
+
----------
|
|
60
|
+
subject_map : dict
|
|
61
|
+
Dictionary {subject_id: [DataFrame, ...]}.
|
|
62
|
+
subjects : list
|
|
63
|
+
List of subject IDs to process.
|
|
64
|
+
feature_col : str
|
|
65
|
+
Name of the column containing the signal (e.g., 'mag').
|
|
66
|
+
label_col : str
|
|
67
|
+
Name of the label column.
|
|
68
|
+
|
|
69
|
+
Returns
|
|
70
|
+
-------
|
|
71
|
+
signals : List[np.ndarray]
|
|
72
|
+
List of 1D float arrays (the streams).
|
|
73
|
+
events : List[Union[int, np.ndarray]]
|
|
74
|
+
List of event start indices (or -1) corresponding to each stream.
|
|
75
|
+
"""
|
|
76
|
+
signals = []
|
|
77
|
+
events = []
|
|
78
|
+
|
|
79
|
+
for s in subjects:
|
|
80
|
+
if s in subject_map:
|
|
81
|
+
for df in subject_map[s]:
|
|
82
|
+
# 1. Extract Signal
|
|
83
|
+
sig = df[feature_col].to_numpy(dtype=np.float32)
|
|
84
|
+
signals.append(sig)
|
|
85
|
+
|
|
86
|
+
# 2. Extract Event Starts
|
|
87
|
+
labels = df[label_col].to_numpy()
|
|
88
|
+
starts = get_event_starts(labels)
|
|
89
|
+
events.append(starts)
|
|
90
|
+
|
|
91
|
+
return signals, events
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from .tester import run_experiment, ModelSpec, train_models, evaluate_models
|
|
2
|
+
from .event_detection import evaluate_recording, FalsePositive
|
|
3
|
+
from .presegmented import evaluate_presegmented
|
|
4
|
+
from .cross_validation import run_subject_cv, aggregate_cv_results
|
|
5
|
+
from .probability_cache import CacheKey, CachedEntry, ProbabilityCache
|
|
6
|
+
from .checks import assert_adl_exclusion_zone, assert_gate_applied_identically
|
|
7
|
+
from .visualization import (
|
|
8
|
+
plot_confidence,
|
|
9
|
+
plot_detection,
|
|
10
|
+
metric_box,
|
|
11
|
+
metric_grid,
|
|
12
|
+
plot_grouped_stacked,
|
|
13
|
+
critical_difference,
|
|
14
|
+
window_bar,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"run_experiment",
|
|
19
|
+
"ModelSpec",
|
|
20
|
+
"train_models",
|
|
21
|
+
"evaluate_models",
|
|
22
|
+
"evaluate_recording",
|
|
23
|
+
"FalsePositive",
|
|
24
|
+
"evaluate_presegmented",
|
|
25
|
+
"assert_adl_exclusion_zone",
|
|
26
|
+
"assert_gate_applied_identically",
|
|
27
|
+
"run_subject_cv",
|
|
28
|
+
"aggregate_cv_results",
|
|
29
|
+
"CacheKey",
|
|
30
|
+
"CachedEntry",
|
|
31
|
+
"ProbabilityCache",
|
|
32
|
+
"plot_confidence",
|
|
33
|
+
"plot_detection",
|
|
34
|
+
"metric_box",
|
|
35
|
+
"metric_grid",
|
|
36
|
+
"plot_grouped_stacked",
|
|
37
|
+
"critical_difference",
|
|
38
|
+
"window_bar",
|
|
39
|
+
]
|