Skip to content

[minor] Shift responsibility #430

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 26 commits into from
Aug 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
0ace5dd
Remove unused property
liamhuber Aug 13, 2024
be19b2e
Shorten variable name
liamhuber Aug 14, 2024
2111214
Refactor: rename method
liamhuber Aug 14, 2024
7f10dff
Call base method and remove specialist
liamhuber Aug 14, 2024
ad22578
Condense has_contents
liamhuber Aug 14, 2024
12aa8f4
Remove unused property
liamhuber Aug 14, 2024
05aa307
Move methods from Node to StorageInterface
liamhuber Aug 14, 2024
0a68534
Have StorageInterface.load just return the new instance
liamhuber Aug 14, 2024
a6cbaf5
Break dependence on Node.working_directory
liamhuber Aug 14, 2024
0180d8c
Refactor: rename obj to node in the storage module
liamhuber Aug 14, 2024
40dc947
:bug: pass argument
liamhuber Aug 14, 2024
c47dc9e
Remove tidy method
liamhuber Aug 14, 2024
2d8c3a3
Clean up using pathlib
liamhuber Aug 14, 2024
f421af9
Rely on pathlib
liamhuber Aug 14, 2024
f6734ff
Remove the post-setup cleanup
liamhuber Aug 14, 2024
dd678ed
Simplify and remove unused
liamhuber Aug 14, 2024
9ec58db
Allow semantic objects to express as pathlib.Path
liamhuber Aug 14, 2024
3ee0456
Leverage new semantic path for storage
liamhuber Aug 14, 2024
962c367
Remove unneeded exception
liamhuber Aug 14, 2024
51194b7
Remove unused imports
liamhuber Aug 14, 2024
966c682
Use a generator in the storage module for available backends
liamhuber Aug 14, 2024
8afb42b
Test loading failure
liamhuber Aug 14, 2024
c67ab22
Fix docstring
liamhuber Aug 14, 2024
186e9ef
Format black
pyiron-runner Aug 14, 2024
fffa6f4
Remove unused import
liamhuber Aug 14, 2024
89514ff
Don't overload builtin name
liamhuber Aug 14, 2024
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
10 changes: 10 additions & 0 deletions pyiron_workflow/mixin/semantics.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from __future__ import annotations

from abc import ABC
from pathlib import Path
from typing import Optional

from bidict import bidict
Expand Down Expand Up @@ -97,6 +98,15 @@ def semantic_root(self) -> Semantic:
"""The parent-most object in this semantic path; may be self."""
return self.parent.semantic_root if isinstance(self.parent, Semantic) else self

def as_path(self, root: Path | str | None = None) -> Path:
"""
The semantic path as a :class:`pathlib.Path`, with a filesystem :param:`root`
(default is the current working directory).
"""
return (Path.cwd() if root is None else Path(root)).joinpath(
*self.semantic_path.split(self.semantic_delimiter)
)

