20from .results
import _evaluator_info, _json_bytes, _json_value, _write, read_run_manifest
106 if not isinstance(artifacts, dict)
or not isinstance(artifacts.get(
"history"), list):
156 def __init__(self, manifest, options, algorithm, evaluate, seed, configuration, execution):
164 self.
total = algorithm.budget
172 identity = _json_value({
173 "version": 1,
"algorithm": type(algorithm).__name__,
"evaluator": _evaluator_info(evaluate),
174 "history_every": options.history_every,
"lineage": options.lineage,
175 "checkpoint_every": options.checkpoint_every,
"execution": execution,
179 raise ValueError(
"No working run bundle metadata to resume.")
180 saved = json.loads(self.
_identity_path.read_text(encoding=
"utf-8"))
181 self.
seed = saved[
"seed"]
if seed
is None else seed
183 if manifest.exists():
184 previous = read_run_manifest(manifest)
185 if previous.get(
"bundle", {}).get(
"id") != self.
run_id:
186 raise ValueError(
"The working state belongs to a different run bundle.")
190 raise FileExistsError(f
"A bundle already owns {self.directory}.")
191 if options.history_every
is not None and self.
history.exists()
and any(self.
history.iterdir()):
192 raise FileExistsError(f
"Archive history directory must be empty: {self.history}.")
193 self.
seed = randbits(32)
if seed
is None else seed
197 identity.update(seed=self.
seed, id=self.
run_id)
199 if identity != saved:
200 raise ValueError(
"Run bundle settings, seed, or evaluator differ from the saved run.")
203 def _capture(self, algorithm):
204 from ._archive_data
import _named_data
205 from ._archive_history
import _archive_payloads, _write_archive_frame
207 payload = _archive_payloads(_named_data(algorithm.container))
208 state = algorithm.nb_evaluations, sha256(_json_bytes(payload)).hexdigest()
209 if self.
_last == state:
212 self.
frames.append(_sha256_file(path))
215 def _history_entries(self):
216 return [{
"file": f
"history/frame-{number:06d}.json",
"sha256": digest}
217 for number, digest
in enumerate(self.
frames)]
219 def _restore_history(self, state):
220 from ._archive_history
import _FRAME, _numbered_paths
222 self.
frames = list(state[
"frames"])
224 self.
_last = state[
"last"]
226 _artifact_path(self.
directory, entry,
True)
227 for path
in _numbered_paths(self.
history, _FRAME):
228 if int(_FRAME.fullmatch(path.name)[1]) >= len(self.
frames):
233 def record(self, algorithm, state=None):
234 from .lineage
import LineageRecorder
236 with ExitStack()
as stack:
238 checkpointed = self.
options.checkpoint_every
is not None
240 self.
recorder._attach(algorithm, checkpointed=checkpointed,
241 state=
None if state
is None else state[
"lineage"])
243 if self.
options.history_every
is not None:
244 self.
history.mkdir(exist_ok=
True)
250 def at_iteration(search, _elapsed):
255 def at_finish(search, _elapsed):
256 if self.
options.checkpoint_every
is None or search.nb_evaluations == self.
total:
259 for event, callback
in ((
"iteration", at_iteration), (
"finished_optimisation", at_finish)):
260 algorithm.add_callback(event, callback)
261 stack.callback(algorithm._callbacks.get(event).remove, callback)
266 def check_resume(self, state, evaluations):
267 if not isinstance(state, dict)
or state.get(
"id") != self.
run_id:
268 raise ValueError(
"The checkpoint belongs to a different run bundle.")
270 raise ValueError(
"The working checkpoint predates the published run boundary.")
276 def _publish(self, path):
277 digest = _sha256_file(path)
278 name = f
"{path.stem}-{digest}{path.suffix}"
279 entry = {
"file": name,
"sha256": digest}
281 if not destination.exists():
282 with _atomic_output_path(destination)
as pending:
283 copyfile(path, pending)
285 _artifact_path(self.
directory, entry,
True)
288 def describe(self, best, attempted, *, resumed_from):
289 artifacts = {
"history": self.
_history_entries(),
"lineage":
None,
"checkpoint":
None}
292 if self.
options.checkpoint_every
is not None:
294 return {
"version": 1,
"id": self.
run_id,
"status":
"complete" if attempted >= self.
total else "paused",
295 "history_every": self.
options.history_every,
"checkpoint_every": self.
options.checkpoint_every,
296 "resumed_from": resumed_from,
297 "artifacts": artifacts,
"best_lineage_id":
None if self.
recorder is None else self.
recorder.id_for(best)}