jitterbug-inference 2.1.1__py3-none-any.whl

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.
jitterbug/__init__.py ADDED
@@ -0,0 +1,78 @@
1
+ """
2
+ Jitterbug: Framework for Jitter-Based Congestion Inference
3
+
4
+ A modern Python framework for detecting network congestion through jitter analysis
5
+ and change point detection in Round-Trip Time (RTT) measurements.
6
+
7
+ Key Features:
8
+ - Multiple change point detection algorithms
9
+ - Jitter dispersion and KS-test analysis methods
10
+ - Flexible data input formats (CSV, JSON, InfluxDB)
11
+ - Comprehensive configuration management
12
+ - Type-safe Pydantic models
13
+ - Modern CLI interface
14
+
15
+ Example Usage:
16
+ from jitterbug import JitterbugAnalyzer
17
+ from jitterbug.models import JitterbugConfig
18
+
19
+ # Load configuration
20
+ config = JitterbugConfig()
21
+
22
+ # Create analyzer
23
+ analyzer = JitterbugAnalyzer(config)
24
+
25
+ # Analyze RTT data
26
+ results = analyzer.analyze_from_file('rtts.csv')
27
+
28
+ # Get congestion periods
29
+ congested_periods = results.get_congested_periods()
30
+ """
31
+
32
+ from importlib.metadata import PackageNotFoundError
33
+ from importlib.metadata import version as _pkg_version
34
+
35
+ from .analyzer import JitterbugAnalyzer
36
+ from .models import (
37
+ ChangePoint,
38
+ ChangePointDetectionConfig,
39
+ CongestionInference,
40
+ CongestionInferenceResult,
41
+ DataProcessingConfig,
42
+ JitterAnalysis,
43
+ JitterAnalysisConfig,
44
+ JitterbugConfig,
45
+ LatencyJump,
46
+ LatencyJumpConfig,
47
+ MinimumRTTDataset,
48
+ RTTDataset,
49
+ RTTMeasurement,
50
+ )
51
+
52
+ try:
53
+ __version__ = _pkg_version("jitterbug-inference") # the distribution, not the package
54
+ except PackageNotFoundError: # running from a source tree without an install
55
+ __version__ = "0.0.0+unknown"
56
+ __author__ = "Esteban Carisimo"
57
+ __email__ = "esteban.carisimo@northwestern.edu"
58
+
59
+ __all__ = [
60
+ # Main analyzer
61
+ "JitterbugAnalyzer",
62
+ # Data models
63
+ "RTTMeasurement",
64
+ "RTTDataset",
65
+ "MinimumRTTDataset",
66
+ # Analysis models
67
+ "ChangePoint",
68
+ "LatencyJump",
69
+ "JitterAnalysis",
70
+ "CongestionInference",
71
+ "CongestionInferenceResult",
72
+ # Configuration models
73
+ "JitterbugConfig",
74
+ "ChangePointDetectionConfig",
75
+ "JitterAnalysisConfig",
76
+ "LatencyJumpConfig",
77
+ "DataProcessingConfig",
78
+ ]
@@ -0,0 +1,13 @@
1
+ """
2
+ Analysis modules for Jitterbug.
3
+ """
4
+
5
+ from .congestion_inference_analyzer import CongestionInferenceAnalyzer
6
+ from .jitter_analyzer import JitterAnalyzer
7
+ from .latency_jump_analyzer import LatencyJumpAnalyzer
8
+
9
+ __all__ = [
10
+ "JitterAnalyzer",
11
+ "LatencyJumpAnalyzer",
12
+ "CongestionInferenceAnalyzer",
13
+ ]
@@ -0,0 +1,158 @@
1
+ """
2
+ Congestion inference analysis implementation.
3
+ """
4
+
5
+ import logging
6
+
7
+ import numpy as np
8
+
9
+ from ..models import CongestionInference, JitterAnalysis, LatencyJump
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class CongestionInferenceAnalyzer:
15
+ """
16
+ Analyzer for inferring congestion based on latency jumps and jitter analysis.
17
+
18
+ Combines results from latency jump detection and jitter analysis to make
19
+ final congestion inferences.
20
+ """
21
+
22
+ def __init__(self) -> None:
23
+ """Initialize the congestion inference analyzer."""
24
+
25
+ def infer(
26
+ self, latency_jumps: list[LatencyJump], jitter_analyses: list[JitterAnalysis]
27
+ ) -> list[CongestionInference]:
28
+ """
29
+ Infer congestion periods based on latency jumps and jitter analysis.
30
+
31
+ Uses the original v1 stateful congestion inference logic:
32
+ - Congestion = True when BOTH latency jump AND jitter are detected
33
+ - Congestion = False when there's NO latency jump (regardless of jitter)
34
+ - Maintains congestion state between periods
35
+
36
+ Parameters
37
+ ----------
38
+ latency_jumps : List[LatencyJump]
39
+ List of latency jump analysis results.
40
+ jitter_analyses : List[JitterAnalysis]
41
+ List of jitter analysis results.
42
+
43
+ Returns
44
+ -------
45
+ List[CongestionInference]
46
+ List of congestion inference results.
47
+ """
48
+ logger.info("Inferring congestion periods")
49
+
50
+ if not latency_jumps or not jitter_analyses:
51
+ logger.warning("No latency jumps or jitter analyses available")
52
+ return []
53
+
54
+ # Match latency jumps with jitter analyses
55
+ matched_pairs = []
56
+ for jump in latency_jumps:
57
+ # Find corresponding jitter analysis
58
+ corresponding_jitter = None
59
+ for jitter in jitter_analyses:
60
+ if (
61
+ abs(jump.start_epoch - jitter.start_epoch) < 1
62
+ and abs(jump.end_epoch - jitter.end_epoch) < 1
63
+ ):
64
+ corresponding_jitter = jitter
65
+ break
66
+
67
+ if corresponding_jitter is None:
68
+ logger.warning(
69
+ "No corresponding jitter analysis found for jump "
70
+ f"{jump.start_epoch}-{jump.end_epoch}"
71
+ )
72
+ continue
73
+
74
+ matched_pairs.append((jump, corresponding_jitter))
75
+
76
+ if not matched_pairs:
77
+ logger.warning("No matched pairs of latency jumps and jitter analyses")
78
+ return []
79
+
80
+ # Apply exact v1-style stateful congestion inference
81
+ inferences = []
82
+ congestion_state = False # Track congestion state across periods
83
+
84
+ for jump, jitter in matched_pairs:
85
+ # Exact v1 logic from cong_inference.py lines 49-52
86
+ if jump.has_jump and jitter.has_significant_jitter:
87
+ # Both latency jump AND jitter detected -> congestion = True
88
+ congestion_state = True
89
+ elif not jump.has_jump:
90
+ # No latency jump -> congestion = False (regardless of jitter)
91
+ congestion_state = False
92
+ # else: jump but no jitter -> maintain previous congestion state (no change)
93
+
94
+ # Calculate confidence
95
+ if congestion_state:
96
+ confidence = 0.8
97
+ if jump.magnitude > jump.threshold * 2:
98
+ confidence += 0.1
99
+ confidence = min(1.0, confidence)
100
+ else:
101
+ confidence = 0.0
102
+
103
+ inference = CongestionInference(
104
+ start_timestamp=jump.start_timestamp,
105
+ end_timestamp=jump.end_timestamp,
106
+ start_epoch=jump.start_epoch,
107
+ end_epoch=jump.end_epoch,
108
+ is_congested=congestion_state,
109
+ confidence=confidence,
110
+ latency_jump=jump,
111
+ jitter_analysis=jitter,
112
+ )
113
+
114
+ inferences.append(inference)
115
+
116
+ return inferences
117
+
118
+ def get_inference_statistics(self, inferences: list[CongestionInference]) -> dict:
119
+ """
120
+ Calculate statistics for congestion inferences.
121
+
122
+ Parameters
123
+ ----------
124
+ inferences : List[CongestionInference]
125
+ List of congestion inference results.
126
+
127
+ Returns
128
+ -------
129
+ dict
130
+ Dictionary containing inference statistics.
131
+ """
132
+ if not inferences:
133
+ return {
134
+ "total_periods": 0,
135
+ "congested_periods": 0,
136
+ "congestion_ratio": 0.0,
137
+ "average_confidence": 0.0,
138
+ "total_duration": 0.0,
139
+ "congestion_duration": 0.0,
140
+ }
141
+
142
+ congested_periods = [inf for inf in inferences if inf.is_congested]
143
+ total_duration = sum(inf.end_epoch - inf.start_epoch for inf in inferences)
144
+ congestion_duration = sum(inf.end_epoch - inf.start_epoch for inf in congested_periods)
145
+
146
+ return {
147
+ "total_periods": len(inferences),
148
+ "congested_periods": len(congested_periods),
149
+ "congestion_ratio": len(congested_periods) / len(inferences),
150
+ "average_confidence": float(np.mean([inf.confidence for inf in congested_periods]))
151
+ if congested_periods
152
+ else 0.0,
153
+ "total_duration": total_duration,
154
+ "congestion_duration": congestion_duration,
155
+ "congestion_time_ratio": congestion_duration / total_duration
156
+ if total_duration > 0
157
+ else 0.0,
158
+ }
@@ -0,0 +1,303 @@
1
+ """
2
+ Jitter analysis implementation.
3
+ """
4
+
5
+ import logging
6
+
7
+ import numpy as np
8
+ import scipy.stats
9
+
10
+ from ..models import (
11
+ ChangePoint,
12
+ JitterAnalysis,
13
+ JitterAnalysisConfig,
14
+ MinimumRTTDataset,
15
+ RTTDataset,
16
+ )
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ class JitterAnalyzer:
22
+ """
23
+ Analyzer for jitter-based congestion detection.
24
+
25
+ Supports two methods:
26
+ 1. Jitter dispersion analysis
27
+ 2. Kolmogorov-Smirnov test
28
+
29
+ Parameters
30
+ ----------
31
+ config : JitterAnalysisConfig
32
+ Configuration for jitter analysis.
33
+ """
34
+
35
+ def __init__(self, config: JitterAnalysisConfig):
36
+ """
37
+ Initialize the jitter analyzer.
38
+
39
+ Parameters
40
+ ----------
41
+ config : JitterAnalysisConfig
42
+ Configuration for jitter analysis.
43
+ """
44
+ self.config = config
45
+
46
+ def analyze_jitter_dispersion(
47
+ self, dataset: MinimumRTTDataset, change_points: list[ChangePoint]
48
+ ) -> list[JitterAnalysis]:
49
+ """
50
+ Analyze jitter using dispersion method.
51
+
52
+ Parameters
53
+ ----------
54
+ dataset : MinimumRTTDataset
55
+ Dataset containing minimum RTT values.
56
+ change_points : List[ChangePoint]
57
+ List of detected change points.
58
+
59
+ Returns
60
+ -------
61
+ List[JitterAnalysis]
62
+ List of jitter analysis results.
63
+ """
64
+ logger.info("Analyzing jitter using dispersion method")
65
+
66
+ if len(change_points) < 2:
67
+ logger.warning("Need at least 2 change points for jitter analysis")
68
+ return []
69
+
70
+ # Convert to arrays
71
+ epochs, rtt_values = dataset.to_arrays()
72
+
73
+ # Compute jitter dispersion
74
+ jitter_epochs, jitter_dispersion = self._compute_jitter_dispersion(epochs, rtt_values)
75
+
76
+ # Analyze jitter for each period between change points
77
+ results = []
78
+
79
+ for i in range(len(change_points) - 1):
80
+ start_cp = change_points[i]
81
+ end_cp = change_points[i + 1]
82
+
83
+ # Get jitter values for this period
84
+ period_mask = (jitter_epochs >= start_cp.epoch) & (jitter_epochs <= end_cp.epoch)
85
+
86
+ if np.sum(period_mask) < 2:
87
+ continue
88
+
89
+ period_jitter = jitter_dispersion[period_mask]
90
+
91
+ # Compare with previous period if available
92
+ if i > 0:
93
+ prev_cp = change_points[i - 1]
94
+ prev_mask = (jitter_epochs >= prev_cp.epoch) & (jitter_epochs < start_cp.epoch)
95
+
96
+ if np.sum(prev_mask) > 0:
97
+ prev_jitter = jitter_dispersion[prev_mask]
98
+
99
+ # Test for significant increase (original v1 logic)
100
+ mean_increase = np.mean(period_jitter) > (
101
+ np.mean(prev_jitter) + self.config.threshold
102
+ )
103
+ jitter_metric = np.mean(period_jitter) - np.mean(prev_jitter)
104
+
105
+ results.append(
106
+ JitterAnalysis(
107
+ start_timestamp=start_cp.timestamp,
108
+ end_timestamp=end_cp.timestamp,
109
+ start_epoch=start_cp.epoch,
110
+ end_epoch=end_cp.epoch,
111
+ has_significant_jitter=mean_increase,
112
+ jitter_metric=float(jitter_metric),
113
+ method="jitter_dispersion",
114
+ threshold=self.config.threshold,
115
+ )
116
+ )
117
+
118
+ return results
119
+
120
+ def analyze_ks_test(
121
+ self, dataset: RTTDataset, change_points: list[ChangePoint]
122
+ ) -> list[JitterAnalysis]:
123
+ """
124
+ Analyze jitter using Kolmogorov-Smirnov test.
125
+
126
+ Parameters
127
+ ----------
128
+ dataset : RTTDataset
129
+ Dataset containing RTT measurements.
130
+ change_points : List[ChangePoint]
131
+ List of detected change points.
132
+
133
+ Returns
134
+ -------
135
+ List[JitterAnalysis]
136
+ List of jitter analysis results.
137
+ """
138
+ logger.info("Analyzing jitter using Kolmogorov-Smirnov test")
139
+
140
+ if len(change_points) < 2:
141
+ logger.warning("Need at least 2 change points for jitter analysis")
142
+ return []
143
+
144
+ # Convert to arrays
145
+ epochs, rtt_values = dataset.to_arrays()
146
+
147
+ # Compute jitter
148
+ jitter_epochs, jitter_values = self._compute_jitter(epochs, rtt_values)
149
+
150
+ # Analyze jitter for each period between change points
151
+ results = []
152
+
153
+ for i in range(len(change_points) - 1):
154
+ start_cp = change_points[i]
155
+ end_cp = change_points[i + 1]
156
+
157
+ # Get jitter values for this period
158
+ period_mask = (jitter_epochs >= start_cp.epoch) & (jitter_epochs <= end_cp.epoch)
159
+
160
+ if np.sum(period_mask) < 2:
161
+ continue
162
+
163
+ period_jitter = jitter_values[period_mask]
164
+
165
+ # Compare with previous period if available
166
+ if i > 0:
167
+ prev_cp = change_points[i - 1]
168
+ prev_mask = (jitter_epochs >= prev_cp.epoch) & (jitter_epochs < start_cp.epoch)
169
+
170
+ if np.sum(prev_mask) > 0:
171
+ prev_jitter = jitter_values[prev_mask]
172
+
173
+ # Perform KS test (original v1 logic)
174
+ try:
175
+ ks_stat, p_value = scipy.stats.ks_2samp(prev_jitter, period_jitter)
176
+ has_significant_jitter = p_value < self.config.significance_level
177
+
178
+ results.append(
179
+ JitterAnalysis(
180
+ start_timestamp=start_cp.timestamp,
181
+ end_timestamp=end_cp.timestamp,
182
+ start_epoch=start_cp.epoch,
183
+ end_epoch=end_cp.epoch,
184
+ has_significant_jitter=has_significant_jitter,
185
+ jitter_metric=float(ks_stat),
186
+ method="ks_test",
187
+ threshold=self.config.significance_level,
188
+ p_value=float(p_value),
189
+ )
190
+ )
191
+
192
+ except ValueError as e: # scipy: degenerate or empty samples
193
+ logger.warning(f"KS test failed for period {i}: {e}")
194
+ continue
195
+
196
+ return results
197
+
198
+ def _compute_jitter(self, epochs: np.ndarray, rtt_values: np.ndarray) -> tuple:
199
+ """
200
+ Compute jitter values from RTT measurements.
201
+
202
+ Parameters
203
+ ----------
204
+ epochs : np.ndarray
205
+ Epoch timestamps.
206
+ rtt_values : np.ndarray
207
+ RTT values.
208
+
209
+ Returns
210
+ -------
211
+ tuple
212
+ Tuple of (jitter_epochs, jitter_values).
213
+ """
214
+ if len(epochs) < 2:
215
+ raise ValueError("Need at least 2 samples to compute jitter")
216
+
217
+ # Jitter is the difference between consecutive RTT measurements
218
+ jitter_epochs = epochs[1:]
219
+ jitter_values = rtt_values[1:] - rtt_values[:-1]
220
+
221
+ return jitter_epochs, jitter_values
222
+
223
+ def _compute_jitter_dispersion(self, epochs: np.ndarray, rtt_values: np.ndarray) -> tuple:
224
+ """
225
+ Compute jitter dispersion using moving average and IQR filtering.
226
+
227
+ Parameters
228
+ ----------
229
+ epochs : np.ndarray
230
+ Epoch timestamps.
231
+ rtt_values : np.ndarray
232
+ RTT values.
233
+
234
+ Returns
235
+ -------
236
+ tuple
237
+ Tuple of (dispersion_epochs, dispersion_values).
238
+ """
239
+ # First compute basic jitter
240
+ jitter_epochs, jitter_values = self._compute_jitter(epochs, rtt_values)
241
+
242
+ # Apply moving IQR filter
243
+ filtered_jitter = self._moving_iqr_filter(jitter_values, self.config.moving_iqr_order)
244
+
245
+ # Apply moving average filter
246
+ final_jitter = self._moving_average_filter(
247
+ filtered_jitter, self.config.moving_average_order
248
+ )
249
+
250
+ # Adjust epochs for filter lengths
251
+ filter_offset = self.config.moving_iqr_order + self.config.moving_average_order // 2
252
+ final_epochs = jitter_epochs[filter_offset : filter_offset + len(final_jitter)]
253
+
254
+ return final_epochs, final_jitter
255
+
256
+ def _moving_iqr_filter(self, values: np.ndarray, window_size: int) -> np.ndarray:
257
+ """
258
+ Apply moving IQR filter to values.
259
+
260
+ Parameters
261
+ ----------
262
+ values : np.ndarray
263
+ Input values.
264
+ window_size : int
265
+ Window size for IQR calculation.
266
+
267
+ Returns
268
+ -------
269
+ np.ndarray
270
+ Filtered values.
271
+ """
272
+ if len(values) < window_size * 2 + 1:
273
+ return np.array([])
274
+
275
+ iqr_values = []
276
+
277
+ for i in range(window_size, len(values) - window_size):
278
+ window = values[i - window_size : i + window_size + 1]
279
+ q1, q3 = np.percentile(window, [25, 75])
280
+ iqr_values.append(q3 - q1)
281
+
282
+ return np.array(iqr_values)
283
+
284
+ def _moving_average_filter(self, values: np.ndarray, window_size: int) -> np.ndarray:
285
+ """
286
+ Apply moving average filter to values.
287
+
288
+ Parameters
289
+ ----------
290
+ values : np.ndarray
291
+ Input values.
292
+ window_size : int
293
+ Window size for moving average.
294
+
295
+ Returns
296
+ -------
297
+ np.ndarray
298
+ Filtered values.
299
+ """
300
+ if len(values) < window_size:
301
+ return np.array([])
302
+
303
+ return np.convolve(values, np.ones(window_size) / window_size, mode="valid")
@@ -0,0 +1,150 @@
1
+ """
2
+ Latency jump analysis implementation.
3
+ """
4
+
5
+ import logging
6
+
7
+ import numpy as np
8
+
9
+ from ..models import (
10
+ ChangePoint,
11
+ LatencyJump,
12
+ LatencyJumpConfig,
13
+ MinimumRTTDataset,
14
+ )
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class LatencyJumpAnalyzer:
20
+ """
21
+ Analyzer for detecting significant latency jumps.
22
+
23
+ Identifies periods where the baseline latency increases significantly
24
+ compared to the previous period.
25
+
26
+ Parameters
27
+ ----------
28
+ config : LatencyJumpConfig
29
+ Configuration for latency jump analysis.
30
+ """
31
+
32
+ def __init__(self, config: LatencyJumpConfig):
33
+ """
34
+ Initialize the latency jump analyzer.
35
+
36
+ Parameters
37
+ ----------
38
+ config : LatencyJumpConfig
39
+ Configuration for latency jump analysis.
40
+ """
41
+ self.config = config
42
+
43
+ def analyze(
44
+ self, dataset: MinimumRTTDataset, change_points: list[ChangePoint]
45
+ ) -> list[LatencyJump]:
46
+ """
47
+ Analyze latency jumps between change points.
48
+
49
+ Parameters
50
+ ----------
51
+ dataset : MinimumRTTDataset
52
+ Dataset containing minimum RTT values.
53
+ change_points : List[ChangePoint]
54
+ List of detected change points.
55
+
56
+ Returns
57
+ -------
58
+ List[LatencyJump]
59
+ List of latency jump analysis results.
60
+ """
61
+ logger.info("Analyzing latency jumps")
62
+
63
+ if len(change_points) < 2:
64
+ logger.warning("Need at least 2 change points for latency jump analysis")
65
+ return []
66
+
67
+ # Convert to arrays
68
+ epochs, rtt_values = dataset.to_arrays()
69
+
70
+ # Analyze jumps for each period between change points
71
+ results = []
72
+
73
+ for i in range(len(change_points) - 1):
74
+ start_cp = change_points[i]
75
+ end_cp = change_points[i + 1]
76
+
77
+ # Get RTT values for this period
78
+ period_mask = (epochs >= start_cp.epoch) & (epochs <= end_cp.epoch)
79
+
80
+ if np.sum(period_mask) < 1:
81
+ continue
82
+
83
+ period_rtt = rtt_values[period_mask]
84
+
85
+ # Compare with previous period if available
86
+ if i > 0:
87
+ prev_cp = change_points[i - 1]
88
+ prev_mask = (epochs >= prev_cp.epoch) & (epochs < start_cp.epoch)
89
+
90
+ if np.sum(prev_mask) > 0:
91
+ prev_rtt = rtt_values[prev_mask]
92
+
93
+ # Calculate mean RTT for both periods
94
+ mean_prev = np.mean(prev_rtt)
95
+ mean_current = np.mean(period_rtt)
96
+
97
+ # Check for significant jump
98
+ magnitude = mean_current - mean_prev
99
+ has_jump = magnitude > self.config.threshold
100
+
101
+ results.append(
102
+ LatencyJump(
103
+ start_timestamp=start_cp.timestamp,
104
+ end_timestamp=end_cp.timestamp,
105
+ start_epoch=start_cp.epoch,
106
+ end_epoch=end_cp.epoch,
107
+ has_jump=has_jump,
108
+ magnitude=float(magnitude),
109
+ threshold=self.config.threshold,
110
+ )
111
+ )
112
+
113
+ return results
114
+
115
+ def get_jump_statistics(self, latency_jumps: list[LatencyJump]) -> dict:
116
+ """
117
+ Calculate statistics for latency jumps.
118
+
119
+ Parameters
120
+ ----------
121
+ latency_jumps : List[LatencyJump]
122
+ List of latency jump results.
123
+
124
+ Returns
125
+ -------
126
+ dict
127
+ Dictionary containing jump statistics.
128
+ """
129
+ if not latency_jumps:
130
+ return {
131
+ "total_periods": 0,
132
+ "jump_periods": 0,
133
+ "jump_ratio": 0.0,
134
+ "average_magnitude": 0.0,
135
+ "max_magnitude": 0.0,
136
+ "min_magnitude": 0.0,
137
+ }
138
+
139
+ jump_periods = [jump for jump in latency_jumps if jump.has_jump]
140
+ magnitudes = [jump.magnitude for jump in latency_jumps if jump.has_jump]
141
+
142
+ return {
143
+ "total_periods": len(latency_jumps),
144
+ "jump_periods": len(jump_periods),
145
+ "jump_ratio": len(jump_periods) / len(latency_jumps),
146
+ "average_magnitude": float(np.mean(magnitudes)) if magnitudes else 0.0,
147
+ "max_magnitude": float(np.max(magnitudes)) if magnitudes else 0.0,
148
+ "min_magnitude": float(np.min(magnitudes)) if magnitudes else 0.0,
149
+ "threshold_used": self.config.threshold,
150
+ }