-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2292 lines (1992 loc) · 93.6 KB
/
main.py
File metadata and controls
2292 lines (1992 loc) · 93.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
DTS-GSSF Platform (single-file)
===============================
Dual-Timescale Graph State-Space Forecasting with:
- Graph-structured "SSM-ish" backbone (efficient long memory)
- Online residual correction via Kalman-style filtering (fast timescale)
- Drift detection (Page-Hinkley) + drift-triggered LoRA-style low-rank adaptation
- Hierarchical reconciliation (stations -> lines -> districts -> total) via weighted projection (MinT/OLS)
UI:
- Streamlit dashboard to generate realistic Astana bus passenger-flow data,
train the model, and run an online simulation with analytics.
This file is intentionally self-contained for clarity.
It implements the full DTS-GSSF pipeline from the draft spec.
Run (recommended):
uv run streamlit run main.py
CLI:
uv run python main.py --online
Mac (Apple Silicon):
Uses MPS if available; otherwise CPU.
You can set: PYTORCH_ENABLE_MPS_FALLBACK=1
"""
from __future__ import annotations
import argparse
import dataclasses
import datetime as dt
import json
import logging
import math
import os
import random
import time
from dataclasses import dataclass
from typing import Callable, Dict, Iterable, List, Optional, Tuple
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
# ----------------------------
# Logging & reproducibility
# ----------------------------
LOG = logging.getLogger("dts_gssf")
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
class RichLogger:
"""
Styled console logging with headers, progress bars, and metrics tables.
Inspired by best practices from MIT CSAIL, Stanford AI Lab, and Harvard ML research.
"""
COLORS = {
"header": "\033[1;36m", # Cyan bold
"success": "\033[1;32m", # Green bold
"warning": "\033[1;33m", # Yellow bold
"error": "\033[1;31m", # Red bold
"info": "\033[0;37m", # White
"accent": "\033[1;35m", # Magenta bold
"dim": "\033[2m", # Dim
"reset": "\033[0m",
"bold": "\033[1m",
"blue": "\033[1;34m",
}
BOX = {
"tl": "╔", "tr": "╗", "bl": "╚", "br": "╝",
"h": "═", "v": "║", "cross": "╬",
"light_h": "─", "light_v": "│",
}
@classmethod
def header(cls, title: str, width: int = 70) -> None:
"""Print a prominent boxed header."""
c = cls.COLORS
b = cls.BOX
title_centered = title.center(width - 2)
print(f"\n{c['header']}{b['tl']}{b['h'] * (width - 2)}{b['tr']}{c['reset']}")
print(f"{c['header']}{b['v']}{c['bold']}{title_centered}{c['header']}{b['v']}{c['reset']}")
print(f"{c['header']}{b['bl']}{b['h'] * (width - 2)}{b['br']}{c['reset']}\n")
@classmethod
def section(cls, title: str, width: int = 50) -> None:
"""Print a section divider with title."""
c = cls.COLORS
side = (width - len(title) - 2) // 2
line = cls.BOX["light_h"] * side
print(f"\n{c['accent']}{line} {title} {line}{c['reset']}")
@classmethod
def subsection(cls, title: str) -> None:
"""Print a subsection header."""
c = cls.COLORS
print(f"\n{c['blue']}▸ {title}{c['reset']}")
@classmethod
def metric(cls, name: str, value: object, unit: str = "", delta: Optional[float] = None) -> None:
"""Print a single metric with optional delta."""
c = cls.COLORS
name_fmt = f"{name:.<25}"
val_str = f"{value}{unit}"
if delta is not None:
delta_color = c["success"] if delta < 0 else c["warning"]
delta_str = f" ({delta:+.4f})"
print(f" {c['dim']}{name_fmt}{c['reset']} {c['bold']}{val_str}{c['reset']}{delta_color}{delta_str}{c['reset']}")
else:
print(f" {c['dim']}{name_fmt}{c['reset']} {c['bold']}{val_str}{c['reset']}")
@classmethod
def metrics_row(cls, metrics: Dict[str, object]) -> None:
"""Print multiple metrics in a single row."""
c = cls.COLORS
parts = [f"{c['dim']}{k}:{c['reset']} {c['bold']}{v}{c['reset']}" for k, v in metrics.items()]
print(" " + " │ ".join(parts))
@classmethod
def progress_bar(cls, current: int, total: int, width: int = 30, desc: str = "") -> str:
"""Return a text progress bar."""
pct = current / max(1, total)
filled = int(width * pct)
bar = "█" * filled + "░" * (width - filled)
return f"{desc} [{bar}] {current}/{total} ({pct*100:.0f}%)"
@classmethod
def table(cls, headers: List[str], rows: List[List[object]], col_widths: Optional[List[int]] = None) -> None:
"""Print a formatted table."""
c = cls.COLORS
b = cls.BOX
if col_widths is None:
col_widths = [max(len(str(h)), max(len(str(r[i])) for r in rows) if rows else 0) + 2
for i, h in enumerate(headers)]
header_line = f" {c['bold']}"
sep_line = f" {c['dim']}"
for i, h in enumerate(headers):
header_line += f"{str(h):^{col_widths[i]}}" + (b["light_v"] if i < len(headers) - 1 else "")
sep_line += b["light_h"] * col_widths[i] + ("┼" if i < len(headers) - 1 else "")
print(header_line + c["reset"])
print(sep_line + c["reset"])
for row in rows:
row_line = " "
for i, cell in enumerate(row):
row_line += f"{str(cell):^{col_widths[i]}}" + (b["light_v"] if i < len(row) - 1 else "")
print(row_line)
@classmethod
def success(cls, msg: str) -> None:
"""Print a success message."""
print(f" {cls.COLORS['success']}✓{cls.COLORS['reset']} {msg}")
@classmethod
def warning(cls, msg: str) -> None:
"""Print a warning message."""
print(f" {cls.COLORS['warning']}⚠{cls.COLORS['reset']} {msg}")
@classmethod
def error(cls, msg: str) -> None:
"""Print an error message."""
print(f" {cls.COLORS['error']}✗{cls.COLORS['reset']} {msg}")
@classmethod
def info(cls, msg: str) -> None:
"""Print an info message."""
print(f" {cls.COLORS['info']}ℹ{cls.COLORS['reset']} {msg}")
@classmethod
def epoch_summary(cls, epoch: int, total_epochs: int, train_loss: float,
val_loss: float, lr: float, elapsed: float,
best_val: Optional[float] = None) -> None:
"""Print a formatted epoch summary line."""
c = cls.COLORS
is_best = best_val is not None and val_loss <= best_val
best_marker = f" {c['success']}★{c['reset']}" if is_best else ""
print(f" {c['bold']}Epoch {epoch:>2}/{total_epochs}{c['reset']} │ "
f"train: {c['warning']}{train_loss:.4f}{c['reset']} │ "
f"val: {c['accent']}{val_loss:.4f}{c['reset']}{best_marker} │ "
f"lr: {lr:.2e} │ {elapsed:.1f}s")
def set_seed(seed: int) -> None:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed) # harmless on CPU/MPS
# ----------------------------
# Utilities
# ----------------------------
def device_auto() -> torch.device:
if torch.cuda.is_available():
return torch.device("cuda")
if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
return torch.device("mps")
return torch.device("cpu")
def to_tensor(x: np.ndarray, device: torch.device, dtype=torch.float32) -> torch.Tensor:
return torch.as_tensor(x, dtype=dtype, device=device)
def softplus(x: torch.Tensor) -> torch.Tensor:
return F.softplus(x, beta=1.0, threshold=20.0)
# ----------------------------
# Astana bus-network generator
# ----------------------------
ASTANA_DISTRICTS = ["Esil", "Almaty", "Saryarka", "Baikonur"]
ASTANA_PLACES = [
"Khan Shatyr", "Baiterek", "Mega Silk Way", "Expo 2017", "Nurly Zhol",
"Astana Mall", "Keruen City", "Palace of Peace", "Central Park", "Triumphal Arch",
"Independence Square", "University Quarter", "River Embankment", "Botanical Garden",
"Saryarka Ave", "Respublika Ave", "Turan Ave", "Kabanbay Batyr Ave", "Mangilik El Ave",
"Syganak St", "Sarayshyk St", "Kenesary St", "Abylai Khan Ave", "Seifullin St",
"Bogenbai Batyr Ave", "Kosmonavtov St", "Shakarim St", "Zhastar Ave", "Dostyk St",
]
def _pick_unique(names: List[str], n: int, seed: int) -> List[str]:
rng = random.Random(seed)
pool = names[:]
rng.shuffle(pool)
out = []
while len(out) < n:
out.extend(pool)
return out[:n]
@dataclass(frozen=True)
class NetworkSpec:
station_names: List[str]
station_district: List[str]
lines: Dict[str, List[int]]
A_phys: np.ndarray
edges: List[Tuple[int, int]]
def build_astana_network(n_stations: int = 28, n_lines: int = 9, seed: int = 7) -> NetworkSpec:
rng = np.random.default_rng(seed)
names = _pick_unique(ASTANA_PLACES, n_stations, seed=seed)
district_probs = np.array([0.30, 0.30, 0.25, 0.15])
station_district = list(rng.choice(ASTANA_DISTRICTS, size=n_stations, p=district_probs))
lines: Dict[str, List[int]] = {}
base_perm = list(range(n_stations))
rng.shuffle(base_perm)
for li in range(n_lines):
line_len = int(rng.integers(9, min(15, n_stations)))
start = int((li * 3) % n_stations)
path = [base_perm[(start + k) % n_stations] for k in range(line_len)]
if li > 0:
prev = lines[f"Line {li}"]
hubs = rng.choice(prev, size=min(2, len(prev)), replace=False)
path[: len(hubs)] = list(hubs)
seen = set()
path2 = []
for x in path:
xi = int(x)
if xi not in seen:
path2.append(xi)
seen.add(xi)
lines[f"Line {li+1}"] = path2
edges = set()
for stations in lines.values():
for a, b in zip(stations[:-1], stations[1:]):
edges.add((min(a, b), max(a, b)))
hubs = rng.choice(np.arange(n_stations), size=max(3, n_stations // 6), replace=False)
for _ in range(n_stations // 2):
a, b = int(rng.choice(hubs)), int(rng.choice(hubs))
if a != b:
edges.add((min(a, b), max(a, b)))
edges_list = [(a, b) for (a, b) in edges]
A = np.zeros((n_stations, n_stations), dtype=np.float32)
for a, b in edges_list:
A[a, b] = 1.0
A[b, a] = 1.0
np.fill_diagonal(A, 1.0)
A = A / (A.sum(axis=1, keepdims=True) + 1e-8)
return NetworkSpec(
station_names=names,
station_district=station_district,
lines=lines,
A_phys=A.astype(np.float32),
edges=edges_list,
)
@dataclass(frozen=True)
class DataGenConfig:
seed: int = 7
days: int = 365 # Default ensures >=50k records with freq_min=10
freq_min: int = 10
start: str = "2025-10-01 05:00:00"
base_mean: float = 18.0
overdispersion_kappa: float = 8.0
rush_hour_boost: float = 2.2
weekend_scale: float = 0.78
night_scale: float = 0.45
event_prob_per_day: float = 0.35 # Increased for richness
disruption_prob_per_day: float = 0.15 # Increased for richness
drift_day: int = 45 # Adjusted for longer duration
drift_scale: float = 1.25
drift_station_frac: float = 0.30
@dataclass(frozen=True)
class DataBundle:
cfg: DataGenConfig
net: NetworkSpec
time_index: pd.DatetimeIndex
X: np.ndarray
y_bottom: np.ndarray
y_all: np.ndarray
series_names: List[str]
S: np.ndarray
meta: Dict[str, object]
def total_records(days: int, freq_min: int) -> int:
steps_per_day = int((24 * 60) // max(1, freq_min))
return int(steps_per_day * max(1, days))
def ensure_min_records(cfg: DataGenConfig, min_records: int = 50_000) -> DataGenConfig:
steps_per_day = int((24 * 60) // max(1, cfg.freq_min))
min_days = int(math.ceil(min_records / max(1, steps_per_day)))
if cfg.days < min_days:
return dataclasses.replace(cfg, days=min_days)
return cfg
def _time_features(idx: pd.DatetimeIndex) -> np.ndarray:
hour = idx.hour.to_numpy(dtype=np.float32) + idx.minute.to_numpy(dtype=np.float32) / 60.0
dow = idx.dayofweek.to_numpy(dtype=np.float32)
hod_sin = np.sin(2 * np.pi * hour / 24.0)
hod_cos = np.cos(2 * np.pi * hour / 24.0)
dow_sin = np.sin(2 * np.pi * dow / 7.0)
dow_cos = np.cos(2 * np.pi * dow / 7.0)
is_weekend = (dow >= 5).astype(np.float32)
return np.stack([hod_sin, hod_cos, dow_sin, dow_cos, is_weekend], axis=1).astype(np.float32)
def _astana_weather(idx: pd.DatetimeIndex, seed: int) -> np.ndarray:
rng = np.random.default_rng(seed + 101)
t = np.arange(len(idx))
temp = -8 + 6 * np.sin(2 * np.pi * t / (len(idx) + 1)) + rng.normal(0, 1.2, size=len(idx))
precip = (rng.random(len(idx)) < 0.05).astype(np.float32)
wind = 4 + 2 * rng.random(len(idx))
return np.stack([temp, precip, wind], axis=1).astype(np.float32)
def _daily_events(idx: pd.DatetimeIndex, net: NetworkSpec, cfg: DataGenConfig) -> Tuple[np.ndarray, Dict]:
rng = np.random.default_rng(cfg.seed + 202)
T, N = len(idx), len(net.station_names)
event_mult = np.ones((T, N), dtype=np.float32)
event_days = sorted(set(idx.normalize()))
event_log = []
venue_keywords = ["Expo", "Khan Shatyr", "Baiterek", "Mega", "Palace", "Central Park"]
venue_stations = [i for i, name in enumerate(net.station_names) if any(k in name for k in venue_keywords)]
if not venue_stations:
venue_stations = list(range(N))
for day in event_days:
if rng.random() < cfg.event_prob_per_day:
vs = rng.choice(venue_stations, size=int(rng.integers(1, 3)), replace=False)
start_hour = int(rng.integers(16, 20))
dur_hours = int(rng.integers(2, 5))
strength = float(rng.uniform(1.2, 1.9))
mask = (idx.normalize() == day) & (idx.hour >= start_hour) & (idx.hour < start_hour + dur_hours)
for v in vs:
event_mult[mask, int(v)] *= strength
event_log.append(dict(day=str(day.date()), start_hour=start_hour, hours=dur_hours,
strength=strength, stations=[net.station_names[int(v)] for v in vs]))
return event_mult, {"events": event_log}
def _service_disruptions(idx: pd.DatetimeIndex, net: NetworkSpec, cfg: DataGenConfig) -> Tuple[np.ndarray, Dict]:
rng = np.random.default_rng(cfg.seed + 303)
T, N = len(idx), len(net.station_names)
mult = np.ones((T, N), dtype=np.float32)
days = sorted(set(idx.normalize()))
log = []
for day in days:
if rng.random() < cfg.disruption_prob_per_day:
line_name = rng.choice(list(net.lines.keys()))
path = net.lines[line_name]
if len(path) < 5:
continue
start = int(rng.integers(0, len(path) - 4))
corridor = path[start:start + int(rng.integers(3, 6))]
start_hour = int(rng.integers(7, 17))
dur_hours = int(rng.integers(2, 6))
severity = float(rng.uniform(0.55, 0.85))
mask = (idx.normalize() == day) & (idx.hour >= start_hour) & (idx.hour < start_hour + dur_hours)
for s in corridor:
mult[mask, int(s)] *= severity
log.append(dict(day=str(day.date()), line=line_name, start_hour=start_hour,
hours=dur_hours, severity=severity,
corridor=[net.station_names[int(s)] for s in corridor]))
return mult, {"disruptions": log}
def _rush_profile(idx: pd.DatetimeIndex, cfg: DataGenConfig) -> np.ndarray:
hour = idx.hour.to_numpy(dtype=np.float32) + idx.minute.to_numpy(dtype=np.float32) / 60.0
morning = np.exp(-0.5 * ((hour - 8.3) / 1.35) ** 2)
evening = np.exp(-0.5 * ((hour - 18.0) / 1.7) ** 2)
base = 0.6 + cfg.rush_hour_boost * (0.55 * morning + 0.75 * evening)
night = ((hour < 6.0) | (hour > 22.0)).astype(np.float32)
base = base * (1.0 - night * (1.0 - cfg.night_scale))
return base.astype(np.float32)
def _weekly_profile(idx: pd.DatetimeIndex, cfg: DataGenConfig) -> np.ndarray:
dow = idx.dayofweek.to_numpy(dtype=np.float32)
weekend = (dow >= 5).astype(np.float32)
return (1.0 - weekend * (1.0 - cfg.weekend_scale)).astype(np.float32)
def _station_popularity(net: NetworkSpec, seed: int) -> np.ndarray:
rng = np.random.default_rng(seed + 404)
N = len(net.station_names)
pop = rng.lognormal(mean=0.0, sigma=0.35, size=N).astype(np.float32)
hub_kw = ["Nurly Zhol", "Expo", "Mega", "Khan Shatyr", "Baiterek", "Central Park"]
for i, name in enumerate(net.station_names):
if any(k in name for k in hub_kw):
pop[i] *= 1.35
for i, d in enumerate(net.station_district):
if d == "Esil":
pop[i] *= 1.18
elif d == "Baikonur":
pop[i] *= 0.95
return pop
def build_hierarchy(net: NetworkSpec) -> Tuple[np.ndarray, List[str], Dict[str, List[int]], Dict[str, List[int]]]:
N = len(net.station_names)
line_groups = {ln: [int(i) for i in idxs] for ln, idxs in net.lines.items()}
district_groups: Dict[str, List[int]] = {d: [] for d in ASTANA_DISTRICTS}
for i, d in enumerate(net.station_district):
district_groups[d].append(i)
series_names = []
rows = []
for i, name in enumerate(net.station_names):
series_names.append(f"Station | {name}")
row = np.zeros(N, dtype=np.float32); row[i] = 1.0
rows.append(row)
for ln, idxs in line_groups.items():
series_names.append(f"Line | {ln}")
row = np.zeros(N, dtype=np.float32); row[idxs] = 1.0
rows.append(row)
for d, idxs in district_groups.items():
series_names.append(f"District | {d}")
row = np.zeros(N, dtype=np.float32); row[idxs] = 1.0
rows.append(row)
series_names.append("Network | Total")
rows.append(np.ones(N, dtype=np.float32))
S = np.stack(rows, axis=0).astype(np.float32)
return S, series_names, line_groups, district_groups
def _nb_sample(mu: np.ndarray, kappa: float, rng: np.random.Generator) -> np.ndarray:
mu = np.clip(mu, 1e-4, None)
shape = kappa
scale = mu / kappa
lam = rng.gamma(shape=shape, scale=scale)
return rng.poisson(lam).astype(np.float32)
def generate_astana_data(cfg: DataGenConfig, net: NetworkSpec) -> DataBundle:
cfg = ensure_min_records(cfg)
set_seed(cfg.seed)
rng = np.random.default_rng(cfg.seed)
freq = f"{cfg.freq_min}min"
idx = pd.date_range(cfg.start, periods=int((24*60//cfg.freq_min)*cfg.days), freq=freq)
T, N = len(idx), len(net.station_names)
time_feat = _time_features(idx)
weather = _astana_weather(idx, cfg.seed)
rush = _rush_profile(idx, cfg)
weekly = _weekly_profile(idx, cfg)
pop = _station_popularity(net, cfg.seed)
event_mult, event_meta = _daily_events(idx, net, cfg)
disrupt_mult, disrupt_meta = _service_disruptions(idx, net, cfg)
drift_start = idx[0] + pd.Timedelta(days=cfg.drift_day)
drift_mask = np.asarray(idx >= drift_start, dtype=np.float32)
drift_station = rng.choice(np.arange(N), size=max(1, int(cfg.drift_station_frac*N)), replace=False)
drift_station_flag = np.zeros(N, dtype=np.float32); drift_station_flag[drift_station] = 1.0
base = cfg.base_mean * pop[None, :] * rush[:, None] * weekly[:, None]
temp = weather[:, 0:1]
precip = weather[:, 1:2]
temp_norm = (temp + 20.0) / 35.0
weather_mult = (0.92 + 0.10 * temp_norm) * (1.0 - 0.08 * precip)
mu = base * weather_mult
mu = mu * event_mult * disrupt_mult
A = net.A_phys.astype(np.float32)
mu = 0.85 * mu + 0.15 * (mu @ A.T)
mu = mu * (1.0 + drift_mask[:, None] * drift_station_flag[None, :] * (cfg.drift_scale - 1.0))
y = _nb_sample(mu, kappa=cfg.overdispersion_kappa, rng=rng)
# Features: lag(1,2,4), time(5), weather(3), flags(event,disruption,drift)
X = np.zeros((T, N, 14), dtype=np.float32)
for lag_i, lag in enumerate([1, 2, 4]):
X[lag:, :, lag_i] = y[:-lag, :]
X[:, :, 3:8] = time_feat[:, None, :]
X[:, :, 8:11] = weather[:, None, :]
X[:, :, 11] = (event_mult > 1.0).astype(np.float32)
X[:, :, 12] = (disrupt_mult < 1.0).astype(np.float32)
X[:, :, 13] = drift_mask[:, None] * drift_station_flag[None, :]
S, series_names, line_groups, district_groups = build_hierarchy(net)
y_all = (S @ y.T).T.astype(np.float32)
meta = {
"drift_start": str(drift_start),
"drift_stations": [net.station_names[int(i)] for i in drift_station],
**event_meta,
**disrupt_meta,
"line_groups": {k: [net.station_names[i] for i in v] for k, v in line_groups.items()},
"district_groups": {k: [net.station_names[i] for i in v] for k, v in district_groups.items()},
}
return DataBundle(cfg=cfg, net=net, time_index=idx, X=X, y_bottom=y, y_all=y_all,
series_names=series_names, S=S, meta=meta)
# ----------------------------
# Dataset utilities
# ----------------------------
@dataclass(frozen=True)
class WindowConfig:
lookback: int = 48
horizon: int = 12
stride: int = 1
@dataclass
class SplitConfig:
train_frac: float = 0.70
val_frac: float = 0.10
test_frac: float = 0.20
class WindowDataset(torch.utils.data.Dataset):
def __init__(self, X: np.ndarray, y_all: np.ndarray, wcfg: WindowConfig, start: int, end: int):
self.X = X
self.y = y_all
self.wcfg = wcfg
self.idxs = []
L, H, stride = wcfg.lookback, wcfg.horizon, wcfg.stride
for t in range(start + L, end - H, stride):
self.idxs.append(t)
def __len__(self) -> int:
return len(self.idxs)
def __getitem__(self, k: int) -> Dict[str, torch.Tensor]:
t = self.idxs[k]
L, H = self.wcfg.lookback, self.wcfg.horizon
x = self.X[t - L : t]
y = self.y[t : t + H]
return {"x": torch.from_numpy(x).float(), "y": torch.from_numpy(y).float()}
def make_splits(T: int, cfg: SplitConfig) -> Tuple[Tuple[int,int], Tuple[int,int], Tuple[int,int]]:
n_train = int(T * cfg.train_frac)
n_val = int(T * cfg.val_frac)
train = (0, n_train)
val = (n_train, n_train + n_val)
test = (n_train + n_val, T)
return train, val, test
# ----------------------------
# Model: Graph SSM + LoRA
# ----------------------------
class LoRALinear(nn.Module):
def __init__(self, in_features: int, out_features: int, r: int = 8, alpha: float = 16.0, bias: bool = True):
super().__init__()
self.r = r
self.scale = alpha / max(1, r)
self.base = nn.Linear(in_features, out_features, bias=bias)
if r > 0:
self.A = nn.Parameter(torch.zeros(r, in_features))
self.B = nn.Parameter(torch.zeros(out_features, r))
nn.init.kaiming_uniform_(self.A, a=math.sqrt(5))
nn.init.zeros_(self.B)
else:
self.register_parameter("A", None)
self.register_parameter("B", None)
def forward(self, x: torch.Tensor) -> torch.Tensor:
y = self.base(x)
if self.r > 0:
y = y + self.scale * ((x @ self.A.T) @ self.B.T)
return y
def lora_parameters(self) -> Iterable[nn.Parameter]:
if self.r <= 0:
return []
return [self.A, self.B]
class GatedSSMBlock(nn.Module):
def __init__(self, d_in: int, d_model: int, dropout: float = 0.1, lora_r: int = 8):
super().__init__()
self.d_model = d_model
self.in_proj = LoRALinear(d_in, d_model, r=lora_r, alpha=16.0)
self.gate_a = nn.Linear(d_model, d_model)
self.gate_b = nn.Linear(d_model, d_model)
self.norm = nn.LayerNorm(d_model)
self.drop = nn.Dropout(dropout)
nn.init.constant_(self.gate_a.bias, -1.0)
nn.init.zeros_(self.gate_b.bias)
def forward(self, x: torch.Tensor) -> torch.Tensor:
B, L, N, _ = x.shape
u = self.drop(F.gelu(self.in_proj(x)))
u2 = u.reshape(B * N, L, self.d_model)
s = torch.zeros((B * N, self.d_model), device=u.device, dtype=u.dtype)
for t in range(L):
ut = u2[:, t, :]
a = torch.sigmoid(self.gate_a(ut))
b = torch.tanh(self.gate_b(ut))
s = a * s + (1.0 - a) * b
s = self.norm(s).reshape(B, N, self.d_model)
return s
class GraphPropagation(nn.Module):
def __init__(self, N: int, d: int, A_phys: np.ndarray, K: int = 2, alpha_phys: float = 0.6, d_emb: int = 16):
super().__init__()
self.K = K
self.alpha_phys = alpha_phys
self.register_buffer("A_phys", torch.from_numpy(A_phys).float())
self.E1 = nn.Parameter(torch.randn(N, d_emb) * 0.05)
self.E2 = nn.Parameter(torch.randn(N, d_emb) * 0.05)
self.Wg = nn.Linear(d, d, bias=False)
self.norm = nn.LayerNorm(d)
def adaptive_adj(self) -> torch.Tensor:
logits = F.relu(self.E1 @ self.E2.T)
return F.softmax(logits, dim=-1)
def forward(self, h: torch.Tensor) -> torch.Tensor:
A_adp = self.adaptive_adj()
A = self.alpha_phys * self.A_phys + (1.0 - self.alpha_phys) * A_adp
out = h
for _ in range(self.K):
out = torch.einsum("ij,bjd->bid", A, out)
out = F.gelu(self.Wg(out))
return self.norm(out + h)
class DTSGSSF(nn.Module):
def __init__(self, N: int, F_in: int, n_series: int, n_agg: int, A_phys: np.ndarray,
d_model: int = 64, horizon: int = 12, K: int = 2, lora_r: int = 8, dropout: float = 0.1):
super().__init__()
self.horizon = horizon
self.ssm = GatedSSMBlock(F_in, d_model, dropout=dropout, lora_r=lora_r)
self.graph = GraphPropagation(N, d_model, A_phys=A_phys, K=K, alpha_phys=0.6, d_emb=16)
self.head_bottom = LoRALinear(d_model, horizon, r=lora_r, alpha=16.0, bias=True)
self.pool = nn.Sequential(nn.LayerNorm(d_model), nn.Linear(d_model, d_model), nn.GELU())
self.head_agg = LoRALinear(d_model, horizon * n_agg, r=lora_r, alpha=16.0, bias=True)
self.log_kappa = nn.Parameter(torch.tensor(math.log(8.0), dtype=torch.float32))
self.N = N
self.n_series = n_series
self.n_agg = n_agg
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
h = self.graph(self.ssm(x)) # (B,N,d)
eta_bottom = self.head_bottom(h) # (B,N,H)
mu_bottom = torch.exp(eta_bottom).permute(0, 2, 1) # (B,H,N)
pooled = self.pool(h).mean(dim=1) # (B,d)
eta_agg = self.head_agg(pooled).view(x.shape[0], self.horizon, self.n_agg)
mu_agg = torch.exp(eta_agg) # (B,H,n_agg)
mu_all = torch.cat([mu_bottom, mu_agg], dim=-1) # (B,H,n_series)
kappa = softplus(self.log_kappa) + 1e-4
return mu_all, kappa
def freeze_base_for_adaptation(self) -> None:
for p in self.parameters():
p.requires_grad = False
def unfreeze_lora(m: nn.Module) -> None:
if isinstance(m, LoRALinear):
for p in m.lora_parameters():
p.requires_grad = True
self.apply(unfreeze_lora)
self.log_kappa.requires_grad = True
def unfreeze_all(self) -> None:
for p in self.parameters():
p.requires_grad = True
# ----------------------------
# Losses & metrics
# ----------------------------
def nb_nll(y: torch.Tensor, mu: torch.Tensor, kappa: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
y = torch.clamp(y, min=0.0)
mu = torch.clamp(mu, min=eps)
k = torch.clamp(kappa, min=eps)
loglik = (torch.lgamma(y + k) - torch.lgamma(k) - torch.lgamma(y + 1.0)
+ k * (torch.log(k) - torch.log(k + mu))
+ y * (torch.log(mu) - torch.log(k + mu)))
return -loglik
def mae_np(a: np.ndarray, b: np.ndarray) -> float:
return float(np.mean(np.abs(a - b)))
def rmse_np(a: np.ndarray, b: np.ndarray) -> float:
return float(np.sqrt(np.mean((a - b) ** 2)))
# ----------------------------
# Hierarchical reconciliation
# ----------------------------
def reconcile_mint(y_hat: np.ndarray, S: np.ndarray, W_diag: np.ndarray) -> np.ndarray:
W_inv = np.diag(1.0 / (W_diag + 1e-8)).astype(np.float64)
S64 = S.astype(np.float64)
middle = S64.T @ W_inv @ S64
middle_inv = np.linalg.pinv(middle)
P = S64 @ middle_inv @ S64.T @ W_inv
return ((P @ y_hat.T).T).astype(np.float32)
def coherence_error(y: np.ndarray, S: np.ndarray, bottom_dim: int) -> float:
yb = y[..., :bottom_dim]
implied = (S @ yb.T).T
num = np.linalg.norm((y - implied).reshape(-1))
den = np.linalg.norm(y.reshape(-1)) + 1e-8
return float(num / den)
# ----------------------------
# Online residual correction + drift detection
# ----------------------------
@dataclass
class OnlineConfig:
d_r: int = 16
F_decay: float = 0.92
q: float = 0.06
ph_delta: float = 0.005
ph_lambda: float = 0.85
adapt_window: int = 192
adapt_steps: int = 18
adapt_lr: float = 8e-3
adapt_weight_decay: float = 1e-4
beta: float = 0.005 # Lowered from 0.04 to avoid chasing noise
r_scale: float = 1.0 # Increased trust in base model
class ResidualKalman:
def __init__(self, n_series: int, cfg: OnlineConfig, seed: int = 0):
self.cfg = cfg
rng = np.random.default_rng(seed + 999)
P = rng.normal(0.0, 1.0, size=(cfg.d_r, n_series)).astype(np.float32)
P = P / (np.linalg.norm(P, axis=1, keepdims=True) + 1e-8)
self.P = P
self.PT = P.T
self.F = np.eye(cfg.d_r, dtype=np.float32) * cfg.F_decay
self.Q = np.eye(cfg.d_r, dtype=np.float32) * cfg.q
self.R = np.eye(cfg.d_r, dtype=np.float32) * cfg.r_scale # Use r_scale here
self.e = np.zeros((cfg.d_r,), dtype=np.float32)
self.Sigma = np.eye(cfg.d_r, dtype=np.float32) * 1.0
def predict(self) -> np.ndarray:
self.e = self.F @ self.e
self.Sigma = self.F @ self.Sigma @ self.F.T + self.Q
return (self.PT @ self.e).astype(np.float32)
def update(self, r: np.ndarray) -> np.ndarray:
r_tilde = (self.P @ r).astype(np.float32)
S = self.Sigma + self.R
Sinv = np.linalg.inv(S.astype(np.float64)).astype(np.float32)
K = self.Sigma @ Sinv
innov = r_tilde - self.e
self.e = self.e + K @ innov
self.Sigma = (np.eye(self.cfg.d_r, dtype=np.float32) - K) @ self.Sigma
return (self.PT @ self.e).astype(np.float32)
class PageHinkley:
def __init__(self, delta: float = 0.005, lamb: float = 0.85):
self.delta = delta
self.lamb = lamb
self.reset()
def reset(self) -> None:
self.t = 0
self.mean = 0.0
self.m = 0.0
self.M = 0.0
def update(self, x: float) -> bool:
self.t += 1
self.mean = self.mean + (x - self.mean) / self.t
self.m = self.m + (x - self.mean - self.delta)
self.M = min(self.M, self.m)
return (self.m - self.M) > self.lamb
# ----------------------------
# Training + evaluation
# ----------------------------
@dataclass(frozen=True)
class TrainConfig:
"""
Training configuration with best practices from MIT CSAIL, Stanford AI Lab, Harvard ML.
Includes:
- Cosine annealing LR schedule with warmup (Loshchilov & Hutter, 2017)
- Early stopping to prevent overfitting
- Gradient accumulation for larger effective batch sizes
"""
epochs: int = 30
batch_size: int = 64
lr: float = 2e-3
lr_min: float = 1e-6
weight_decay: float = 5e-4
grad_clip: float = 1.0
loss_bottom_weight: float = 1.3
loss_agg_weight: float = 0.7
# Learning rate scheduling
warmup_epochs: int = 1
use_cosine_schedule: bool = True
# Early stopping
early_stopping_patience: int = 8
early_stopping_min_delta: float = 1e-4
# Gradient accumulation
accumulation_steps: int = 1
class EarlyStopping:
"""Early stopping to prevent overfitting (Stanford best practice)."""
def __init__(self, patience: int = 5, min_delta: float = 1e-4, mode: str = "min"):
self.patience = patience
self.min_delta = min_delta
self.mode = mode
self.counter = 0
self.best_score: Optional[float] = None
self.should_stop = False
def __call__(self, score: float) -> bool:
if self.best_score is None:
self.best_score = score
return False
if self.mode == "min":
improved = score < (self.best_score - self.min_delta)
else:
improved = score > (self.best_score + self.min_delta)
if improved:
self.best_score = score
self.counter = 0
else:
self.counter += 1
if self.counter >= self.patience:
self.should_stop = True
return self.should_stop
def train_offline(bundle: DataBundle, wcfg: WindowConfig, split: SplitConfig,
mcfg: Dict[str, object], tcfg: TrainConfig,
device: torch.device, verbose: bool = True) -> Tuple[DTSGSSF, Dict[str, float]]:
"""
Offline training with ML best practices:
- Cosine annealing LR schedule with linear warmup
- Early stopping to prevent overfitting
- Gradient accumulation for larger effective batch sizes
"""
T, N, F_in = bundle.X.shape
n_series = bundle.y_all.shape[1]
n_agg = n_series - N
train_rng, val_rng, test_rng = make_splits(T, split)
ds_train = WindowDataset(bundle.X, bundle.y_all, wcfg, train_rng[0], train_rng[1])
ds_val = WindowDataset(bundle.X, bundle.y_all, wcfg, val_rng[0], val_rng[1])
# Optimized DataLoader (pin_memory for faster GPU transfer, if available)
dl_train = torch.utils.data.DataLoader(
ds_train,
batch_size=tcfg.batch_size,
shuffle=True,
drop_last=True,
pin_memory=(device.type == 'cuda'),
)
dl_val = torch.utils.data.DataLoader(
ds_val,
batch_size=tcfg.batch_size,
shuffle=False,
drop_last=False,
pin_memory=(device.type == 'cuda'),
)
model = DTSGSSF(
N=N, F_in=F_in, n_series=n_series, n_agg=n_agg, A_phys=bundle.net.A_phys,
d_model=int(mcfg.get("d_model", 64)), horizon=wcfg.horizon, K=int(mcfg.get("K", 2)),
lora_r=int(mcfg.get("lora_r", 8)), dropout=float(mcfg.get("dropout", 0.1))
).to(device)
opt = torch.optim.AdamW(model.parameters(), lr=tcfg.lr, weight_decay=tcfg.weight_decay)
# Learning rate scheduler with warmup + cosine annealing
if tcfg.use_cosine_schedule:
def lr_lambda(epoch: int) -> float:
if epoch < tcfg.warmup_epochs:
# Linear warmup
return (epoch + 1) / max(1, tcfg.warmup_epochs)
else:
# Cosine annealing
progress = (epoch - tcfg.warmup_epochs) / max(1, tcfg.epochs - tcfg.warmup_epochs)
return max(tcfg.lr_min / tcfg.lr, 0.5 * (1.0 + math.cos(math.pi * progress)))
scheduler = torch.optim.lr_scheduler.LambdaLR(opt, lr_lambda)
else:
scheduler = None
# Early stopping
early_stopper = EarlyStopping(
patience=tcfg.early_stopping_patience,
min_delta=tcfg.early_stopping_min_delta,
mode="min"
)
best_val = float("inf")
best_state = None
def batch_loss(batch: Dict[str, torch.Tensor]) -> torch.Tensor:
x = batch["x"].to(device)
y = batch["y"].to(device)
mu, kappa = model(x)
loss = nb_nll(y, mu, kappa).mean(dim=(0, 1)) # (n_series,)
w = torch.ones((n_series,), device=device)
w[:N] *= tcfg.loss_bottom_weight
w[N:] *= tcfg.loss_agg_weight
return (loss * w).mean()
for ep in range(tcfg.epochs):
model.train()
t0 = time.time()
tr = 0.0
nb = 0
opt.zero_grad(set_to_none=True)
for i, batch in enumerate(dl_train):
L = batch_loss(batch)
# Gradient accumulation: normalize loss by accumulation steps
if tcfg.accumulation_steps > 1:
L = L / tcfg.accumulation_steps
L.backward()
# Update weights every accumulation_steps batches
if (i + 1) % tcfg.accumulation_steps == 0 or (i + 1) == len(dl_train):
nn.utils.clip_grad_norm_(model.parameters(), tcfg.grad_clip)
opt.step()
opt.zero_grad(set_to_none=True)
tr += float(L.detach().cpu()) * (tcfg.accumulation_steps if tcfg.accumulation_steps > 1 else 1)
nb += 1
model.eval()
with torch.no_grad():
vl = 0.0; vn = 0
for batch in dl_val:
vl += float(batch_loss(batch).detach().cpu()); vn += 1
vl = vl / max(1, vn)
# Get current learning rate
current_lr = opt.param_groups[0]['lr']
if verbose:
train_loss = tr / max(1, nb)
best_val_print = best_val if best_val < float("inf") else None
RichLogger.epoch_summary(ep + 1, tcfg.epochs, train_loss, vl, current_lr, time.time() - t0, best_val_print)
is_best = vl < (best_val - 1e-6)
if is_best:
best_val = vl
best_state = {
"model_state_dict": model.state_dict(),
"config": dataclasses.asdict(mcfg) if dataclasses.is_dataclass(mcfg) else dict(mcfg),
"train_config": dataclasses.asdict(tcfg),
"window_config": dataclasses.asdict(wcfg),
"split_config": dataclasses.asdict(split),
"epoch": ep,
"val_loss": vl,
"data_meta": {
"N": N,
"F_in": F_in,
"n_series": n_series,