jitterbug-inference 2.2.0__tar.gz → 2.4.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.
Files changed (32) hide show
  1. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/PKG-INFO +29 -4
  2. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/README.md +25 -3
  3. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/pyproject.toml +3 -1
  4. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/pyproject.toml.orig +4 -1
  5. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/analyzer.py +15 -3
  6. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/cli/main.py +322 -0
  7. jitterbug_inference-2.4.0/src/jitterbug/io/compression.py +108 -0
  8. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/io/data_loader.py +15 -7
  9. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/io/exporters.py +26 -6
  10. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/models/__init__.py +2 -0
  11. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/models/config.py +116 -1
  12. jitterbug_inference-2.4.0/src/jitterbug/streaming/__init__.py +53 -0
  13. jitterbug_inference-2.4.0/src/jitterbug/streaming/online_analyzer.py +356 -0
  14. jitterbug_inference-2.4.0/src/jitterbug/streaming/replay.py +159 -0
  15. jitterbug_inference-2.4.0/src/jitterbug/streaming/verdict.py +96 -0
  16. jitterbug_inference-2.4.0/src/jitterbug/streaming/window_backend.py +363 -0
  17. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/__init__.py +0 -0
  18. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/analysis/__init__.py +0 -0
  19. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/analysis/clustering_analyzer.py +0 -0
  20. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/analysis/congestion_inference_analyzer.py +0 -0
  21. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/analysis/jitter_analyzer.py +0 -0
  22. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/analysis/latency_jump_analyzer.py +0 -0
  23. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/cli/__init__.py +0 -0
  24. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/detection/__init__.py +0 -0
  25. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/detection/algorithms.py +0 -0
  26. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/detection/change_point_detector.py +0 -0
  27. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/io/__init__.py +0 -0
  28. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/models/analysis.py +0 -0
  29. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/models/rtt_data.py +0 -0
  30. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/py.typed +0 -0
  31. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/visualization/__init__.py +0 -0
  32. {jitterbug_inference-2.2.0 → jitterbug_inference-2.4.0}/src/jitterbug/visualization/plotter.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: jitterbug-inference
3
- Version: 2.2.0
3
+ Version: 2.4.0
4
4
  Summary: Framework for jitter-based network congestion inference
5
5
  Keywords: network,congestion,rtt,jitter,analysis,changepoint,detection
6
6
  Author: Esteban Carisimo
@@ -32,6 +32,7 @@ Requires-Dist: bayesian-changepoint>=1.2 ; extra == 'all'
32
32
  Requires-Dist: torch>=2.0 ; extra == 'all'
33
33
  Requires-Dist: scikit-learn>=1.3 ; extra == 'all'
34
34
  Requires-Dist: influxdb-client>=1.30.0 ; extra == 'all'
35
+ Requires-Dist: zstandard>=0.23 ; python_full_version < '3.14' and extra == 'all'
35
36
  Requires-Dist: matplotlib>=3.5.0 ; extra == 'all'
36
37
  Requires-Dist: ipykernel>=6.0.0 ; extra == 'all'
37
38
  Requires-Dist: jupyter>=1.0.0 ; extra == 'all'
@@ -43,6 +44,7 @@ Requires-Dist: influxdb-client>=1.30.0 ; extra == 'influx'
43
44
  Requires-Dist: ipykernel>=6.0.0 ; extra == 'jupyter'
44
45
  Requires-Dist: jupyter>=1.0.0 ; extra == 'jupyter'
45
46
  Requires-Dist: matplotlib>=3.5.0 ; extra == 'visualization'
47
+ Requires-Dist: zstandard>=0.23 ; python_full_version < '3.14' and extra == 'zstd'
46
48
  Maintainer: Esteban Carisimo
47
49
  Maintainer-email: Esteban Carisimo <esteban.carisimo@northwestern.edu>
48
50
  Requires-Python: >=3.10
@@ -57,6 +59,7 @@ Provides-Extra: clustering
57
59
  Provides-Extra: influx
58
60
  Provides-Extra: jupyter
59
61
  Provides-Extra: visualization
62
+ Provides-Extra: zstd
60
63
  Description-Content-Type: text/markdown
61
64
 
62
65
  # 🐞 Jitterbug
