Spaces:
Running

File size: 11,960 Bytes
d1ffd83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)