count-ts-window-selector 0.2.0__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.
@@ -0,0 +1,1578 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import csv
5
+ import json
6
+ import re
7
+ from dataclasses import asdict, dataclass
8
+ from datetime import date, datetime, time, timedelta
9
+ from pathlib import Path
10
+ from typing import Any, Iterable, Mapping, Sequence
11
+
12
+ import numpy as np
13
+ from scipy import stats
14
+
15
+ DEFAULT_DATA_DIR = Path(__file__).resolve().parents[2] / "data"
16
+
17
+ __all__ = [
18
+ "DataSuitabilityError",
19
+ "CandidateWindowError",
20
+ "NoPoissonCompatibleWindowError",
21
+ "HorizonBoundaryError",
22
+ "WindowSelectionConfig",
23
+ "HorizonRecommendationConfig",
24
+ "check_data_suitability",
25
+ "filter_candidate_windows",
26
+ "aggregate_counts_by_window",
27
+ "compute_fano_factor",
28
+ "compute_fano_confidence_interval",
29
+ "select_time_window",
30
+ "extract_horizon",
31
+ "evaluate_horizon",
32
+ "rank_accepted_windows",
33
+ "build_arrival_intensity_series",
34
+ "save_tseda_arrival_intensity_series",
35
+ "plot_arrival_intensity",
36
+ "tune_horizon_windows",
37
+ "recommend_optimal_horizon",
38
+ "build_daily_window_table",
39
+ "teseda_export",
40
+ "main",
41
+ ]
42
+
43
+
44
+ class DataSuitabilityError(ValueError):
45
+ """Raised when a series is not suitable for the non-hurdle workflow."""
46
+
47
+
48
+ class CandidateWindowError(ValueError):
49
+ """Raised when user-provided candidate windows do not meet coverage requirements."""
50
+
51
+
52
+ class NoPoissonCompatibleWindowError(ValueError):
53
+ """Raised when no Poisson-compatible time window remains after filtering."""
54
+
55
+
56
+ class HorizonBoundaryError(ValueError):
57
+ """Raised when a requested horizon is not fully covered by the dataset."""
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class WindowSelectionConfig:
62
+ """Configuration for suitability checks, feature filtering, and interval tests."""
63
+
64
+ min_event_rate: float = 5.0
65
+ max_zero_window_proportion: float = 0.1
66
+ min_windows: int = 30
67
+ confidence_level: float = 0.90
68
+
69
+ def __post_init__(self) -> None:
70
+ if self.min_event_rate <= 0:
71
+ raise ValueError("min_event_rate must be positive.")
72
+ if not 0.0 <= self.max_zero_window_proportion <= 1.0:
73
+ raise ValueError("max_zero_window_proportion must be between 0 and 1.")
74
+ if self.min_windows <= 0:
75
+ raise ValueError("min_windows must be positive.")
76
+ if not 0.0 < self.confidence_level < 1.0:
77
+ raise ValueError("confidence_level must be between 0 and 1.")
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class HorizonRecommendationConfig:
82
+ """Reliability gates and tie-breakers for horizon recommendations."""
83
+
84
+ min_valid_horizon_proportion: float = 0.80
85
+ min_valid_horizons: int = 10
86
+ acceptance_rate_tolerance: float = 0.02
87
+ prefer_shorter_horizon: bool = True
88
+
89
+ def __post_init__(self) -> None:
90
+ if not 0.0 < self.min_valid_horizon_proportion <= 1.0:
91
+ raise ValueError("min_valid_horizon_proportion must be in (0, 1].")
92
+ if self.min_valid_horizons <= 0:
93
+ raise ValueError("min_valid_horizons must be positive.")
94
+ if self.acceptance_rate_tolerance < 0:
95
+ raise ValueError("acceptance_rate_tolerance must be non-negative.")
96
+
97
+
98
+ def _coerce_count_series(series: Sequence[float] | Iterable[float] | np.ndarray) -> np.ndarray:
99
+ counts = np.asarray(list(series), dtype=float)
100
+ if counts.ndim == 0:
101
+ counts = counts.reshape(1)
102
+ if counts.size == 0:
103
+ raise ValueError("The count time series is empty.")
104
+ if np.any(~np.isfinite(counts)):
105
+ raise ValueError("The count time series contains NaN or infinite values.")
106
+ if np.any(counts < 0):
107
+ raise ValueError("The count time series contains negative counts; only non-negative counts are supported.")
108
+ return counts
109
+
110
+
111
+ def check_data_suitability(
112
+ series: Sequence[float] | Iterable[float] | np.ndarray,
113
+ *,
114
+ min_event_rate: float = 5.0,
115
+ max_zero_window_proportion: float = 0.1,
116
+ ) -> dict[str, float]:
117
+ """Validate that the series is dense enough for a non-hurdle Poisson workflow.
118
+
119
+ The method uses the raw observation interval as the zero-window scale before any
120
+ window aggregation is evaluated. This is the required first suitability screen.
121
+ """
122
+
123
+ counts = _coerce_count_series(series)
124
+ observed_event_rate = float(np.mean(counts))
125
+ zero_window_proportion = float(np.mean(counts == 0))
126
+
127
+ if observed_event_rate < min_event_rate:
128
+ raise DataSuitabilityError(
129
+ "Observed event rate "
130
+ f"({observed_event_rate:.3f}) is below min_event_rate ({min_event_rate}). "
131
+ "The data are too sparse for the current non-hurdle Poisson-based workflow. "
132
+ "Consider sparse, zero-heavy, or hurdle-type count models; hurdle support is forthcoming in this software."
133
+ )
134
+
135
+ if zero_window_proportion > max_zero_window_proportion:
136
+ raise DataSuitabilityError(
137
+ "Proportion of zero-count windows "
138
+ f"({zero_window_proportion:.3f}) exceeds max_zero_window_proportion ({max_zero_window_proportion:.3f}). "
139
+ "The data contain an excessive number of zeros for the current non-hurdle Poisson-based workflow. "
140
+ "Consider sparse, zero-heavy, or hurdle-type count models; hurdle support is forthcoming in this software."
141
+ )
142
+
143
+ return {
144
+ "observed_event_rate": observed_event_rate,
145
+ "zero_window_proportion": zero_window_proportion,
146
+ }
147
+
148
+
149
+ def filter_candidate_windows(
150
+ series: Sequence[float] | Iterable[float] | np.ndarray,
151
+ candidate_windows: Sequence[int] | Iterable[int],
152
+ *,
153
+ min_windows: int = 30,
154
+ ) -> list[int]:
155
+ """Keep only candidate window sizes that yield at least min_windows non-overlapping bins."""
156
+
157
+ counts = _coerce_count_series(series)
158
+ cleaned = []
159
+ for candidate in candidate_windows:
160
+ try:
161
+ window_size = int(candidate)
162
+ except (TypeError, ValueError) as exc:
163
+ raise CandidateWindowError(
164
+ f"Candidate micro-window {candidate!r} is not an integer."
165
+ ) from exc
166
+ if isinstance(candidate, bool) or float(candidate) != window_size:
167
+ raise CandidateWindowError(
168
+ f"Candidate micro-window {candidate!r} is not an integer."
169
+ )
170
+ if window_size <= 0:
171
+ raise CandidateWindowError(
172
+ f"Candidate micro-window {candidate!r} must be a positive integer."
173
+ )
174
+ if len(counts) // window_size >= min_windows:
175
+ cleaned.append(window_size)
176
+
177
+ if not cleaned:
178
+ raise CandidateWindowError(
179
+ f"Requested windows are too long for the available data length ({len(counts)} observations). "
180
+ f"The package requires at least {min_windows} non-overlapping windows for each candidate."
181
+ )
182
+
183
+ return sorted(set(cleaned))
184
+
185
+
186
+ def aggregate_counts_by_window(
187
+ series: Sequence[float] | Iterable[float] | np.ndarray,
188
+ window_size: int,
189
+ ) -> np.ndarray:
190
+ """Aggregate a count series into non-overlapping windows of the requested size."""
191
+
192
+ counts = _coerce_count_series(series)
193
+ if window_size <= 0:
194
+ raise ValueError("window_size must be a positive integer.")
195
+ if len(counts) < window_size:
196
+ raise CandidateWindowError(
197
+ f"Window size {window_size} exceeds the data length ({len(counts)} observations)."
198
+ )
199
+
200
+ n_windows = len(counts) // window_size
201
+ if n_windows < 1:
202
+ raise CandidateWindowError(
203
+ f"Window size {window_size} leaves no full non-overlapping windows for the input series."
204
+ )
205
+
206
+ truncated = counts[: n_windows * window_size]
207
+ grouped = truncated.reshape(n_windows, window_size)
208
+ return grouped.sum(axis=1)
209
+
210
+
211
+ def compute_fano_factor(windowed_counts: Sequence[float] | np.ndarray) -> dict[str, float]:
212
+ """Return the sample Fano factor and the associated mean and variance."""
213
+
214
+ counts = np.asarray(windowed_counts, dtype=float).reshape(-1)
215
+ if counts.size == 0:
216
+ raise ValueError("The aggregated count window is empty.")
217
+ if counts.size < 2:
218
+ raise ValueError("At least two aggregated window counts are required for a Fano-factor calculation.")
219
+ if np.any(counts < 0):
220
+ raise ValueError("Aggregated window counts must be non-negative.")
221
+
222
+ mean_count = float(np.mean(counts))
223
+ if mean_count <= 0:
224
+ raise ValueError("The mean aggregated count must be positive for a Fano-factor analysis.")
225
+
226
+ variance = float(np.var(counts, ddof=1))
227
+ fano_factor = variance / mean_count
228
+ return {
229
+ "mean_count": mean_count,
230
+ "variance": variance,
231
+ "fano_factor": fano_factor,
232
+ }
233
+
234
+
235
+ def compute_fano_confidence_interval(
236
+ windowed_counts: Sequence[float] | np.ndarray,
237
+ *,
238
+ confidence_level: float = 0.90,
239
+ ) -> dict[str, float]:
240
+ """Compute chi-square-based Fano bounds for a Poisson reference around 1."""
241
+
242
+ counts = np.asarray(windowed_counts, dtype=float).reshape(-1)
243
+ if counts.size < 2:
244
+ raise ValueError("At least two aggregated window counts are required for a confidence interval.")
245
+
246
+ alpha = 1.0 - confidence_level
247
+ degrees_of_freedom = counts.size - 1
248
+ if degrees_of_freedom <= 0:
249
+ raise ValueError("The number of aggregated windows must exceed 1 to compute a confidence interval.")
250
+
251
+ lower_quantile = stats.chi2.ppf(alpha / 2.0, degrees_of_freedom)
252
+ upper_quantile = stats.chi2.ppf(1.0 - alpha / 2.0, degrees_of_freedom)
253
+ lower_bound = float(lower_quantile / degrees_of_freedom)
254
+ upper_bound = float(upper_quantile / degrees_of_freedom)
255
+ return {
256
+ "fano_lower": lower_bound,
257
+ "fano_upper": upper_bound,
258
+ }
259
+
260
+
261
+ def select_time_window(
262
+ series: Sequence[float] | Iterable[float] | np.ndarray,
263
+ candidate_windows: Sequence[int] | Iterable[int],
264
+ *,
265
+ config: WindowSelectionConfig | None = None,
266
+ ) -> list[dict[str, float | int]]:
267
+ """Validate the series, filter candidate windows, and return Poisson-compatible windows.
268
+
269
+ The result is a list of dictionaries with keys: window_size, fano_factor,
270
+ fano_lower, and fano_upper.
271
+ """
272
+
273
+ if config is None:
274
+ config = WindowSelectionConfig()
275
+
276
+ counts = _coerce_count_series(series)
277
+ check_data_suitability(
278
+ counts,
279
+ min_event_rate=config.min_event_rate,
280
+ max_zero_window_proportion=config.max_zero_window_proportion,
281
+ )
282
+
283
+ valid_windows = filter_candidate_windows(
284
+ counts,
285
+ candidate_windows,
286
+ min_windows=config.min_windows,
287
+ )
288
+
289
+ acceptable_windows: list[dict[str, float | int]] = []
290
+ for window_size in valid_windows:
291
+ aggregated = aggregate_counts_by_window(counts, window_size)
292
+ fano_summary = compute_fano_factor(aggregated)
293
+ interval = compute_fano_confidence_interval(
294
+ aggregated,
295
+ confidence_level=config.confidence_level,
296
+ )
297
+ fano_value = float(fano_summary["fano_factor"])
298
+ fano_lower = float(interval["fano_lower"])
299
+ fano_upper = float(interval["fano_upper"])
300
+
301
+ if fano_lower <= fano_value <= fano_upper:
302
+ acceptable_windows.append(
303
+ {
304
+ "window_size": int(window_size),
305
+ "fano_factor": fano_value,
306
+ "fano_lower": fano_lower,
307
+ "fano_upper": fano_upper,
308
+ }
309
+ )
310
+
311
+ return acceptable_windows
312
+
313
+
314
+ _DURATION_PATTERN = re.compile(
315
+ r"^\s*(?P<value>\d+(?:\.\d+)?)\s*(?P<unit>d(?:ays?)?|h(?:ours?)?|m(?:in(?:utes?)?)?|s(?:ec(?:onds?)?)?)?\s*$",
316
+ re.IGNORECASE,
317
+ )
318
+
319
+
320
+ def _coerce_datetime(value: datetime | date | str, *, parameter: str) -> datetime:
321
+ if isinstance(value, datetime):
322
+ return value
323
+ if isinstance(value, date):
324
+ return datetime.combine(value, time.min)
325
+ if not isinstance(value, str):
326
+ raise TypeError(f"{parameter} must be a datetime, date, or ISO-8601 string.")
327
+ return _parse_timestamp(value)
328
+
329
+
330
+ def _coerce_duration(
331
+ value: timedelta | int | float | str,
332
+ *,
333
+ parameter: str,
334
+ numeric_unit: str,
335
+ ) -> timedelta:
336
+ if isinstance(value, timedelta):
337
+ result = value
338
+ elif isinstance(value, (int, float)) and not isinstance(value, bool):
339
+ multiplier = {"days": 86400.0, "hours": 3600.0, "minutes": 60.0, "seconds": 1.0}[numeric_unit]
340
+ result = timedelta(seconds=float(value) * multiplier)
341
+ elif isinstance(value, str):
342
+ match = _DURATION_PATTERN.fullmatch(value)
343
+ if match is None:
344
+ raise ValueError(
345
+ f"{parameter} must be a timedelta or a value such as '14 days', '2h', or '30m'."
346
+ )
347
+ amount = float(match.group("value"))
348
+ unit_text = (match.group("unit") or numeric_unit).lower()
349
+ if unit_text.startswith("d"):
350
+ result = timedelta(days=amount)
351
+ elif unit_text.startswith("h"):
352
+ result = timedelta(hours=amount)
353
+ elif unit_text.startswith("m"):
354
+ result = timedelta(minutes=amount)
355
+ else:
356
+ result = timedelta(seconds=amount)
357
+ else:
358
+ raise TypeError(f"{parameter} must be a timedelta, number, or duration string.")
359
+
360
+ if result <= timedelta(0):
361
+ raise ValueError(f"{parameter} must be positive.")
362
+ return result
363
+
364
+
365
+ def _iso_datetime(value: datetime) -> str:
366
+ return value.isoformat(timespec="seconds")
367
+
368
+
369
+ def _load_temporal_records(
370
+ data: str | Path | Sequence[datetime | Mapping[str, Any]] | Iterable[datetime | Mapping[str, Any]],
371
+ *,
372
+ datetime_column: str,
373
+ count_column: str | None,
374
+ ) -> tuple[list[datetime], list[float | None]]:
375
+ if isinstance(data, (str, Path)):
376
+ path = _resolve_data_file(data)
377
+ with path.open("r", newline="") as handle:
378
+ reader = csv.DictReader(handle)
379
+ if reader.fieldnames is None:
380
+ raise ValueError(f"The file {path} does not appear to contain a CSV header row.")
381
+ if datetime_column not in reader.fieldnames:
382
+ raise ValueError(
383
+ f"Expected a '{datetime_column}' column in {path}, found {reader.fieldnames}."
384
+ )
385
+ if count_column is not None and count_column not in reader.fieldnames:
386
+ raise ValueError(
387
+ f"Expected a '{count_column}' column in {path}, found {reader.fieldnames}."
388
+ )
389
+ raw_records: list[datetime | Mapping[str, Any]] = list(reader)
390
+ else:
391
+ raw_records = list(data)
392
+
393
+ timestamps: list[datetime] = []
394
+ values: list[float | None] = []
395
+ for record in raw_records:
396
+ if isinstance(record, datetime):
397
+ raw_timestamp = record
398
+ raw_count = None
399
+ elif isinstance(record, Mapping):
400
+ if datetime_column not in record:
401
+ raise ValueError(f"Record is missing the '{datetime_column}' datetime column.")
402
+ raw_timestamp = record[datetime_column]
403
+ raw_count = record.get(count_column) if count_column is not None else None
404
+ if count_column is not None and raw_count is None:
405
+ raise ValueError(f"Record is missing the '{count_column}' count column.")
406
+ else:
407
+ raise TypeError("Temporal data must contain datetime values or mappings with a datetime column.")
408
+
409
+ timestamp = _coerce_datetime(raw_timestamp, parameter=datetime_column)
410
+ timestamps.append(timestamp)
411
+ values.append(float(raw_count) if raw_count is not None else None)
412
+
413
+ if not timestamps:
414
+ raise ValueError("The temporal dataset is empty.")
415
+ awareness = [timestamp.utcoffset() is not None for timestamp in timestamps]
416
+ if any(awareness) and not all(awareness):
417
+ raise ValueError("The datetime column mixes timezone-aware and timezone-naive values.")
418
+
419
+ ordered = sorted(zip(timestamps, values), key=lambda item: item[0])
420
+ return [item[0] for item in ordered], [item[1] for item in ordered]
421
+
422
+
423
+ def extract_horizon(
424
+ data: str | Path | Sequence[datetime | Mapping[str, Any]] | Iterable[datetime | Mapping[str, Any]],
425
+ *,
426
+ start_date: datetime | date | str | None = None,
427
+ horizon_window: timedelta | int | float | str | None = None,
428
+ datetime_column: str = "timestamp",
429
+ count_column: str | None = None,
430
+ base_resolution: timedelta | int | float | str = "1h",
431
+ boundary_policy: str = "error",
432
+ ) -> dict[str, Any]:
433
+ """Extract a complete half-open horizon and aggregate it to a regular count grid."""
434
+
435
+ if boundary_policy not in {"error", "truncate"}:
436
+ raise ValueError("boundary_policy must be either 'error' or 'truncate'.")
437
+
438
+ resolution = _coerce_duration(
439
+ base_resolution,
440
+ parameter="base_resolution",
441
+ numeric_unit="hours",
442
+ )
443
+ timestamps, supplied_counts = _load_temporal_records(
444
+ data,
445
+ datetime_column=datetime_column,
446
+ count_column=count_column,
447
+ )
448
+ source_start = timestamps[0]
449
+ source_end = timestamps[-1]
450
+ is_full_range = horizon_window is None
451
+ inferred_full_start = is_full_range and start_date is None
452
+ if start_date is None:
453
+ requested_start = source_start
454
+ if is_full_range:
455
+ day_start = requested_start.replace(hour=0, minute=0, second=0, microsecond=0)
456
+ elapsed = (requested_start - day_start).total_seconds()
457
+ requested_start = day_start + timedelta(
458
+ seconds=(int(elapsed // resolution.total_seconds()) * resolution.total_seconds())
459
+ )
460
+ else:
461
+ requested_start = _coerce_datetime(start_date, parameter="start_date")
462
+ horizon = (
463
+ None
464
+ if horizon_window is None
465
+ else _coerce_duration(horizon_window, parameter="horizon_window", numeric_unit="days")
466
+ )
467
+ if is_full_range:
468
+ source_day_start = source_end.replace(hour=0, minute=0, second=0, microsecond=0)
469
+ elapsed_to_source_end = (source_end - source_day_start).total_seconds()
470
+ requested_end = source_day_start + timedelta(
471
+ seconds=(
472
+ int(elapsed_to_source_end // resolution.total_seconds()) + 1
473
+ )
474
+ * resolution.total_seconds()
475
+ )
476
+ else:
477
+ requested_end = requested_start + horizon # type: ignore[operator]
478
+
479
+ starts_before_source = requested_start < source_start and not inferred_full_start
480
+ ends_after_source = (
481
+ False
482
+ if is_full_range
483
+ else requested_end > source_end
484
+ )
485
+ if (starts_before_source or ends_after_source) and boundary_policy == "error":
486
+ raise HorizonBoundaryError(
487
+ f"Requested horizon [{_iso_datetime(requested_start)}, {_iso_datetime(requested_end)}) "
488
+ f"is not fully covered by the available bounds [{_iso_datetime(source_start)}, "
489
+ f"{_iso_datetime(source_end)}]."
490
+ )
491
+
492
+ actual_start = (
493
+ requested_start
494
+ if inferred_full_start
495
+ else max(requested_start, source_start)
496
+ )
497
+ available_end = requested_end if is_full_range else source_end
498
+ actual_end = min(requested_end, available_end)
499
+ if actual_end <= actual_start:
500
+ raise HorizonBoundaryError("The requested horizon does not overlap the available dataset.")
501
+
502
+ available_seconds = (actual_end - actual_start).total_seconds()
503
+ resolution_seconds = resolution.total_seconds()
504
+ complete_intervals = int(available_seconds // resolution_seconds)
505
+ remainder_seconds = available_seconds - complete_intervals * resolution_seconds
506
+ aggregated_end = actual_start + timedelta(seconds=complete_intervals * resolution_seconds)
507
+ if complete_intervals < 1:
508
+ raise HorizonBoundaryError(
509
+ "The requested horizon contains fewer than one complete base-resolution interval."
510
+ )
511
+
512
+ counts = np.zeros(complete_intervals, dtype=float)
513
+ selected_event_count = 0
514
+ for timestamp, supplied_count in zip(timestamps, supplied_counts):
515
+ if not (actual_start <= timestamp < aggregated_end):
516
+ continue
517
+ index = int((timestamp - actual_start).total_seconds() // resolution_seconds)
518
+ if index >= complete_intervals:
519
+ continue
520
+ increment = 1.0 if supplied_count is None else supplied_count
521
+ if not np.isfinite(increment) or increment < 0:
522
+ raise ValueError("Count values must be finite and non-negative.")
523
+ counts[index] += increment
524
+ selected_event_count += 1 if supplied_count is None else int(supplied_count)
525
+
526
+ boundary_metadata = {
527
+ "requested_start": _iso_datetime(requested_start),
528
+ "requested_end": _iso_datetime(requested_end),
529
+ "actual_start": _iso_datetime(actual_start),
530
+ "actual_end": _iso_datetime(aggregated_end),
531
+ "source_start": _iso_datetime(source_start),
532
+ "source_end": _iso_datetime(source_end),
533
+ "is_complete": is_full_range or not (starts_before_source or ends_after_source),
534
+ "truncated_prefix": (
535
+ _iso_datetime(source_start)
536
+ if starts_before_source and boundary_policy == "truncate"
537
+ else None
538
+ ),
539
+ "truncated_suffix": (
540
+ _iso_datetime(aggregated_end)
541
+ if ends_after_source and boundary_policy == "truncate"
542
+ else None
543
+ ),
544
+ "remainder_seconds": remainder_seconds,
545
+ }
546
+ interval_starts = [
547
+ actual_start + timedelta(seconds=index * resolution_seconds)
548
+ for index in range(complete_intervals)
549
+ ]
550
+ return {
551
+ "evaluation_mode": "full_range" if is_full_range else "horizon_scoped",
552
+ "start_date": boundary_metadata["actual_start"],
553
+ "end_date": boundary_metadata["actual_end"],
554
+ "requested_start_date": boundary_metadata["requested_start"],
555
+ "requested_end_date": boundary_metadata["requested_end"],
556
+ "horizon_window": str(horizon) if horizon is not None else None,
557
+ "evaluation_duration": str(aggregated_end - actual_start),
558
+ "base_resolution": str(resolution),
559
+ "base_resolution_seconds": resolution_seconds,
560
+ "is_complete": boundary_metadata["is_complete"],
561
+ "boundary_metadata": boundary_metadata,
562
+ "number_of_events": selected_event_count,
563
+ "number_of_base_intervals": complete_intervals,
564
+ "interval_starts": interval_starts,
565
+ "counts": counts.tolist(),
566
+ }
567
+
568
+
569
+ def evaluate_horizon(
570
+ data: str | Path | Sequence[datetime | Mapping[str, Any]] | Iterable[datetime | Mapping[str, Any]],
571
+ candidate_windows: Sequence[int] | Iterable[int],
572
+ *,
573
+ start_date: datetime | date | str | None = None,
574
+ horizon_window: timedelta | int | float | str | None = None,
575
+ datetime_column: str = "timestamp",
576
+ count_column: str | None = None,
577
+ base_resolution: timedelta | int | float | str = "1h",
578
+ boundary_policy: str = "error",
579
+ config: WindowSelectionConfig | None = None,
580
+ ) -> dict[str, Any]:
581
+ """Evaluate candidates within a bounded horizon or the full dataset range."""
582
+
583
+ if config is None:
584
+ config = WindowSelectionConfig()
585
+ horizon = extract_horizon(
586
+ data,
587
+ start_date=start_date,
588
+ horizon_window=horizon_window,
589
+ datetime_column=datetime_column,
590
+ count_column=count_column,
591
+ base_resolution=base_resolution,
592
+ boundary_policy=boundary_policy,
593
+ )
594
+ counts = np.asarray(horizon["counts"], dtype=float)
595
+ try:
596
+ suitability = check_data_suitability(
597
+ counts,
598
+ min_event_rate=config.min_event_rate,
599
+ max_zero_window_proportion=config.max_zero_window_proportion,
600
+ )
601
+ except DataSuitabilityError as exc:
602
+ mode = "Full-range" if horizon["evaluation_mode"] == "full_range" else "Horizon-scoped"
603
+ raise DataSuitabilityError(f"{mode} evaluation failed suitability screening: {exc}") from exc
604
+ requested_candidates: list[int] = []
605
+ for candidate in candidate_windows:
606
+ try:
607
+ window_size = int(candidate)
608
+ except (TypeError, ValueError) as exc:
609
+ raise CandidateWindowError(
610
+ f"Candidate micro-window {candidate!r} is not an integer."
611
+ ) from exc
612
+ if isinstance(candidate, bool) or float(candidate) != window_size or window_size <= 0:
613
+ raise CandidateWindowError(
614
+ f"Candidate micro-window {candidate!r} must be a positive integer."
615
+ )
616
+ requested_candidates.append(window_size)
617
+
618
+ valid_candidates = filter_candidate_windows(
619
+ counts,
620
+ requested_candidates,
621
+ min_windows=config.min_windows,
622
+ )
623
+ valid_set = set(valid_candidates)
624
+ rejected_candidates = [
625
+ {
626
+ "window_size": candidate,
627
+ "number_of_windows": len(counts) // candidate,
628
+ "required_windows": config.min_windows,
629
+ "reason": "insufficient_coverage",
630
+ }
631
+ for candidate in sorted(set(requested_candidates))
632
+ if candidate not in valid_set
633
+ ]
634
+
635
+ candidates: list[dict[str, Any]] = []
636
+ for window_size in valid_candidates:
637
+ aggregated = aggregate_counts_by_window(counts, window_size)
638
+ fano = compute_fano_factor(aggregated)
639
+ interval = compute_fano_confidence_interval(
640
+ aggregated,
641
+ confidence_level=config.confidence_level,
642
+ )
643
+ lower = float(interval["fano_lower"])
644
+ upper = float(interval["fano_upper"])
645
+ fano_value = float(fano["fano_factor"])
646
+ accepted = lower <= fano_value <= upper
647
+ candidates.append(
648
+ {
649
+ "window_size": int(window_size),
650
+ "number_of_windows": int(len(aggregated)),
651
+ "mean_count": float(fano["mean_count"]),
652
+ "sample_variance": float(fano["variance"]),
653
+ "variance": float(fano["variance"]),
654
+ "fano_factor": fano_value,
655
+ "fano_lower": lower,
656
+ "fano_upper": upper,
657
+ "confidence_band_width": upper - lower,
658
+ "confidence_level": config.confidence_level,
659
+ "accepted": accepted,
660
+ }
661
+ )
662
+
663
+ accepted_candidates = [candidate for candidate in candidates if candidate["accepted"]]
664
+ ranked_candidates = rank_accepted_windows(accepted_candidates)
665
+ diagnostics: dict[str, Any] = {"global_non_stationarity_suspected": False}
666
+ if (
667
+ horizon["evaluation_mode"] == "full_range"
668
+ and not accepted_candidates
669
+ and any(
670
+ float(candidate["fano_factor"]) > float(candidate["fano_upper"])
671
+ for candidate in candidates
672
+ )
673
+ ):
674
+ diagnostics = {
675
+ "global_non_stationarity_suspected": True,
676
+ "message": (
677
+ "No full-range candidate was accepted because observed dispersion exceeded "
678
+ "the Poisson upper bound. Global non-stationarity may have inflated the "
679
+ "sample variance; evaluate bounded local macro-horizons with the two-stage workflow."
680
+ ),
681
+ }
682
+ return {
683
+ **horizon,
684
+ "observed_event_rate": suitability["observed_event_rate"],
685
+ "zero_window_proportion": suitability["zero_window_proportion"],
686
+ "suitability_status": "suitable",
687
+ "suitability_diagnostics": suitability,
688
+ "min_windows": config.min_windows,
689
+ "confidence_level": config.confidence_level,
690
+ "requested_candidate_windows": requested_candidates,
691
+ "candidate_windows": candidates,
692
+ "valid_candidate_windows": valid_candidates,
693
+ "rejected_candidate_windows": rejected_candidates,
694
+ "accepted_windows": accepted_candidates,
695
+ "ranked_accepted_windows": ranked_candidates,
696
+ "selected_window": ranked_candidates[0] if ranked_candidates else None,
697
+ "poisson_compatible_window_found": bool(accepted_candidates),
698
+ "diagnostics": diagnostics,
699
+ }
700
+
701
+
702
+ def rank_accepted_windows(
703
+ accepted_windows: Sequence[Mapping[str, Any]] | Iterable[Mapping[str, Any]],
704
+ *,
705
+ prefer_shorter_window: bool = True,
706
+ ) -> list[dict[str, Any]]:
707
+ """Rank accepted candidates by dispersion, precision, and window-width policy."""
708
+
709
+ ranked = [dict(candidate) for candidate in accepted_windows]
710
+ for candidate in ranked:
711
+ missing = {
712
+ key
713
+ for key in (
714
+ "window_size",
715
+ "fano_factor",
716
+ "confidence_band_width",
717
+ )
718
+ if key not in candidate
719
+ }
720
+ if missing:
721
+ raise ValueError(
722
+ "Accepted-window diagnostics are missing required fields: "
723
+ + ", ".join(sorted(missing))
724
+ + "."
725
+ )
726
+
727
+ direction = 1 if prefer_shorter_window else -1
728
+ ranked.sort(
729
+ key=lambda candidate: (
730
+ abs(float(candidate["fano_factor"]) - 1.0),
731
+ float(candidate["confidence_band_width"]),
732
+ direction * int(candidate["window_size"]),
733
+ )
734
+ )
735
+ return ranked
736
+
737
+
738
+ def build_arrival_intensity_series(
739
+ data: str | Path | Sequence[datetime | Mapping[str, Any]] | Iterable[datetime | Mapping[str, Any]],
740
+ *,
741
+ window_size: int,
742
+ start_date: datetime | date | str | None = None,
743
+ horizon_window: timedelta | int | float | str | None = None,
744
+ datetime_column: str = "timestamp",
745
+ count_column: str | None = None,
746
+ base_resolution: timedelta | int | float | str = "1h",
747
+ boundary_policy: str = "error",
748
+ rate_unit: str = "hour",
749
+ ) -> dict[str, Any]:
750
+ """Build chronological non-overlapping arrival rates for a selected window."""
751
+
752
+ if isinstance(window_size, bool) or not isinstance(window_size, (int, np.integer)):
753
+ raise ValueError("window_size must be a positive integer.")
754
+ if window_size <= 0:
755
+ raise ValueError("window_size must be a positive integer.")
756
+
757
+ horizon = extract_horizon(
758
+ data,
759
+ start_date=start_date,
760
+ horizon_window=horizon_window,
761
+ datetime_column=datetime_column,
762
+ count_column=count_column,
763
+ base_resolution=base_resolution,
764
+ boundary_policy=boundary_policy,
765
+ )
766
+ counts = np.asarray(horizon["counts"], dtype=float)
767
+ aggregated = aggregate_counts_by_window(counts, int(window_size))
768
+ complete_windows = len(aggregated)
769
+ window_duration_seconds = float(horizon["base_resolution_seconds"]) * int(window_size)
770
+ rate_units = {
771
+ "second": 1.0,
772
+ "minute": 60.0,
773
+ "hour": 3600.0,
774
+ "day": 86400.0,
775
+ }
776
+ if rate_unit not in rate_units:
777
+ raise ValueError("rate_unit must be one of: second, minute, hour, day.")
778
+ normalizer = window_duration_seconds / rate_units[rate_unit]
779
+ rows = [
780
+ {
781
+ "window_start": horizon["interval_starts"][
782
+ index * int(window_size)
783
+ ].isoformat(timespec="seconds"),
784
+ "window_midpoint": (
785
+ horizon["interval_starts"][index * int(window_size)]
786
+ + timedelta(seconds=window_duration_seconds / 2.0)
787
+ ).isoformat(timespec="seconds"),
788
+ "arrival_intensity": float(value / normalizer),
789
+ }
790
+ for index, value in enumerate(aggregated)
791
+ ]
792
+ return {
793
+ "evaluation_mode": horizon["evaluation_mode"],
794
+ "start_date": horizon["start_date"],
795
+ "end_date": horizon["end_date"],
796
+ "window_size": int(window_size),
797
+ "base_resolution": horizon["base_resolution"],
798
+ "sampling_period_seconds": window_duration_seconds,
799
+ "sampling_period": str(timedelta(seconds=window_duration_seconds)),
800
+ "intensity_unit": f"arrivals per {rate_unit}",
801
+ "number_of_complete_windows": complete_windows,
802
+ "remainder_base_intervals": len(counts) - complete_windows * int(window_size),
803
+ "rows": rows,
804
+ "columns": ["window_start", "window_midpoint", "arrival_intensity"],
805
+ }
806
+
807
+
808
+ def save_tseda_arrival_intensity_series(
809
+ data: str | Path | Sequence[datetime | Mapping[str, Any]] | Iterable[datetime | Mapping[str, Any]],
810
+ *,
811
+ window_size: int,
812
+ output_path: str | Path,
813
+ start_date: datetime | date | str | None = None,
814
+ horizon_window: timedelta | int | float | str | None = None,
815
+ datetime_column: str = "timestamp",
816
+ count_column: str | None = None,
817
+ base_resolution: timedelta | int | float | str = "1h",
818
+ boundary_policy: str = "error",
819
+ rate_unit: str = "hour",
820
+ ) -> dict[str, Any]:
821
+ """Save one selected-window intensity trajectory as a TSEDA two-column CSV."""
822
+
823
+ summary = build_arrival_intensity_series(
824
+ data,
825
+ window_size=window_size,
826
+ start_date=start_date,
827
+ horizon_window=horizon_window,
828
+ datetime_column=datetime_column,
829
+ count_column=count_column,
830
+ base_resolution=base_resolution,
831
+ boundary_policy=boundary_policy,
832
+ rate_unit=rate_unit,
833
+ )
834
+ destination = Path(output_path)
835
+ destination.parent.mkdir(parents=True, exist_ok=True)
836
+ with destination.open("w", newline="") as handle:
837
+ writer = csv.writer(handle)
838
+ writer.writerow(["window_midpoint", "arrival_intensity"])
839
+ for row in summary["rows"]:
840
+ writer.writerow([row["window_midpoint"], row["arrival_intensity"]])
841
+ return {
842
+ **summary,
843
+ "output_file": str(destination),
844
+ "timestamp_coordinate": "window_midpoint",
845
+ "columns": ["window_midpoint", "arrival_intensity"],
846
+ "number_of_exported_rows": len(summary["rows"]),
847
+ }
848
+
849
+
850
+ def plot_arrival_intensity(
851
+ intensity_series: Mapping[str, Any] | Sequence[Mapping[str, Any]],
852
+ *,
853
+ output_path: str | Path | None = None,
854
+ title: str | None = None,
855
+ show: bool = False,
856
+ ) -> Any:
857
+ """Plot a chronological arrival-intensity series and optionally save it."""
858
+
859
+ if isinstance(intensity_series, Mapping):
860
+ raw_rows = intensity_series.get("rows")
861
+ if raw_rows is None:
862
+ raise ValueError("The intensity-series mapping must contain a 'rows' field.")
863
+ intensity_unit = intensity_series.get("intensity_unit", "arrivals per time unit")
864
+ rows = list(raw_rows)
865
+ else:
866
+ rows = list(intensity_series)
867
+ intensity_unit = "arrivals per time unit"
868
+ if not rows:
869
+ raise ValueError("The arrival-intensity series is empty.")
870
+ try:
871
+ time_coordinate = (
872
+ "window_midpoint"
873
+ if "window_midpoint" in rows[0]
874
+ else "window_start"
875
+ )
876
+ window_starts = [
877
+ datetime.fromisoformat(str(row[time_coordinate])) for row in rows
878
+ ]
879
+ intensities = [float(row["arrival_intensity"]) for row in rows]
880
+ except KeyError as exc:
881
+ raise ValueError(
882
+ "Each intensity row must contain window_start/window_midpoint and arrival_intensity."
883
+ ) from exc
884
+
885
+ try:
886
+ import matplotlib.pyplot as plt
887
+ except ImportError as exc:
888
+ raise ImportError(
889
+ "plot_arrival_intensity requires matplotlib; install the project dev dependencies."
890
+ ) from exc
891
+
892
+ figure, axis = plt.subplots(figsize=(12, 4.5))
893
+ axis.plot(window_starts, intensities, marker="o", linewidth=1.5, markersize=3)
894
+ axis.set_title(title or "Arrival Intensity Variation Over Time")
895
+ axis.set_xlabel(
896
+ "Window midpoint" if time_coordinate == "window_midpoint" else "Window start"
897
+ )
898
+ axis.set_ylabel(str(intensity_unit))
899
+ axis.grid(alpha=0.25)
900
+ figure.autofmt_xdate()
901
+ figure.tight_layout()
902
+
903
+ if output_path is not None:
904
+ destination = Path(output_path)
905
+ destination.parent.mkdir(parents=True, exist_ok=True)
906
+ figure.savefig(destination, dpi=160, bbox_inches="tight")
907
+ if show:
908
+ plt.show()
909
+ return figure
910
+
911
+
912
+ def tune_horizon_windows(
913
+ data: str | Path | Sequence[datetime | Mapping[str, Any]] | Iterable[datetime | Mapping[str, Any]],
914
+ candidate_horizons: Sequence[timedelta | int | float | str],
915
+ candidate_windows: Sequence[int] | Iterable[int],
916
+ *,
917
+ step_size: timedelta | int | float | str = "1d",
918
+ datetime_column: str = "timestamp",
919
+ count_column: str | None = None,
920
+ base_resolution: timedelta | int | float | str = "1h",
921
+ boundary_policy: str = "error",
922
+ config: WindowSelectionConfig | None = None,
923
+ ) -> list[dict[str, Any]]:
924
+ """Compare horizon lengths by repeatedly evaluating complete sliding horizons."""
925
+
926
+ if config is None:
927
+ config = WindowSelectionConfig()
928
+ if boundary_policy not in {"error", "truncate"}:
929
+ raise ValueError("boundary_policy must be either 'error' or 'truncate'.")
930
+ timestamps, values = _load_temporal_records(
931
+ data,
932
+ datetime_column=datetime_column,
933
+ count_column=count_column,
934
+ )
935
+ records = [
936
+ (
937
+ timestamp
938
+ if count_column is None
939
+ else {datetime_column: timestamp, count_column: value}
940
+ )
941
+ for timestamp, value in zip(timestamps, values)
942
+ ]
943
+ candidate_micro_windows = list(candidate_windows)
944
+ source_end = timestamps[-1]
945
+ step = _coerce_duration(step_size, parameter="step_size", numeric_unit="days")
946
+ summaries: list[dict[str, Any]] = []
947
+
948
+ for raw_horizon in candidate_horizons:
949
+ horizon = _coerce_duration(
950
+ raw_horizon,
951
+ parameter="candidate_horizon",
952
+ numeric_unit="days",
953
+ )
954
+ start = timestamps[0]
955
+ attempted = 0
956
+ suitability_valid = 0
957
+ suitability_failed = 0
958
+ coverage_failed = 0
959
+ accepted_horizons = 0
960
+ confidence_widths: list[float] = []
961
+ dispersion_deviations: list[float] = []
962
+ accepted_results: list[dict[str, Any]] = []
963
+
964
+ while start + horizon <= source_end:
965
+ attempted += 1
966
+ try:
967
+ result = evaluate_horizon(
968
+ records,
969
+ candidate_micro_windows,
970
+ start_date=start,
971
+ horizon_window=horizon,
972
+ datetime_column=datetime_column,
973
+ count_column=count_column,
974
+ base_resolution=base_resolution,
975
+ boundary_policy=boundary_policy,
976
+ config=config,
977
+ )
978
+ except DataSuitabilityError:
979
+ suitability_failed += 1
980
+ except CandidateWindowError:
981
+ suitability_valid += 1
982
+ coverage_failed += 1
983
+ else:
984
+ suitability_valid += 1
985
+ if result["poisson_compatible_window_found"]:
986
+ accepted_horizons += 1
987
+ accepted_results.append(result)
988
+ for candidate in result["candidate_windows"]:
989
+ confidence_widths.append(float(candidate["confidence_band_width"]))
990
+ dispersion_deviations.append(abs(float(candidate["fano_factor"]) - 1.0))
991
+ start += step
992
+
993
+ summaries.append(
994
+ {
995
+ "horizon_window": str(horizon),
996
+ "horizon_window_days": horizon.total_seconds() / 86400.0,
997
+ "step_size": str(step),
998
+ "attempted_horizons": attempted,
999
+ "suitability_valid_horizons": suitability_valid,
1000
+ "suitability_failed_horizons": suitability_failed,
1001
+ "candidate_coverage_failed_horizons": coverage_failed,
1002
+ "accepted_horizons": accepted_horizons,
1003
+ "poisson_acceptance_rate": (
1004
+ accepted_horizons / suitability_valid if suitability_valid else None
1005
+ ),
1006
+ "suitability_valid_horizon_proportion": (
1007
+ suitability_valid / attempted if attempted else None
1008
+ ),
1009
+ "mean_confidence_band_width": (
1010
+ float(np.mean(confidence_widths)) if confidence_widths else None
1011
+ ),
1012
+ "median_dispersion_deviation": (
1013
+ float(np.median(dispersion_deviations))
1014
+ if dispersion_deviations
1015
+ else None
1016
+ ),
1017
+ "accepted_results": accepted_results,
1018
+ "diagnostics": {
1019
+ "zero_suitability_valid_horizons": suitability_valid == 0,
1020
+ "attempted_but_invalid": attempted == 0,
1021
+ },
1022
+ }
1023
+ )
1024
+
1025
+ return summaries
1026
+
1027
+
1028
+ def recommend_optimal_horizon(
1029
+ comparison_table: Sequence[Mapping[str, Any]] | Iterable[Mapping[str, Any]],
1030
+ *,
1031
+ config: HorizonRecommendationConfig | None = None,
1032
+ ) -> dict[str, Any]:
1033
+ """Apply an explicit deterministic rule to a horizon tuning comparison table."""
1034
+
1035
+ if config is None:
1036
+ config = HorizonRecommendationConfig()
1037
+ candidates = [dict(candidate) for candidate in comparison_table]
1038
+ audit: list[dict[str, Any]] = []
1039
+ qualified: list[tuple[dict[str, Any], dict[str, Any], float]] = []
1040
+
1041
+ for candidate in candidates:
1042
+ acceptance_rate = candidate.get("poisson_acceptance_rate")
1043
+ valid_proportion = candidate.get("suitability_valid_horizon_proportion")
1044
+ valid_count = candidate.get("suitability_valid_horizons")
1045
+ try:
1046
+ horizon_days = float(candidate["horizon_window_days"])
1047
+ except (KeyError, TypeError, ValueError):
1048
+ try:
1049
+ horizon_days = (
1050
+ _coerce_duration(
1051
+ candidate["horizon_window"],
1052
+ parameter="horizon_window",
1053
+ numeric_unit="days",
1054
+ ).total_seconds()
1055
+ / 86400.0
1056
+ )
1057
+ except (KeyError, TypeError, ValueError) as exc:
1058
+ raise ValueError(
1059
+ "Each comparison row must provide horizon_window_days or a valid horizon_window."
1060
+ ) from exc
1061
+
1062
+ failures: list[dict[str, Any]] = []
1063
+ if acceptance_rate is None:
1064
+ failures.append(
1065
+ {
1066
+ "gate": "poisson_acceptance_rate_available",
1067
+ "observed": None,
1068
+ "required": "not null",
1069
+ }
1070
+ )
1071
+ if valid_proportion is None or valid_proportion < config.min_valid_horizon_proportion:
1072
+ failures.append(
1073
+ {
1074
+ "gate": "min_valid_horizon_proportion",
1075
+ "observed": valid_proportion,
1076
+ "required": config.min_valid_horizon_proportion,
1077
+ }
1078
+ )
1079
+ if valid_count is None or valid_count < config.min_valid_horizons:
1080
+ failures.append(
1081
+ {
1082
+ "gate": "min_valid_horizons",
1083
+ "observed": valid_count,
1084
+ "required": config.min_valid_horizons,
1085
+ }
1086
+ )
1087
+
1088
+ audit_entry = {
1089
+ "horizon_window": candidate.get("horizon_window"),
1090
+ "horizon_window_days": horizon_days,
1091
+ "outcome": "rejected" if failures else "qualified",
1092
+ "stage": "reliability_gate" if failures else None,
1093
+ "failures": failures,
1094
+ "metrics": {
1095
+ "poisson_acceptance_rate": acceptance_rate,
1096
+ "suitability_valid_horizon_proportion": valid_proportion,
1097
+ "suitability_valid_horizons": valid_count,
1098
+ "median_dispersion_deviation": candidate.get(
1099
+ "median_dispersion_deviation"
1100
+ ),
1101
+ "mean_confidence_band_width": candidate.get(
1102
+ "mean_confidence_band_width"
1103
+ ),
1104
+ },
1105
+ }
1106
+ audit.append(audit_entry)
1107
+ if not failures:
1108
+ qualified.append((candidate, audit_entry, horizon_days))
1109
+
1110
+ if not qualified:
1111
+ return {
1112
+ "recommended_horizon": None,
1113
+ "rule_config": asdict(config),
1114
+ "selected_metrics": None,
1115
+ "candidate_audit": audit,
1116
+ "diagnostics": {
1117
+ "status": "no_reliable_candidate",
1118
+ "message": "No candidate passed the coverage and sample-size gate.",
1119
+ },
1120
+ }
1121
+
1122
+ maximum_acceptance = max(
1123
+ float(candidate["poisson_acceptance_rate"])
1124
+ for candidate, _, _ in qualified
1125
+ )
1126
+ acceptance_floor = maximum_acceptance - config.acceptance_rate_tolerance
1127
+ retained: list[tuple[dict[str, Any], dict[str, Any], float]] = []
1128
+ for candidate, audit_entry, horizon_days in qualified:
1129
+ acceptance_rate = float(candidate["poisson_acceptance_rate"])
1130
+ if acceptance_rate < acceptance_floor:
1131
+ audit_entry.update(
1132
+ {
1133
+ "outcome": "rejected",
1134
+ "stage": "acceptance_rate_filter",
1135
+ "failures": [
1136
+ {
1137
+ "gate": "acceptance_rate_tolerance",
1138
+ "observed": acceptance_rate,
1139
+ "required": acceptance_floor,
1140
+ "maximum_observed": maximum_acceptance,
1141
+ "tolerance": config.acceptance_rate_tolerance,
1142
+ }
1143
+ ],
1144
+ }
1145
+ )
1146
+ else:
1147
+ retained.append((candidate, audit_entry, horizon_days))
1148
+
1149
+ rankable: list[tuple[dict[str, Any], dict[str, Any], float]] = []
1150
+ for candidate, audit_entry, horizon_days in retained:
1151
+ dispersion = candidate.get("median_dispersion_deviation")
1152
+ width = candidate.get("mean_confidence_band_width")
1153
+ missing_metrics = [
1154
+ name
1155
+ for name, value in (
1156
+ ("median_dispersion_deviation", dispersion),
1157
+ ("mean_confidence_band_width", width),
1158
+ )
1159
+ if value is None
1160
+ ]
1161
+ if missing_metrics:
1162
+ audit_entry.update(
1163
+ {
1164
+ "outcome": "rejected",
1165
+ "stage": "dispersion_precision_tie_break",
1166
+ "failures": [
1167
+ {
1168
+ "gate": "tie_break_metrics_available",
1169
+ "observed": missing_metrics,
1170
+ "required": "not null",
1171
+ }
1172
+ ],
1173
+ }
1174
+ )
1175
+ else:
1176
+ rankable.append((candidate, audit_entry, horizon_days))
1177
+
1178
+ if not rankable:
1179
+ return {
1180
+ "recommended_horizon": None,
1181
+ "rule_config": asdict(config),
1182
+ "selected_metrics": None,
1183
+ "candidate_audit": audit,
1184
+ "diagnostics": {
1185
+ "status": "no_rankable_candidate",
1186
+ "maximum_acceptance_rate": maximum_acceptance,
1187
+ "acceptance_rate_floor": acceptance_floor,
1188
+ },
1189
+ }
1190
+
1191
+ horizon_direction = 1.0 if config.prefer_shorter_horizon else -1.0
1192
+ ranked = sorted(
1193
+ rankable,
1194
+ key=lambda item: (
1195
+ float(item[0]["median_dispersion_deviation"]),
1196
+ float(item[0]["mean_confidence_band_width"]),
1197
+ horizon_direction * item[2],
1198
+ ),
1199
+ )
1200
+ selected, selected_audit, _ = ranked[0]
1201
+ selected_audit.update(
1202
+ {
1203
+ "outcome": "selected",
1204
+ "stage": "dispersion_precision_tie_break",
1205
+ "failures": [],
1206
+ }
1207
+ )
1208
+ for _, audit_entry, _ in ranked[1:]:
1209
+ audit_entry.update(
1210
+ {
1211
+ "outcome": "runner_up",
1212
+ "stage": "dispersion_precision_tie_break",
1213
+ "failures": [],
1214
+ }
1215
+ )
1216
+
1217
+ return {
1218
+ "recommended_horizon": selected["horizon_window"],
1219
+ "rule_config": asdict(config),
1220
+ "selected_metrics": selected,
1221
+ "candidate_audit": audit,
1222
+ "diagnostics": {
1223
+ "status": "recommended",
1224
+ "maximum_acceptance_rate": maximum_acceptance,
1225
+ "acceptance_rate_floor": acceptance_floor,
1226
+ "ranked_candidates": [
1227
+ candidate["horizon_window"] for candidate, _, _ in ranked
1228
+ ],
1229
+ },
1230
+ }
1231
+
1232
+
1233
+ def _resolve_data_file(
1234
+ data_file: str | Path | None,
1235
+ *,
1236
+ data_dir: str | Path | None = None,
1237
+ ) -> Path:
1238
+ """Resolve a dataset path, defaulting to the repository data directory when possible."""
1239
+
1240
+ base_dir = Path(data_dir) if data_dir is not None else DEFAULT_DATA_DIR
1241
+ if data_file is None:
1242
+ if base_dir.exists() and base_dir.is_dir():
1243
+ csv_files = sorted(base_dir.glob("*.csv"))
1244
+ if not csv_files:
1245
+ raise FileNotFoundError(f"No CSV files were found in {base_dir}.")
1246
+ if len(csv_files) > 1:
1247
+ raise ValueError(
1248
+ "Multiple CSV files were found in the default data directory. "
1249
+ "Please pass data_file explicitly."
1250
+ )
1251
+ return csv_files[0]
1252
+ if base_dir.exists() and base_dir.is_file():
1253
+ return base_dir
1254
+ raise FileNotFoundError(f"No dataset file found at {base_dir}.")
1255
+
1256
+ resolved = Path(data_file)
1257
+ if resolved.is_dir():
1258
+ csv_files = sorted(resolved.glob("*.csv"))
1259
+ if not csv_files:
1260
+ raise FileNotFoundError(f"No CSV files were found in {resolved}.")
1261
+ if len(csv_files) > 1:
1262
+ raise ValueError(
1263
+ f"Multiple CSV files were found in {resolved}. Please select a single file to export."
1264
+ )
1265
+ return csv_files[0]
1266
+
1267
+ return resolved
1268
+
1269
+
1270
+ def _parse_timestamp(raw_value: str) -> datetime:
1271
+ """Parse ISO-like timestamps drawn from the repository datasets."""
1272
+
1273
+ text = str(raw_value).strip()
1274
+ if not text:
1275
+ raise ValueError("Encountered an empty timestamp value.")
1276
+
1277
+ if text.endswith("Z"):
1278
+ text = text[:-1] + "+00:00"
1279
+
1280
+ if "." in text:
1281
+ base, fraction = text.rsplit(".", 1)
1282
+ if len(fraction) > 6 and fraction[-1].isdigit():
1283
+ text = base + "." + fraction[:6]
1284
+
1285
+ try:
1286
+ return datetime.fromisoformat(text)
1287
+ except ValueError:
1288
+ pass
1289
+
1290
+ for fmt in (
1291
+ "%Y-%m-%d %H:%M:%S.%f",
1292
+ "%Y-%m-%d %H:%M:%S",
1293
+ "%Y-%m-%dT%H:%M:%S.%f",
1294
+ "%Y-%m-%dT%H:%M:%S",
1295
+ ):
1296
+ try:
1297
+ return datetime.strptime(text, fmt)
1298
+ except ValueError:
1299
+ continue
1300
+
1301
+ raise ValueError(f"Could not parse timestamp value: {raw_value!r}")
1302
+
1303
+
1304
+ def _load_event_timestamps(
1305
+ data_file: str | Path | None = None,
1306
+ *,
1307
+ data_dir: str | Path | None = None,
1308
+ timestamp_column: str = "timestamp",
1309
+ ) -> list[datetime]:
1310
+ """Load a timestamp column from a CSV file."""
1311
+
1312
+ path = _resolve_data_file(data_file, data_dir=data_dir)
1313
+ with path.open("r", newline="") as handle:
1314
+ reader = csv.DictReader(handle)
1315
+ if reader.fieldnames is None:
1316
+ raise ValueError(f"The file {path} does not appear to contain a CSV header row.")
1317
+
1318
+ if timestamp_column not in reader.fieldnames:
1319
+ if len(reader.fieldnames) == 1 and reader.fieldnames[0].strip().lower() == timestamp_column:
1320
+ values = [row[reader.fieldnames[0]] for row in reader]
1321
+ else:
1322
+ raise ValueError(
1323
+ f"Expected a '{timestamp_column}' column in {path}, found {reader.fieldnames}."
1324
+ )
1325
+ else:
1326
+ values = [row[timestamp_column] for row in reader]
1327
+
1328
+ timestamps = [_parse_timestamp(value) for value in values if str(value).strip()]
1329
+ if not timestamps:
1330
+ raise ValueError(f"No valid timestamps were found in {path}.")
1331
+
1332
+ return sorted(timestamps)
1333
+
1334
+
1335
+ def _find_full_day_bounds(timestamps: Sequence[datetime]) -> tuple[date, date, dict[str, object | None]]:
1336
+ """Return the first and last full calendar days in the data and any omitted partial days."""
1337
+
1338
+ first_ts = timestamps[0]
1339
+ last_ts = timestamps[-1]
1340
+
1341
+ first_day = first_ts.date()
1342
+ last_day = last_ts.date()
1343
+
1344
+ first_full_day = first_day
1345
+ if first_ts.time() != time(0, 0):
1346
+ first_full_day = first_day + timedelta(days=1)
1347
+
1348
+ last_full_day = last_day
1349
+ if last_ts.time() != time(23, 59, 59, 999999):
1350
+ last_full_day = last_day - timedelta(days=1)
1351
+
1352
+ omits: dict[str, object | None] = {
1353
+ "prefix": None,
1354
+ "suffix": None,
1355
+ }
1356
+ if first_full_day != first_day:
1357
+ start_value = datetime.combine(first_day, time.min)
1358
+ end_value = datetime.combine(first_day, time.max)
1359
+ omits["prefix"] = {
1360
+ "start": start_value.isoformat(timespec="microseconds"),
1361
+ "end": end_value.isoformat(timespec="microseconds"),
1362
+ }
1363
+ if last_full_day != last_day:
1364
+ start_value = datetime.combine(last_day, time.min)
1365
+ end_value = datetime.combine(last_day, time.max)
1366
+ omits["suffix"] = {
1367
+ "start": start_value.isoformat(timespec="microseconds"),
1368
+ "end": end_value.isoformat(timespec="microseconds"),
1369
+ }
1370
+
1371
+ return first_full_day, last_full_day, omits
1372
+
1373
+
1374
+ def build_daily_window_table(
1375
+ data_file: str | Path | None = None,
1376
+ *,
1377
+ window_size_hours: int = 1,
1378
+ data_dir: str | Path | None = None,
1379
+ timestamp_column: str = "timestamp",
1380
+ output_path: str | Path | None = None,
1381
+ ) -> dict[str, object]:
1382
+ """Build a daily tabular export with one row per day and one column per time-window block.
1383
+
1384
+ The method starts at the first full calendar day and ends at the last full calendar day.
1385
+ Any leading or trailing partial days are omitted and reported in the returned metadata.
1386
+ """
1387
+
1388
+ if window_size_hours <= 0:
1389
+ raise ValueError("window_size_hours must be a positive integer.")
1390
+ if 24 % window_size_hours != 0:
1391
+ raise ValueError("window_size_hours must divide evenly into 24 hours to form a full day table.")
1392
+
1393
+ source_path = _resolve_data_file(data_file, data_dir=data_dir)
1394
+ timestamps = _load_event_timestamps(source_path, timestamp_column=timestamp_column)
1395
+ first_full_day, last_full_day, omitted = _find_full_day_bounds(timestamps)
1396
+
1397
+ if first_full_day > last_full_day:
1398
+ raise ValueError(
1399
+ "The dataset does not contain a full day of timestamps after trimming partial calendar days. "
1400
+ "Please provide a longer observation period."
1401
+ )
1402
+
1403
+ windows_per_day = 24 // window_size_hours
1404
+ day_totals: dict[date, list[int]] = {
1405
+ day: [0 for _ in range(windows_per_day)] for day in (first_full_day + timedelta(days=i) for i in range((last_full_day - first_full_day).days + 1))
1406
+ }
1407
+
1408
+ for ts in timestamps:
1409
+ current_day = ts.date()
1410
+ if current_day < first_full_day or current_day > last_full_day:
1411
+ continue
1412
+ day_start = datetime.combine(current_day, time.min)
1413
+ elapsed_seconds = (ts - day_start).total_seconds()
1414
+ window_index = int(elapsed_seconds // (window_size_hours * 3600))
1415
+ if 0 <= window_index < windows_per_day:
1416
+ day_totals[current_day][window_index] += 1
1417
+
1418
+ columns = [f"window_{idx:02d}" for idx in range(windows_per_day)]
1419
+ rows: list[dict[str, object]] = []
1420
+ for day in [first_full_day + timedelta(days=i) for i in range((last_full_day - first_full_day).days + 1)]:
1421
+ row: dict[str, object] = {"date": day.isoformat()}
1422
+ for idx, value in enumerate(day_totals[day]):
1423
+ row[f"window_{idx:02d}"] = int(value)
1424
+ rows.append(row)
1425
+
1426
+ if output_path is None:
1427
+ output_path = source_path.parent / f"{source_path.stem}_daily_window_{window_size_hours}h.csv"
1428
+ output_path = Path(output_path)
1429
+ output_path.parent.mkdir(parents=True, exist_ok=True)
1430
+
1431
+ with output_path.open("w", newline="") as handle:
1432
+ writer = csv.writer(handle)
1433
+ writer.writerow(["date", *columns])
1434
+ for row in rows:
1435
+ writer.writerow([row["date"], *[row[column] for column in columns]])
1436
+
1437
+ return {
1438
+ "source_file": str(source_path),
1439
+ "output_file": str(output_path),
1440
+ "window_size_hours": int(window_size_hours),
1441
+ "windows_per_day": int(windows_per_day),
1442
+ "first_full_day": first_full_day.isoformat(),
1443
+ "last_full_day": last_full_day.isoformat(),
1444
+ "omitted_prefix": omitted.get("prefix"),
1445
+ "omitted_suffix": omitted.get("suffix"),
1446
+ "rows": rows,
1447
+ "columns": columns,
1448
+ }
1449
+
1450
+
1451
+ def teseda_export(
1452
+ data_file: str | Path | None = None,
1453
+ *,
1454
+ window_size_hours: int = 1,
1455
+ data_dir: str | Path | None = None,
1456
+ timestamp_column: str = "timestamp",
1457
+ output_path: str | Path | None = None,
1458
+ intensity_unit: str | None = None,
1459
+ ) -> dict[str, object]:
1460
+ """Create a two-column TSEDA-ready export: window_start and arrival_intensity.
1461
+
1462
+ The arrival intensity is normalized to a per-hour rate: count / window_size_hours.
1463
+ The output includes the sampling period (the selected window width) and the intensity unit.
1464
+ """
1465
+
1466
+ if window_size_hours <= 0:
1467
+ raise ValueError("window_size_hours must be a positive integer.")
1468
+ if 24 % window_size_hours != 0:
1469
+ raise ValueError("window_size_hours must divide evenly into 24 hours to produce a regular daily grid.")
1470
+
1471
+ source_path = _resolve_data_file(data_file, data_dir=data_dir)
1472
+ timestamps = _load_event_timestamps(source_path, timestamp_column=timestamp_column)
1473
+ first_full_day, last_full_day, omitted = _find_full_day_bounds(timestamps)
1474
+
1475
+ if first_full_day > last_full_day:
1476
+ raise ValueError(
1477
+ "The dataset does not contain a full day of timestamps after trimming partial calendar days. "
1478
+ "Please provide a longer observation period."
1479
+ )
1480
+
1481
+ windows_per_day = 24 // window_size_hours
1482
+ day_range = [first_full_day + timedelta(days=i) for i in range((last_full_day - first_full_day).days + 1)]
1483
+ rows: list[dict[str, object]] = []
1484
+
1485
+ for day in day_range:
1486
+ day_start = datetime.combine(day, time.min)
1487
+ for idx in range(windows_per_day):
1488
+ window_start = day_start + timedelta(hours=idx * window_size_hours)
1489
+ window_end = window_start + timedelta(hours=window_size_hours)
1490
+ count = 0
1491
+ for ts in timestamps:
1492
+ if ts.date() != day:
1493
+ continue
1494
+ if window_start <= ts < window_end:
1495
+ count += 1
1496
+ intensity = count / float(window_size_hours)
1497
+ rows.append({
1498
+ "window_start": window_start.isoformat(timespec="seconds"),
1499
+ "arrival_intensity": float(intensity),
1500
+ })
1501
+
1502
+ if output_path is None:
1503
+ output_path = source_path.parent / f"{source_path.stem}_teseda_{window_size_hours}h.csv"
1504
+ output_path = Path(output_path)
1505
+ output_path.parent.mkdir(parents=True, exist_ok=True)
1506
+
1507
+ with output_path.open("w", newline="") as handle:
1508
+ writer = csv.writer(handle)
1509
+ writer.writerow(["window_start", "arrival_intensity"])
1510
+ for row in rows:
1511
+ writer.writerow([row["window_start"], row["arrival_intensity"]])
1512
+
1513
+ if intensity_unit is None:
1514
+ intensity_unit = "arrivals per hour"
1515
+
1516
+ return {
1517
+ "source_file": str(source_path),
1518
+ "output_file": str(output_path),
1519
+ "sampling_period_hours": int(window_size_hours),
1520
+ "sampling_period": f"{window_size_hours} hours",
1521
+ "intensity_unit": intensity_unit,
1522
+ "first_full_day": first_full_day.isoformat(),
1523
+ "last_full_day": last_full_day.isoformat(),
1524
+ "omitted_prefix": omitted.get("prefix"),
1525
+ "omitted_suffix": omitted.get("suffix"),
1526
+ "rows": rows,
1527
+ }
1528
+
1529
+
1530
+ def main(argv: Sequence[str] | None = None) -> int:
1531
+ parser = argparse.ArgumentParser(
1532
+ description="Select Poisson-compatible time windows for higher-event-rate count time series."
1533
+ )
1534
+ parser.add_argument("counts", nargs="+", type=float, help="Observed count values in the time series.")
1535
+ parser.add_argument(
1536
+ "--candidate-window",
1537
+ dest="candidate_windows",
1538
+ type=int,
1539
+ action="append",
1540
+ default=None,
1541
+ help="Candidate window size to test. Repeat the flag to test multiple windows.",
1542
+ )
1543
+ parser.add_argument("--min-event-rate", type=float, default=5.0, help="Minimum average event rate required.")
1544
+ parser.add_argument(
1545
+ "--max-zero-window-proportion",
1546
+ type=float,
1547
+ default=0.1,
1548
+ help="Maximum allowed proportion of zero-count windows.",
1549
+ )
1550
+ parser.add_argument("--min-windows", type=int, default=30, help="Minimum number of non-overlapping windows required.")
1551
+ parser.add_argument(
1552
+ "--confidence-level",
1553
+ type=float,
1554
+ default=0.90,
1555
+ help="Confidence level used for Fano-factor acceptance bounds.",
1556
+ )
1557
+
1558
+ args = parser.parse_args(argv)
1559
+ config = WindowSelectionConfig(
1560
+ min_event_rate=args.min_event_rate,
1561
+ max_zero_window_proportion=args.max_zero_window_proportion,
1562
+ min_windows=args.min_windows,
1563
+ confidence_level=args.confidence_level,
1564
+ )
1565
+
1566
+ candidate_windows = args.candidate_windows or [1, 2, 3, 5, 10, 15, 30, 60]
1567
+
1568
+ try:
1569
+ results = select_time_window(args.counts, candidate_windows, config=config)
1570
+ except (DataSuitabilityError, CandidateWindowError, ValueError) as exc:
1571
+ parser.exit(1, f"Error: {exc}\n")
1572
+
1573
+ if not results:
1574
+ print("No candidate window satisfied the Poisson-compatible Fano criterion.")
1575
+ return 0
1576
+
1577
+ print(json.dumps(results, indent=2))
1578
+ return 0