@@ -112,9 +115,10 @@ See [docs/INSTALLATION.md](https://github.com/estcarisimo/jitterbug/blob/main/do
112
115
 
113
116
  | Extra | Installs | Use it for |
114
117
  | --- | --- | --- |
115
- | `bcp` | [bayesian-changepoint](https://pypi.org/project/bayesian-changepoint/) + torch | The Bayesian detector used in the paper |
118
+ | `bcp` | [bayesian-changepoint](https://pypi.org/project/bayesian-changepoint/) + torch | The Bayesian detector used in the paper, and the online mode (`jitterbug stream` / `replay`) |
116
119
  | `clustering` | scikit-learn | The non-sequential mode (`--mode clustering`) |
117
120
  | `influx` | influxdb-client | Loading RTTs straight from InfluxDB |
121
+ | `zstd` | zstandard (not needed on Python 3.14+) | Reading and writing `.zst`-compressed files |
118
122
  | `visualization` | matplotlib | `jitterbug visualize` and the plotting helpers |
119
123
  | `jupyter` | JupyterLab, ipykernel | The notebooks in `examples/` |
120
124
  | `all` | everything above | |
@@ -150,6 +154,10 @@ jitterbug analyze examples/network_analysis/data/raw.csv --summary-only
150
154
 
151
155
  # CSV instead of JSON (Parquet is also supported if `pyarrow` is installed)
152
156
  jitterbug analyze rtts.csv --output results.csv --output-format csv
157
+
158
+ # Zstandard-compressed input and output: a trailing .zst is enough (needs the `zstd` extra
159
+ # before Python 3.14)
160
+ jitterbug analyze rtts.csv.zst --output results.json.zst
153
161
  ```
154
162
 
155
163
  ### Validate input before analyzing
@@ -168,6 +176,20 @@ jitterbug visualize examples/network_analysis/data/raw.csv --output-dir plots
168
176
 
169
177
  The figures are described in [docs/VISUALIZATION_USAGE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/VISUALIZATION_USAGE.md), together with the `JitterbugPlotter` API for your own scripts.
170
178
 
179
+ ### Online mode: stream and replay
180
+
181
+ ```bash
182
+ # Infer congestion as samples arrive: `epoch,rtt` lines on stdin, one JSON event per line;
183
+ # needs `uv sync --extra bcp`
184
+ my-probe | jitterbug stream --events verdicts
185
+
186
+ # Replay a recorded dataset through the online pipeline and score it against a reference
187
+ jitterbug replay examples/network_analysis/data/raw.csv \
188
+ --reference examples/network_analysis/expected_results/kstest_inferences.csv
189
+ ```
190
+
191
+ On the paper dataset congestion onsets are reported 15 min after they start (median; 90 min at most); see [docs/ONLINE_MODE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/ONLINE_MODE.md) for the method, the results on the paper dataset and the `streaming` configuration section.
192
+
171
193
  ### Configuration files
172
194
 
173
195
  ```bash
@@ -317,8 +339,10 @@ src/jitterbug/
317
339
  │ ├── jitter_analyzer.py # jitter dispersion and KS test
318
340
  │ ├── congestion_inference_analyzer.py
319
341
  │ └── clustering_analyzer.py # non-sequential mode (GMM / k-means over intervals)
342
+ ├── streaming/ # Online mode: OnlineJitterbug (Bayesian online change points) and
343
+ │ # SlidingWindowJitterbug (offline pipeline on a window); replay/score
320
344
  ├── io/ # DataLoader (CSV, scamper JSON, InfluxDB) and exporters
321
- ├── cli/main.py # Typer CLI: analyze, validate, config, visualize, version
345
+ ├── cli/main.py # Typer CLI: analyze, validate, config, visualize, stream, replay, version
322
346
  └── visualization/ # JitterbugPlotter (matplotlib): the figures behind `jitterbug visualize`
323
347
  ```
324
348
 
@@ -436,6 +460,7 @@ Contributions are welcome! Please see the [Contributing Guide](https://github.co
436
460
  | [docs/ALGORITHM_SELECTION_GUIDE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/ALGORITHM_SELECTION_GUIDE.md) | Choosing a change point detector |
437
461
  | [docs/ALGORITHM_USAGE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/ALGORITHM_USAGE.md) | Per-detector options and examples |
438
462
  | [docs/VISUALIZATION_USAGE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/VISUALIZATION_USAGE.md) | `jitterbug visualize`, the five figures, `JitterbugPlotter` |
463
+ | [docs/PERFORMANCE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/PERFORMANCE.md) | Runtime across releases, and where the speedup comes from |
439
464
  | [examples/README.md](https://github.com/estcarisimo/jitterbug/blob/main/examples/README.md) | Scripts and notebooks |
440
465
 
441
466
  ## 📄 License
@@ -445,7 +470,7 @@ This project is licensed under the MIT License - see the [LICENSE](https://githu
445
470
  ## 🔗 Related Resources
446
471
 
447
472
  - [Jitterbug paper (PAM 2022)](https://doi.org/10.1007/978-3-030-98785-5_7)
448
- - [bayesian_changepoint_detection](https://github.com/estcarisimo/bayesian_changepoint_detection): the Bayesian detector behind the `bcp` extra
473
+ - [bayesian_changepoint_detection](https://github.com/hildensia/bayesian_changepoint_detection) ([docs](https://estcarisimo.github.io/bayesian_changepoint_detection/), PyPI [`bayesian-changepoint`](https://pypi.org/project/bayesian-changepoint/)): the Bayesian detector behind the `bcp` extra. Its 1.2 release made the paper's configuration about 6× faster than Jitterbug 1.0 and more accurate than the version Jitterbug used before; see [docs/PERFORMANCE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/PERFORMANCE.md#what-changed-in-the-bayesian-library)
449
474
  - [ruptures](https://centre-borelli.github.io/ruptures-docs/): the default change point library
450
475
  - [scamper](https://www.caida.org/catalog/software/scamper/): the measurement tool whose JSON output Jitterbug reads
451
476
 
@@ -51,9 +51,10 @@ See [docs/INSTALLATION.md](https://github.com/estcarisimo/jitterbug/blob/main/do
51
51
 
52
52
  | Extra | Installs | Use it for |
53
53
  | --- | --- | --- |
54
- | `bcp` | [bayesian-changepoint](https://pypi.org/project/bayesian-changepoint/) + torch | The Bayesian detector used in the paper |
54
+ | `bcp` | [bayesian-changepoint](https://pypi.org/project/bayesian-changepoint/) + torch | The Bayesian detector used in the paper, and the online mode (`jitterbug stream` / `replay`) |
55
55
  | `clustering` | scikit-learn | The non-sequential mode (`--mode clustering`) |
56
56
  | `influx` | influxdb-client | Loading RTTs straight from InfluxDB |
57
+ | `zstd` | zstandard (not needed on Python 3.14+) | Reading and writing `.zst`-compressed files |
57
58
  | `visualization` | matplotlib | `jitterbug visualize` and the plotting helpers |
58
59
  | `jupyter` | JupyterLab, ipykernel | The notebooks in `examples/` |
59
60
  | `all` | everything above | |
@@ -89,6 +90,10 @@ jitterbug analyze examples/network_analysis/data/raw.csv --summary-only
89
90
 
90
91
  # CSV instead of JSON (Parquet is also supported if `pyarrow` is installed)
91
92
  jitterbug analyze rtts.csv --output results.csv --output-format csv
93
+
94
+ # Zstandard-compressed input and output: a trailing .zst is enough (needs the `zstd` extra
95
+ # before Python 3.14)
96
+ jitterbug analyze rtts.csv.zst --output results.json.zst
92
97
  ```
93
98
 
94
99
  ### Validate input before analyzing
@@ -107,6 +112,20 @@ jitterbug visualize examples/network_analysis/data/raw.csv --output-dir plots
107
112
 
108
113
  The figures are described in [docs/VISUALIZATION_USAGE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/VISUALIZATION_USAGE.md), together with the `JitterbugPlotter` API for your own scripts.
109
114
 
115
+ ### Online mode: stream and replay
116
+
117
+ ```bash
118
+ # Infer congestion as samples arrive: `epoch,rtt` lines on stdin, one JSON event per line;
119
+ # needs `uv sync --extra bcp`
120
+ my-probe | jitterbug stream --events verdicts
121
+
122
+ # Replay a recorded dataset through the online pipeline and score it against a reference
123
+ jitterbug replay examples/network_analysis/data/raw.csv \
124
+ --reference examples/network_analysis/expected_results/kstest_inferences.csv
125
+ ```
126
+
127
+ On the paper dataset congestion onsets are reported 15 min after they start (median; 90 min at most); see [docs/ONLINE_MODE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/ONLINE_MODE.md) for the method, the results on the paper dataset and the `streaming` configuration section.
128
+
110
129
  ### Configuration files
111
130
 
112
131
  ```bash
@@ -256,8 +275,10 @@ src/jitterbug/
256
275
  │ ├── jitter_analyzer.py # jitter dispersion and KS test
257
276
  │ ├── congestion_inference_analyzer.py
258
277
  │ └── clustering_analyzer.py # non-sequential mode (GMM / k-means over intervals)
278
+ ├── streaming/ # Online mode: OnlineJitterbug (Bayesian online change points) and
279
+ │ # SlidingWindowJitterbug (offline pipeline on a window); replay/score
259
280
  ├── io/ # DataLoader (CSV, scamper JSON, InfluxDB) and exporters
260
- ├── cli/main.py # Typer CLI: analyze, validate, config, visualize, version
281
+ ├── cli/main.py # Typer CLI: analyze, validate, config, visualize, stream, replay, version
261
282
  └── visualization/ # JitterbugPlotter (matplotlib): the figures behind `jitterbug visualize`
262
283
  ```
263
284
 
@@ -375,6 +396,7 @@ Contributions are welcome! Please see the [Contributing Guide](https://github.co
375
396
  | [docs/ALGORITHM_SELECTION_GUIDE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/ALGORITHM_SELECTION_GUIDE.md) | Choosing a change point detector |
376
397
  | [docs/ALGORITHM_USAGE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/ALGORITHM_USAGE.md) | Per-detector options and examples |
377
398
  | [docs/VISUALIZATION_USAGE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/VISUALIZATION_USAGE.md) | `jitterbug visualize`, the five figures, `JitterbugPlotter` |
399
+ | [docs/PERFORMANCE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/PERFORMANCE.md) | Runtime across releases, and where the speedup comes from |
378
400
  | [examples/README.md](https://github.com/estcarisimo/jitterbug/blob/main/examples/README.md) | Scripts and notebooks |
379
401
 
380
402
  ## 📄 License
@@ -384,7 +406,7 @@ This project is licensed under the MIT License - see the [LICENSE](https://githu
384
406
  ## 🔗 Related Resources
385
407
 
386
408
  - [Jitterbug paper (PAM 2022)](https://doi.org/10.1007/978-3-030-98785-5_7)
387
- - [bayesian_changepoint_detection](https://github.com/estcarisimo/bayesian_changepoint_detection): the Bayesian detector behind the `bcp` extra
409
+ - [bayesian_changepoint_detection](https://github.com/hildensia/bayesian_changepoint_detection) ([docs](https://estcarisimo.github.io/bayesian_changepoint_detection/), PyPI [`bayesian-changepoint`](https://pypi.org/project/bayesian-changepoint/)): the Bayesian detector behind the `bcp` extra. Its 1.2 release made the paper's configuration about 6× faster than Jitterbug 1.0 and more accurate than the version Jitterbug used before; see [docs/PERFORMANCE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/PERFORMANCE.md#what-changed-in-the-bayesian-library)
388
410
  - [ruptures](https://centre-borelli.github.io/ruptures-docs/): the default change point library
389
411
  - [scamper](https://www.caida.org/catalog/software/scamper/): the measurement tool whose JSON output Jitterbug reads
390
412
 
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "jitterbug-inference"
7
- version = "2.2.0"
7
+ version = "2.4.0"
8
8
  description = "Framework for jitter-based network congestion inference"
9
9
  readme = "README.md"
10
10
  keywords = [
@@ -63,6 +63,7 @@ bcp = [
63
63
  bayesian = ["jitterbug-inference[bcp]"]
64
64
  clustering = ["scikit-learn>=1.3"]
65
65
  influx = ["influxdb-client>=1.30.0"]
66
+ zstd = ["zstandard>=0.23; python_version < '3.14'"]
66
67
  visualization = ["matplotlib>=3.5.0"]
67
68
  jupyter = [
68
69
  "ipykernel>=6.0.0",
@@ -73,6 +74,7 @@ all = [
73
74
  "torch>=2.0",
74
75
  "scikit-learn>=1.3",
75
76
  "influxdb-client>=1.30.0",
77
+ "zstandard>=0.23; python_version < '3.14'",
76
78
  "matplotlib>=3.5.0",
77
79
  "ipykernel>=6.0.0",
78
80
  "jupyter>=1.0.0",
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "jitterbug-inference"
7
- version = "2.2.0"
7
+ version = "2.4.0"
8
8
  description = "Framework for jitter-based network congestion inference"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -58,6 +58,8 @@ bayesian = ["jitterbug-inference[bcp]"] # deprecated alias for the old extra na
58
58
  # Non-sequential (clustering) analysis mode: `analysis_mode: clustering`
59
59
  clustering = ["scikit-learn>=1.3"]
60
60
  influx = ["influxdb-client>=1.30.0"]
61
+ # Zstandard (`.zst`) input and output; Python 3.14+ has it in the standard library
62
+ zstd = ["zstandard>=0.23; python_version < '3.14'"]
61
63
  visualization = ["matplotlib>=3.5.0"]
62
64
  jupyter = ["ipykernel>=6.0.0", "jupyter>=1.0.0"]
63
65
  # Every optional back end and front end.
@@ -66,6 +68,7 @@ all = [
66
68
  "torch>=2.0",
67
69
  "scikit-learn>=1.3",
68
70
  "influxdb-client>=1.30.0",
71
+ "zstandard>=0.23; python_version < '3.14'",
69
72
  "matplotlib>=3.5.0",
70
73
  "ipykernel>=6.0.0",
71
74
  "jupyter>=1.0.0",
@@ -15,6 +15,8 @@ from .analysis import (
15
15
  )
16
16
  from .detection import ChangePointDetector
17
17
  from .io import DataLoader
18
+ from .io.compression import open_text
19
+ from .io.exporters import reject_zstd_parquet
18
20
  from .models import (
19
21
  ChangePoint,
20
22
  CongestionInferenceResult,
@@ -312,9 +314,17 @@ class JitterbugAnalyzer:
312
314
  results : CongestionInferenceResult
313
315
  Analysis results to save.
314
316
  output_path : Union[str, Path]
315
- Path to save results to.
317
+ Path to save results to. JSON and CSV are compressed with Zstandard when it
318
+ ends in ``.zst`` (``results.json.zst``).
316
319
  format : Optional[str]
317
320
  Output format ('json', 'csv', 'parquet'). If None, uses config default.
321
+
322
+ Raises
323
+ ------
324
+ ValueError
325
+ If the format is unknown, or Parquet is requested with a ``.zst`` path.
326
+ ImportError
327
+ If the path ends in ``.zst`` and no Zstandard codec is available.
318
328
  """
319
329
  output_path = Path(output_path)
320
330
  format = format or self.config.output_format
@@ -322,14 +332,16 @@ class JitterbugAnalyzer:
322
332
  if format == "json":
323
333
  import json
324
334
 
325
- with output_path.open("w") as f:
335
+ with open_text(output_path, "w") as f:
326
336
  json.dump(results.model_dump(), f, indent=2, default=str)
327
337
 
328
338
  elif format == "csv":
329
339
  df = results.to_dataframe()
330
- df.to_csv(output_path, index=False)
340
+ with open_text(output_path, "w", newline="") as f:
341
+ df.to_csv(f, index=False)
331
342
 
332
343
  elif format == "parquet":
344
+ reject_zstd_parquet(output_path)
333
345
  df = results.to_dataframe()
334
346
  df.to_parquet(output_path)
335
347
 
@@ -4,7 +4,10 @@ Main CLI application using Typer.
4
4
 
5
5
  import json
6
6
  import logging
7
+ import math
7
8
  import sys
9
+ import time
10
+ from collections.abc import Iterator
8
11
  from pathlib import Path
9
12
  from typing import Any
10
13
 
@@ -16,6 +19,7 @@ from rich.table import Table
16
19
 
17
20
  from ..analyzer import JitterbugAnalyzer
18
21
  from ..io import DataLoader
22
+ from ..io.compression import open_text
19
23
  from ..models import CongestionInferenceResult, JitterbugConfig
20
24
 
21
25
  # matplotlib is an optional dependency; the visualize command checks for it at run time.
@@ -27,6 +31,8 @@ except ImportError: # pragma: no cover - only if the package itself is broken
27
31
 
28
32
  # Initialize Rich console
29
33
  console = Console()
34
+ # `jitterbug stream` writes JSON lines to stdout, so its messages go to stderr.
35
+ err_console = Console(stderr=True)
30
36
 
31
37
 
32
38
  def _apply_overrides(
@@ -64,6 +70,33 @@ def _apply_overrides(
64
70
  return JitterbugConfig.model_validate(data)
65
71
 
66
72
 
73
+ def _apply_streaming_overrides(
74
+ base: JitterbugConfig,
75
+ *,
76
+ backend: str | None = None,
77
+ decision: str | None = None,
78
+ hazard_lambda: float | None = None,
79
+ min_period_samples: int | None = None,
80
+ min_time_elapsed: int | None = None,
81
+ verbose: bool = False,
82
+ ) -> JitterbugConfig:
83
+ """Return a copy of ``base`` with the online-mode flags that were actually given."""
84
+ data = base.model_dump()
85
+ if backend is not None:
86
+ data["streaming"]["backend"] = backend
87
+ if decision is not None:
88
+ data["streaming"]["decision"] = decision
89
+ if hazard_lambda is not None:
90
+ data["streaming"]["hazard_lambda"] = hazard_lambda
91
+ if min_period_samples is not None:
92
+ data["streaming"]["min_period_samples"] = min_period_samples
93
+ if min_time_elapsed is not None:
94
+ data["streaming"]["min_time_elapsed"] = min_time_elapsed
95
+ if verbose:
96
+ data["verbose"] = True
97
+ return JitterbugConfig.model_validate(data)
98
+
99
+
67
100
  # Create Typer app
68
101
  app = typer.Typer(
69
102
  name="jitterbug",
@@ -426,6 +459,295 @@ def visualize(
426
459
  raise typer.Exit(1) from None
427
460
 
428
461
 
462
+ def _iter_lines(source: Path | None, follow: bool) -> Iterator[str]:
463
+ """
464
+ Complete lines of ``source`` (stdin when None); with ``follow``, keep waiting for more.
465
+
466
+ A writer that is still appending may have flushed half a line; it is held back until
467
+ its newline arrives. Without ``follow`` a trailing unterminated line is yielded at EOF.
468
+ """
469
+ if source is None:
470
+ yield from sys.stdin
471
+ return
472
+ with open_text(source) as f:
473
+ partial = ""
474
+ while True:
475
+ chunk = f.readline()
476
+ if chunk:
477
+ partial += chunk
478
+ if partial.endswith("\n"):
479
+ yield partial
480
+ partial = ""
481
+ elif follow:
482
+ time.sleep(0.5)
483
+ else:
484
+ if partial:
485
+ yield partial
486
+ return
487
+
488
+
489
+ def _parse_sample(line: str) -> tuple[float, float] | None:
490
+ """``epoch,rtt`` (extra columns ignored) or None for blank, header and junk lines."""
491
+ parts = line.strip().split(",")
492
+ if len(parts) < 2:
493
+ return None
494
+ try:
495
+ epoch, rtt = float(parts[0]), float(parts[1])
496
+ except ValueError:
497
+ return None
498
+ if not (math.isfinite(epoch) and math.isfinite(rtt)):
499
+ return None
500
+ return epoch, rtt
501
+
502
+
503
+ @app.command()
504
+ def stream(
505
+ source: str = typer.Argument(
506
+ "-", help="File with one 'epoch,rtt' sample per line, or '-' for standard input"
507
+ ),
508
+ follow: bool = typer.Option(
509
+ False, "--follow", "-f", help="Keep reading the file as it grows (like tail -f)"
510
+ ),
511
+ output: Path | None = typer.Option(
512
+ None, "--output", "-o", help="Write events here as JSON lines instead of stdout"
513
+ ),
514
+ events: str = typer.Option(
515
+ "all", "--events", help="Which events to emit: all, verdicts, change-points"
516
+ ),
517
+ config: Path | None = typer.Option(
518
+ None, "--config", "-c", help="Configuration file (YAML or JSON)", exists=True
519
+ ),
520
+ backend: str | None = typer.Option(
521
+ None, "--backend", help="Online back end: bocpd (incremental) or window (offline rerun)"
522
+ ),
523
+ decision: str | None = typer.Option(
524
+ None, "--decision", help="Change point rule: map, lag, window (bocpd back end only)"
525
+ ),
526
+ hazard_lambda: float | None = typer.Option(
527
+ None, "--hazard-lambda", help="Expected run length in bins (bocpd back end only)"
528
+ ),
529
+ min_period_samples: int | None = typer.Option(
530
+ None, "--min-period-samples", help="Jitter samples before a provisional verdict"
531
+ ),
532
+ min_time_elapsed: int | None = typer.Option(
533
+ None,
534
+ "--min-time-elapsed",
535
+ help="Minimum seconds between change points (bocpd; the window back end uses "
536
+ "change_point_detection.min_time_elapsed)",
537
+ ),
538
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable verbose logging"),
539
+ ) -> None:
540
+ """
541
+ Infer congestion online from a stream of RTT samples.
542
+
543
+ The default back end (bocpd) needs the bcp extra; --backend window reruns the offline
544
+ pipeline on a trailing window instead (its cadence and window come from the streaming
545
+ section of --config; --decision and --hazard-lambda do not apply to it).
546
+
547
+ Reads 'epoch,rtt' lines (seconds, milliseconds; a header line is skipped) and prints one
548
+ JSON object per event: change points, provisional verdicts and final verdicts. Samples
549
+ must arrive in time order; a sample older than the last one is dropped. The last bin is
550
+ closed when the input ends (or on Ctrl-C with --follow), as 'jitterbug replay' does.
551
+
552
+ [bold]Examples:[/bold]
553
+
554
+ • From a probe writing to standard output:
555
+ [cyan]my-probe | jitterbug stream[/cyan]
556
+
557
+ • Following a file that another process appends to:
558
+ [cyan]jitterbug stream rtts.csv --follow --events verdicts[/cyan]
559
+ """
560
+ logging.basicConfig(
561
+ level=logging.DEBUG if verbose else logging.WARNING,
562
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
563
+ stream=sys.stderr,
564
+ )
565
+ if events not in ("all", "verdicts", "change-points"):
566
+ err_console.print(
567
+ f"❌ Error: --events must be all, verdicts or change-points, not {events}"
568
+ )
569
+ raise typer.Exit(2)
570
+ if follow and source == "-":
571
+ err_console.print("--follow has no effect on standard input", style="yellow")
572
+ try:
573
+ from ..streaming import create_online_analyzer
574
+
575
+ jitterbug_config = JitterbugConfig.from_file(config) if config else JitterbugConfig()
576
+ jitterbug_config = _apply_streaming_overrides(
577
+ jitterbug_config,
578
+ backend=backend,
579
+ decision=decision,
580
+ hazard_lambda=hazard_lambda,
581
+ min_period_samples=min_period_samples,
582
+ min_time_elapsed=min_time_elapsed,
583
+ verbose=verbose,
584
+ )
585
+ online = create_online_analyzer(jitterbug_config)
586
+ path = None if source == "-" else Path(source)
587
+ if path is not None and not path.exists():
588
+ raise FileNotFoundError(f"Input file not found: {path}")
589
+ sink = output.open("w") if output else sys.stdout
590
+ n_samples = n_skipped = n_events = 0
591
+ wanted = {"all": None, "verdicts": "verdict", "change-points": "change_point"}[events]
592
+
593
+ def emit(batch: list[Any]) -> None:
594
+ nonlocal n_events
595
+ for event in batch:
596
+ if wanted is not None and event.kind != wanted:
597
+ continue
598
+ sink.write(json.dumps(event.to_dict()) + "\n")
599
+ sink.flush()
600
+ n_events += 1
601
+
602
+ try:
603
+ try:
604
+ for line in _iter_lines(path, follow):
605
+ sample = _parse_sample(line)
606
+ if sample is None:
607
+ n_skipped += bool(line.strip())
608
+ continue
609
+ n_samples += 1
610
+ emit(online.push(*sample))
611
+ except KeyboardInterrupt:
612
+ # Ctrl-C is how a --follow stream ends; close it like an EOF.
613
+ err_console.print("interrupted", style="yellow")
614
+ # The input ended (stdin EOF, a file without --follow, or Ctrl-C): close the
615
+ # open bin so the result matches `jitterbug replay` on the same data.
616
+ emit(online.flush())
617
+ finally:
618
+ if output:
619
+ sink.close()
620
+ err_console.print(
621
+ f"{n_samples} samples read, {n_skipped} lines skipped, {n_events} events emitted"
622
+ )
623
+ except Exception as e:
624
+ err_console.print(f"❌ Error: {e}", style="red")
625
+ raise typer.Exit(1) from None
626
+
627
+
628
+ @app.command()
629
+ def replay(
630
+ input_file: Path = typer.Argument(
631
+ ..., help="RTT data file to replay in time order", exists=True
632
+ ),
633
+ output: Path | None = typer.Option(
634
+ None, "--output", "-o", help="Write every event as a JSON array to this file"
635
+ ),
636
+ reference: Path | None = typer.Option(
637
+ None,
638
+ "--reference",
639
+ help="CSV with starts,ends,congestion columns to score the final verdicts against",
640
+ exists=True,
641
+ ),
642
+ format: str | None = typer.Option(
643
+ None, "--format", help="Input format (csv, json, scamper); inferred from the file"
644
+ ),
645
+ config: Path | None = typer.Option(
646
+ None, "--config", "-c", help="Configuration file (YAML or JSON)", exists=True
647
+ ),
648
+ backend: str | None = typer.Option(
649
+ None, "--backend", help="Online back end: bocpd (incremental) or window (offline rerun)"
650
+ ),
651
+ decision: str | None = typer.Option(
652
+ None, "--decision", help="Change point rule: map, lag, window (bocpd back end only)"
653
+ ),
654
+ hazard_lambda: float | None = typer.Option(
655
+ None, "--hazard-lambda", help="Expected run length in bins (bocpd back end only)"
656
+ ),
657
+ min_period_samples: int | None = typer.Option(
658
+ None, "--min-period-samples", help="Jitter samples before a provisional verdict"
659
+ ),
660
+ min_time_elapsed: int | None = typer.Option(
661
+ None,
662
+ "--min-time-elapsed",
663
+ help="Minimum seconds between change points (bocpd; the window back end uses "
664
+ "change_point_detection.min_time_elapsed)",
665
+ ),
666
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable verbose logging"),
667
+ ) -> None:
668
+ """
669
+ Replay a recorded dataset through the online pipeline and summarize the result.
670
+
671
+ [bold]Examples:[/bold]
672
+
673
+ • Paper dataset against the paper's KS reference:
674
+ [cyan]jitterbug replay examples/network_analysis/data/raw.csv \\
675
+ --reference examples/network_analysis/expected_results/kstest_inferences.csv[/cyan]
676
+
677
+ • Keep every event:
678
+ [cyan]jitterbug replay rtts.csv --output events.json[/cyan]
679
+ """
680
+ logging.basicConfig(
681
+ level=logging.DEBUG if verbose else logging.WARNING,
682
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
683
+ stream=sys.stderr,
684
+ )
685
+ try:
686
+ from ..streaming import events_to_json, score
687
+ from ..streaming import replay as replay_dataset
688
+
689
+ jitterbug_config = JitterbugConfig.from_file(config) if config else JitterbugConfig()
690
+ jitterbug_config = _apply_streaming_overrides(
691
+ jitterbug_config,
692
+ backend=backend,
693
+ decision=decision,
694
+ hazard_lambda=hazard_lambda,
695
+ min_period_samples=min_period_samples,
696
+ min_time_elapsed=min_time_elapsed,
697
+ verbose=verbose,
698
+ )
699
+ with Progress(
700
+ SpinnerColumn(),
701
+ TextColumn("[progress.description]{task.description}"),
702
+ console=console,
703
+ transient=True,
704
+ ) as progress:
705
+ task = progress.add_task("Replaying...", total=None)
706
+ dataset = DataLoader().load_from_file(input_file, format)
707
+ events = replay_dataset(dataset, jitterbug_config)
708
+ progress.update(task, total=1, completed=1)
709
+ summary = score(events, reference)
710
+ if output:
711
+ events_to_json(events, output)
712
+
713
+ table = Table(title="Online replay", show_header=True, header_style="bold")
714
+ table.add_column("Metric")
715
+ table.add_column("Value", justify="right")
716
+ labels = {
717
+ "change_points": "Change points",
718
+ "periods": "Periods with a final verdict",
719
+ "congested": "Congested periods",
720
+ "onset_delay_min_median": "Onset delay, median (min)",
721
+ "onset_delay_min_max": "Onset delay, max (min)",
722
+ "return_delay_min_median": "Return delay, median (min)",
723
+ "return_delay_min_max": "Return delay, max (min)",
724
+ "provisional_flips": "Provisional verdicts that flipped",
725
+ "provisional_pairs": "Provisional/final pairs",
726
+ "provisional_lead_h_mean": "Provisional lead, mean (h)",
727
+ "recovered": "Reference congested periods recovered",
728
+ "reference_congested": "Reference congested periods",
729
+ "spurious": "Spurious congested periods",
730
+ "boundaries_within_30min": "Reference boundaries with a change point within 30 min",
731
+ "reference_boundaries": "Reference boundaries",
732
+ }
733
+ for key, label in labels.items():
734
+ if key in summary:
735
+ value = summary[key]
736
+ if value is None:
737
+ text = "-"
738
+ elif isinstance(value, float):
739
+ text = f"{value:.1f}"
740
+ else:
741
+ text = str(value)
742
+ table.add_row(label, text)
743
+ console.print(table)
744
+ if output:
745
+ console.print(f"\n✅ Events saved to [bold]{output}[/bold]")
746
+ except Exception as e:
747
+ console.print(f"❌ Error: {e}", style="red")
748
+ raise typer.Exit(1) from None
749
+
750
+
429
751
  @app.command()
430
752
  def version() -> None:
431
753
  """Show Jitterbug version information."""