pyiron_base.storage.datacontainer module

Data structure for versatile data handling.

class pyiron_base.storage.datacontainer.DataContainer(*args, **kwargs)

Bases: DataContainerBase, HasHDF

Mutable sequence with optional keys.

If no argument is given, the constructor creates a new empty DataContainerBase. If specified init maybe a Sequence, Set or Mapping and all recursive occurrences of these are also wrapped by DataContainerBase.

>>> pl = DataContainerBase([3, 2, 1, 0])
>>> pm = DataContainerBase({"foo": 24, "bar": 42})

Access can be like a normal list with integers or optionally with strings as keys.

>>> pl[0]
3
>>> pl[2]
1
>>> pm["foo"]
24

Keys do not have to be present for all elements.

>>> pl2 = DataContainerBase([1,2])
>>> pl2["end"] = 3
>>> pl2
DataContainerBase({0: 1, 1: 2, 'end': 3})

It is also allowed to set an item one past the length of the DataContainerBase, this is then equivalent to appending that element. This allows to use the update method also with other DataContainerBases

>>> pl[len(pl)] = -1
>>> pl
DataContainerBase([3, 2, 1, 0, -1])
>>> pl.pop(-1)
-1

Where strings are used they may also be used as attributes. Getting keys which clash with methods of DataContainerBase must be done with item access, but setting them works without overwriting the instance methods, but is not recommended for readability.

>>> pm.foo
24
>>> pm.tail = 23
>>> pm
DataContainerBase({'foo': 24, 'bar': 42, 'tail': 23})

Keys and indices can be tuples to traverse nested DataContainerBases.

>>> pn = DataContainerBase({"foo": {"bar": [4, 2]}})
>>> pn["foo", "bar"]
DataContainerBase([4, 2])
>>> pn["foo", "bar", 0]
4

Using keys with “/” in them is equivalent to the above after splitting the key.

>>> pn["foo/bar"] == pn["foo", "bar"]
True
>>> pn["foo/bar/0"] == pn["foo", "bar", 0]
True

To make that work strings that are only decimal digits are automatically converted to integers before accessing the list and keys are restricted to not only contain digits on initialization.

