From 698a657009c62fcd15e31f8bf6066459d8dd8a84 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 28 Oct 2026 21:47:56 +0000 Subject: [PATCH] =?UTF-8?q?feat:=20results-library=20phase=200b=20?= =?UTF-8?q?=E2=80=94=20honest=20reads?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Aggregator.from_directory(..., on_error="skip"|"raise"): an unreadable zip (BadZipFile, or EOFError / zlib.error from a damaged member) is skipped, logged and recorded in agg.errors as (path, exception) instead of failing the whole scan; a partial extraction is removed. unzip_directory gains the same on_error and returns its errors; add_directory, filter and slicing carry errors along. - An empty aggregator logs a warning naming the directory and filters; every print in the aggregator is now logging. - AggregateCSV: strict=True by default; header is the union of every row's columns; rows are built before the file is opened and written via open_atomic, so a failed or interrupted save leaves the previous CSV whole; save() reports (logs and returns) columns blank in every row; add_label_column joins a dict of labels by key (search id, or key=callable), and under strict a positional list must match the aggregator's length. - Row regression test on an asymmetric latent PDF (median, max_lh, 1-sigma and 3-sigma bounds all distinct). - post_fit_output docstring states the zip is always written and the folder is removed only under remove_files; the "Removing all files" log is conditional. Refs #1734 Co-Authored-By: Claude Opus 5.5 --- autofit/aggregator/aggregator.py | 130 ++++++-- .../summary/aggregate_csv/__init__.py | 113 +++++-- .../summary/aggregate_csv/column.py | 31 +- autofit/non_linear/search/abstract_search.py | 11 +- .../summary_files/test_aggregate_csv.py | 3 +- .../summary_files/test_honest_reads.py | 309 ++++++++++++++++++ 6 files changed, 540 insertions(+), 57 deletions(-) create mode 100644 test_autofit/aggregator/summary_files/test_honest_reads.py diff --git a/autofit/aggregator/aggregator.py b/autofit/aggregator/aggregator.py index 77144dc9d..c827e17e8 100755 --- a/autofit/aggregator/aggregator.py +++ b/autofit/aggregator/aggregator.py @@ -15,10 +15,11 @@ import logging import os import zipfile +import zlib from collections import defaultdict from pathlib import Path from shutil import rmtree -from typing import List, Union, Iterator, Optional +from typing import List, Union, Iterator, Optional, Tuple from autonerves.test_mode import is_test_mode @@ -32,6 +33,35 @@ logger = logging.getLogger(__name__) +ON_ERROR_VALUES = ("skip", "raise") +""" +What ``Aggregator.from_directory`` does with an unreadable zip: ``"skip"`` it and +record it in ``Aggregator.errors``, or ``"raise"``. +""" + + +def _check_on_error(on_error: str): + if on_error not in ON_ERROR_VALUES: + raise ValueError( + f"on_error must be one of {ON_ERROR_VALUES}, not {on_error!r}." + ) + + +ZIP_READ_ERRORS = (zipfile.BadZipFile, EOFError, zlib.error) +""" +What reading one damaged result zip raises: ``BadZipFile`` for a missing or bad +central directory or a CRC mismatch, ``EOFError`` and ``zlib.error`` for a member +truncated or corrupted part-way through. +""" + + +def _bad_zip_error(zip_path: Path, error: Exception) -> zipfile.BadZipFile: + return zipfile.BadZipFile( + f"File is not a readable zip file ({type(error).__name__}: {error}): \n " + f"{zip_path.parent} \n" + f"{zip_path.name}" + ) + class AggregatorGroup: def __init__(self, groups: ["AggregatorGroup"]): @@ -85,20 +115,42 @@ def values(self, name: str, parser=lambda o: o) -> List[List]: return [group.values(name, parser=parser) for group in self.groups] -def unzip_directory(directory: str): +def unzip_directory( + directory: str, on_error: str = "raise" +) -> List[Tuple[Path, Exception]]: """ Unzip all zip files in a directory recursively. + + Parameters + ---------- + directory + The directory searched recursively for zips. + on_error + ``"raise"`` (the default) raises on the first unreadable zip; ``"skip"`` + logs it, carries on, and returns it among the ``(path, exception)`` pairs. + + Returns + ------- + The ``(path, exception)`` of every zip that could not be read. """ + _check_on_error(on_error) + + errors = [] + for root, _, filenames in os.walk(directory): for filename in filenames: if filename.endswith(".zip"): + zip_path = Path(root) / filename try: - with zipfile.ZipFile(Path(root) / filename, "r") as f: + with zipfile.ZipFile(zip_path, "r") as f: f.extractall(Path(root) / filename[:-4]) - except zipfile.BadZipFile: - raise zipfile.BadZipFile( - f"File is not a zip file: \n " f"{root} \n" f"{filename}" - ) + except ZIP_READ_ERRORS as e: + if on_error == "raise": + raise _bad_zip_error(zip_path, e) from e + logger.warning(f"Skipping unreadable zip {zip_path}: {e}") + errors.append((zip_path, e)) + + return errors def _is_search_output(root, dirs, filenames) -> bool: @@ -131,6 +183,7 @@ def __init__( search_outputs: List[SearchOutput], grid_search_outputs: List[GridSearchOutput], temporary_directory: Optional[TemporaryExtraction] = None, + errors: Optional[List[Tuple[Path, Exception]]] = None, ): """ Class to aggregate phase results for all subdirectories in a given directory. @@ -144,9 +197,12 @@ def __init__( ``from_directory`` was called with ``unzip_temporary=True``. Held so ``close`` can remove it eagerly; the search outputs keep it alive regardless. + errors + The ``(path, exception)`` of every output ``from_directory`` could not + read and skipped (``on_error="skip"``), exposed as ``errors``. """ if len(search_outputs) > 20: - print( + logger.info( "When aggregating many searches it can be more efficient to use the database.\n" "Checkout the database cookbook at this URL: " "https://pyautofit.readthedocs.io/en/latest/cookbooks/database.html" @@ -156,6 +212,7 @@ def __init__( # Set here rather than lazily: ``__getattr__`` returns an # ``AttributePredicate`` for any name it does not find. self._temporary_directory = temporary_directory + self.errors = list(errors or []) def grid_searches(self): """ @@ -180,6 +237,7 @@ def from_directory( completed_only=False, reference: Optional[dict] = None, unzip_temporary: bool = False, + on_error: str = "skip", ) -> "Aggregator": """ Aggregate phase results for all subdirectories in a given directory. @@ -210,14 +268,21 @@ def from_directory( beside it and carries a ``.completed`` file still uses that directory and is not extracted again; one whose sibling directory has no ``.completed`` file is extracted, because such a directory is written after the search was archived and does not stand for the search. + on_error + What to do with a zip that cannot be read (``ZIP_READ_ERRORS``): ``"skip"`` (the default) logs + a warning, leaves it out and records ``(path, exception)`` in the returned aggregator's + ``errors``, so one corrupt archive does not hide every other result; ``"raise"`` raises. Returns ------- An aggregator whose search outputs are ordered by path, so that the same results tree gives the same order on every machine regardless of the filesystem's directory-entry order. """ - print("Aggregator loading search_outputs... could take some time.") + _check_on_error(on_error) + logger.info("Aggregator loading search_outputs... could take some time.") + + errors = [] temporary_directory = None temporary_roots = [] incomplete_count = 0 @@ -274,15 +339,21 @@ def scan(scan_directory, extract_temporary=False, owner=None): ) if extract_temporary: extracted = temporary_path(zip_path, scan_directory) + existed = extracted.exists() try: with zipfile.ZipFile(zip_path, "r") as f: f.extractall(extracted) - except zipfile.BadZipFile: - raise zipfile.BadZipFile( - f"File is not a zip file: \n " - f"{root} \n" - f"{filename}" + except ZIP_READ_ERRORS as e: + if on_error == "raise": + raise _bad_zip_error(zip_path, e) from e + logger.warning( + f"Aggregator: skipping unreadable zip {zip_path}: {e}" ) + errors.append((zip_path, e)) + if not existed: + # A partial extraction is not a search output. + rmtree(extracted, ignore_errors=True) + continue if extract_temporary: # Outside the tree being walked, so it is scanned separately. temporary_roots.append(extracted) @@ -371,31 +442,44 @@ def scan_all(scan_directory): search_outputs, grid_search_outputs = scan_all(test_mode_directory) if len(search_outputs) == 0: - print(f"\nNo search_outputs found in {directory}\n") + # Loud: an empty aggregator otherwise flows on into empty tables and + # plots that look like a result. + logger.warning( + f"Aggregator found no search outputs in {directory} " + f"(completed_only={completed_only}, unzip_temporary={unzip_temporary}, " + f"excluded as incomplete={incomplete_count}, unreadable={len(errors)})." + ) else: - print( - f"\n A total of {str(len(search_outputs))} search_outputs and results were found." + logger.info( + f"A total of {str(len(search_outputs))} search_outputs and results were found." ) # A search dropped for having no ``.completed`` file is invisible in the # count above, so a run that aggregates a fraction of its searches looks # like a complete one. Say how many were left out. if completed_only and incomplete_count > 0: - print( - f" {incomplete_count} further search_outputs were excluded because " + logger.warning( + f"{incomplete_count} further search_outputs were excluded because " f"they have no .completed file." ) + if errors: + logger.warning( + f"{len(errors)} unreadable output(s) were skipped; see Aggregator.errors." + ) + return cls( search_outputs, grid_search_outputs, temporary_directory=temporary_directory, + errors=errors, ) def add_directory( self, directory: Union[str, Path], unzip_temporary: bool = False, + on_error: str = "skip", ): """ Add a directory to the aggregator. @@ -408,13 +492,17 @@ def add_directory( If `True` zips are extracted into a temporary directory that is cleaned up automatically, as in ``from_directory``. The added search outputs keep that directory alive; ``close`` does not remove it. + on_error + As in ``from_directory``; skipped outputs are added to ``errors``. """ aggregator = Aggregator.from_directory( directory, unzip_temporary=unzip_temporary, + on_error=on_error, ) self.search_outputs.extend(aggregator.search_outputs) self.grid_search_outputs.extend(aggregator.grid_search_outputs) + self.errors.extend(aggregator.errors) def close(self): """ @@ -467,6 +555,7 @@ def __getitem__(self, item: Union[slice, int]) -> Union["Aggregator", SearchOutp return Aggregator( self.search_outputs[item], self.grid_search_outputs, + errors=self.errors, ) return self.search_outputs[item] @@ -500,10 +589,11 @@ def query(self, *predicates) -> "Aggregator": for predicate in predicates: search_outputs = predicate.filter(search_outputs) search_outputs = list(search_outputs) - print(f"Filter found a total of {str(len(search_outputs))} results") + logger.info(f"Filter found a total of {str(len(search_outputs))} results") return Aggregator( search_outputs=list(search_outputs), grid_search_outputs=self.grid_search_outputs, + errors=self.errors, ) def values(self, name: str, parser=lambda o: o) -> Iterator: diff --git a/autofit/aggregator/summary/aggregate_csv/__init__.py b/autofit/aggregator/summary/aggregate_csv/__init__.py index 30bcef07f..a61abbfdb 100644 --- a/autofit/aggregator/summary/aggregate_csv/__init__.py +++ b/autofit/aggregator/summary/aggregate_csv/__init__.py @@ -1,10 +1,10 @@ -from typing import Optional, Callable, List, Union - +import csv +import logging from pathlib import Path +from typing import Optional, Callable, List, Union, Hashable from autofit.aggregator.aggregator import Aggregator - -import csv +from autofit.tools.util import open_atomic from autofit.aggregator.summary.aggregate_csv.column import ( LabelColumn, @@ -14,9 +14,11 @@ ) from autofit.aggregator.summary.aggregate_csv.row import Row +logger = logging.getLogger(__name__) + class AggregateCSV: - def __init__(self, aggregator: Aggregator, strict: bool = False): + def __init__(self, aggregator: Aggregator, strict: bool = True): """ Summarise results from the aggregator as a CSV. @@ -24,9 +26,11 @@ def __init__(self, aggregator: Aggregator, strict: bool = False): ---------- aggregator strict - 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 each such column and its values are left empty. + If True (the default) an argument matching neither the samples_summary + nor the latent_summary raises a KeyError, as does a keyed label with no + value for a search and a label list whose length differs from the + aggregator's. If False a warning is logged once for each such column and + its values are left empty. """ if len(aggregator) == 0: raise ValueError("The aggregator is empty.") @@ -90,7 +94,8 @@ def add_computed_column( def add_label_column( self, name: str, - values: list, + values: Union[list, dict], + key: Optional[Callable[[object], Hashable]] = None, ): """ Add a column to the summary table that is a label. @@ -100,52 +105,102 @@ def add_label_column( name The name of the column values - The values of the column + Either a dict joined to each search by key (``key(search_output)``, the + search's ``id`` by default), which pairs each label with its search + whatever order the aggregator holds them in; or a list paired with the + searches by position, which must then be as long as the aggregator. + key + Computes the join key of a search output for a dict of ``values``. """ + if ( + not isinstance(values, dict) + and self._strict + and len(values) != len(self._aggregator) + ): + raise ValueError( + f"The label column '{name}' has {len(values)} values but the " + f"aggregator holds {len(self._aggregator)} searches. Pass a dict " + f"keyed by search id to join labels by key." + ) + self._columns.append( LabelColumn( name, values, + key=key, + strict=self._strict, ) ) + def _rows(self) -> List[dict]: + return [ + Row( + result, + self._columns, + i, + ).dict() + for i, result in enumerate(self._aggregator) + ] + + @staticmethod + def _union_fieldnames(rows: List[dict]) -> List[str]: + fieldnames = {} + for row in rows: + fieldnames.update(dict.fromkeys(row)) + return list(fieldnames) + @property def fieldnames(self) -> List[str]: """ - The fieldnames for the CSV file. + The fieldnames for the CSV file: the union of every row's columns, in the + order they first appear, so a column only some searches have (e.g. a + computed dict column) is not dropped because the first row lacks it. """ - for i, result in enumerate(self._aggregator): - row = Row( - result, - self._columns, - i, - ) - return row.column_names + return self._union_fieldnames(self._rows()) - def save(self, path: Union[str, Path]): + def save(self, path: Union[str, Path]) -> List[str]: """ Save the summary table to a CSV file. + Every row is computed before the file is opened and the file is written + atomically (``open_atomic``), so an error or an interrupted save leaves any + previous CSV at ``path`` whole. + Parameters ---------- path The path to save the file to + + Returns + ------- + The columns that are blank in every row, which are also logged as a warning. """ + path = Path(path) folder_path = path.parent if path.suffix else path folder_path.mkdir(parents=True, exist_ok=True) - with open(path, "w") as f: + rows = self._rows() + fieldnames = self._union_fieldnames(rows) + + with open_atomic(path, "w") as f: writer = csv.DictWriter( f, - fieldnames=self.fieldnames, + fieldnames=fieldnames, ) writer.writeheader() - for i, result in enumerate(self._aggregator): - row = Row( - result, - self._columns, - i, - ) - - writer.writerow(row.dict()) + for row in rows: + writer.writerow(row) + + blank = [ + name + for name in fieldnames + if all(row.get(name) in (None, "") for row in rows) + ] + if blank: + logger.warning( + f"The summary CSV {path} has columns blank in every row: " + f"{', '.join(blank)}." + ) + + return blank diff --git a/autofit/aggregator/summary/aggregate_csv/column.py b/autofit/aggregator/summary/aggregate_csv/column.py index ba7694102..cd29aa122 100644 --- a/autofit/aggregator/summary/aggregate_csv/column.py +++ b/autofit/aggregator/summary/aggregate_csv/column.py @@ -169,7 +169,13 @@ def value(self, row: "Row"): class LabelColumn(AbstractColumn): - def __init__(self, name: str, values: list): + def __init__( + self, + name: str, + values, + key: Optional[Callable] = None, + strict: bool = False, + ): """ A column in the summary table that is a label. @@ -177,9 +183,30 @@ def __init__(self, name: str, values: list): ---------- name The name of the column + values + A dict joined to each row by key, or a list paired with rows by position. + key + Computes a row's join key from its search output (its ``id`` by default). + strict + If True a dict with no value for a row's key raises a KeyError; if False + the value is left empty. """ super().__init__(name) self.values = values + self.key = key + self.strict = strict def value(self, row: "Row"): - return self.values[row.number] + if not isinstance(self.values, dict): + return self.values[row.number] + + key = self.key(row.result) if self.key is not None else row.result.id + try: + return self.values[key] + except KeyError: + if self.strict: + raise KeyError( + f"The label column '{self.name}' has no value for the search " + f"with key {key!r}." + ) + return None diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index 55cb21615..480ec0fb9 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -549,16 +549,17 @@ def result_via_completed_fit( def post_fit_output(self, search_internal, finalize_search_internal: bool = True): """ - Cleans up the output folder after a completed non-linear search: removes the - folder of results so only its `.zip` file is left (for supercomputers with a - file-count limit), when `remove_files=True` in the `general.yaml` `output` - section. ``finalize_search_internal=False`` when the fit just ran, since + Archives the output folder of a completed non-linear search into its `.zip` + file (always), and then removes the folder so only the `.zip` is left (for + supercomputers with a file-count limit) only when `remove_files=True` in the + `general.yaml` `output` section; with `remove_files=False` both are kept. + ``finalize_search_internal=False`` when the fit just ran, since ``start_resume_fit`` finalized the internal state before writing ``.completed``. """ if finalize_search_internal: self.finalize_search_internal(search_internal=search_internal) - if not self.disable_output: + if not self.disable_output and getattr(self.paths, "remove_files", False): self.logger.info("Removing all files except for .zip file") self.paths.zip_remove() diff --git a/test_autofit/aggregator/summary_files/test_aggregate_csv.py b/test_autofit/aggregator/summary_files/test_aggregate_csv.py index cd98a5b38..8e1d5800b 100644 --- a/test_autofit/aggregator/summary_files/test_aggregate_csv.py +++ b/test_autofit/aggregator/summary_files/test_aggregate_csv.py @@ -285,10 +285,11 @@ def test_max_log_likelihood_differs_from_median( def test_unresolvable_argument_warns( output_path, - summary, + aggregator, load_output, caplog, ): + summary = AggregateCSV(aggregator, strict=False) summary.add_variable("does.not.exist") with caplog.at_level( diff --git a/test_autofit/aggregator/summary_files/test_honest_reads.py b/test_autofit/aggregator/summary_files/test_honest_reads.py new file mode 100644 index 000000000..65c01a59c --- /dev/null +++ b/test_autofit/aggregator/summary_files/test_honest_reads.py @@ -0,0 +1,309 @@ +""" +Honest reads (results-library phase 0b): the aggregator and AggregateCSV report +problems (a corrupt zip, an unknown column, a column only some rows have, an +interrupted save) instead of hiding them. +""" +import csv +import logging +import shutil +import zipfile +from pathlib import Path + +import pytest + +import autofit as af +from autofit.aggregator import Aggregator +from autofit.aggregator.summary.aggregate_csv import AggregateCSV, ValueType +from autofit.aggregator.summary.aggregate_csv.column import Column +from autofit.aggregator.summary.aggregate_csv.row import Row +from autofit.example.model import Gaussian +from autofit.non_linear.samples.sample import Sample +from autofit.non_linear.samples.summary import SamplesSummary + +AGGREGATE_SUMMARY = Path(__file__).parent / "aggregate_summary" + + +@pytest.fixture(name="tree") +def make_tree(tmp_path): + """ + A results tree of the two summary fixtures, one zipped, plus one corrupt zip. + """ + tree = tmp_path / "tree" + shutil.copytree(AGGREGATE_SUMMARY, tree) + + shutil.make_archive(str(tree / "fit_2"), "zip", tree / "fit_2") + shutil.rmtree(tree / "fit_2") + + (tree / "fit_3.zip").write_bytes(b"PK\x03\x04 truncated") + + return tree + + +def test__from_directory__corrupt_zip_is_collected(tree): + aggregator = Aggregator.from_directory(tree) + + assert len(aggregator) == 2 + assert len(aggregator.errors) == 1 + + path, error = aggregator.errors[0] + assert Path(path).name == "fit_3.zip" + assert isinstance(error, zipfile.BadZipFile) + + +def test__from_directory__corrupt_zip_raises_on_request(tree): + with pytest.raises(zipfile.BadZipFile, match="fit_3.zip"): + Aggregator.from_directory(tree, on_error="raise") + + +def test__from_directory__unzip_temporary_collects_corrupt_zip(tree): + with Aggregator.from_directory(tree, unzip_temporary=True) as aggregator: + assert len(aggregator) == 2 + assert len(aggregator.errors) == 1 + + +def test__from_directory__damaged_member_is_collected(tree): + """ + A zip whose central directory reads but whose member data is damaged fails only + on extraction (``zlib.error`` / CRC ``BadZipFile``), and is collected the same way. + """ + (tree / "fit_3.zip").unlink() + + damaged = tree / "fit_4.zip" + with zipfile.ZipFile(damaged, "w", zipfile.ZIP_DEFLATED) as f: + f.writestr("data.txt", "".join(str(i) for i in range(5000))) + + data = bytearray(damaged.read_bytes()) + start = zipfile.sizeFileHeader + len("data.txt") + for i in range(start, start + 64): + data[i] ^= 0xFF + damaged.write_bytes(bytes(data)) + + aggregator = Aggregator.from_directory(tree) + + assert len(aggregator) == 2 + assert [Path(path).name for path, _ in aggregator.errors] == ["fit_4.zip"] + + with pytest.raises(zipfile.BadZipFile, match="fit_4.zip"): + Aggregator.from_directory(tree, on_error="raise") + + +def test__from_directory__rejects_unknown_on_error(tree): + with pytest.raises(ValueError, match="on_error"): + Aggregator.from_directory(tree, on_error="ignore") + + +def test__from_directory__empty_warns_naming_directory_and_filters(tmp_path, caplog): + with caplog.at_level(logging.WARNING, logger="autofit.aggregator.aggregator"): + aggregator = Aggregator.from_directory(tmp_path, completed_only=True) + + assert len(aggregator) == 0 + messages = [record.getMessage() for record in caplog.records] + assert any(str(tmp_path) in m and "completed_only=True" in m for m in messages) + + +def test__from_directory__reports_through_logging_not_print(tree, capsys): + Aggregator.from_directory(tree) + + assert capsys.readouterr().out == "" + + +# --- AggregateCSV ---------------------------------------------------------------------- + + +@pytest.fixture(name="aggregator") +def make_aggregator(): + return Aggregator.from_directory(AGGREGATE_SUMMARY) + + +def _load(path): + with open(path) as f: + return list(csv.DictReader(f)) + + +def test__aggregate_csv__unknown_column_raises_by_default(aggregator, tmp_path): + summary = AggregateCSV(aggregator) + summary.add_variable("does.not.exist") + + with pytest.raises(KeyError, match="does.not.exist"): + summary.save(tmp_path / "summary.csv") + + assert not (tmp_path / "summary.csv").exists() + + +def _name(output): + # The two summary fixtures are copies with the same search id, so the tests + # join on the directory name instead. + return Path(output.directory).name + + +def test__aggregate_csv__header_is_union_of_rows(aggregator, tmp_path): + def compute(result): + if _name(result) == "fit_1": + return {"only_first": 1} + return {"only_second": 2} + + summary = AggregateCSV(aggregator) + summary.add_computed_column("computed", compute) + summary.save(tmp_path / "summary.csv") + + with open(tmp_path / "summary.csv") as f: + header = next(csv.reader(f)) + + assert header == ["id", "computed_only_first", "computed_only_second"] + + rows = _load(tmp_path / "summary.csv") + assert rows[0]["computed_only_first"] == "1" + assert rows[0]["computed_only_second"] == "" + assert rows[1]["computed_only_second"] == "2" + + +def test__aggregate_csv__interrupted_save_leaves_previous_csv( + aggregator, tmp_path, monkeypatch +): + path = tmp_path / "summary.csv" + + summary = AggregateCSV(aggregator) + summary.add_variable("galaxies.lens.bulge.centre.centre_0") + summary.save(path) + before = path.read_bytes() + + original = csv.DictWriter.writerow + calls = [] + + def writerow(self, row): + calls.append(row) + if len(calls) == 2: + raise KeyboardInterrupt + return original(self, row) + + monkeypatch.setattr(csv.DictWriter, "writerow", writerow) + + summary.add_label_column("label", ["a", "b"]) + with pytest.raises(KeyboardInterrupt): + summary.save(path) + + assert path.read_bytes() == before + assert list(tmp_path.iterdir()) == [path] + + +def test__aggregate_csv__save_reports_blank_columns(aggregator, tmp_path, caplog): + summary = AggregateCSV(aggregator) + summary.add_computed_column("nothing", lambda result: None) + + with caplog.at_level( + logging.WARNING, logger="autofit.aggregator.summary.aggregate_csv" + ): + blank = summary.save(tmp_path / "summary.csv") + + assert blank == ["nothing"] + assert any("nothing" in record.getMessage() for record in caplog.records) + + +def test__aggregate_csv__label_column_joined_by_key(aggregator, tmp_path): + summary = AggregateCSV(aggregator) + summary.add_label_column("name", {"fit_2": "fit_2", "fit_1": "fit_1"}, key=_name) + summary.add_computed_column("directory", _name) + summary.save(tmp_path / "summary.csv") + + for row in _load(tmp_path / "summary.csv"): + assert row["name"] == row["directory"] + + +def test__aggregate_csv__label_column_joined_by_search_id(aggregator, tmp_path): + summary = AggregateCSV(aggregator) + summary.add_label_column("label", {aggregator[0].id: "labelled"}) + summary.save(tmp_path / "summary.csv") + + assert [row["label"] for row in _load(tmp_path / "summary.csv")] == [ + "labelled", + "labelled", + ] + + +def test__aggregate_csv__label_column_missing_key_raises(aggregator, tmp_path): + summary = AggregateCSV(aggregator) + summary.add_label_column("label", {"fit_1": "first"}, key=_name) + + with pytest.raises(KeyError, match="label"): + summary.save(tmp_path / "summary.csv") + + +def test__aggregate_csv__label_list_of_wrong_length_raises(aggregator): + summary = AggregateCSV(aggregator) + + with pytest.raises(ValueError, match="label"): + summary.add_label_column("label", ["a", "b", "c"]) + + +# --- Row: asymmetric latent PDF -------------------------------------------------------- + + +class _AsymmetricLatentResult: + """ + A search output whose latent PDF is asymmetric about its median, so a lower and + upper bound, a 1-sigma and a 3-sigma interval and the median and max-likelihood + values are all distinct numbers: any swap between them shows up as a wrong value. + """ + + id = "asymmetric" + + def __init__(self): + self.model = af.Model(Gaussian) + sample = Sample( + log_likelihood=1.0, + log_prior=0.0, + weight=1.0, + kwargs={"centre": 0.5, "normalization": 2.0, "sigma": 3.0}, + ) + self.samples_summary = SamplesSummary( + model=self.model, + max_log_likelihood_sample=sample, + median_pdf_sample=sample, + ) + self.latent_summary = SamplesSummary( + model=None, + median_pdf_sample=Sample( + log_likelihood=1.0, + log_prior=0.0, + weight=1.0, + kwargs={"latent.flux": 3.0}, + ), + max_log_likelihood_sample=Sample( + log_likelihood=2.0, + log_prior=0.0, + weight=1.0, + kwargs={"latent.flux": 3.6}, + ), + values_at_sigma_1={"latent.flux": (2.5, 5.0)}, + values_at_sigma_3={"latent.flux": (0.4, 11.0)}, + ) + + def value(self, name): + if name == "latent.latent_summary": + return self.latent_summary + return None + + +def test__row__asymmetric_latent_values(): + column = Column( + "latent.flux", + value_types=[ + ValueType.Median, + ValueType.MaxLogLikelihood, + ValueType.ValuesAt1Sigma, + ValueType.ValuesAt3Sigma, + ], + strict=True, + ) + + row = Row(_AsymmetricLatentResult(), [column], 0) + + assert row.dict() == { + "id": "asymmetric", + "latent_flux": 3.0, + "latent_flux_max_lh": 3.6, + "latent_flux_lower_1_sigma": 2.5, + "latent_flux_upper_1_sigma": 5.0, + "latent_flux_lower_3_sigma": 0.4, + "latent_flux_upper_3_sigma": 11.0, + }