|
11 | 11 |
|
12 | 12 | import functools |
13 | 13 | import importlib.metadata |
| 14 | +import json |
14 | 15 | import platform as _platform |
| 16 | +import re |
15 | 17 | import subprocess |
| 18 | +from collections.abc import Mapping |
| 19 | +from dataclasses import asdict |
16 | 20 | from dataclasses import dataclass |
17 | 21 | from dataclasses import replace |
18 | 22 | from datetime import UTC |
@@ -158,6 +162,113 @@ def display_rows(self) -> list[tuple[str, str]]: |
158 | 162 | return rows |
159 | 163 |
|
160 | 164 |
|
| 165 | +def _stem_value(value: Any) -> str: |
| 166 | + """Format a parameter value for use in a filename stem.""" |
| 167 | + return re.sub(r"[^A-Za-z0-9_+-]", "-", str(value).replace(".", "p")) |
| 168 | + |
| 169 | + |
| 170 | +def format_stem( |
| 171 | + name: str, |
| 172 | + params: Mapping[str, Any] | None = None, |
| 173 | + run_label: str | None = None, |
| 174 | +) -> str: |
| 175 | + """Build a filename stem encoding a script's parameters. |
| 176 | +
|
| 177 | + Joins ``name``, one ``{key}{value}`` segment per ``params`` entry (in |
| 178 | + insertion order), and ``run_label`` when given, with underscores. |
| 179 | + Values and the run label are formatted with ``str()``; ``.`` becomes |
| 180 | + ``p`` (so ``0.7`` → ``0p7`` and the filename keeps a single suffix) |
| 181 | + and any character outside ``[A-Za-z0-9_+-]`` becomes ``-``. ``name`` |
| 182 | + is used verbatim. |
| 183 | +
|
| 184 | + Examples |
| 185 | + -------- |
| 186 | + >>> format_stem("study", {"seed": 42, "noise": 0.7}, "pilot") |
| 187 | + 'study_seed42_noise0p7_pilot' |
| 188 | + """ |
| 189 | + parts = [name] |
| 190 | + for key, value in (params or {}).items(): |
| 191 | + parts.append(f"{key}{_stem_value(value)}") |
| 192 | + if run_label: |
| 193 | + parts.append(_stem_value(run_label)) |
| 194 | + return "_".join(parts) |
| 195 | + |
| 196 | + |
| 197 | +def unique_path(directory: Path | str, stem: str, suffix: str) -> Path: |
| 198 | + """Return a non-clobbering path: ``stem+suffix``, else ``stem_v2+suffix``, ... |
| 199 | +
|
| 200 | + Creates ``directory`` (with parents) if it does not exist. Never |
| 201 | + returns a path that already exists, so earlier outputs are never |
| 202 | + overwritten. |
| 203 | + """ |
| 204 | + directory = Path(directory) |
| 205 | + directory.mkdir(parents=True, exist_ok=True) |
| 206 | + path = directory / f"{stem}{suffix}" |
| 207 | + version = 2 |
| 208 | + while path.exists(): |
| 209 | + path = directory / f"{stem}_v{version}{suffix}" |
| 210 | + version += 1 |
| 211 | + return path |
| 212 | + |
| 213 | + |
| 214 | +def _json_default(obj: Any) -> Any: |
| 215 | + """``json.dumps`` fallback for numpy values and paths.""" |
| 216 | + if isinstance(obj, np.generic): |
| 217 | + return obj.item() |
| 218 | + if isinstance(obj, np.ndarray): |
| 219 | + return obj.tolist() |
| 220 | + if isinstance(obj, Path): |
| 221 | + return str(obj) |
| 222 | + raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable") |
| 223 | + |
| 224 | + |
| 225 | +def _capture_metadata( |
| 226 | + params: Mapping[str, Any] | None, |
| 227 | + seed: int | None, |
| 228 | + note: str | None, |
| 229 | +) -> Provenance: |
| 230 | + """Capture a :class:`Provenance`, resolving the seed from ``params``.""" |
| 231 | + if seed is None and params is not None and "seed" in params: |
| 232 | + seed = int(params["seed"]) |
| 233 | + prov = Provenance.capture(seed=seed) |
| 234 | + if note is not None: |
| 235 | + prov = replace(prov, note=note) |
| 236 | + return prov |
| 237 | + |
| 238 | + |
| 239 | +def save_json( |
| 240 | + data: Any, |
| 241 | + directory: Path | str, |
| 242 | + name: str, |
| 243 | + *, |
| 244 | + params: Mapping[str, Any] | None = None, |
| 245 | + run_label: str | None = None, |
| 246 | + seed: int | None = None, |
| 247 | + note: str | None = None, |
| 248 | +) -> Path: |
| 249 | + """Write ``data`` to a self-describing, non-clobbering JSON file. |
| 250 | +
|
| 251 | + The file holds the envelope ``{"provenance": ..., "params": ..., |
| 252 | + "data": ...}``. The filename encodes ``params`` and ``run_label`` |
| 253 | + (see :func:`format_stem`); an existing file is never overwritten (a |
| 254 | + ``_v2``/``_v3`` suffix is added instead). The provenance record |
| 255 | + stores the seed from ``seed`` or, when omitted, from |
| 256 | + ``params["seed"]``. numpy scalars and arrays in ``data`` are |
| 257 | + converted to JSON-native values. |
| 258 | +
|
| 259 | + Returns the written path. |
| 260 | + """ |
| 261 | + prov = _capture_metadata(params, seed, note) |
| 262 | + path = unique_path(directory, format_stem(name, params, run_label), ".json") |
| 263 | + envelope = { |
| 264 | + "provenance": asdict(prov), |
| 265 | + "params": dict(params or {}), |
| 266 | + "data": data, |
| 267 | + } |
| 268 | + path.write_text(json.dumps(envelope, indent=2, default=_json_default)) |
| 269 | + return path |
| 270 | + |
| 271 | + |
161 | 272 | def _set_provenance(result: Any, prov: Provenance) -> None: |
162 | 273 | """Assign ``prov`` to ``result.provenance``, working around frozen results.""" |
163 | 274 | try: |
@@ -204,4 +315,11 @@ def with_provenance(self, **fields: Any) -> HasProvenance: |
204 | 315 | return self |
205 | 316 |
|
206 | 317 |
|
207 | | -__all__ = ["HasProvenance", "Provenance", "stamp_wall_time"] |
| 318 | +__all__ = [ |
| 319 | + "HasProvenance", |
| 320 | + "Provenance", |
| 321 | + "format_stem", |
| 322 | + "save_json", |
| 323 | + "stamp_wall_time", |
| 324 | + "unique_path", |
| 325 | +] |
0 commit comments