forked from caoji2001/HOSER
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_pipeline.py
More file actions
3454 lines (2922 loc) · 137 KB
/
python_pipeline.py
File metadata and controls
3454 lines (2922 loc) · 137 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
#!/usr/bin/env python3
"""
Bulletproof Python Pipeline for HOSER Evaluation
This script imports gene.py and evaluation.py directly to orchestrate
trajectory generation and evaluation. Designed to work with evaluation
directories created by setup_evaluation.py.
Usage:
# From inside an evaluation directory created by setup_evaluation.py:
cd hoser-evaluation-xyz-20241024_123456
uv run python ../python_pipeline.py [OPTIONS]
# Or with explicit paths:
uv run python python_pipeline.py --eval-dir path/to/eval/dir [OPTIONS]
Options:
--eval-dir DIR Evaluation directory (default: current directory)
--seed SEED Random seed (default: from config)
--models MODEL1,MODEL2 Models to run (default: auto-detect all)
--od-source SOURCE OD source: train or test (default: from config)
--skip-gene Skip generation (use existing trajectories)
--skip-eval Skip evaluation
--force Force re-run even if results exist
--cuda DEVICE CUDA device (default: from config)
--num-gene N Number of trajectories (default: from config)
--wandb-project PROJECT WandB project name (default: from config)
--no-wandb Disable WandB logging entirely
--verbose Enable verbose output
--run-scenarios Run scenario analysis after evaluation
--scenarios-config PATH Path to scenarios config YAML
"""
import os
import sys
import argparse
import threading
import re
from functools import wraps
from pathlib import Path
from typing import List, Dict, Any, Optional, Callable, Set
import logging
class _SafeStreamHandler(logging.StreamHandler):
def emit(self, record):
try:
super().emit(record)
except (PermissionError, OSError, ValueError):
# Some cluster environments can intermittently make stdout/stderr
# unwritable (e.g., closed TTY, redirected stream). Logging should
# never crash or spam internal tracebacks.
return
def flush(self):
try:
super().flush()
except (PermissionError, OSError, ValueError):
return
class _SafeFileHandler(logging.FileHandler):
def emit(self, record):
try:
super().emit(record)
except (PermissionError, OSError, ValueError):
return
def flush(self):
try:
super().flush()
except (PermissionError, OSError, ValueError):
return
# Detect if we're running from inside an eval directory or from project root
SCRIPT_DIR = Path(__file__).parent
CURRENT_DIR = Path.cwd()
# Add appropriate paths for imports based on location
if (CURRENT_DIR / "models").exists() and (CURRENT_DIR / "config").exists():
# Running from inside an evaluation directory
EVAL_DIR = CURRENT_DIR
PROJECT_ROOT = SCRIPT_DIR # python_pipeline.py is in project root
else:
# Running from project root or elsewhere
EVAL_DIR = None # Will be set from args
PROJECT_ROOT = SCRIPT_DIR
sys.path.insert(0, str(PROJECT_ROOT))
# Import the programmatic interfaces
from gene import generate_trajectories_programmatic # noqa: E402
from evaluation import evaluate_trajectories_programmatic # noqa: E402
from utils import set_seed # noqa: E402
import yaml # noqa: E402
import torch # noqa: E402
import wandb # noqa: E402
from tools.model_detection import extract_model_name # noqa: E402
# Configure logging
# Some environments (shared filesystems, read-only eval dirs, restrictive symlinks)
# can make a log file unwritable. In that case, fall back to stderr logging only.
logging.raiseExceptions = False
_log_handlers: List[logging.Handler] = [_SafeStreamHandler()]
try:
# Open immediately so unwritable paths are detected here (not during emit/flush).
_log_handlers.append(
_SafeFileHandler(Path.cwd() / "pipeline.log", mode="a", encoding="utf-8")
)
except OSError:
pass
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
handlers=_log_handlers,
)
logger = logging.getLogger(__name__)
# Phase Decorator Infrastructure
# Phase registry - auto-populated by decorator
PHASE_REGISTRY: Dict[str, Callable] = {}
def phase(name: str, critical: bool = False):
"""Decorator to register a pipeline phase
Args:
name: Phase identifier (used in CLI)
critical: If True, pipeline stops on failure
"""
def decorator(func):
PHASE_REGISTRY[name] = {"func": func, "critical": critical, "name": name}
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator
class PipelineConfig:
"""Configuration for the evaluation pipeline"""
def __init__(self, config_path: str = None, eval_dir: Path = None):
# Store evaluation directory
self.eval_dir = eval_dir
# Default values
self.wandb_project = "hoser-evaluation"
self.dataset = "Beijing"
self.cuda_device = 0
self.num_gene = 100
self.seed = 42
self.models = [] # Auto-detect
self.od_sources = ["train", "test"]
# Optional dataset root override (can be absolute or relative to eval dir)
# Used by eval workspaces that keep datasets outside ../data/{dataset}.
self.data_dir: Optional[str] = None
# NEW: Phase-based control (replaces skip_* flags)
# Note: stored as a set for membership checks; execution order is defined
# in `_phase_execution_order()`.
self.phases: Set[str] = {
"generation",
"base_eval",
"perturbation_correction",
"paired_analysis",
"cross_dataset",
"road_network_translate",
"abnormal",
"abnormal_od_extract",
"abnormal_od_generate",
"abnormal_od_evaluate",
"wang_abnormality",
"lmtad_spatial_abnormality",
"scenarios",
}
# When True, `phases` was set explicitly by the operator (e.g., via --only).
# In that case we should NOT auto-add phases based on feature flags, so that
# `--only X` really means only X.
self.phases_explicit: bool = False
# Other settings
self.force = False
self.enable_wandb = True
self.verbose = False
self.beam_width = 4
self.beam_search = True # Use beam search by default (set False for A* search)
self.grid_size = 0.001
self.edr_eps = 100.0
self.background_sync = True # Background WandB sync
self.run_scenarios = False # NEW: Run scenario analysis after eval
self.scenarios_config = None # NEW: Path to scenarios config
self.cross_dataset_eval = None # NEW: Path to cross-dataset for evaluation
self.cross_dataset_name = (
None # NEW: Name of cross-dataset (e.g., BJUT_Beijing)
)
self.run_abnormal_detection = False # NEW: Run abnormal trajectory detection
self.abnormal_config = None # NEW: Path to abnormal detection config
self.run_wang_detection = (
False # NEW: Run Wang statistical abnormality detection
)
self.wang_config = None # NEW: Path to Wang statistical detection config
self.run_lmtad_spatial_detection = (
False # NEW: Run LM-TAD spatial abnormality detection
)
self.lmtad_spatial_config = None # NEW: Path to LM-TAD spatial config file
self.lmtad_source_eval_dir = None # NEW: Path to LM-TAD source eval directory
self.lmtad_num_trajectories_per_od = (
None # NEW: Override num trajectories per OD pair
)
self.lmtad_max_od_pairs = None # NEW: Override max OD pairs to sample
self.lmtad_max_duplicate_ratio = (
0.1 # NEW: Duplicate threshold for LM-TAD validation
)
# Phase B: perturbation correction evaluation (optional)
self.perturbation_source_csv: Optional[str] = None
self.perturbation_od_source: str = "train"
self.perturbation_max_entries: Optional[int] = None
self.perturbation_seed: int = 0
self.perturbation_use_astar: bool = True
self.perturbation_lmtad_checkpoint: Optional[str] = None
self.perturbation_lmtad_repo: Optional[str] = None
self.perturbation_lmtad_batch_size: int = 128
# Load from YAML if provided
if config_path:
self.load_from_yaml(config_path)
def load_from_yaml(self, config_path: str):
"""Load configuration from YAML file"""
with open(config_path, "r") as f:
config_data = yaml.safe_load(f)
# Update attributes from config
for key, value in config_data.items():
if key == "wandb":
wandb_config = value
self.wandb_project = wandb_config.get("project", self.wandb_project)
self.enable_wandb = wandb_config.get("enable", self.enable_wandb)
self.background_sync = wandb_config.get(
"background_sync", self.background_sync
)
elif key == "logging":
logging_config = value
self.verbose = logging_config.get("verbose", self.verbose)
elif key == "phases":
# Ensure phases is always a set (YAML may load as list)
self.phases = set(value) if isinstance(value, (list, set)) else value
elif hasattr(self, key):
setattr(self, key, value)
class ModelDetector:
"""Auto-detect models in the models directory"""
def __init__(self, models_dir: Path):
self.models_dir = models_dir
@staticmethod
def _extract_model_type_from_filename(filename: str) -> str:
"""Extract a canonical model type from a checkpoint filename.
Delegates to the centralized `tools.model_detection.extract_model_name` so
naming conventions remain consistent across the codebase.
"""
return extract_model_name(filename)
def detect_models(self) -> List[str]:
"""Detect all available models and return unique model types"""
if not self.models_dir.exists():
raise FileNotFoundError(f"Models directory not found: {self.models_dir}")
model_files = list(self.models_dir.glob("*.pth"))
if not model_files:
raise FileNotFoundError(f"No .pth files found in {self.models_dir}")
model_types = []
for model_file in model_files:
model_type = self._extract_model_type_from_filename(model_file.name)
model_types.append(model_type)
# Remove duplicates and sort
unique_types = sorted(list(set(model_types)))
logger.info(f"Detected models: {unique_types}")
return unique_types
def find_model_file(self, model_type: str) -> Optional[Path]:
"""Find the actual model file for a given model type"""
for model_file in self.models_dir.glob("*.pth"):
extracted_type = self._extract_model_type_from_filename(model_file.name)
if extracted_type == model_type:
return model_file
return None
class TrajectoryGenerator:
"""Generate trajectories using HOSER models"""
def __init__(self, config: PipelineConfig):
self.config = config
@staticmethod
def _infer_seed_from_model_type(model_type: str) -> Optional[int]:
"""Infer a numeric seed from a model type string.
Examples:
- "seed42" -> 42
- "distilled_l0p001_seed43" -> 43
Returns:
Parsed seed integer if present, otherwise None.
"""
match = re.search(r"seed(\d+)", model_type)
if not match:
return None
try:
return int(match.group(1))
except ValueError:
return None
def generate_trajectories(
self, model_path: Path, model_type: str, od_source: str
) -> tuple[Path, dict]:
"""Generate trajectories for a specific model and OD source
Returns:
Tuple of (output_path, performance_metrics)
"""
logger.info(f"Generating trajectories: {model_type} ({od_source} OD)")
model_seed = self._infer_seed_from_model_type(model_type) or self.config.seed
# Use the programmatic interface (returns dict with output_file, num_generated, performance)
result = generate_trajectories_programmatic(
dataset=self.config.dataset,
model_path=str(model_path),
od_source=od_source,
seed=model_seed,
num_gene=self.config.num_gene,
data_dir=self.config.data_dir,
cuda_device=self.config.cuda_device,
beam_search=self.config.beam_search,
beam_width=self.config.beam_width,
enable_wandb=False, # We'll handle WandB separately
wandb_project=None,
wandb_run_name=None,
wandb_tags=None,
model_type=model_type,
)
output_path = Path(result["output_file"])
performance = result.get("performance", {})
# Log performance summary
if performance:
logger.info(
f"Generation performance: {performance.get('throughput_traj_per_sec', 0):.2f} traj/s, "
+ f"mean time: {performance.get('total_time_mean', 0):.3f}s"
)
logger.info(f"Trajectories saved to: {output_path}")
return output_path, performance
class TrajectoryEvaluator:
"""Evaluate generated trajectories against real data with smart caching"""
def __init__(self, config: PipelineConfig):
self.config = config
self.evaluation_cache = {} # Cache full evaluations by (file, od_source)
def evaluate_trajectories(
self,
generated_file: Path,
model_type: str,
od_source: str,
generation_performance: dict = None,
) -> Dict[str, Any]:
"""Evaluate generated trajectories with caching and optional performance metrics
Args:
generated_file: Path to generated trajectories
model_type: Model type identifier
od_source: OD source (train/test)
generation_performance: Optional performance metrics from generation
"""
cache_key = (str(generated_file), od_source)
# Check if we've already evaluated this exact combination
if cache_key in self.evaluation_cache:
logger.info(
f"Using cached evaluation results for {model_type} ({od_source} OD)"
)
cached_results = self.evaluation_cache[cache_key]
# Update with new performance metrics if provided
if generation_performance:
cached_results["generation_performance"] = generation_performance
return cached_results
logger.info(f"Evaluating trajectories: {model_type} ({od_source} OD)")
# Use the programmatic interface with performance metrics
results = evaluate_trajectories_programmatic(
generated_file=str(generated_file),
dataset=self.config.dataset,
od_source=od_source, # Pass OD source to load correct real data
data_dir=getattr(self.config, "data_dir", None),
grid_size=self.config.grid_size,
edr_eps=self.config.edr_eps,
enable_wandb=False, # We'll handle WandB separately
wandb_project=None,
wandb_run_name=None,
wandb_tags=None,
generation_performance=generation_performance, # Pass performance metrics
)
# Cache the results
self.evaluation_cache[cache_key] = results
# Add our metadata
results["metadata"]["model_type"] = model_type
results["metadata"]["od_source"] = od_source
results["metadata"]["seed"] = self.config.seed
# Re-save the results file with updated metadata
# Find the results file path from the eval directory structure
eval_dirs = sorted(Path("./eval").glob("20*"), key=lambda x: x.stat().st_mtime)
if eval_dirs:
latest_results_file = eval_dirs[-1] / "results.json"
if latest_results_file.exists():
import json
with open(latest_results_file, "w") as f:
json.dump(results, f, indent=4)
logger.debug(
f"Updated results file with model metadata: {latest_results_file}"
)
logger.info(f"Evaluation completed for {model_type} ({od_source} OD)")
return results
class WandBManager:
"""Manage WandB logging efficiently with background uploads"""
def __init__(self, config: PipelineConfig):
self.config = config
self.runs = {} # Store run objects
self.completed_runs = [] # Track completed runs for background sync
self.sync_thread = None
def init_run(
self, run_name: str, tags: List[str], config_dict: Dict[str, Any]
) -> str:
"""Initialize a WandB run and return run ID"""
if not self.config.enable_wandb:
return "wandb_disabled"
try:
# Use offline mode - no network delays
run = wandb.init(
project=self.config.wandb_project,
name=run_name,
tags=tags,
config=config_dict,
reinit=True,
mode="offline",
)
self.runs[run_name] = run
logger.info(f"WandB run initialized (offline): {run_name}")
return run.id
except Exception as e:
logger.warning(f"Failed to initialize WandB run: {e}")
return "wandb_failed"
def log_metrics(self, run_name: str, metrics: Dict[str, Any]):
"""Log metrics to WandB (offline, no upload delay)"""
if not self.config.enable_wandb or run_name not in self.runs:
return
try:
# Filter out non-scalar metrics
scalar_metrics = {
k: v
for k, v in metrics.items()
if isinstance(v, (int, float)) and k != "metadata"
}
if scalar_metrics:
self.runs[run_name].log(scalar_metrics)
except Exception as e:
logger.warning(f"Failed to log metrics to WandB: {e}")
def finish_run(self, run_name: str):
"""Finish a WandB run and track for background sync"""
if not self.config.enable_wandb or run_name not in self.runs:
return
try:
run = self.runs[run_name]
run_dir = run.dir # Get the run directory before finishing
run.finish()
del self.runs[run_name]
# Track for background sync
self.completed_runs.append(run_dir)
logger.info(f"WandB run completed (offline): {run_name}")
except Exception as e:
logger.warning(f"Failed to finish WandB run: {e}")
def finish_all_runs(self):
"""Finish all remaining WandB runs"""
for run_name in list(self.runs.keys()):
self.finish_run(run_name)
def start_background_sync(self):
"""Start background thread to sync offline runs to WandB"""
if not self.config.enable_wandb or not self.completed_runs:
return
if not self.config.background_sync:
logger.info(f"📤 {len(self.completed_runs)} WandB runs saved offline")
logger.info(" To upload: uv run wandb sync wandb/offline-run-*")
return
def sync_worker():
"""Background worker to sync runs"""
logger.info(
f"📤 Starting background sync of {len(self.completed_runs)} WandB runs..."
)
import subprocess
synced = 0
failed = 0
for run_dir in self.completed_runs:
try:
# Use subprocess to run wandb sync via uv
result = subprocess.run(
["uv", "run", "wandb", "sync", run_dir],
capture_output=True,
text=True,
timeout=300, # 5 min timeout per run
)
if result.returncode == 0:
synced += 1
logger.info(
f"✅ Synced {synced}/{len(self.completed_runs)}: {os.path.basename(run_dir)}"
)
else:
failed += 1
logger.warning(f"⚠️ Sync failed: {os.path.basename(run_dir)}")
except Exception as e:
failed += 1
logger.warning(f"Error syncing {os.path.basename(run_dir)}: {e}")
logger.info(
f"📤 Background sync complete! {synced} synced, {failed} failed"
)
# Start background thread (daemon=False so it completes even if main exits)
self.sync_thread = threading.Thread(target=sync_worker, daemon=False)
self.sync_thread.start()
logger.info("📤 Background WandB sync started (non-blocking)")
logger.info(" Pipeline will exit immediately. Sync continues in background.")
class EvaluationPipeline:
"""Main evaluation pipeline"""
def __init__(self, config: PipelineConfig, eval_dir: Path):
self.config = config
self.eval_dir = eval_dir
self.models_dir = self.eval_dir / "models"
self.detector = ModelDetector(self.models_dir)
self.generator = TrajectoryGenerator(config)
self.evaluator = TrajectoryEvaluator(config)
self.wandb_manager = WandBManager(config)
self.interrupted = False
# Change to eval directory for all operations
os.chdir(self.eval_dir)
logger.info(f"Working directory: {self.eval_dir}")
# Validate configuration
self._validate_config()
# Set random seed
set_seed(config.seed)
# Set PyTorch settings
torch.set_num_threads(torch.get_num_threads())
torch.backends.cudnn.benchmark = True
def _validate_config(self):
"""Validate pipeline configuration"""
logger.info("Validating pipeline configuration...")
def _raise_permission(path: Path, operation: str, exc: PermissionError):
raise PermissionError(
f"Permission denied while trying to {operation}: '{path}'. "
"This usually means the pipeline is running under a different UID than the files, "
"or the filesystem applies root-squash / restrictive directory permissions. "
"Run as the owning user (e.g., your login UID) or relax directory traverse permissions."
) from exc
# Check models directory
if not self.models_dir.exists():
raise FileNotFoundError(f"Models directory not found: {self.models_dir}")
# Check data directory
# Prefer an explicit config.data_dir, but fall back to common layouts.
candidate_dirs = []
if hasattr(self.config, "data_dir") and self.config.data_dir:
configured = Path(self.config.data_dir)
if not configured.is_absolute():
configured = self.eval_dir / configured
candidate_dirs.append(configured)
# Common eval layout: <eval-root>/../data/<dataset>
candidate_dirs.append(self.eval_dir.parent / "data" / self.config.dataset)
# Project-root layout: <repo>/data/<dataset>
candidate_dirs.append(PROJECT_ROOT / "data" / self.config.dataset)
data_dir = next((p for p in candidate_dirs if p.exists()), None)
if data_dir is None:
raise FileNotFoundError(
"Data directory not found. Tried: "
+ ", ".join(str(p) for p in candidate_dirs)
)
# Resolve symlink if needed
try:
if data_dir.is_symlink():
data_dir = data_dir.resolve()
except PermissionError as e:
_raise_permission(data_dir, "probe dataset symlink", e)
# Check required data files
required_files = ["test.csv", "roadmap.geo"]
for file in required_files:
file_path = data_dir / file
if not file_path.exists():
raise FileNotFoundError(f"Required data file not found: {file_path}")
# Validate cross-dataset evaluation if configured
if self.config.cross_dataset_eval:
cross_data_dir = Path(self.config.cross_dataset_eval)
if not cross_data_dir.is_absolute():
# Relative to eval dir
cross_data_dir = self.eval_dir / cross_data_dir
if not cross_data_dir.exists():
raise FileNotFoundError(
f"Cross-dataset directory not found: {cross_data_dir}"
)
# Resolve symlink if needed
try:
if cross_data_dir.is_symlink():
cross_data_dir = cross_data_dir.resolve()
except PermissionError as e:
_raise_permission(cross_data_dir, "probe cross-dataset symlink", e)
# Check required cross-dataset files
for file in required_files:
file_path = cross_data_dir / file
if not file_path.exists():
raise FileNotFoundError(
f"Required cross-dataset file not found: {file_path}"
)
logger.info(
f"✓ Cross-dataset evaluation enabled: {self.config.cross_dataset_name or cross_data_dir.name}"
)
# Check dataset config file (not required, just for validation)
# Config is in the eval directory itself
# Validate CUDA device
if torch.cuda.is_available():
if self.config.cuda_device >= torch.cuda.device_count():
raise ValueError(
f"CUDA device {self.config.cuda_device} not available. Only {torch.cuda.device_count()} devices found."
)
else:
logger.warning("CUDA not available, using CPU")
# Validate parameters
if self.config.num_gene <= 0:
raise ValueError("num_gene must be positive")
if self.config.beam_width <= 0:
raise ValueError("beam_width must be positive")
if self.config.grid_size <= 0:
raise ValueError("grid_size must be positive")
if self.config.edr_eps <= 0:
raise ValueError("edr_eps must be positive")
logger.info("Configuration validation passed")
def _check_existing_results(
self, model_type: str, od_source: str
) -> Optional[Path]:
"""Check if A* generated file exists and return path if found.
Only returns files that are confirmed to be A* search (beam_search_enabled: false).
If only beam search files exist, returns None to trigger A* generation.
"""
if self.config.force:
return None
def _csv_has_at_least_n_lines(path: Path, n_lines: int) -> bool:
try:
with open(path, "r") as f:
for i, _ in enumerate(f, start=1):
if i >= n_lines:
return True
return False
except OSError:
return False
# Check for existing generated file
model_seed = (
TrajectoryGenerator._infer_seed_from_model_type(model_type)
or self.config.seed
)
gene_dir = Path(f"./gene/{self.config.dataset}/seed{model_seed}")
# Try multiple patterns to support both Porto and Beijing naming conventions
patterns = [
f"*{model_type}*{od_source}.csv", # Primary: Porto and most Beijing
f"*{model_type}*{od_source}od*.csv", # Backward compatibility
f"{model_type}*{od_source}*.csv", # Beijing: model_type first
]
generated_files = []
for pattern in patterns:
generated_files.extend(gene_dir.glob(pattern))
if not generated_files:
return None
# Check each file to see if it's A* (beam_search_enabled: false)
# Sort by modification time, newest first
generated_files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
import json
for csv_file in generated_files:
# Check for corresponding perf.json file
perf_file = csv_file.parent / f"{csv_file.stem}_perf.json"
if perf_file.exists():
try:
with open(perf_file) as f:
perf_data = json.load(f)
# Check if this is an A* file (beam_search_enabled: false)
beam_search_enabled = perf_data.get("beam_search_enabled", True)
if not beam_search_enabled:
expected_traj = int(self.config.num_gene)
actual_traj = perf_data.get("num_trajectories")
# If perf metadata indicates an incomplete run, ignore it.
if isinstance(actual_traj, int) and actual_traj < expected_traj:
logger.warning(
"Ignoring incomplete generated file %s: %s/%s trajectories",
csv_file.name,
actual_traj,
expected_traj,
)
continue
# Fallback safety if perf is missing/old.
if not isinstance(actual_traj, int):
# header + expected trajectories
if not _csv_has_at_least_n_lines(csv_file, expected_traj + 1):
logger.warning(
"Ignoring incomplete generated file %s: fewer than %s lines",
csv_file.name,
expected_traj + 1,
)
continue
logger.info(
f"Found existing A* generated file: {csv_file.name}"
)
return csv_file
else:
logger.debug(
f"Skipping beam search file: {csv_file.name} "
f"(looking for A* file)"
)
continue
except (json.JSONDecodeError, KeyError) as e:
logger.warning(
f"Could not parse perf.json for {csv_file.name}: {e}. "
f"Assuming beam search, skipping."
)
continue
else:
# No perf.json file - assume it's an old file or beam search
# Skip it and continue looking
logger.debug(
f"No perf.json found for {csv_file.name}, skipping "
f"(looking for A* file)"
)
continue
# No A* files found, only beam search files exist
logger.info(
f"No A* generated file found for {model_type} ({od_source} OD). "
f"Will generate with A* search."
)
return None
def _handle_error(
self,
error: Exception,
context: str,
model_type: str = None,
od_source: str = None,
):
"""Handle errors with comprehensive logging"""
error_msg = f"Error in {context}"
if model_type:
error_msg += f" for {model_type}"
if od_source:
error_msg += f" ({od_source} OD)"
error_msg += f": {str(error)}"
logger.error(error_msg)
logger.error(f"Error type: {type(error).__name__}")
# Log stack trace for debugging
import traceback
logger.error(f"Stack trace:\n{traceback.format_exc()}")
# Continue execution unless it's a critical error
if isinstance(error, (FileNotFoundError, ValueError, KeyError)):
logger.error("Critical error encountered, stopping pipeline")
raise
else:
logger.warning(
"Non-critical error encountered, continuing with next operation"
)
def _build_file_to_model_mapping(self) -> Dict[str, tuple]:
"""Build mapping of generated file -> (model_type, od_source) from eval results"""
import json
mapping = {}
eval_dir = Path("./eval")
if not eval_dir.exists():
logger.warning("No eval directory found, cannot build file mapping")
return mapping
# Scan all evaluation result directories
for eval_subdir in eval_dir.iterdir():
if not eval_subdir.is_dir():
continue
results_file = eval_subdir / "results.json"
if results_file.exists():
try:
with open(results_file) as f:
results = json.load(f)
metadata = results.get("metadata", {})
generated_file = metadata.get("generated_file", "")
model_type = metadata.get("model_type", "")
od_source = metadata.get("od_source", "")
if generated_file and model_type and od_source:
# Normalize path to just the filename
file_path = Path(generated_file)
mapping[file_path.name] = (model_type, od_source)
logger.debug(
f"Mapped {file_path.name} -> {model_type} ({od_source} OD)"
)
except Exception as e:
logger.warning(f"Failed to read {results_file}: {e}")
logger.info(f"Built mapping for {len(mapping)} generated files")
return mapping
def _run_scenario_analysis(self):
"""Run scenario-based analysis on all generated trajectories"""
from tools.analyze_scenarios import (
run_scenario_analysis,
run_cross_model_scenario_analysis,
)
# Auto-detect scenarios config if not provided
if not self.config.scenarios_config:
# Try config/scenarios_{dataset}.yaml first
scenarios_config = Path(
f"./config/scenarios_{self.config.dataset.lower()}.yaml"
)
if not scenarios_config.exists():
# Fallback to config/scenarios.yaml
scenarios_config = Path("./config/scenarios.yaml")
if not scenarios_config.exists():
logger.warning("No scenarios config found, skipping scenario analysis")
return
else:
scenarios_config = Path(self.config.scenarios_config)
# Copy config to eval directory for reproducibility
config_copy = Path("./config") / scenarios_config.name
config_copy.parent.mkdir(exist_ok=True)
# Only copy if source and destination are different
import shutil
if scenarios_config.resolve() != config_copy.resolve():
shutil.copy(scenarios_config, config_copy)
logger.info(f"Copied scenarios config to {config_copy}")
else:
logger.info(f"Using existing scenarios config: {config_copy}")
# Build mapping of generated files to models
file_mapping = self._build_file_to_model_mapping()
# Output directory for scenarios
scenarios_output = Path("./scenarios")
# Step 1: Run individual model analysis for each OD source
logger.info("\n🎯 Step 1: Analyzing individual models...")
for od_source in self.config.od_sources:
logger.info(f"\nRunning scenario analysis for {od_source} OD...")
try:
# Find generated files for this OD source
gene_dir = Path(f"./gene/{self.config.dataset}/seed{self.config.seed}")
if not gene_dir.exists():
logger.warning(f"Gene directory not found: {gene_dir}")
continue
generated_files = list(gene_dir.glob("*.csv"))
if not generated_files:
logger.warning(f"No generated files found in {gene_dir}")
continue
# Filter by OD source using the mapping
od_files = []
for gen_file in generated_files:
if gen_file.name in file_mapping:
_, file_od = file_mapping[gen_file.name]
if file_od == od_source:
od_files.append(gen_file)
if not od_files:
logger.warning(f"No generated files found for {od_source} OD")
continue
logger.info(f"Found {len(od_files)} files for {od_source} OD")
# Run analysis on each generated file (one per model)
for gen_file in od_files:
# Get model name from mapping
if gen_file.name in file_mapping:
model_name, _ = file_mapping[gen_file.name]
else:
logger.warning(
f"No model mapping for {gen_file.name}, skipping"
)
continue
output_dir = scenarios_output / od_source / model_name
logger.info(f" Analyzing {model_name} ({od_source} OD)...")
run_scenario_analysis(
generated_file=gen_file,