diff --git a/autofit/aggregator/aggregator.py b/autofit/aggregator/aggregator.py index 2793fc81f..7258dbafb 100755 --- a/autofit/aggregator/aggregator.py +++ b/autofit/aggregator/aggregator.py @@ -93,6 +93,21 @@ def unzip_directory(directory: str): ) +def _is_search_output(root, dirs, filenames) -> bool: + """ + Whether an ``os.walk`` step has landed on a search output directory. + + The sentinel is ``files/search.json``, which ``save_all`` always writes; the + ``"files" in dirs`` guard keeps the walk from returning the ``files`` + directory itself as a search output. A bare ``metadata`` file is still + accepted so output folders (and archived zips) written before the sentinel + changed continue to aggregate. + """ + if "files" in dirs and (Path(root) / "files" / "search.json").exists(): + return True + return "metadata" in filenames + + def is_relative_to(path_a, path_b): """Return True if the path is relative to another path or False.""" try: @@ -152,7 +167,7 @@ def from_directory( Aggregate phase results for all subdirectories in a given directory. The whole directory structure is traversed and a Phase object created for each directory that contains a - metadata file. + ``files/search.json`` file (or, for legacy output, a ``metadata`` file). Zipped search outputs are extracted as they are encountered, in the same traversal. A zip whose extracted directory already exists is skipped, so repeat calls do not pay the extraction cost again; @@ -192,7 +207,7 @@ def scan(scan_directory): def should_add(): return not completed_only or ".completed" in filenames - if "metadata" in filenames: + if _is_search_output(root, dirs, filenames): if should_add(): search_outputs.append( SearchOutput( diff --git a/autofit/aggregator/search_output.py b/autofit/aggregator/search_output.py index 09c5888cf..293e66e9d 100644 --- a/autofit/aggregator/search_output.py +++ b/autofit/aggregator/search_output.py @@ -196,7 +196,8 @@ class SearchOutput(AbstractSearchOutput, fit_interface.Fit): def __init__(self, directory: Path, reference: dict = None): """ - Represents the output of a single search. Comprises a metadata file and other dataset files. + Represents the output of a single search. Comprises the ``files`` directory + written by the search (including ``search.json``) and other dataset files. Parameters ---------- @@ -213,18 +214,6 @@ def __init__(self, directory: Path, reference: dict = None): self.directory = directory - self.file_path = directory / "metadata" - - try: - with open(self.file_path) as f: - self.text = f.read() - pairs = [ - line.split("=") for line in self.text.split("\n") if "=" in line - ] - self.__dict__.update({pair[0]: pair[1] for pair in pairs}) - except FileNotFoundError: - pass - @property def samples_summary(self) -> SamplesSummary: """ @@ -427,11 +416,40 @@ def unique_tag(self): """ return self.search.unique_tag + @property + def non_linear_search(self) -> Optional[str]: + """ + Lower-cased class name of the search (e.g. "emcee"), read from + ``files/search.json``. + + Legacy output folders which predate that sentinel are read from the + ``non_linear_search=`` line of their ``metadata`` file instead. + """ + search_path = self.directory / "files" / "search.json" + try: + with open(search_path) as f: + class_path = json.load(f)["class_path"] + except (FileNotFoundError, KeyError, json.JSONDecodeError): + pass + else: + return class_path.rsplit(".", 1)[-1].lower() + + try: + text = (self.directory / "metadata").read_text() + except FileNotFoundError: + return None + for line in text.split("\n"): + if "=" in line: + key, _, value = line.partition("=") + if key.strip() == "non_linear_search": + return value.strip() + return None + def __str__(self): - return self.text + return f"" def __repr__(self): - return "".format(self) + return str(self) class GridSearchOutput(AbstractSearchOutput): diff --git a/autofit/non_linear/paths/directory.py b/autofit/non_linear/paths/directory.py index 47b551bf8..e82cb7b6e 100644 --- a/autofit/non_linear/paths/directory.py +++ b/autofit/non_linear/paths/directory.py @@ -381,7 +381,6 @@ def save_all(self, search_config_dict=None, info=None): pass self.save_json("model", to_dict(self.model)) - self._save_metadata(search_name=type(self.search).__name__.lower()) @AbstractPaths.parent.setter def parent(self, parent: AbstractPaths): @@ -469,17 +468,6 @@ def for_sub_analysis(self, analysis_name: str): return SubDirectoryPaths(parent=self, analysis_name=analysis_name) - def _save_metadata(self, search_name): - """ - Save metadata associated with the phase, such as the name of the pipeline, the - name of the phase and the name of the dataset being fit - """ - with open_(self.output_path / "metadata", "a") as f: - f.write( - f"""name={self.name}\nnon_linear_search={search_name} - """ - ) - def _save_model_info(self, model): """ Save the model.info file, which summarises every parameter and prior. diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index f258208ef..afd7a7fc2 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -570,11 +570,13 @@ class represented by model M and gives a score for their fitness. info=info, ) else: - # Skip mode still needs the metadata + identifier files written - # so downstream aggregator scraping can discover the search - # directory. `save_all` is lightweight (a handful of JSON dumps) - # and skips the expensive `analysis.save_attributes` / - # `visualize_before_fit` calls that `pre_fit_output` would add. + # Skip mode still needs `save_all` to run so that + # `files/search.json` — the sentinel the aggregator scans for — and + # the identifier files exist, letting downstream aggregator + # scraping discover the search directory. `save_all` is lightweight + # (a handful of JSON dumps) and skips the expensive + # `analysis.save_attributes` / `visualize_before_fit` calls that + # `pre_fit_output` would add. if hasattr(self.paths, "save_all"): self.paths.save_all( info=info, diff --git a/test_autofit/aggregator/search_output/metadata b/test_autofit/aggregator/search_output/metadata deleted file mode 100644 index e69de29bb..000000000 diff --git a/test_autofit/aggregator/search_output_derived/metadata b/test_autofit/aggregator/search_output_derived/metadata deleted file mode 100644 index de64cba2f..000000000 --- a/test_autofit/aggregator/search_output_derived/metadata +++ /dev/null @@ -1,3 +0,0 @@ -name=tutorial_3_non_linear_search -non_linear_search=emcee - \ No newline at end of file diff --git a/test_autofit/aggregator/summary_files/aggregate_summary/fit_1/files/search.json b/test_autofit/aggregator/summary_files/aggregate_summary/fit_1/files/search.json new file mode 100644 index 000000000..9f1a09d8a --- /dev/null +++ b/test_autofit/aggregator/summary_files/aggregate_summary/fit_1/files/search.json @@ -0,0 +1 @@ +{"type": "instance", "class_path": "autofit.non_linear.search.nest.dynesty.search.static.DynestyStatic", "arguments": {}} diff --git a/test_autofit/aggregator/summary_files/aggregate_summary/fit_1/metadata b/test_autofit/aggregator/summary_files/aggregate_summary/fit_1/metadata deleted file mode 100644 index e69de29bb..000000000 diff --git a/test_autofit/aggregator/summary_files/aggregate_summary/fit_2/files/search.json b/test_autofit/aggregator/summary_files/aggregate_summary/fit_2/files/search.json new file mode 100644 index 000000000..9f1a09d8a --- /dev/null +++ b/test_autofit/aggregator/summary_files/aggregate_summary/fit_2/files/search.json @@ -0,0 +1 @@ +{"type": "instance", "class_path": "autofit.non_linear.search.nest.dynesty.search.static.DynestyStatic", "arguments": {}} diff --git a/test_autofit/aggregator/summary_files/aggregate_summary/fit_2/metadata b/test_autofit/aggregator/summary_files/aggregate_summary/fit_2/metadata deleted file mode 100644 index e69de29bb..000000000 diff --git a/test_autofit/aggregator/test_from_directory.py b/test_autofit/aggregator/test_from_directory.py index 92a5bc0fa..832761c00 100644 --- a/test_autofit/aggregator/test_from_directory.py +++ b/test_autofit/aggregator/test_from_directory.py @@ -1,3 +1,4 @@ +import json import shutil import zipfile from pathlib import Path @@ -34,7 +35,7 @@ def test_from_directory(scan_directory): def test_zip_extracted_and_loaded(zipped_directory): aggregator = Aggregator.from_directory(zipped_directory) assert len(aggregator) == 1 - assert (zipped_directory / "search_output" / "metadata").exists() + assert (zipped_directory / "search_output" / "files" / "search.json").exists() def test_zip_not_re_extracted(zipped_directory): @@ -76,7 +77,7 @@ def make_test_mode_directory(tmp_path): Mirrors the on-disk layout a search produces under test mode: the results live beneath an inserted ``test_mode`` segment (``output/test_mode/prefix``) while the caller points ``from_directory`` at the real-run location - (``output/prefix``), which holds no metadata. + (``output/prefix``), which holds no search output of its own. """ source = Path(__file__).parent / "search_output" real_directory = tmp_path / "output" / "prefix" @@ -99,3 +100,71 @@ def test_from_directory_no_fallback_when_not_test_mode(test_mode_directory, monk ) aggregator = Aggregator.from_directory(test_mode_directory) assert len(aggregator) == 0 + + +def _write_search_json(directory: Path, class_path: str): + files = directory / "files" + files.mkdir(parents=True) + (files / "search.json").write_text( + json.dumps( + { + "type": "instance", + "class_path": class_path, + "arguments": {}, + } + ) + ) + + +def test_search_json_is_the_sentinel(tmp_path): + """ + A directory holding ``files/search.json`` is discovered exactly once, and it + is the search directory itself which is returned rather than its ``files`` + child. + """ + _write_search_json( + tmp_path / "a", + "autofit.non_linear.search.nest.dynesty.search.static.DynestyStatic", + ) + + aggregator = Aggregator.from_directory(tmp_path) + + assert len(aggregator) == 1 + assert list(aggregator)[0].directory == tmp_path / "a" + + +def test_files_directory_without_search_json_not_discovered(tmp_path): + (tmp_path / "b" / "files").mkdir(parents=True) + (tmp_path / "b" / "files" / "model.json").write_text("{}") + + assert len(Aggregator.from_directory(tmp_path)) == 0 + + +def test_legacy_metadata_still_discovered(tmp_path): + """ + Output folders written before ``files/search.json`` became the sentinel are + still aggregated via their ``metadata`` file. + """ + legacy = tmp_path / "c" + legacy.mkdir() + (legacy / "metadata").write_text("name=legacy\nnon_linear_search=emcee\n") + + aggregator = Aggregator.from_directory(tmp_path) + + assert len(aggregator) == 1 + output = list(aggregator)[0] + assert output.directory == legacy + assert output.non_linear_search == "emcee" + + +def test_non_linear_search_from_search_json(directory): + aggregator = Aggregator.from_directory(directory) + + assert { + output.directory.name + for output in aggregator.query(aggregator.non_linear_search == "dynestystatic") + } == {"search_output", "fit_1", "fit_2"} + assert [ + output.directory.name + for output in aggregator.query(aggregator.non_linear_search == "emcee") + ] == ["search_output_derived"]