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
55 changes: 55 additions & 0 deletions autofit/aggregator/aggregator.py
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,61 @@ def query(self, *predicates) -> "Aggregator":
errors=self.errors,
)

def latest_per(
self,
key: Tuple[str, ...] = ("path_prefix", "unique_tag", "name"),
by: str = "completed_at",
) -> "Aggregator":
"""
Keep, for each value of ``key``, only the search output with the greatest
``by``: the latest of several fits of the same search to the same object
(sibling hashes, e.g. a rerun after a model or search setting changed).

``completed_at`` comes from the status record or the ``.completed`` member of
the result's zip, never the zip's modification time, which copying or
re-zipping resets. Outputs with no ``by`` value lose to any that have one;
remaining ties go to the greater path, so the choice is the same on every
machine.

Parameters
----------
key
Attributes of a search output that together name one fit of one object.
The default suits both layouts in use: the object in ``path_prefix``
(``unique_tag`` shared) or in ``unique_tag`` (``path_prefix`` shared).
by
The attribute that orders the outputs within a key.
"""

def value_of(search_output, attribute):
value = getattr(search_output, attribute, None)
return None if value is None else str(value)

latest = {}
for search_output in self.search_outputs:
group = tuple(value_of(search_output, k) for k in key)
order = (
value_of(search_output, by) is not None,
value_of(search_output, by) or "",
str(search_output.directory),
)
if group not in latest or order > latest[group][0]:
latest[group] = (order, search_output)

search_outputs = sorted(
(search_output for _, search_output in latest.values()),
key=lambda output: str(output.directory),
)
logger.info(
f"latest_per kept {len(search_outputs)} of {len(self.search_outputs)} "
f"search outputs."
)
return Aggregator(
search_outputs=search_outputs,
grid_search_outputs=self.grid_search_outputs,
errors=self.errors,
)

def values(self, name: str, parser=lambda o: o) -> Iterator:
"""
Get values from outputs with a given name.
Expand Down
36 changes: 36 additions & 0 deletions autofit/aggregator/search_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
import pickle
import tempfile
import weakref
import zipfile
from abc import ABC
from datetime import datetime, timezone
from hashlib import md5
from pathlib import Path
from shutil import rmtree
Expand Down Expand Up @@ -110,6 +112,40 @@ def is_complete(self) -> bool:
"""
return (self.directory / ".completed").exists()

@cached_property
def completed_at(self) -> Optional[str]:
"""
When the search completed (ISO 8601), or ``None`` if it has not.

Taken from the status record beside the output (``<directory>.status.json``)
when it says ``completed``, else from the ``.completed`` member of the zip
beside the output, else from the ``.completed`` file's modification time. The
zip's own modification time is never used: copying or re-zipping resets it.
An output extracted to a temporary directory has neither sibling, so its
``.completed`` time is the extraction time; index the tree
(``python -m autofit.results index``) to compare such outputs.
"""
directory = Path(self.directory)
try:
with open(f"{directory}.status.json") as f:
status = json.load(f)
if status.get("state") == "completed" and status.get("updated"):
return status["updated"]
except (OSError, ValueError, AttributeError):
pass
try:
with zipfile.ZipFile(f"{directory}.zip") as f:
return datetime(*f.getinfo(".completed").date_time).isoformat()
except (OSError, KeyError, zipfile.BadZipFile):
pass
try:
mtime = (directory / ".completed").stat().st_mtime
except OSError:
return None
return datetime.fromtimestamp(mtime, timezone.utc).isoformat(
timespec="seconds"
)

@property
def parent_identifier(self) -> Optional[str]:
"""
Expand Down
2 changes: 2 additions & 0 deletions autofit/config/general.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ inversion:
check_reconstruction: true # If True, the inversion's reconstruction is checked to ensure the solution of a meshs's mapper is not an invalid solution where the values are all the same.
reconstruction_vmax_factor: 0.5 # Plots of an Inversion's reconstruction use the reconstructed data's bright value multiplied by this factor.
output:
dataset_identity: true # If True, every fit writes files/dataset_identity.json at start: its object id, the paths of its inputs (from Analysis.dataset_identity) and, with dataset_identity_sha256, their SHA256, so the results index can find duplicate and wrong-input fits.
dataset_identity_sha256: true # If True, dataset_identity.json records the SHA256 of each input file (reads every input once at fit start). If False, only paths and sizes are recorded.
force_pickle_overwrite: false # If True pickle files output by a search (e.g. samples.pickle) are recreated when a new model-fit is performed.
force_visualize_overwrite: false # If True, visualization images output by a search (e.g. subplots of the fit) are recreated when a new model-fit is performed.
info_whitespace_length: 80 # Length of whitespace between the parameter names and values in the model.info / result.info
Expand Down
13 changes: 13 additions & 0 deletions autofit/non_linear/analysis/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,19 @@ def shared_state_from(self, instance):
def save_attributes(self, paths: AbstractPaths):
pass

def dataset_identity(self) -> Optional[Dict]:
"""
What this analysis fits, for the fit's ``files/dataset_identity.json``
(``autofit.non_linear.status.identity``).

Override to return a dict with any of ``object_id`` (a stable name for the
object, e.g. a catalogue id), ``external_ids`` (a dict of other ids),
``inputs`` (a dict of name to the path of each input file, which are hashed)
and ``centre`` (a sequence of numbers, e.g. a cutout centre). The default,
``None``, records only the search's ``unique_tag`` as the ``object_id``.
"""
return None

def save_results(self, paths: AbstractPaths, result: Result):
pass

Expand Down
2 changes: 2 additions & 0 deletions autofit/non_linear/search/abstract_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
from autofit.non_linear.search.internal_state import SearchInternalStateMixin
from autofit.non_linear.search.updates import SearchUpdatesMixin
from autofit.non_linear.status import status_notify, status_recorded
from autofit.non_linear.status.identity import write_dataset_identity
from autofit.non_linear.search.test_mode_bypass import TestModeBypass, TestModeMixin
from autofit.non_linear.test_mode import test_mode_level, skip_fit_output

Expand Down Expand Up @@ -405,6 +406,7 @@ def start_resume_fit(self, analysis: Analysis, model: AbstractPriorModel) -> Res
self.timer.start()

status_notify(self, "start")
write_dataset_identity(self, analysis)

mode = test_mode_level()
if mode >= 2:
Expand Down
8 changes: 7 additions & 1 deletion autofit/non_linear/status/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,16 @@
``None``. It is called at each full update (``FitContext.update``); the record adds
``eta_s`` from the fraction's rate.

``states`` is the single vocabulary of run states, failure classes and product names.
``states`` is the single vocabulary of run states, result states, failure classes and
product names. ``identity`` writes ``dataset_identity.json`` (results-library phase 1).
"""
from autofit.non_linear.status.states import (
COLLECTOR_STATES,
TERMINAL_STATES,
WRITTEN_STATES,
FailureClass,
Product,
ResultState,
RunState,
failure_class_of,
)
Expand All @@ -34,3 +36,7 @@
status_recorded,
status_interval_s,
)
from autofit.non_linear.status.identity import (
dataset_identity_enabled,
write_dataset_identity,
)
Loading
Loading