runtime.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from __future__ import annotations
  2. from dataclasses import dataclass
  3. from datetime import datetime
  4. import json
  5. from pathlib import Path
  6. import tomllib
  7. from typing import Any
  8. @dataclass(frozen=True)
  9. class RuntimePaths:
  10. root_dir: Path
  11. analysis_dir: Path
  12. output_root: Path
  13. run_dir: Path
  14. def load_config(root_dir: Path) -> dict[str, Any]:
  15. config_path = root_dir / "config.toml"
  16. with config_path.open("rb") as f:
  17. return tomllib.load(f)
  18. def init_runtime_paths(analysis_dir: Path, run_name: str | None = None) -> RuntimePaths:
  19. root_dir = analysis_dir.parent
  20. output_root = root_dir / "analysis_output"
  21. output_root.mkdir(parents=True, exist_ok=True)
  22. safe_run_name = run_name or datetime.now().strftime("run_%Y%m%d_%H%M%S")
  23. run_dir = output_root / safe_run_name
  24. run_dir.mkdir(parents=True, exist_ok=True)
  25. return RuntimePaths(
  26. root_dir=root_dir,
  27. analysis_dir=analysis_dir,
  28. output_root=output_root,
  29. run_dir=run_dir,
  30. )
  31. def backend_dir(paths: RuntimePaths, backend: str) -> Path:
  32. out = paths.run_dir / backend
  33. out.mkdir(parents=True, exist_ok=True)
  34. return out
  35. def write_json(path: Path, payload: dict[str, Any]) -> None:
  36. path.parent.mkdir(parents=True, exist_ok=True)
  37. with path.open("w", encoding="utf-8") as f:
  38. json.dump(payload, f, indent=2)