Spaces:
Running

hyperFVC / workflow /utils /fvc_paths.py
lauransotomayor's picture
Mirror GitHub Pages presentation build (part 4)
d1ffd83 verified
Raw History Blame Contribute Delete
12 kB
"""Resolve project paths from ``configs/paths.yaml`` instead of hardcoding them.
The dataset behind this repository has lived on several drives (an external
SSD, an archive disk, and the ``/data`` mount inside the Docker/Jetson images),
so a literal path baked into a script only works on the machine it was written
on. This module reads the declared roots from ``configs/paths.yaml``, picks the
first one that exists, and lets every script ask for a *logical* location.
Typical use from a script anywhere in the tree::
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2])) # repo root
from utils.fvc_paths import site, layout
predictors = layout("predictors", site="site1", grid="3072")
masks = layout("masks", site="site1", grid="3072")
Every lookup honours an environment-variable override, so a one-off run against
a different disk needs no edit::
FVC_DATA_ROOT=/mnt/backup/calperumResearch python main_site_specific_models.py
Run ``python utils/fvc_paths.py --check`` to see which roots and sites resolve
on the current machine.
"""
from __future__ import annotations
import os
from functools import lru_cache
from pathlib import Path
from typing import Any
import yaml
__all__ = [
"repo_root",
"config",
"root",
"site",
"layout",
"resolve",
"PathResolutionError",
]
CONFIG_RELPATH = Path("configs") / "paths.yaml"
# Environment variable pointing at an alternative config file, for running the
# same checkout against a second data layout without editing the tracked YAML.
CONFIG_ENV = "FVC_PATHS_CONFIG"
class PathResolutionError(RuntimeError):
"""Raised when a root, site, or layout template cannot be resolved."""
@lru_cache(maxsize=1)
def repo_root() -> Path:
"""Return the repository root, located by walking up to ``configs/paths.yaml``."""
here = Path(__file__).resolve()
for candidate in (here, *here.parents):
if (candidate / CONFIG_RELPATH).is_file():
return candidate
raise PathResolutionError(
f"could not locate {CONFIG_RELPATH} above {here}; "
"is this file still inside the fvc_function checkout?"
)
@lru_cache(maxsize=1)
def config() -> dict[str, Any]:
"""Load and cache ``configs/paths.yaml`` (or ``$FVC_PATHS_CONFIG``)."""
override = os.environ.get(CONFIG_ENV, "").strip()
path = Path(override).expanduser() if override else repo_root() / CONFIG_RELPATH
if not path.is_file():
raise PathResolutionError(f"paths config not found: {path}")
with path.open("r", encoding="utf-8") as handle:
loaded = yaml.safe_load(handle) or {}
if not isinstance(loaded, dict):
raise PathResolutionError(f"paths config must be a mapping: {path}")
return loaded
def _expand(raw: str) -> Path:
"""Expand ``~`` and ``$VARS``; resolve relative paths against the repo root."""
expanded = Path(os.path.expandvars(str(raw))).expanduser()
return expanded if expanded.is_absolute() else (repo_root() / expanded).resolve()
def root(name: str, *, required: bool = True) -> Path:
"""Resolve a named storage root declared under ``roots:``.
Resolution order: the root's ``env`` variable, then each entry in
``candidates`` until one exists on disk.
Args:
name: Root key, e.g. ``"data"``, ``"qgis"``, ``"uas"``, ``"scratch"``.
required: When True (default), raise if no candidate exists. Pass False
to fall back to the first candidate — appropriate for output roots
that are about to be created.
Raises:
PathResolutionError: If the root is undeclared, or ``required`` is True
and no candidate exists. The message lists every path tried.
"""
roots = config().get("roots", {})
if name not in roots:
raise PathResolutionError(
f"unknown root {name!r}; declared roots: {sorted(roots)}"
)
spec = roots[name] or {}
env_var = spec.get("env")
if env_var:
override = os.environ.get(env_var, "").strip()
if override:
return _expand(override)
candidates = [_expand(c) for c in spec.get("candidates", [])]
if not candidates:
raise PathResolutionError(f"root {name!r} declares no candidates")
for candidate in candidates:
if candidate.exists():
return candidate
# Roots flagged `create: true` are outputs — make them rather than fail.
if spec.get("create"):
candidates[0].mkdir(parents=True, exist_ok=True)
return candidates[0]
if not required:
return candidates[0]
tried = "\n ".join(str(c) for c in candidates)
hint = f" or set ${env_var}" if env_var else ""
raise PathResolutionError(
f"no candidate for root {name!r} exists on this machine. Tried:\n {tried}\n"
f"Edit {CONFIG_RELPATH}{hint}."
)
def site(key: str, *, required: bool = True) -> Path:
"""Resolve a site directory declared under ``sites:``.
Args:
key: Short site key, e.g. ``"site1"``. Also accepts an on-disk directory
name (``"site1_1_DD0001"``) or an absolute path, both returned as-is
after expansion, so callers can accept either from the command line.
"""
sites = config().get("sites", {})
if key in sites:
spec = sites[key] or {}
try:
base = root(spec["root"], required=required)
except KeyError as exc: # malformed entry
raise PathResolutionError(
f"site {key!r} is missing a 'root' field in {CONFIG_RELPATH}"
) from exc
return base / spec["dir"]
# Passthrough: an absolute path or a bare directory name under the data root.
candidate = Path(os.path.expandvars(key)).expanduser()
if candidate.is_absolute():
return candidate
if "/" in key or key.startswith("."):
return _expand(key)
raise PathResolutionError(
f"unknown site {key!r}; declared sites: {sorted(sites)}. "
f"Pass an absolute path, or add the site to {CONFIG_RELPATH}."
)
def layout(name: str, *, required: bool = False, **fields: Any) -> Path:
"""Build a path from a named template under ``layout:``.
``site`` is resolved through :func:`site` before substitution; any other
field is substituted verbatim. Fields omitted by the caller fall back to
``defaults:`` in the config.
Templates describe outputs as well as inputs, so by default this does not
require the path (or its root) to exist — use ``required=True``, or
``--check``, to gate on existence.
Example::
layout("predictors", site="site1", grid="3072")
# -> <data root>/site1_1_DD0001/inputs/predictors/tiles_3072
"""
templates = config().get("layout", {})
if name not in templates:
raise PathResolutionError(
f"unknown layout {name!r}; declared layouts: {sorted(templates)}"
)
values: dict[str, Any] = dict(config().get("defaults", {}))
values.update(fields)
values["site"] = site(str(values.get("site")), required=required)
template = templates[name]
try:
return Path(template.format(**{k: str(v) for k, v in values.items()}))
except KeyError as exc:
missing = exc.args[0]
raise PathResolutionError(
f"layout {name!r} needs a {missing!r} argument "
f"(template: {template})"
) from exc
def resolve(spec: str, **fields: Any) -> Path:
"""Resolve a ``"<kind>:<name>"`` string, for CLI arguments and config files.
Supported kinds: ``root``, ``site``, ``layout``. Anything else is treated as
a literal filesystem path, so callers can accept either form::
resolve("layout:predictors", site="site1", grid="3072")
resolve("site:site1")
resolve("/mnt/scratch/tiles") # passthrough
"""
kind, _, name = spec.partition(":")
if not name:
return _expand(spec)
if kind == "root":
return root(name)
if kind == "site":
return site(name)
if kind == "layout":
return layout(name, **fields)
return _expand(spec)
def _check() -> int:
"""Print every declared root and site with its resolution status."""
cfg = config()
ok = True
print(f"repo root: {repo_root()}")
print(f"config: {os.environ.get(CONFIG_ENV) or repo_root() / CONFIG_RELPATH}\n")
print("roots:")
for name in cfg.get("roots", {}):
try:
path = root(name)
mark = "OK " if path.exists() else "MISSING"
ok &= path.exists()
print(f" [{mark}] {name:<10} {path}")
except PathResolutionError as exc:
ok = False
detail = str(exc).replace("\n", "\n ")
print(f" [FAIL ] {name:<10} {detail}")
print("\nsites:")
for name in cfg.get("sites", {}):
try:
path = site(name, required=False)
mark = "OK " if path.exists() else "MISSING"
print(f" [{mark}] {name:<20} {path}")
except PathResolutionError as exc:
print(f" [FAIL ] {name:<20} {exc}")
print("\nAll roots resolved." if ok else "\nSome roots did not resolve (see above).")
return 0 if ok else 1
def _shell_exports() -> str:
"""Emit ``FVC_ROOT_<NAME>`` / ``FVC_SITE_<NAME>`` assignments for shell ``eval``.
Lets a shell script resolve every declared location in one interpreter start
rather than one per lookup. Consumed by ``scripts/lib/fvc_env.sh``.
"""
lines = [f"FVC_REPO_ROOT={_quote(repo_root())}"]
for name in config().get("roots", {}):
try:
lines.append(f"FVC_ROOT_{name.upper()}={_quote(root(name, required=False))}")
except PathResolutionError:
continue
for name in config().get("sites", {}):
try:
lines.append(f"FVC_SITE_{name.upper()}={_quote(site(name, required=False))}")
except PathResolutionError:
continue
return "\n".join(lines)
def _quote(value: Any) -> str:
"""Single-quote a path for safe shell eval (roots contain spaces, e.g. 'Extreme SSD')."""
text = str(value).replace("'", "'\\''")
return f"'{text}'"
if __name__ == "__main__":
import argparse
import sys
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"--check", action="store_true", help="report resolution status for all entries"
)
parser.add_argument("--root", help="print a resolved root and exit")
parser.add_argument("--site", help="print a resolved site and exit")
parser.add_argument("--layout", help="print a resolved layout template and exit")
parser.add_argument(
"--set",
action="append",
default=[],
metavar="KEY=VALUE",
help="field for --layout, e.g. --set site=site1 --set grid=3072",
)
parser.add_argument(
"--shell",
action="store_true",
help="emit shell assignments for all roots and sites (for eval)",
)
parser.add_argument(
"--required",
action="store_true",
help="with --root/--site, fail if the path does not exist",
)
args = parser.parse_args()
try:
if args.shell:
print(_shell_exports())
elif args.root:
print(root(args.root, required=args.required))
elif args.site:
print(site(args.site, required=args.required))
elif args.layout:
fields = dict(kv.split("=", 1) for kv in args.set)
print(layout(args.layout, required=args.required, **fields))
else:
sys.exit(_check())
except PathResolutionError as exc:
print(f"fvc_paths: {exc}", file=sys.stderr)
sys.exit(2)
except ValueError:
print("fvc_paths: --set expects KEY=VALUE", file=sys.stderr)
sys.exit(2)