def __getstate__(self):
state = super().__getstate__()
state["_parent"] = None
Expand Down
129 changes: 39 additions & 90 deletions pyiron_workflow/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from pyiron_workflow.mixin.run import Runnable, ReadinessError
from pyiron_workflow.mixin.semantics import Semantic
from pyiron_workflow.mixin.single_output import ExploitsSingleOutput
from pyiron_workflow.storage import StorageInterface, PickleStorage
from pyiron_workflow.storage import StorageInterface, available_backends
from pyiron_workflow.topology import (
get_nodes_in_data_tree,
set_run_connections_according_to_linear_dag,
Expand All @@ -33,7 +33,6 @@
from pathlib import Path

import graphviz
from pyiron_snippets.files import DirectoryObject

from pyiron_workflow.channels import OutputSignal
from pyiron_workflow.nodes.composite import Composite
Expand Down Expand Up @@ -343,13 +342,16 @@ def _after_node_setup(
if delete_existing_savefiles:
self.delete_storage(backend=autoload)

if autoload is not None and self.any_storage_has_contents(autoload):
logger.info(
f"A saved file was found for the node {self.full_label} -- "
f"attempting to load it...(To delete the saved file instead, use "
f"`delete_existing_savefiles=True`)"
)
self.load(backend=autoload)
if autoload is not None:
for backend in available_backends(backend=autoload):
if backend.has_contents(self):
logger.info(
f"A saved file was found for the node {self.full_label} -- "
f"attempting to load it...(To delete the saved file instead, "
f"use `delete_existing_savefiles=True`) "
)
self.load(backend=autoload)
break

self.set_input_values(*args, **kwargs)

Expand All @@ -359,8 +361,6 @@ def _after_node_setup(
except ReadinessError:
pass

self.graph_root.tidy_working_directory()

@property
def graph_path(self) -> str:
"""
Expand Down Expand Up @@ -786,25 +786,6 @@ def replace_with(self, other: Node | type[Node]):
else:
logger.info(f"Could not replace_child {self.label}, as it has no parent.")

@classmethod
def _storage_interfaces(cls):
return {"pickle": PickleStorage}

@classmethod
def allowed_backends(cls):
return tuple(cls._storage_interfaces().keys())

@property
def storage_directory(self) -> DirectoryObject:
return self.working_directory

@property
def storage_path(self) -> str:
return self.graph_path

def tidy_storage_directory(self):
self.tidy_working_directory()

_save_load_warnings = """
HERE BE DRAGONS!!!

Expand All @@ -829,13 +810,10 @@ def tidy_storage_directory(self):

def save(self, backend: str | StorageInterface = "pickle"):
"""
Writes the node to file (using HDF5) such that a new node instance of the same
type can :meth:`load()` the data to return to the same state as the save point,
i.e. the same data IO channel values, the same flags, etc.
Writes the node to file using the requested interface as a back end.
"""
if isinstance(backend, str):
backend = self._storage_interfaces()[backend]()
backend.save(self)
for backend in available_backends(backend=backend, only_requested=True):
backend.save(self)

save.__doc__ += _save_load_warnings

Expand All @@ -847,69 +825,40 @@ def save_checkpoint(self, backend: str | StorageInterface = "pickle"):

def load(self, backend: str | StorageInterface = "pickle"):
"""
Loads the node file (from HDF5) such that this node restores its state at time
of loading.
Loads the node file and set the loaded state as the node's own.

Raises:
TypeError: when the saved node has a different class name.
"""
if isinstance(backend, str):
backend = self._storage_interfaces()[backend]()

if backend.has_contents(self):
backend.load(self)
else:
# Check for saved content using any other backend
for backend_class in self.allowed_backends():
backend = self._storage_interfaces()[backend_class]()
if backend.has_contents(self):
backend.load(self)
break
for backend in available_backends(backend=backend):
if backend.has_contents(self):
inst = backend.load(self)
break
raise FileNotFoundError(f"{self.label} could not find saved content.")

if inst.__class__ != self.__class__:
raise TypeError(
f"{self.label} cannot load, as it has type "
f"{self.__class__.__name__}, but the saved node has type "
f"{inst.__class__.__name__}"
)
self.__setstate__(inst.__getstate__())

load.__doc__ += _save_load_warnings

def delete_storage(
self, backend: Literal["pickle"] | StorageInterface | None = None
):
"""Remove save files for _all_ available backends."""
backends_to_check = [
self._storage_interfaces()[backend_class]()
for backend_class in self.allowed_backends()
]
if isinstance(backend, str):
backends_to_check.append(self._storage_interfaces()[backend]())
elif isinstance(backend, StorageInterface):
backends_to_check.append(backend)

for backend in backends_to_check:
try:
backend.delete(self)
except FileNotFoundError:
pass

@property
def storage_root(self):
"""The parent-most object that has storage."""
parent = self.parent
if isinstance(parent, Node):
return parent.storage_root
else:
return self

def any_storage_has_contents(
self, backend: Literal["pickle"] | StorageInterface | None
self,
backend: Literal["pickle"] | StorageInterface | None = None,
only_requested: bool = False,
):
if isinstance(backend, str) and self._storage_interfaces()[
backend
]().has_contents(self):
return True
elif isinstance(backend, StorageInterface) and backend.has_contents(self):
return True
else:
return any(
self._storage_interfaces()[backend]().has_contents(self)
for backend in self.allowed_backends()
)
"""Remove save file(s)."""
for backend in available_backends(
backend=backend, only_requested=only_requested
):
backend.delete(self)

def has_savefile(self, backend: Literal["pickle"] | StorageInterface | None = None):
return any(be.has_contents(self) for be in available_backends(backend=backend))

@property
def import_ready(self) -> bool:
Expand Down
Loading
Loading