diff --git a/autofit/__init__.py b/autofit/__init__.py index 4cd27e10b..2e4287267 100644 --- a/autofit/__init__.py +++ b/autofit/__init__.py @@ -35,6 +35,7 @@ from .non_linear.samples import SamplesStored from .aggregator.summary.aggregate_csv import AggregateCSV from .aggregator.summary.aggregate_csv import ValueType +from .aggregator.summary.aggregate_csv.merge import merge_csv from .aggregator.summary.aggregate_images import AggregateImages from .aggregator.summary.aggregate_fits import AggregateFITS from autofit.aggregator.fit_interface import Fit diff --git a/autofit/aggregator/search_output.py b/autofit/aggregator/search_output.py index 7d143cbb8..8f4a53a7e 100644 --- a/autofit/aggregator/search_output.py +++ b/autofit/aggregator/search_output.py @@ -98,6 +98,51 @@ def cleanup(self): self._finalizer() +def plain(document): + """ + ``document`` (JSON written by autonerves ``to_dict``) with every type tag resolved + to plain Python: ``instance`` (or any other typed object with ``arguments``, e.g. + a model) → its arguments plus ``class_path`` when it has one; ``dict`` → + its arguments; ``list`` / ``tuple`` → a list; ``ndarray`` → a (nested) list; + ``np.number`` → its value; ``path`` → a string; ``type`` / ``function`` → its + class path; ``compound_dict`` → a list of ``[key, value]`` pairs. + """ + if isinstance(document, list): + return [plain(item) for item in document] + if not isinstance(document, dict): + return document + kind = document.get("type") + if kind == "instance": + return { + "class_path": document.get("class_path"), + **{k: plain(v) for k, v in (document.get("arguments") or {}).items()}, + } + if kind == "dict": + return {k: plain(v) for k, v in (document.get("arguments") or {}).items()} + if kind in ("list", "tuple"): + return [plain(item) for item in document.get("values") or []] + if kind == "ndarray": + return document.get("array") + if kind == "np.number": + return document.get("value") + if kind == "path": + return document.get("path") + if kind in ("type", "function"): + return document.get("class_path") + if kind == "compound_dict": + return [ + [plain(item.get("key")), plain(item.get("value"))] + for item in document.get("arguments") or [] + ] + if kind is not None and isinstance(document.get("arguments"), dict): + # Any other typed object (a model, collection, prior ...): its arguments. + plain_document = {k: plain(v) for k, v in document["arguments"].items()} + if "class_path" in document: + plain_document = {"class_path": document["class_path"], **plain_document} + return plain_document + return {k: plain(v) for k, v in document.items()} + + class AbstractSearchOutput(ABC): def __init__( self, @@ -273,6 +318,23 @@ def open_member(self, path: str, mode: str = "rb"): """ return (self.directory / path).open(mode) + def plain(self, name: str): + """ + The JSON file ``files/.json`` as plain Python (dicts, lists, numbers, + strings), without reconstructing the classes it was saved from: an object saved + with its type (autonerves ``to_dict``) becomes the dict of its arguments plus + its ``class_path``, an array a (nested) list, a path a string. + + Use it to read a typed product (e.g. a ``wcs.json``) where its classes are not + importable or not wanted, such as when exporting a catalogue. Returns ``None`` + when the file does not exist. + """ + member = self.directory / "files" / f"{name}.json" + if not member.exists(): + return None + with member.open("r") as f: + return plain(json.load(f)) + def value(self, name: str, kind: Optional[str] = None): """ Load the value of some object in the files directory for the search. diff --git a/autofit/aggregator/summary/aggregate_csv/__init__.py b/autofit/aggregator/summary/aggregate_csv/__init__.py index a61abbfdb..048790399 100644 --- a/autofit/aggregator/summary/aggregate_csv/__init__.py +++ b/autofit/aggregator/summary/aggregate_csv/__init__.py @@ -1,10 +1,12 @@ import csv +import json import logging +from collections import Counter from pathlib import Path -from typing import Optional, Callable, List, Union, Hashable +from typing import Optional, Callable, Dict, List, Union, Hashable from autofit.aggregator.aggregator import Aggregator -from autofit.tools.util import open_atomic +from autofit.tools.util import NumpyEncoder, open_atomic from autofit.aggregator.summary.aggregate_csv.column import ( LabelColumn, @@ -13,6 +15,17 @@ ValueType, ) from autofit.aggregator.summary.aggregate_csv.row import Row +from autofit.aggregator.summary.aggregate_csv.cache import ( + RowCache, + csv_text, + row_fingerprint, + spec_digest, +) +from autofit.aggregator.summary.aggregate_csv.merge import ( + MergeException, + merge_csv, + sort_rows, +) logger = logging.getLogger(__name__) @@ -38,12 +51,17 @@ def __init__(self, aggregator: Aggregator, strict: bool = True): self._aggregator = aggregator self._strict = strict self._columns = [] + self.stats: Dict[str, int] = {} + """What the last ``save`` did: rows ``computed``, ``cached``, ``errors`` and + ``expected`` (rows for expected results with no output).""" def add_variable( self, argument: str, name: Optional[str] = None, value_types: list = (ValueType.Median,), + unit: Optional[str] = None, + prior_edge: bool = False, ): """ Add a variable to include columns for in the summary table. @@ -59,6 +77,11 @@ def add_variable( An optional name for the column. If not provided, the argument will be used. value_types Value types to include. See ValueType. + unit + The unit of the values, recorded in the ``columns.json`` sidecar. + prior_edge + Add a ``_at_prior_edge`` flag column: whether the median lies within + 1% of the prior's width from one of its limits. """ self._columns.append( Column( @@ -66,6 +89,8 @@ def add_variable( name=name, value_types=value_types, strict=self._strict, + unit=unit, + prior_edge=prior_edge, ) ) @@ -158,7 +183,47 @@ def fieldnames(self) -> List[str]: """ return self._union_fieldnames(self._rows()) - def save(self, path: Union[str, Path]) -> List[str]: + @staticmethod + def _fields(column, value) -> Dict[str, str]: + """ + The CSV fields ``column`` writes for ``value``, as the text the CSV holds. + """ + if isinstance(value, dict): + fields = {} + for key, item in value.items(): + fields[f"{column.name}_{key}" if key else column.name] = csv_text(item) + return fields + return {column.name: csv_text(value)} + + def _fieldnames(self, rows, computed_fields, expected, honest) -> List[str]: + """ + The header, from the columns rather than from the rows: the same for every + shard of an export and whatever row sorts first. A computed column returning a + dict contributes the fields its rows produced (sorted). + """ + fieldnames = ["id"] + (["dataset", "search"] if expected is not None else []) + for column in self._columns: + if isinstance(column, Column): + fieldnames += column.fields() + elif isinstance(column, ComputedColumn): + fields = computed_fields.get(column.name) or {column.name} + fieldnames += sorted(fields, key=lambda f: (f != column.name, f)) + else: + fieldnames.append(column.name) + if honest: + fieldnames.append("status_reason") + return fieldnames + + def save( + self, + path: Union[str, Path], + cache: bool = False, + shard=None, + expected=None, + sort_by: Optional[str] = None, + on_error: str = "raise", + columns_json: bool = False, + ) -> List[str]: """ Save the summary table to a CSV file. @@ -170,18 +235,174 @@ def save(self, path: Union[str, Path]) -> List[str]: ---------- path The path to save the file to + cache + Keep the rows in ``.rows.jsonl`` and reuse them for results whose + files and column definitions are unchanged, so refreshing a large export + after a few new results reads only those results. + shard + ``"i/N"`` or ``(i, N)``: export only shard ``i`` of ``N`` + (``autofit.results.shard``); merge the parts with ``merge_csv``. Rows are + then sorted by ``sort_by`` (default ``id``). + expected + A ``CompletenessReport`` (``autofit.results.ResultsLibrary.check``): adds + ``dataset`` and ``search`` columns, and a row with its ``status_reason`` + for every expected result that is not done, so nothing expected is missing + from the table without a reason. + sort_by + Sort the rows by this column (ties broken by the whole row), as + ``merge_csv`` does: a merge of shards is then byte-identical to a serial + export with the same ``sort_by``. + on_error + ``"raise"`` (the default) stops at the first result that cannot be + summarised; ``"row"`` gives it a row whose ``status_reason`` is the error + and goes on. With ``"row"`` or ``expected`` every row has a + ``status_reason`` (empty when nothing is missing). + columns_json + Write ``.columns.json`` beside the CSV: for each column its source, + kind (``parameter``, ``latent``, ``derived``, ``label``, ``flag``, + ``meta``), statistic, bound (``quantile_1sigma`` / ``quantile_3sigma``), + unit and how many rows leave it blank. Returns ------- The columns that are blank in every row, which are also logged as a warning. """ - path = Path(path) + from autofit.results.shard import in_shard, parse_shard + if on_error not in ("raise", "row"): + raise ValueError(f"on_error is 'raise' or 'row', not {on_error!r}.") + path = Path(path) folder_path = path.parent if path.suffix else path folder_path.mkdir(parents=True, exist_ok=True) - rows = self._rows() - fieldnames = self._union_fieldnames(rows) + shard = parse_shard(shard) + if shard is not None and sort_by is None: + sort_by = "id" + honest = on_error == "row" or expected is not None + + data_columns = [c for c in self._columns if not isinstance(c, LabelColumn)] + row_cache = None + if cache: + row_cache = RowCache( + path, spec_digest([c.spec() for c in data_columns] + [honest]) + ).load() + for column in data_columns: + kind = row_cache.meta.get("kinds", {}).get(column.name) + if getattr(column, "kind", "") is None and kind: + column.kind = kind + + checks = {} + if expected is not None: + for check in expected.results: + if check.record is not None: + checks.setdefault( + str(Path(check.record.output_path).resolve()), check + ) + + stats = Counter() + owners = {} + computed_fields = {} + rows = [] + exported = set() + out_of_shard = [] + for number, result in enumerate(self._aggregator): + output_path = _output_path(result) + if not in_shard(output_path, shard): + out_of_shard.append(output_path) + continue + row = Row(result, self._columns, number) + entry = None + fingerprint = None + if row_cache is not None: + fingerprint = row_fingerprint(Path(output_path)) + entry = row_cache.get(output_path, fingerprint) + if entry is not None: + stats["cached"] += 1 + else: + try: + values = {c.name: self._fields(c, c.value(row)) for c in data_columns} + entry = { + "id": result.id, + "values": values, + "reasons": list(dict.fromkeys(row.reasons)), + } + if row_cache is not None: + row_cache.put(output_path, fingerprint, entry) + stats["computed"] += 1 + except Exception as exception: + if on_error == "raise": + raise + logger.warning(f"Could not summarise {output_path}: {exception}") + stats["errors"] += 1 + entry = { + "id": _id_or_none(result), + "values": {}, + "reasons": [f"error:{type(exception).__name__}: {exception}"], + } + + data = {"id": entry["id"]} + reasons = list(entry["reasons"]) + if expected is not None: + check = checks.get(output_path) + data["dataset"] = check.expected.dataset if check else None + data["search"] = check.expected.search if check else None + if check is not None: + exported.add(id(check)) + if check.status != "done": + reasons.append(_check_reason(check)) + for column in self._columns: + if isinstance(column, LabelColumn): + try: + fields = self._fields(column, column.value(row)) + except Exception as exception: + if on_error == "raise": + raise + reasons.append(f"error:{type(exception).__name__}: {exception}") + fields = {} + else: + fields = entry["values"].get(column.name, {}) + if isinstance(column, ComputedColumn): + computed_fields.setdefault(column.name, set()).update(fields) + for field in fields: + owners.setdefault(field, column) + data.update(fields) + if honest: + data["status_reason"] = ";".join(dict.fromkeys(reasons)) + rows.append(data) + + if expected is not None: + for check in expected.results: + if id(check) in exported: + continue + record = check.record + key = ( + str(Path(record.output_path).resolve()) + if record + else f"{check.expected.dataset}/{check.expected.search}" + ) + if not in_shard(key, shard): + continue + reason = "not_exported" if check.status == "done" else _check_reason(check) + rows.append( + { + "id": record.identifier if record else None, + "dataset": check.expected.dataset, + "search": check.expected.search, + "status_reason": reason, + } + ) + stats["expected"] += 1 + + if sort_by is not None: + rows = sort_rows(rows, sort_by) + + fieldnames = self._fieldnames(rows, computed_fields, expected, honest) + for column in self._columns: + if isinstance(column, Column): + for field in column.fields(): + owners.setdefault(field, column) + else: + owners.setdefault(column.name, column) with open_atomic(path, "w") as f: writer = csv.DictWriter( @@ -192,15 +413,82 @@ def save(self, path: Union[str, Path]) -> List[str]: for row in rows: writer.writerow(row) + if row_cache is not None: + row_cache.meta["kinds"] = { + c.name: c.kind for c in data_columns if getattr(c, "kind", None) + } + row_cache.save(keep=out_of_shard) + blank = [ name for name in fieldnames if all(row.get(name) in (None, "") for row in rows) ] + if columns_json: + self._write_columns_json(path, fieldnames, rows, owners) if blank: logger.warning( f"The summary CSV {path} has columns blank in every row: " f"{', '.join(blank)}." ) + self.stats = { + name: stats.get(name, 0) + for name in ("computed", "cached", "errors", "expected") + } return blank + + @staticmethod + def _write_columns_json(path: Path, fieldnames, rows, owners): + meta = { + "id": "the search output's id", + "dataset": "the expected dataset (ResultsLibrary)", + "search": "the expected search (ResultsLibrary)", + "status_reason": "why values of the row are missing; empty when none are", + } + columns = [] + for field in fieldnames: + if field in meta and field not in owners: + entry = {"source": meta[field], "kind": "meta"} + else: + entry = owners[field].describe(field) + columns.append( + { + "name": field, + **entry, + "n_blank": sum(1 for row in rows if row.get(field) in (None, "")), + } + ) + json_path = path.with_suffix(".columns.json") if path.suffix else Path( + f"{path}.columns.json" + ) + with open_atomic(json_path, "w") as f: + json.dump({"csv": path.name, "n_rows": len(rows), "columns": columns}, f, indent=1) + + +def _output_path(search_output) -> str: + """ + The resolved ``output_path`` of a search output, whether read from a folder or a + zip: the key of its cached row, its shard and its expected result, so a tree read + through a symlink is the same tree. + """ + from autofit.aggregator.zip_member import ZipMember + + directory = search_output.directory + if isinstance(directory, ZipMember): + path = str(Path(directory.zip_path).resolve()) + return path[: -len(".zip")] if path.endswith(".zip") else path + return str(Path(directory).resolve()) + + +def _id_or_none(search_output): + try: + return search_output.id + except Exception: + return None + + +def _check_reason(check) -> str: + if check.missing_products: + return "missing_product:" + ",".join(check.missing_products) + return check.reason or check.status diff --git a/autofit/aggregator/summary/aggregate_csv/cache.py b/autofit/aggregator/summary/aggregate_csv/cache.py new file mode 100644 index 000000000..30df06dab --- /dev/null +++ b/autofit/aggregator/summary/aggregate_csv/cache.py @@ -0,0 +1,228 @@ +""" +``RowCache``: the rows of a previous export, so a refresh only reads the results that +are new or changed. + +The cache sits beside the CSV (``.rows.jsonl``): a header line with the column +specification it was built for, then one line per result — its ``output_path``, the +``row_fingerprint`` it had and its row, as the text the CSV holds. A row is reused +only while the result's fingerprint and the whole column specification are unchanged; +a different specification (a column added, renamed, or a computed column's code edited) +discards the cache. Label columns are never cached — they are cheap, and change often. + +Rows of results that failed are not cached, so they are retried. The cache is written +atomically after the CSV: a run killed in between leaves an older cache, which only +costs re-reading results next time. +""" +import functools +import hashlib +import inspect +import json +import logging +import os +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Tuple + +from autofit.tools.util import NumpyEncoder, open_atomic + +logger = logging.getLogger(__name__) + +SCHEMA = 1 + + +def _stable_repr(value) -> str: + """ + A representation of ``value`` that is the same in every process for the same + value: sets are sorted (their order follows hash randomisation). A value whose + ``repr`` holds a memory address stays unstable, so the cache never reuses rows + computed with it — slower, never stale. + """ + if isinstance(value, (set, frozenset)): + return f"{type(value).__name__}({sorted(_stable_repr(v) for v in value)})" + if isinstance(value, (list, tuple)): + return f"{type(value).__name__}({[_stable_repr(v) for v in value]})" + if isinstance(value, dict): + return f"dict({sorted((_stable_repr(k), _stable_repr(v)) for k, v in value.items())})" + return repr(value) + + +def _code_digest(code, digest) -> None: + digest.update(code.co_code) + for const in code.co_consts: + if hasattr(const, "co_code"): + _code_digest(const, digest) + else: + digest.update(_stable_repr(const).encode("utf-8")) + digest.update(repr(code.co_names).encode("utf-8")) + + +def _function_digest(function, digest, seen) -> None: + if id(function) in seen: + return + seen.add(id(function)) + + if isinstance(function, functools.partial): + digest.update(b"partial") + _function_digest(function.func, digest, seen) + digest.update(_stable_repr(function.args).encode("utf-8")) + digest.update(_stable_repr(function.keywords).encode("utf-8")) + return + + code = getattr(function, "__code__", None) + if code is None: + digest.update(repr(function).encode("utf-8")) + return + + digest.update( + f"{getattr(function, '__module__', '')}.{getattr(function, '__qualname__', '')}".encode() + ) + _code_digest(code, digest) + for value in (function.__defaults__ or ()) + tuple( + (function.__kwdefaults__ or {}).items() + ): + digest.update(_stable_repr(value).encode("utf-8")) + for cell in function.__closure__ or (): + try: + value = cell.cell_contents + except ValueError: + continue + if callable(value) and hasattr(value, "__code__"): + _function_digest(value, digest, seen) + else: + digest.update(_stable_repr(value).encode("utf-8")) + # Functions the column calls by global name, from its own module (an edited + # helper must invalidate the rows too). + module = getattr(function, "__module__", None) + for name in code.co_names: + value = function.__globals__.get(name) + if inspect.isfunction(value) and value.__module__ == module: + _function_digest(value, digest, seen) + + +def function_digest(function) -> str: + """ + A digest of what ``function`` computes, so editing a computed column's function + (even a lambda), a value it captured, a default, or a helper function it calls + from its module invalidates the rows it produced. + """ + digest = hashlib.sha1() + _function_digest(function, digest, set()) + return digest.hexdigest() + + +def row_fingerprint(output_path: Path) -> List: + """ + What a cached row of the result at ``output_path`` is valid for: the zip's size and + modification time, or for a folder every file a row can read — everything under + ``files/`` but the search's internal checkpoint, plus ``.identifier`` and + ``.completed`` — since rewriting a file in place does not touch its folder. + """ + zip_path = Path(f"{output_path}.zip") + entries = [] + if zip_path.exists(): + stat = zip_path.stat() + entries.append(["zip", stat.st_size, stat.st_mtime_ns]) + if output_path.is_dir(): + for name in (".identifier", ".completed"): + path = output_path / name + if path.exists(): + stat = path.stat() + entries.append([name, stat.st_size, stat.st_mtime_ns]) + files = output_path / "files" + for root, dirs, names in os.walk(files): + dirs[:] = sorted(d for d in dirs if not d.startswith("search_internal")) + for name in sorted(names): + path = Path(root) / name + stat = path.stat() + entries.append( + [str(path.relative_to(output_path)), stat.st_size, stat.st_mtime_ns] + ) + return entries + + +def csv_text(value) -> str: + """ + The text ``csv`` writes for ``value``; cached rows hold this, so a row read back + from the cache is written exactly as a freshly computed one. + """ + return "" if value is None else str(value) + + +def spec_digest(parts: Iterable) -> str: + return hashlib.sha1( + json.dumps(list(parts), sort_keys=True, default=str).encode("utf-8") + ).hexdigest() + + +def cache_path(csv_path: os.PathLike) -> Path: + return Path(f"{csv_path}.rows.jsonl") + + +class RowCache: + def __init__(self, csv_path: os.PathLike, spec: str): + """ + The row cache of the CSV at ``csv_path`` for the column specification ``spec`` + (``spec_digest``). + """ + self.path = cache_path(csv_path) + self.spec = spec + self.meta: Dict = {} + self._rows: Dict[str, Tuple[List, Dict]] = {} + self._new: Dict[str, Tuple[List, Dict]] = {} + + def load(self) -> "RowCache": + try: + with open(self.path) as f: + header = json.loads(f.readline() or "{}") + if header.get("schema") != SCHEMA or header.get("spec") != self.spec: + return self + self.meta = header.get("meta") or {} + for line in f: + entry = json.loads(line) + self._rows[entry["output_path"]] = ( + entry["fingerprint"], + entry["row"], + ) + except FileNotFoundError: + pass + except (OSError, ValueError, KeyError) as exception: + logger.warning(f"Ignoring unreadable row cache {self.path}: {exception}") + self._rows = {} + return self + + def get(self, output_path: str, fingerprint: List) -> Optional[Dict]: + cached = self._rows.get(output_path) + if cached is not None and cached[0] == fingerprint: + return dict(cached[1]) + return None + + def put(self, output_path: str, fingerprint: List, row: Dict): + self._new[output_path] = (fingerprint, row) + + def save(self, keep: Iterable[str] = ()): + """ + Write the rows put in this run, plus the cached rows of ``keep`` (results of + other shards, which this run did not read). + """ + rows = {path: self._rows[path] for path in keep if path in self._rows} + rows.update(self._new) + with open_atomic(self.path, "w") as f: + f.write( + json.dumps({"schema": SCHEMA, "spec": self.spec, "meta": self.meta}) + + "\n" + ) + for output_path in sorted(rows): + fingerprint, row = rows[output_path] + f.write( + json.dumps( + { + "output_path": output_path, + "fingerprint": fingerprint, + "row": row, + }, + cls=NumpyEncoder, + ) + + "\n" + ) + + def cached_paths(self) -> List[str]: + return list(self._rows) diff --git a/autofit/aggregator/summary/aggregate_csv/column.py b/autofit/aggregator/summary/aggregate_csv/column.py index cd29aa122..13b68cf0e 100644 --- a/autofit/aggregator/summary/aggregate_csv/column.py +++ b/autofit/aggregator/summary/aggregate_csv/column.py @@ -1,4 +1,5 @@ import logging +import math from abc import ABC, abstractmethod from enum import Enum from typing import Optional, Callable @@ -22,6 +23,19 @@ def __init__(self, name: str): def value(self, row: "Row"): pass + def spec(self) -> list: + """ + What the column computes, for the row cache key: a change to it invalidates + cached rows. + """ + return [type(self).__name__, self.name] + + def describe(self, field: str) -> dict: + """ + The ``columns.json`` entry of the output field ``field`` this column writes. + """ + return {"source": None, "kind": "derived"} + class ValueType(Enum): """ @@ -41,6 +55,8 @@ def __init__( name: Optional[str] = None, value_types: list[ValueType] = (ValueType.Median,), strict: bool = False, + unit: Optional[str] = None, + prior_edge: bool = False, ): """ A column in the summary table. @@ -57,6 +73,12 @@ def __init__( If True an argument matching neither the samples_summary nor the latent_summary raises a KeyError. If False (the default) a warning is logged once for the column and the values are left empty. + unit + The unit of the values, recorded in ``columns.json``. + prior_edge + Add a ``_at_prior_edge`` column: whether the median lies within 1% of + the prior's width from one of its limits, measured in log space for a log + prior (empty for a prior without two finite limits, e.g. a latent). """ super().__init__( name @@ -68,8 +90,77 @@ def __init__( self.argument = argument self.value_types = value_types self.strict = strict + self.unit = unit + self.prior_edge = prior_edge + self.kind = None self._has_warned = False + def spec(self) -> list: + return super().spec() + [ + self.argument, + [value_type.name for value_type in self.value_types], + self.strict, + self.unit, + self.prior_edge, + ] + + _BOUNDS = { + "": ("median", None), + "max_lh": ("max_log_likelihood", None), + "lower_1_sigma": ("lower", "quantile_1sigma"), + "upper_1_sigma": ("upper", "quantile_1sigma"), + "lower_3_sigma": ("lower", "quantile_3sigma"), + "upper_3_sigma": ("upper", "quantile_3sigma"), + "at_prior_edge": ("flag", None), + } + + def fields(self) -> list: + """ + The CSV fields this column writes, in order. + """ + suffixes = [] + if ValueType.Median in self.value_types: + suffixes.append("") + if ValueType.MaxLogLikelihood in self.value_types: + suffixes.append("max_lh") + if ValueType.ValuesAt1Sigma in self.value_types: + suffixes += ["lower_1_sigma", "upper_1_sigma"] + if ValueType.ValuesAt3Sigma in self.value_types: + suffixes += ["lower_3_sigma", "upper_3_sigma"] + if self.prior_edge: + suffixes.append("at_prior_edge") + return [f"{self.name}_{suffix}" if suffix else self.name for suffix in suffixes] + + def describe(self, field: str) -> dict: + suffix = "" if field == self.name else field[len(self.name) + 1 :] + statistic, bound = self._BOUNDS.get(suffix, (None, None)) + return { + "source": self.argument, + "kind": "flag" if suffix == "at_prior_edge" else (self.kind or "parameter"), + "statistic": statistic, + "bound": bound, + "unit": None if suffix == "at_prior_edge" else self.unit, + } + + def _at_prior_edge(self, row: "Row", value) -> Optional[bool]: + if value is None: + return None + try: + prior = row.result.model.object_for_path(self.path) + lower = float(prior.lower_limit) + upper = float(prior.upper_limit) + except Exception: + return None + if type(prior).__name__.startswith("Log"): + # A log prior's width is in log space: 50 is mid-way in LogUniform(1e-4, 1e4). + if lower <= 0 or value <= 0: + return None + lower, upper, value = math.log10(lower), math.log10(upper), math.log10(value) + width = upper - lower + if not (width > 0 and width != float("inf")): + return None + return bool(min(value - lower, upper - value) < 0.01 * width) + def _check_argument(self, row: "Row"): """ Check that the argument matches the samples_summary or latent_summary @@ -100,6 +191,16 @@ def _check_argument(self, row: "Row"): def value(self, row: "Row"): self._check_argument(row) + if self.path in row.parameter_paths: + self.kind = "parameter" + elif self.path in row.known_paths: + self.kind = "latent" + else: + row.reasons.append( + "missing_latent_summary" + if row.latent_summary is None + else f"missing_value:{self.argument}" + ) result = {} @@ -133,6 +234,10 @@ def value(self, row: "Row"): result["lower_3_sigma"] = None result["upper_3_sigma"] = None + if self.prior_edge: + median = row.median_pdf_sample_kwargs.get(self.path) + result["at_prior_edge"] = self._at_prior_edge(row, median) + return result @property @@ -158,6 +263,14 @@ def __init__(self, name: str, compute: Callable): super().__init__(name) self.compute = compute + def spec(self) -> list: + from autofit.aggregator.summary.aggregate_csv.cache import function_digest + + return super().spec() + [function_digest(self.compute)] + + def describe(self, field: str) -> dict: + return {"source": getattr(self.compute, "__qualname__", None), "kind": "derived"} + def value(self, row: "Row"): try: @@ -196,6 +309,9 @@ def __init__( self.key = key self.strict = strict + def describe(self, field: str) -> dict: + return {"source": None, "kind": "label"} + def value(self, row: "Row"): if not isinstance(self.values, dict): return self.values[row.number] diff --git a/autofit/aggregator/summary/aggregate_csv/merge.py b/autofit/aggregator/summary/aggregate_csv/merge.py new file mode 100644 index 000000000..f5b6ea22b --- /dev/null +++ b/autofit/aggregator/summary/aggregate_csv/merge.py @@ -0,0 +1,133 @@ +""" +Merge CSV parts exported in shards (``AggregateCSV.save(path, shard="i/N")``) into one +CSV, the way any scheduler can run them: Slurm array tasks, a laptop process pool, or +one after another. + +The merge is strict where a silent result would be wrong: + +- every part with rows must have the same header (the same columns in the same + order); parts of one export do, so a disagreement means parts of different exports + (or a computed column returning dicts with different keys in different shards). A + part with no rows (an empty shard) is not compared; +- a key (``id`` by default) seen in several parts is kept once when the rows are + identical, and refused when they differ; rows with an empty key (expected results + with no output) are kept once per distinct row; +- rows are sorted (``sort_rows``), so a merge is byte-identical to a serial export saved + with the same ``sort_by``, whatever the shard count. +""" +import csv +import os +from pathlib import Path +from typing import Dict, Iterable, List, Sequence, Union + +from autofit.tools.util import open_atomic + +PathLike = Union[str, os.PathLike] + + +class MergeException(Exception): + pass + + +def sort_rows(rows: Iterable[Dict], by: str) -> List[Dict]: + """ + ``rows`` sorted by the column ``by``, ties broken by the whole row, so the order + never depends on how the rows were found. + """ + return sorted( + rows, + key=lambda row: ( + str(row.get(by) if row.get(by) is not None else ""), + tuple(str(value if value is not None else "") for value in row.values()), + ), + ) + + +def write_rows(path: PathLike, fieldnames: Sequence[str], rows: Iterable[Dict]): + """ + Write ``rows`` to the CSV at ``path`` atomically (``open_atomic``). + """ + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with open_atomic(path, "w") as f: + writer = csv.DictWriter(f, fieldnames=list(fieldnames), lineterminator="\r\n") + writer.writeheader() + for row in rows: + writer.writerow(row) + + +def merge_csv( + parts: Sequence[PathLike], + path: PathLike, + key: str = "id", + sort_by: str = None, +) -> int: + """ + Merge the CSV ``parts`` into ``path`` (see the module docstring). + + Parameters + ---------- + parts + The CSV files to merge, e.g. ``summary.part0.csv`` .. ``summary.part3.csv``. + key + The column that identifies a row; rows sharing a non-empty key are duplicates. + sort_by + The column the merged rows are sorted by (default: ``key``). + + Returns + ------- + The number of rows written. + + Raises + ------ + MergeException + When the headers disagree, a duplicate key has different rows, or ``key`` is not + a column. + """ + if not parts: + raise MergeException("No parts to merge.") + sort_by = sort_by or key + + header = None + first = None + rows = [] + seen = {} + seen_unkeyed = set() + for part in parts: + with open(part, newline="") as f: + reader = csv.DictReader(f) + fieldnames = list(reader.fieldnames or []) + part_rows = list(reader) + if key not in fieldnames: + raise MergeException(f"{part} has no '{key}' column.") + if not part_rows: + continue + if header is None: + header, first = fieldnames, part + elif fieldnames != header: + raise MergeException( + f"The header of {part} differs from that of {first}: " + f"{fieldnames} != {header}." + ) + for row in part_rows: + value = row[key] + if value: + if value in seen: + if seen[value] != row: + raise MergeException( + f"Key {key}={value} has different rows in two parts." + ) + continue + seen[value] = row + else: + identity = tuple(row.items()) + if identity in seen_unkeyed: + continue + seen_unkeyed.add(identity) + rows.append(row) + + if header is None: + with open(parts[0], newline="") as f: + header = list(csv.DictReader(f).fieldnames or []) + write_rows(path, header, sort_rows(rows, sort_by)) + return len(rows) diff --git a/autofit/aggregator/summary/aggregate_csv/row.py b/autofit/aggregator/summary/aggregate_csv/row.py index 88f985c60..58c96b4c5 100644 --- a/autofit/aggregator/summary/aggregate_csv/row.py +++ b/autofit/aggregator/summary/aggregate_csv/row.py @@ -23,6 +23,8 @@ def __init__( self.result = result self._columns = columns self.number = number + self.reasons = [] + """Why values of this row are missing (``status_reason``), filled by columns.""" def _all_paths(self, path: Tuple[str, ...]): model = self.result.model @@ -38,9 +40,23 @@ def _add_paths(self, kwargs): } @cached_property - def _latent_summary(self): + def latent_summary(self): return self.result.value("latent.latent_summary") + @property + def _latent_summary(self): + return self.latent_summary + + @cached_property + def parameter_paths(self) -> set: + """ + The argument paths of the model's parameters (from the samples_summary only). + """ + samples_summary = self.result.samples_summary + return set(self._sample_kwargs(samples_summary.median_pdf_sample)) | set( + self._sample_kwargs(samples_summary.max_log_likelihood_sample) + ) + def _sample_kwargs(self, sample) -> dict: """ The arguments of a sample keyed by every path to each prior, or an @@ -131,12 +147,13 @@ def known_paths(self) -> set: | set(self.values_at_sigma_3_kwargs) ) - def dict(self) -> dict: + def dict(self, columns=None) -> dict: """ - The row as a dictionary including an id and one entry for each column. + The row as a dictionary including an id and one entry for each column (of + ``columns``, default all). """ row = {"id": self.result.id} - for column in self._columns: + for column in self._columns if columns is None else columns: value = column.value(self) if isinstance(value, dict): for key, item in value.items(): diff --git a/autofit/aggregator/summary/aggregate_fits.py b/autofit/aggregator/summary/aggregate_fits.py index 852649701..eff427d94 100644 --- a/autofit/aggregator/summary/aggregate_fits.py +++ b/autofit/aggregator/summary/aggregate_fits.py @@ -1,3 +1,4 @@ +import logging import re from enum import Enum from typing import Dict, List, Union @@ -8,6 +9,9 @@ from autofit.aggregator import Aggregator +logger = logging.getLogger(__name__) + + def subplot_filename(subplot: Enum) -> str: subplot_type = subplot.__class__ return ( @@ -172,10 +176,14 @@ def output_to_folder( folder: Path, name: Union[str, List[str]], hdus: List[Enum], + skip_errors: bool = False, ): """ Output the fits files for every search in the aggregator to a folder. + Each file is written atomically: an interrupted run never leaves a truncated + ``.fits``. + Only include HDUs specific in the hdus argument. Parameters @@ -184,26 +192,39 @@ def output_to_folder( The folder to output the fits files to. hdus The HDUs to output. + skip_errors + Log a search whose fits cannot be written and go on to the next, instead of + stopping. The skipped ``(search_output, exception)`` pairs are returned. name The name of the fits file. This is the attribute of the search output that is used to name the file. OR a list of names for each HDU. """ from astropy.io import fits + from autofit.tools.util import open_atomic + folder.mkdir(parents=True, exist_ok=True) + errors = [] for i, result in enumerate(self.aggregator): - if isinstance(name, str): - output_name = getattr(result, name) - else: - output_name = name[i] - - hdu_list = fits.HDUList( - [fits.PrimaryHDU()] - + self._hdus( - result, - hdus, + try: + if isinstance(name, str): + output_name = getattr(result, name) + else: + output_name = name[i] + + hdu_list = fits.HDUList( + [fits.PrimaryHDU()] + + self._hdus( + result, + hdus, + ) ) - ) - with open(folder / f"{output_name}.fits", "wb") as file: - hdu_list.writeto(file) + with open_atomic(folder / f"{output_name}.fits", "wb") as file: + hdu_list.writeto(file) + except Exception as exception: + if not skip_errors: + raise + logger.warning(f"Could not output the fits of {result}: {exception}") + errors.append((result, exception)) + return errors diff --git a/autofit/results/__main__.py b/autofit/results/__main__.py index 9cdf81758..724c2abc2 100644 --- a/autofit/results/__main__.py +++ b/autofit/results/__main__.py @@ -7,6 +7,7 @@ python -m autofit.results check library.yaml [--no-update] [--output-dir DIR] python -m autofit.results enrich output/ --fn module:function --name NAME \ [--index-dir DIR] [--shard i/N] [--overwrite] + python -m autofit.results merge summary.csv summary.part*.csv [--key id] [--sort-by id] ``index`` brings the index up to date (only new or changed results are opened); ``status`` prints one line per result state, or with ``--state`` the results in that @@ -18,6 +19,7 @@ exits 1 when anything expected is not done. ``enrich`` adds the product ``function(search_output)`` returns to every completed result as ``files/`` (``autofit.results.enrich``); ``--shard i/N`` takes one of N disjoint parts. +``merge`` joins CSV parts exported in shards (``AggregateCSV.save(shard=...)``). """ import argparse import importlib @@ -172,6 +174,23 @@ def command_enrich(arguments) -> int: return 1 if report.errors else 0 +def command_merge(arguments) -> int: + from autofit.aggregator.summary.aggregate_csv.merge import ( + MergeException, + merge_csv, + ) + + try: + n = merge_csv( + arguments.parts, arguments.output, key=arguments.key, sort_by=arguments.sort_by + ) + except (MergeException, OSError) as exception: + print(f"merge failed: {exception}", file=sys.stderr) + return 2 + print(f"merged {len(arguments.parts)} parts into {arguments.output}: {n} rows") + return 0 + + def main(argv=None) -> int: parser = argparse.ArgumentParser( prog="python -m autofit.results", @@ -243,6 +262,13 @@ def add(name, function, help_): help="Rewrite the product where a result already holds it.", ) + merge = commands.add_parser("merge", help="Merge CSV parts exported in shards.") + merge.add_argument("output", help="The merged CSV.") + merge.add_argument("parts", nargs="+", help="The CSV parts.") + merge.add_argument("--key", default="id", help="The column naming a row.") + merge.add_argument("--sort-by", default=None, help="Sort column (default: --key).") + merge.set_defaults(function=command_merge) + arguments = parser.parse_args(argv) return arguments.function(arguments) diff --git a/test_autofit/aggregator/summary_files/test_aggregate_fits.py b/test_autofit/aggregator/summary_files/test_aggregate_fits.py index b260aa563..0dab19f10 100644 --- a/test_autofit/aggregator/summary_files/test_aggregate_fits.py +++ b/test_autofit/aggregator/summary_files/test_aggregate_fits.py @@ -71,6 +71,18 @@ def test_list_of_names(summary, output_directory): ]) +def test_skip_errors(summary, tmp_path): + hdus = [FITSFit.ModelData] + with pytest.raises(IndexError): + summary.output_to_folder(tmp_path / "a", ["one"], hdus) + + errors = summary.output_to_folder(tmp_path / "b", ["one"], hdus, skip_errors=True) + + assert len(errors) == 1 + assert isinstance(errors[0][1], IndexError) + assert [path.name for path in (tmp_path / "b").glob("*")] == ["one.fits"] + + def test_extract_fits_closes_files(summary): """ Each source fits file is opened once per result and closed deterministically — diff --git a/test_autofit/aggregator/summary_files/test_exports.py b/test_autofit/aggregator/summary_files/test_exports.py new file mode 100644 index 000000000..bb1d3efa2 --- /dev/null +++ b/test_autofit/aggregator/summary_files/test_exports.py @@ -0,0 +1,457 @@ +import csv +import json +import shutil +from pathlib import Path + +import pytest + +import autofit as af +from autofit.aggregator import Aggregator +from autofit.aggregator.search_output import plain +from autofit.aggregator.summary.aggregate_csv import ( + AggregateCSV, + MergeException, + ValueType, + merge_csv, +) +from autofit.aggregator.summary.aggregate_csv.cache import cache_path +from autofit.results.__main__ import main + +FIXTURE = Path(__file__).parent / "aggregate_summary" +VARIABLE = "galaxies.lens.bulge.centre.centre_0" + + +def _copy(root: Path, n: int, start: int = 0): + for i in range(start, start + n): + target = root / f"obj{i:04d}" / "search" / f"{i:032x}" + shutil.copytree(FIXTURE / ("fit_1" if i % 2 else "fit_2"), target) + (target / ".identifier").write_text(f"copy\n{i}") + (target / ".completed").write_text("") + search = json.loads((target / "files" / "search.json").read_text()) + search["arguments"] = {"name": "search", "unique_tag": f"obj{i:04d}"} + (target / "files" / "search.json").write_text(json.dumps(search)) + return root + + +def _summary(root, **kwargs): + summary = AggregateCSV(Aggregator.from_directory(root), **kwargs) + summary.add_variable(VARIABLE, value_types=[ValueType.Median, ValueType.ValuesAt1Sigma]) + summary.add_computed_column("doubled", lambda result: 2) + return summary + + +def _read(path): + with open(path, newline="") as f: + return list(csv.DictReader(f)) + + +@pytest.fixture(name="root") +def make_root(tmp_path): + return _copy(tmp_path / "output", 120) + + +def test_refresh_reads_only_new_results(root, tmp_path): + path = tmp_path / "summary.csv" + summary = _summary(root) + summary.save(path, cache=True, sort_by="id") + assert summary.stats["computed"] == 120 + + _copy(root, 30, start=120) + summary = _summary(root) + summary.save(path, cache=True, sort_by="id") + assert summary.stats == {"computed": 30, "cached": 120, "errors": 0, "expected": 0} + + fresh = tmp_path / "fresh.csv" + _summary(root).save(fresh, sort_by="id") + assert path.read_bytes() == fresh.read_bytes() + + +def test_changed_result_or_spec_is_read_again(root, tmp_path): + path = tmp_path / "summary.csv" + _summary(root).save(path, cache=True) + + changed = next(root.glob("obj0003/search/*")) + (changed / "files" / "extra.json").write_text("{}") + summary = _summary(root) + summary.save(path, cache=True) + assert (summary.stats["computed"], summary.stats["cached"]) == (1, 119) + + summary = AggregateCSV(Aggregator.from_directory(root)) + summary.add_variable(VARIABLE) + summary.add_computed_column("doubled", lambda result: 3) # edited code + summary.save(path, cache=True) + assert summary.stats["computed"] == 120 + + +def test_killed_export_leaves_previous_files(root, tmp_path, monkeypatch): + path = tmp_path / "summary.csv" + _summary(root).save(path, cache=True) + before = (path.read_bytes(), cache_path(path).read_bytes()) + + import csv as csv_module + + class Killed(csv_module.DictWriter): + def writerow(self, row): + raise KeyboardInterrupt + + monkeypatch.setattr( + "autofit.aggregator.summary.aggregate_csv.csv.DictWriter", Killed + ) + _copy(root, 5, start=120) + with pytest.raises(KeyboardInterrupt): + _summary(root).save(path, cache=True) + + assert (path.read_bytes(), cache_path(path).read_bytes()) == before + assert not list(tmp_path.glob("*.tmp")) + + +def test_shards_merge_to_the_serial_export(root, tmp_path): + serial = tmp_path / "serial.csv" + _summary(root).save(serial, sort_by="id") + + parts = [] + for i in range(4): + part = tmp_path / f"part{i}.csv" + _summary(root).save(part, shard=f"{i}/4", cache=True) + parts.append(part) + assert sum(len(_read(part)) for part in parts) == 120 + + merged = tmp_path / "merged.csv" + assert merge_csv(parts, merged) == 120 + assert merged.read_bytes() == serial.read_bytes() + + # Merging a part twice is harmless: identical duplicates are kept once. + merge_csv(parts + parts[:1], merged) + assert merged.read_bytes() == serial.read_bytes() + + +def test_merge_refusals(tmp_path): + a = tmp_path / "a.csv" + b = tmp_path / "b.csv" + a.write_text("id,x\r\n1,2\r\n") + b.write_text("id,y\r\n3,4\r\n") + with pytest.raises(MergeException, match="header"): + merge_csv([a, b], tmp_path / "m.csv") + + b.write_text("id,x\r\n1,5\r\n") + with pytest.raises(MergeException, match="different rows"): + merge_csv([a, b], tmp_path / "m.csv") + + with pytest.raises(MergeException, match="no 'name' column"): + merge_csv([a], tmp_path / "m.csv", key="name") + + assert main(["merge", str(tmp_path / "m.csv"), str(a), str(b)]) == 2 + b.write_text("id,x\r\n3,5\r\n") + assert main(["merge", str(tmp_path / "m.csv"), str(a), str(b)]) == 0 + assert [row["id"] for row in _read(tmp_path / "m.csv")] == ["1", "3"] + + +def test_errors_become_rows(root, tmp_path): + summary = _summary(root) + + def explode(result): + if result.id == summary_ids[0]: + raise RuntimeError("boom") + return 1 + + summary_ids = sorted(output.id for output in summary._aggregator) + summary.add_computed_column("explode", explode) + + with pytest.raises(RuntimeError): + summary.save(tmp_path / "raise.csv") + + path = tmp_path / "rows.csv" + summary.save(path, on_error="row", sort_by="id") + rows = _read(path) + assert len(rows) == 120 + assert summary.stats["errors"] == 1 + assert rows[0]["status_reason"] == "error:RuntimeError: boom" + assert rows[0][VARIABLE.replace(".", "_")] == "" + assert all(row["status_reason"] == "" for row in rows[1:]) + + +def test_missing_latent_summary_reason(root, tmp_path): + for latent in root.glob("obj000[0-4]/search/*/files/latent"): + shutil.rmtree(latent) + summary = AggregateCSV(Aggregator.from_directory(root), strict=False) + summary.add_variable("latent.value") + path = tmp_path / "s.csv" + summary.save(path, on_error="row") + reasons = [row["status_reason"] for row in _read(path)] + assert reasons.count("missing_latent_summary") == 5 + + +def test_expected_results_get_rows(root, tmp_path): + library = af.ResultsLibrary.grid( + [f"obj{i:04d}" for i in range(122)], + {"search": {"products": ["files/model.json", "files/coolest.json"], + "location": "{dataset}/search"}}, + roots=root, + index_dir=tmp_path / "index", + ) + report = library.check() + + summary = _summary(root) + path = tmp_path / "s.csv" + summary.save(path, expected=report, sort_by="dataset") + rows = {row["dataset"]: row for row in _read(path)} + + assert len(rows) == 122 + assert rows["obj0121"]["status_reason"] == "no_result" + assert rows["obj0121"]["id"] == "" + assert rows["obj0000"]["search"] == "search" + assert rows["obj0000"]["status_reason"] == "missing_product:files/coolest.json" + assert summary.stats["expected"] == 2 + + +def test_columns_json(root, tmp_path): + summary = AggregateCSV(Aggregator.from_directory(root)) + summary.add_variable( + VARIABLE, + value_types=[ValueType.Median, ValueType.ValuesAt1Sigma], + unit="arcsec", + prior_edge=True, + ) + summary.add_variable("latent.value") + summary.add_label_column("label", {}) + path = tmp_path / "s.csv" + summary.save(path, columns_json=True, on_error="row") + + document = json.loads((tmp_path / "s.columns.json").read_text()) + columns = {column["name"]: column for column in document["columns"]} + name = VARIABLE.replace(".", "_") + + assert document["n_rows"] == 120 + assert columns[name] == { + "name": name, + "source": VARIABLE, + "kind": "parameter", + "statistic": "median", + "bound": None, + "unit": "arcsec", + "n_blank": 0, + } + assert columns[f"{name}_lower_1_sigma"]["bound"] == "quantile_1sigma" + assert columns[f"{name}_at_prior_edge"]["kind"] == "flag" + assert columns["latent_value"]["kind"] == "latent" + assert columns["label"]["kind"] == "label" + assert columns["label"]["n_blank"] == 120 + assert columns["status_reason"]["kind"] == "meta" + edges = {row[f"{name}_at_prior_edge"] for row in _read(path)} + assert edges <= {"True", "False", ""} + + +def test_plain(): + typed = { + "type": "instance", + "class_path": "astropy.wcs.WCS", + "arguments": { + "crpix": {"type": "ndarray", "array": [1.0, 2.0], "dtype": "float64"}, + "names": {"type": "tuple", "values": ["a", {"type": "path", "path": "/x"}]}, + "scale": {"type": "np.number", "dtype": "float32", "value": 0.1}, + "meta": {"type": "dict", "arguments": {"k": {"type": "list", "values": [1]}}}, + }, + } + assert plain(typed) == { + "class_path": "astropy.wcs.WCS", + "crpix": [1.0, 2.0], + "names": ["a", "/x"], + "scale": 0.1, + "meta": {"k": [1]}, + } + assert plain([1, {"a": 2}]) == [1, {"a": 2}] + + +def test_search_output_plain(root): + output = Aggregator.from_directory(root).search_outputs[0] + model = output.plain("model") + assert "type" not in model + assert set(model["galaxies"]["lens"]["bulge"]) >= {"centre"} + assert output.plain("absent") is None + + +# Regressions from the independent review. + + +def test_header_is_the_same_for_every_shard(tmp_path): + root = _copy(tmp_path / "output", 4) + serial = tmp_path / "serial.csv" + summary = _summary(root) + summary.add_label_column("lab", {}) + summary.save(serial, sort_by="id", on_error="row") + + parts = [] + for i in range(8): # most shards are empty + part = tmp_path / f"part{i}.csv" + summary.save(part, shard=f"{i}/8", on_error="row") + parts.append(part) + header = serial.read_text().splitlines()[0] + assert {part.read_text().splitlines()[0] for part in parts} == {header} + merged = tmp_path / "merged.csv" + merge_csv(parts, merged) + assert merged.read_bytes() == serial.read_bytes() + + +def test_error_row_first_does_not_reorder_header(root, tmp_path): + summary = _summary(root) + summary.add_label_column("lab", {}) + first = sorted(output.id for output in summary._aggregator)[0] + + def explode(result): + if result.id == first: + raise RuntimeError("boom") + return 1 + + summary.add_computed_column("explode", explode) + path = tmp_path / "s.csv" + summary.save(path, on_error="row", sort_by="id") + assert path.read_text().splitlines()[0] == ( + f"id,{VARIABLE.replace('.', '_')}," + f"{VARIABLE.replace('.', '_')}_lower_1_sigma," + f"{VARIABLE.replace('.', '_')}_upper_1_sigma,doubled,lab,explode,status_reason" + ) + + +def test_symlinked_root_shards_with_expected(tmp_path): + real = _copy(tmp_path / "real", 12) + link = tmp_path / "link" + link.symlink_to(real) + library = af.ResultsLibrary.grid( + [f"obj{i:04d}" for i in range(14)], + {"search": {"products": ["files/model.json"], "location": "{dataset}/search"}}, + roots=real, + index_dir=tmp_path / "index", + ) + report = library.check() + + def summary(): + return _summary(link) + + serial = tmp_path / "serial.csv" + s = summary() + s.save(serial, expected=report, sort_by="id") + assert s.stats["expected"] == 2 + + parts = [] + for i in range(4): + part = tmp_path / f"part{i}.csv" + summary().save(part, expected=report, shard=f"{i}/4") + parts.append(part) + merged = tmp_path / "merged.csv" + assert merge_csv(parts, merged) == 14 + assert merged.read_bytes() == serial.read_bytes() + + +def test_in_place_latent_change_is_read_again(tmp_path): + root = _copy(tmp_path / "output", 2) + summary = AggregateCSV(Aggregator.from_directory(root)) + summary.add_variable("latent.value") + path = tmp_path / "s.csv" + summary.save(path, cache=True) + + for latent in root.glob("*/search/*/files/latent/latent_summary.json"): + latent.write_text(latent.read_text().replace('"latent.value": 1.0', '"latent.value": 99.0')) + summary = AggregateCSV(Aggregator.from_directory(root)) + summary.add_variable("latent.value") + summary.save(path, cache=True) + + assert summary.stats["computed"] == 2 + assert "99.0" in path.read_text() + + +def test_captured_value_change_is_read_again(tmp_path): + root = _copy(tmp_path / "output", 2) + path = tmp_path / "s.csv" + for k, computed in ((1.0, 2), (2.0, 2), (2.0, 0)): + summary = AggregateCSV(Aggregator.from_directory(root)) + summary.add_computed_column("k", (lambda k: lambda r: k)(k)) + summary.save(path, cache=True) + assert summary.stats["computed"] == computed + assert f",{k}" in path.read_text() + + +def test_cached_csv_equals_fresh_csv(tmp_path): + import numpy as np + + root = _copy(tmp_path / "output", 3) + + def summary(): + s = AggregateCSV(Aggregator.from_directory(root)) + s.add_computed_column("f32", lambda r: np.float32(0.1)) + s.add_computed_column("tup", lambda r: (1, 2)) + s.add_computed_column("d", lambda r: {0: 5, "a": 6}) + s.add_computed_column("arr", lambda r: np.array([1.0, 2.0])) + return s + + fresh = tmp_path / "fresh.csv" + summary().save(fresh, sort_by="id") + cached = tmp_path / "cached.csv" + summary().save(cached, cache=True, sort_by="id") + s = summary() + s.save(cached, cache=True, sort_by="id") + assert s.stats["cached"] == 3 + assert cached.read_bytes() == fresh.read_bytes() + assert "0.1," in fresh.read_text() and "(1, 2)" in fresh.read_text() + + +def test_spec_digest_stable_across_processes(): + import subprocess + import sys + + code = ( + "from autofit.aggregator.summary.aggregate_csv.cache import function_digest\n" + "f = lambda r: r in {'alpha', 'beta', 'gamma', 'delta'}\n" + "print(function_digest(f))\n" + ) + digests = { + subprocess.run( + [sys.executable, "-c", code], + env={**__import__("os").environ, "PYTHONHASHSEED": seed}, + capture_output=True, + text=True, + check=True, + ).stdout + for seed in ("1", "2", "3") + } + assert len(digests) == 1 + + +def test_plain_compound_dict(): + from autonerves.dictable import to_dict + + assert sorted(plain(to_dict({("a", "b"): 1, ("c", "d"): 2}))) == [ + [["a", "b"], 1], + [["c", "d"], 2], + ] + + +def test_merge_twice_with_unkeyed_rows(tmp_path): + part = tmp_path / "p.csv" + part.write_text("id,dataset\r\n,obj1\r\n1,obj0\r\n") + merged = tmp_path / "m.csv" + assert merge_csv([part, part], merged) == 2 + + +def test_prior_edge_in_log_space(): + from autofit.aggregator.summary.aggregate_csv.column import Column + + class Model: + def __init__(self, prior): + self.prior = prior + + def object_for_path(self, path): + return self.prior + + class Result: + pass + + class FakeRow: + result = Result() + + column = Column("x", prior_edge=True) + FakeRow.result.model = Model(af.LogUniformPrior(lower_limit=1e-4, upper_limit=1e4)) + assert column._at_prior_edge(FakeRow, 50.0) is False + assert column._at_prior_edge(FakeRow, 1.1e-4) is True + FakeRow.result.model = Model(af.UniformPrior(lower_limit=0.0, upper_limit=100.0)) + assert column._at_prior_edge(FakeRow, 0.5) is True + assert column._at_prior_edge(FakeRow, 50.0) is False