-
Notifications
You must be signed in to change notification settings - Fork 14
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
Allow lazy loading of DataContainers #367
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
ddf7dd9
First stab at lazily reading DataContainers
pmrv b67eeb1
Save realized stubs
pmrv 6b5a799
Allow to set lazy on init
pmrv 38ed6fb
Add stub for DataContainer to pass lazy
pmrv e3fbce4
Change __repr__ to avoid forces stored HDFStubs
pmrv 91695e1
Add __repr__ to HDFStub
pmrv 4f1bd8b
Simplify HDF5Stub
pmrv 7de0d87
Add docstrings to HDF5Stub
pmrv cdcae2b
Rename realize->load and HDF{5,}Stub
pmrv 7b2e83c
Mention HDFStub support in DataContainer docstring
pmrv 8e89de4
Simple data container + stub tests
pmrv b9cdbb4
Add tests for stub
pmrv 066604e
Add test for recursively lazy containers
pmrv 7d4c50b
HDFStub.register accepts the class directly now
pmrv a24681d
Change relative to global imports
pmrv 0932ff8
Rename overwritten method
pmrv 00922da
Remove unnecessary variable assignments
pmrv 7584aca
Remove debug statements
pmrv 6f1b6be
Fix typo
pmrv File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
""" | ||
Convenience class to lazily read values from HDF. | ||
""" | ||
|
||
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department | ||
# Distributed under the terms of "New BSD License", see the LICENSE file. | ||
|
||
__author__ = "Marvin Poul" | ||
__copyright__ = ( | ||
"Copyright 2020, Max-Planck-Institut für Eisenforschung GmbH - " | ||
"Computational Materials Design (CM) Department" | ||
) | ||
__version__ = "1.0" | ||
__maintainer__ = "Marvin Poul" | ||
__email__ = "[email protected]" | ||
__status__ = "production" | ||
__date__ = "Apr 26, 2021" | ||
|
||
|
||
class HDFStub: | ||
""" | ||
Provides lazy loading of data from HDF. | ||
|
||
Instead of accessing an HDF group directly | ||
|
||
>>> hdf[group_name] | ||
... | ||
|
||
you can wrap this with this class | ||
|
||
>>> stub = HDFStub(hdf, group_name) | ||
|
||
and then later perform this lookup with :method:`.load` | ||
|
||
>>> stub.load() == hdf[group_name] | ||
True | ||
|
||
For simple datatypes there's not a big advantages to this, but :class:`.DataContainer` uses this to load its | ||
contents lazily and ensure that nested containers are also lazily loaded. This is done by customizing what happend | ||
on :method:`.load` via :method:`.register`. This class method adds a callback to the class that will be called | ||
when the specified type name is found in the hdf group that is to be loaded. | ||
|
||
>>> hdf['mytype/NAME'] | ||
MyType | ||
>>> hdf['mytype/TYPE'] | ||
<class 'my.module.MyType'> | ||
>>> HDFStub.register(MyType, lambda hdf, group: print(42) or hdf[group].to_object()) | ||
>>> my = HDFStub(hdf, 'mytype').load() | ||
42 | ||
>>> my | ||
MyType(...) | ||
|
||
This is intended to allow classes that want to be lazily loaded in a certain way to customize what arguments they | ||
pass `to_object()` (and therefore to their own initializers). | ||
""" | ||
|
||
_load_functions = {} | ||
|
||
def __init__(self, hdf, group_name): | ||
""" | ||
Create new stub. | ||
|
||
Args: | ||
hdf (:class:`.ProjectHDFio`): hdf object to load from | ||
group_name (str): node or group name to load from the hdf object | ||
""" | ||
self._hdf = hdf | ||
self._group_name = group_name | ||
|
||
@classmethod | ||
def register(cls, type, load): | ||
""" | ||
Register call back for a new type. | ||
|
||
Args: | ||
type (type): class to be registered | ||
load (function): callback that is called on :method:`.load` when the type matches `type_name`, must | ||
accept `hdf` and `group_name` corresponding to the init parameters of this class and return | ||
(lazily) loaded object | ||
""" | ||
cls._load_functions[str(type)] = load | ||
|
||
def load(self): | ||
""" | ||
Read value from HDF. | ||
|
||
If `group_name` is a node in HDF, simply its value will be returned. If it is a group in HDF and the 'NAME' | ||
node matches any of the types registered with :method:`.register`, it will be loaded with the provided callback. | ||
Otherwise it will be loaded with :method:`.ProjectHDFio.to_object()`. | ||
""" | ||
if self._group_name in self._hdf.list_nodes() or 'TYPE' not in self._hdf[self._group_name].list_nodes(): | ||
return self._hdf[self._group_name] | ||
|
||
load = self._load_functions.get( | ||
self._hdf[self._group_name]['TYPE'], | ||
lambda h, g: h[g].to_object() | ||
) | ||
return load(self._hdf, self._group_name) | ||
|
||
def __repr__(self): | ||
return f"{self.__class__.__name__}({self._hdf}, {self._group_name})" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
from pyiron_base._tests import TestWithProject | ||
from pyiron_base.generic.datacontainer import DataContainer | ||
from pyiron_base.generic.hdfstub import HDFStub | ||
|
||
import numpy as np | ||
|
||
class TestHDFStub(TestWithProject): | ||
|
||
@classmethod | ||
def setUpClass(cls): | ||
super().setUpClass() | ||
cls.hdf = cls.project.create_hdf(cls.project.path, "hdf") | ||
cls.hdf["number"] = 42 | ||
cls.hdf["array"] = np.arange(100) | ||
cls.data = DataContainer([1, 2, "three", 4.0]) | ||
cls.data.to_hdf(cls.hdf, "data") | ||
|
||
def test_load(self): | ||
"""Lazily and eagerly read values should be the same.""" | ||
self.assertEqual(HDFStub(self.hdf, "number").load(), self.hdf["number"], | ||
"Simple number read with load() not equal to eager read.") | ||
self.assertTrue(np.all( HDFStub(self.hdf, "array").load() == self.hdf["array"] ), | ||
"Numpy array read with load() not equal to eager read.") | ||
for v1, v2 in zip(HDFStub(self.hdf, "data").load(), self.data): | ||
self.assertEqual(v1, v2, "Data container values read with load() not equal to original container.") |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Finally, codacy complains that this overrides a built-in type...do you know what it's talking about? In pycharm I don't get any complaint, and I was expecting like when you try to use "id" or "dict" as a variable.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The argument
type
is a builtin. It is the base class of all classes and also a function to create new classes (iirc). Since I'm not using this inside this short method, I think it's ok, but I can also come up with a different name.