>>> pl["0"] == pl[0]
True
>>> DataContainerBase({1: 42})
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "datacontainer.py", line 126, in __init__
        raise ValueError(
ValueError: keys in initializer must not be int or str of decimal digits or in correct order, is 1

When initializing from a dict, it may not have integers or decimal strings as keys unless they match their position in the insertion order. This is to avoid ambiguities in the final order of the DataContainerBase.

>>> DataContainerBase({0: "foo", 1: "bar", 2: 42})
DataContainerBase(['foo', 'bar', 42])
>>> DataContainerBase({0: "foo", 2: 42, 1: "bar"})
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "datacontainer.py", line 132, in __init__
        raise ValueError(
ValueError: keys in initializer must not be int or str of decimal digits or in correct order, is 2

Using keys is completely optional, DataContainerBase can always be treated as a list, with the exception that iter() iterates of the keys and indices. This is to correctly implement the MutableMapping protocol, to convert to a normal list and discard the keys use values().

>>> pm[0]
24
>>> pn["0/0/1"]
2
>>> list(pl)
[0, 1, 2, 3]
>>> list(pl.values())
[3, 2, 1, 0]
>>> list(pl.keys())
[0, 1, 2, 3]

Implements HasGroups. Groups are nested data containers and nodes are everything else.

>>> p = DataContainerBase({"a": 42, "b": [0, 1, 2]})
>>> p.list_groups()
['b']
>>> p.list_nodes()
['a']

Attention

Subclasses beware!

DataContainerBase require some careful treatment when creating subclasses.

1. Since DataContainerBases are expected to recursively instantiate themselves subclasses need to keep their __init__ compatible to the base class. That means being able to be instantiated without arguments, if arguments are given the first one (or `init) has to accept a Mapping or Iterable. Additional arguments may be added, but must be after init and must have a default.

2. Creating new instance attributes that don’t live in the container itself is possible, but you need to use object.__setattr__ the first time you define that attribute. Afterwards using normal assignment syntax works.

3. Subclasses should always be thought of as general data structures, if you want to subclass to have access to the HDF5 functionality or the way the DataContainerBase is shown in jupyter notebooks, but only have a fixed number of attributes it is better to create a new class that has an DataContainerBase as an attribute and dispatch to the DataContainerBase.from_hdf(), DataContainerBase.to_hdf() and DataContainerBase._repr_json_() methods.

A few examples for subclasses

>>> class ExtendedContainer(DataContainerBase):
...     def __init__(self, init=None, my_fancy_field=42, table_name=None):
...         super().__init__(init=init, table_name=table_name)
...         object.__setattr__(self, "my_fancy_field", my_fancy_field)

After defining it once like this you can access my_fancy_field as a normal attribute, but it will not be stored in the container itself and will not be stored in HDF5.

>>> e = ExtendedContainer({'foo': 1, 'bar': 5}, my_fancy_field=23)
>>> e.my_fancy_field
23
>>> e
ExtendedContainer({'foo': 1, 'bar': 5})
>>> e.my_fancy_field = 42
>>> e.my_fancy_field
42
>>> e
ExtendedContainer({'foo': 1, 'bar': 5})

Be aware the DataContainerBase and its subclasses are recursive data structures, i.e. your fancy attribute will be available also on sub groups.

>>> g = e.create_group('sub')
>>> g.fnord = 23
>>> g.my_fancy_field
42
>>> e
ExtendedContainer({'foo': 1, 'bar': 5, 'sub': ExtendedContainer({'fnord': 23})})

For that reason most of time you’ll actually want a class that uses a DataContainerBase for storage, but doesn’t derive from it.

>>> from pyiron_base.interfaces.object import HasStorage
>>> class FancyClass(HasStorage):
...     def __init__(self, foo):
...         super().__init__()
...         self.storage.foo = foo
...
...     @property
...     def foo(self):
...         return self.storage.foo
...
...     @foo.setter
...     def foo(self, val):
...         self.storage.foo = val
...
...     def _repr_json_(self):
...         return self.storage._repr_json_()

If instantiated with the argument lazy=True, data read from HDF5 later via :method:`.from_hdf` are not actually read, but only earmarked to be read later when actually accessed via HDFStub. This is largely transparent, i.e. when accessing an earmarked value it will automatically be loaded and this loaded value is stored in container. The only difference is in the string representation of the container, values not read yet appear as ‘HDFStub(…)’ in the output.

Attention

Subclasses beware! 1. To allow lazy loading sub classes must accept a lazy keyword argument and pass it to super().__init__.

copy()

Returns deep copy of it self. A shallow copy can be obtained via the copy module.

Returns:

deep copy of itself

Return type:

DataContainer

>>> pl = DataContainer([[1,2,3]])
>>> pl.copy() == pl
True
>>> pl.copy() is pl
False
>>> all(a is not b for a, b in zip(pl.copy().values(), pl.values()))
True
class pyiron_base.storage.datacontainer.DataContainerBase(*args, **kwargs)

Bases: MutableMapping, Lockable, HasGroups

Mutable sequence with optional keys.

If no argument is given, the constructor creates a new empty DataContainerBase. If specified init maybe a Sequence, Set or Mapping and all recursive occurrences of these are also wrapped by DataContainerBase.

>>> pl = DataContainerBase([3, 2, 1, 0])
>>> pm = DataContainerBase({"foo": 24, "bar": 42})

Access can be like a normal list with integers or optionally with strings as keys.

>>> pl[0]
3
>>> pl[2]
1
>>> pm["foo"]
24

Keys do not have to be present for all elements.

>>> pl2 = DataContainerBase([1,2])
>>> pl2["end"] = 3
>>> pl2
DataContainerBase({0: 1, 1: 2, 'end': 3})

It is also allowed to set an item one past the length of the DataContainerBase, this is then equivalent to appending that element. This allows to use the update method also with other DataContainerBases

>>> pl[len(pl)] = -1
>>> pl
DataContainerBase([3, 2, 1, 0, -1])
>>> pl.pop(-1)
-1

Where strings are used they may also be used as attributes. Getting keys which clash with methods of DataContainerBase must be done with item access, but setting them works without overwriting the instance methods, but is not recommended for readability.

>>> pm.foo
24
>>> pm.tail = 23
>>> pm
DataContainerBase({'foo': 24, 'bar': 42, 'tail': 23})

Keys and indices can be tuples to traverse nested DataContainerBases.

>>> pn = DataContainerBase({"foo": {"bar": [4, 2]}})
>>> pn["foo", "bar"]
DataContainerBase([4, 2])
>>> pn["foo", "bar", 0]
4

Using keys with “/” in them is equivalent to the above after splitting the key.

>>> pn["foo/bar"] == pn["foo", "bar"]
True
>>> pn["foo/bar/0"] == pn["foo", "bar", 0]
True

To make that work strings that are only decimal digits are automatically converted to integers before accessing the list and keys are restricted to not only contain digits on initialization.

>>> pl["0"] == pl[0]
True
>>> DataContainerBase({1: 42})
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "datacontainer.py", line 126, in __init__
        raise ValueError(
ValueError: keys in initializer must not be int or str of decimal digits or in correct order, is 1

When initializing from a dict, it may not have integers or decimal strings as keys unless they match their position in the insertion order. This is to avoid ambiguities in the final order of the DataContainerBase.

>>> DataContainerBase({0: "foo", 1: "bar", 2: 42})
DataContainerBase(['foo', 'bar', 42])
>>> DataContainerBase({0: "foo", 2: 42, 1: "bar"})
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "datacontainer.py", line 132, in __init__
        raise ValueError(
ValueError: keys in initializer must not be int or str of decimal digits or in correct order, is 2

Using keys is completely optional, DataContainerBase can always be treated as a list, with the exception that iter() iterates of the keys and indices. This is to correctly implement the MutableMapping protocol, to convert to a normal list and discard the keys use values().

>>> pm[0]
24
>>> pn["0/0/1"]
2
>>> list(pl)
[0, 1, 2, 3]
>>> list(pl.values())
[3, 2, 1, 0]
>>> list(pl.keys())
[0, 1, 2, 3]

Implements HasGroups. Groups are nested data containers and nodes are everything else.

>>> p = DataContainerBase({"a": 42, "b": [0, 1, 2]})
>>> p.list_groups()
['b']
>>> p.list_nodes()
['a']

Attention

Subclasses beware!

DataContainerBase require some careful treatment when creating subclasses.

1. Since DataContainerBases are expected to recursively instantiate themselves subclasses need to keep their __init__ compatible to the base class. That means being able to be instantiated without arguments, if arguments are given the first one (or `init) has to accept a Mapping or Iterable. Additional arguments may be added, but must be after init and must have a default.

2. Creating new instance attributes that don’t live in the container itself is possible, but you need to use object.__setattr__ the first time you define that attribute. Afterwards using normal assignment syntax works.

3. Subclasses should always be thought of as general data structures, if you want to subclass to have access to the HDF5 functionality or the way the DataContainerBase is shown in jupyter notebooks, but only have a fixed number of attributes it is better to create a new class that has an DataContainerBase as an attribute and dispatch to the DataContainerBase.from_hdf(), DataContainerBase.to_hdf() and DataContainerBase._repr_json_() methods.

A few examples for subclasses

>>> class ExtendedContainer(DataContainerBase):
...     def __init__(self, init=None, my_fancy_field=42, table_name=None):
...         super().__init__(init=init, table_name=table_name)
...         object.__setattr__(self, "my_fancy_field", my_fancy_field)

After defining it once like this you can access my_fancy_field as a normal attribute, but it will not be stored in the container itself and will not be stored in HDF5.

>>> e = ExtendedContainer({'foo': 1, 'bar': 5}, my_fancy_field=23)
>>> e.my_fancy_field
23
>>> e
ExtendedContainer({'foo': 1, 'bar': 5})
>>> e.my_fancy_field = 42
>>> e.my_fancy_field
42
>>> e
ExtendedContainer({'foo': 1, 'bar': 5})

Be aware the DataContainerBase and its subclasses are recursive data structures, i.e. your fancy attribute will be available also on sub groups.

>>> g = e.create_group('sub')
>>> g.fnord = 23
>>> g.my_fancy_field
42
>>> e
ExtendedContainer({'foo': 1, 'bar': 5, 'sub': ExtendedContainer({'fnord': 23})})

For that reason most of time you’ll actually want a class that uses a DataContainerBase for storage, but doesn’t derive from it.

>>> from pyiron_base.interfaces.object import HasStorage
>>> class FancyClass(HasStorage):
...     def __init__(self, foo):
...         super().__init__()
...         self.storage.foo = foo
...
...     @property
...     def foo(self):
...         return self.storage.foo
...
...     @foo.setter
...     def foo(self, val):
...         self.storage.foo = val
...
...     def _repr_json_(self):
...         return self.storage._repr_json_()
append(val)

Add new value to the container without a key.

Parameters:

val – new element

clear()

Remove all items from DataContainerBase.

copy()

Returns deep copy of it self. A shallow copy can be obtained via the copy module.

Returns:

deep copy of itself

Return type:

DataContainerBase

>>> pl = DataContainerBase([[1,2,3]])
>>> pl.copy() == pl
True
>>> pl.copy() is pl
False
>>> all(a is not b for a, b in zip(pl.copy().values(), pl.values()))
True
create_group(name)

Add a new empty subcontainer under the given key.

Parameters:

name (str) – key under which to store the new subcontainer in this container

Returns:

the newly created subcontainer

Return type:

DataContainerBase

Raises:

ValueError – name already exists in container and is not a sub container

>>> pl = DataContainerBase({})
>>> pl.create_group("group_name")
DataContainerBase([])
>>> list(pl.group_name)
[]
extend(vals)

Append vals to the end of this DataContainerBase.

Parameters:

vals (Sequence) – any python sequence to draw new elements from

get(key, default=None, create=False)

If key exists, behave as generic, if not call create_group.

Parameters:
  • key (str) – key to search

  • default (optional) – return this instead if nothing found

  • create (bool, optional) – create empty container at key if nothing found

Raises:
  • IndexError – if key is not in the container and neither default not

  • create` are give

Returns:

element at key or new empty subcontainer

Return type:

object

groups()

Iterate over keys to nested containers.

Returns:

list of all keys to elements of DataContainerBase.

Return type:

list

has_keys()

Check if the container has keys set or not.

Returns:

True if there is at least one key set

Return type:

bool

insert(index, val, key=None)

Add a new element to the container at the specified position, with an optional key. If the key is already in the container it will be updated to point to the new element at the new index. If index is larger than container, append instead.

Parameters:
  • index (int) – place val after this element

  • val – new element to add

  • key (str, optional) – optional key to mark the new element

mark(index, key)

Add a key to an existing item at index. If key already exists, it is overwritten.

Parameters:
  • index (int) – index of the existing element to mark

  • key (str) – key for the existing element

Raises:

IndexError – if index > len(self)

>>> pl = DataContainerBase([42])
>>> pl.mark(0, "head")
>>> pl.head == 42
True
nodes()

Iterator over keys to terminal nodes.

Returns:

list of keys to normal values.

Return type:

list

read(file_name, wrap=True)

Parse file as dictionary and add its keys to this container.

For supported file types, see fileio.read().

Errors during reading of the files generate a warning, but leave the container unchanged.

Parameters:
  • file_name (str) – path to the input file

  • wrap (bool)

Raises:

ValueError – if file extension doesn’t match one of the supported ones

search(key, stop_on_first_hit=True)

Search for key in the Container hierarchy.

This should be used if there is only one such item in the hierarchy.

If stop_on_first_hit is True the first item found is taken. Otherwise, a ValueError is raised if the key appears multiple times.

Parameters:
  • key (str) – the key to look for

  • stop_on_first_hit (bool) – whether to stop on the first hit

Raises:
  • TypeError – if key is not str

  • KeyError – if key is not found

  • ValueError – if stop_on_first_hit is False and key is found twice

Returns:

element at key

Return type:

object

to_builtin(stringify=False)

Convert the container back to builtin dict’s and list’s recursively.

Parameters:

stringify (bool, optional) – convert all non-recursive elements to str

update(init, wrap=False, blacklist=(), **kwargs)

Add all elements or key-value pairs from init to this container. If wrap is not given, behaves as the generic method.

Parameters:
  • init (Sequence, Set, Mapping) – container to draw new elements from

  • wrap (bool) – if True wrap all encountered Sequences and Mappings in DataContainerBase recursively

  • blacklist (list of types) – when wrap is True, don’t wrap these types even if they’re instances of Sequence or Mapping

  • **kwargs – update from this mapping as well

write(file_name)

Writes the DataContainerBase to a text file.

For supported file types, see fileio.write().

Parameters:

file_name (str) – the name of the file to be writen to.