Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions autofit/aggregator/aggregator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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(
Expand Down
48 changes: 33 additions & 15 deletions autofit/aggregator/search_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
----------
Expand All @@ -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:
"""
Expand Down Expand Up @@ -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"<SearchOutput {self.directory}>"

def __repr__(self):
return "<PhaseOutput {}>".format(self)
return str(self)


class GridSearchOutput(AbstractSearchOutput):
Expand Down
12 changes: 0 additions & 12 deletions autofit/non_linear/paths/directory.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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.
Expand Down
12 changes: 7 additions & 5 deletions autofit/non_linear/search/abstract_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Empty file.
3 changes: 0 additions & 3 deletions test_autofit/aggregator/search_output_derived/metadata

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"type": "instance", "class_path": "autofit.non_linear.search.nest.dynesty.search.static.DynestyStatic", "arguments": {}}
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"type": "instance", "class_path": "autofit.non_linear.search.nest.dynesty.search.static.DynestyStatic", "arguments": {}}
Empty file.
73 changes: 71 additions & 2 deletions test_autofit/aggregator/test_from_directory.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import shutil
import zipfile
from pathlib import Path
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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"
Expand All @@ -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"]
Loading