aiida.orm.nodes package#

Module with Node sub classes for data and processes.

Submodules#

Interface to the attributes of a node instance.

class aiida.orm.nodes.attributes.NodeAttributes(node: Node)[source]#

Bases: object

Interface to the attributes of a node instance.

Attributes are a JSONable dictionary, stored on each node, allowing for arbitrary data to be stored by node subclasses (and thus data plugins).

Once the node is stored, the attributes are generally deemed immutable (except for some updatable keys on process nodes, which can be mutated whilst the node is not “sealed”).

__contains__(key: str) bool[source]#

Check if the node contains an attribute with the given key.

__dict__ = mappingproxy({'__module__': 'aiida.orm.nodes.attributes', '__doc__': 'Interface to the attributes of a node instance.\n\n    Attributes are a JSONable dictionary, stored on each node,\n    allowing for arbitrary data to be stored by node subclasses (and thus data plugins).\n\n    Once the node is stored, the attributes are generally deemed immutable\n    (except for some updatable keys on process nodes, which can be mutated whilst the node is not "sealed").\n    ', '__init__': <function NodeAttributes.__init__>, '__contains__': <function NodeAttributes.__contains__>, 'all': <property object>, 'get': <function NodeAttributes.get>, 'get_many': <function NodeAttributes.get_many>, 'set': <function NodeAttributes.set>, 'set_many': <function NodeAttributes.set_many>, 'reset': <function NodeAttributes.reset>, 'delete': <function NodeAttributes.delete>, 'delete_many': <function NodeAttributes.delete_many>, 'clear': <function NodeAttributes.clear>, 'items': <function NodeAttributes.items>, 'keys': <function NodeAttributes.keys>, '__dict__': <attribute '__dict__' of 'NodeAttributes' objects>, '__weakref__': <attribute '__weakref__' of 'NodeAttributes' objects>, '__annotations__': {}})#
__init__(node: Node) None[source]#

Initialize the interface.

__module__ = 'aiida.orm.nodes.attributes'#
__weakref__#

list of weak references to the object (if defined)

property all: Dict[str, Any]#

Return the complete attributes dictionary.

Warning

While the entity is unstored, this will return references of the attributes on the database model, meaning that changes on the returned values (if they are mutable themselves, e.g. a list or dictionary) will automatically be reflected on the database model as well. As soon as the entity is stored, the returned attributes will be a deep copy and mutations of the database attributes will have to go through the appropriate set methods. Therefore, once stored, retrieving a deep copy can be a heavy operation. If you only need the keys or some values, use the iterators keys and items, or the getters get and get_many instead.

Returns

the attributes as a dictionary

clear() None[source]#

Delete all attributes.

delete(key: str) None[source]#

Delete an attribute.

Parameters

key – name of the attribute

Raises
delete_many(keys: List[str]) None[source]#

Delete multiple attributes.

Parameters

keys – names of the attributes to delete

Raises
get(key: str, default=()) Any[source]#

Return the value of an attribute.

Warning

While the entity is unstored, this will return a reference of the attribute on the database model, meaning that changes on the returned value (if they are mutable themselves, e.g. a list or dictionary) will automatically be reflected on the database model as well. As soon as the entity is stored, the returned attribute will be a deep copy and mutations of the database attributes will have to go through the appropriate set methods.

Parameters
  • key – name of the attribute

  • default – return this value instead of raising if the attribute does not exist

Returns

the value of the attribute

Raises

AttributeError – if the attribute does not exist and no default is specified

get_many(keys: List[str]) List[Any][source]#

Return the values of multiple attributes.

Warning

While the entity is unstored, this will return references of the attributes on the database model, meaning that changes on the returned values (if they are mutable themselves, e.g. a list or dictionary) will automatically be reflected on the database model as well. As soon as the entity is stored, the returned attributes will be a deep copy and mutations of the database attributes will have to go through the appropriate set methods. Therefore, once stored, retrieving a deep copy can be a heavy operation. If you only need the keys or some values, use the iterators keys and items, or the getters get and get_many instead.

Parameters

keys – a list of attribute names

Returns

a list of attribute values

Raises

AttributeError – if at least one attribute does not exist

items() Iterator[Tuple[str, Any]][source]#

Return an iterator over the attributes.

Returns

an iterator with attribute key value pairs

keys() Iterable[str][source]#

Return an iterator over the attribute keys.

Returns

an iterator with attribute keys

reset(attributes: Dict[str, Any]) None[source]#

Reset the attributes.

Note

This will completely clear any existing attributes and replace them with the new dictionary.

Parameters

attributes – a dictionary with the attributes to set

Raises
set(key: str, value: Any) None[source]#

Set an attribute to the given value.

Parameters
  • key – name of the attribute

  • value – value of the attribute

Raises
set_many(attributes: Dict[str, Any]) None[source]#

Set multiple attributes.

Note

This will override any existing attributes that are present in the new dictionary.

Parameters

attributes – a dictionary with the attributes to set

Raises

Interface to control caching of a node instance.

class aiida.orm.nodes.caching.NodeCaching(node: Node)[source]#

Bases: object

Interface to control caching of a node instance.

_HASH_EXTRA_KEY: str = '_aiida_hash'#
_VALID_CACHE_KEY: str = '_aiida_valid_cache'#
__annotations__ = {'_HASH_EXTRA_KEY': 'str', '_VALID_CACHE_KEY': 'str'}#
__dict__ = mappingproxy({'__module__': 'aiida.orm.nodes.caching', '__annotations__': {'_HASH_EXTRA_KEY': 'str', '_VALID_CACHE_KEY': 'str'}, '__doc__': 'Interface to control caching of a node instance.', '_HASH_EXTRA_KEY': '_aiida_hash', '_VALID_CACHE_KEY': '_aiida_valid_cache', '__init__': <function NodeCaching.__init__>, 'get_hash': <function NodeCaching.get_hash>, '_get_hash': <function NodeCaching._get_hash>, '_get_objects_to_hash': <function NodeCaching._get_objects_to_hash>, 'rehash': <function NodeCaching.rehash>, 'clear_hash': <function NodeCaching.clear_hash>, 'get_cache_source': <function NodeCaching.get_cache_source>, 'is_created_from_cache': <property object>, '_get_same_node': <function NodeCaching._get_same_node>, 'get_all_same_nodes': <function NodeCaching.get_all_same_nodes>, '_iter_all_same_nodes': <function NodeCaching._iter_all_same_nodes>, 'is_valid_cache': <property object>, '__dict__': <attribute '__dict__' of 'NodeCaching' objects>, '__weakref__': <attribute '__weakref__' of 'NodeCaching' objects>})#
__init__(node: Node) None[source]#

Initialize the caching interface.

__module__ = 'aiida.orm.nodes.caching'#
__weakref__#

list of weak references to the object (if defined)

_get_hash(ignore_errors: bool = True, **kwargs: t.Any) str | None[source]#

Return the hash for this node based on its attributes.

This will always work, even before storing.

Parameters

ignore_errors – return None on aiida.common.exceptions.HashingError (logging the exception)

_get_objects_to_hash() list[t.Any][source]#

Return a list of objects which should be included in the hash.

_get_same_node() 'Node' | None[source]#

Returns a stored node from which the current Node can be cached or None if it does not exist

If a node is returned it is a valid cache, meaning its _aiida_hash extra matches self.get_hash(). If there are multiple valid matches, the first one is returned. If no matches are found, None is returned.

Returns

a stored Node instance with the same hash as this code or None

Note: this should be only called on stored nodes, or internally from .store() since it first calls clean_value() on the attributes to normalise them.

_iter_all_same_nodes(allow_before_store=False) Iterator[Node][source]#

Returns an iterator of all same nodes.

Note: this should be only called on stored nodes, or internally from .store() since it first calls clean_value() on the attributes to normalise them.

clear_hash() None[source]#

Sets the stored hash of the Node to None.

get_all_same_nodes() list['Node'][source]#

Return a list of stored nodes which match the type and hash of the current node.

All returned nodes are valid caches, meaning their _aiida_hash extra matches self.get_hash().

Note: this can be called only after storing a Node (since at store time attributes will be cleaned with clean_value and the hash should become idempotent to the action of serialization/deserialization)

get_cache_source() str | None[source]#

Return the UUID of the node that was used in creating this node from the cache, or None if it was not cached.

Returns

source node UUID or None

get_hash(ignore_errors: bool = True, **kwargs: t.Any) str | None[source]#

Return the hash for this node based on its attributes.

Parameters

ignore_errors – return None on aiida.common.exceptions.HashingError (logging the exception)

property is_created_from_cache: bool#

Return whether this node was created from a cached node.

Returns

boolean, True if the node was created by cloning a cached node, False otherwise

property is_valid_cache: bool#

Hook to exclude certain Node classes from being considered a valid cache.

The base class assumes that all node instances are valid to cache from, unless the _VALID_CACHE_KEY extra has been set to False explicitly. Subclasses can override this property with more specific logic, but should probably also consider the value returned by this base class.

rehash() None[source]#

Regenerate the stored hash of the Node.

Interface for comments of a node instance.

class aiida.orm.nodes.comments.NodeComments(node: Node)[source]#

Bases: object

Interface for comments of a node instance.

__dict__ = mappingproxy({'__module__': 'aiida.orm.nodes.comments', '__doc__': 'Interface for comments of a node instance.', '__init__': <function NodeComments.__init__>, 'add': <function NodeComments.add>, 'get': <function NodeComments.get>, 'all': <function NodeComments.all>, 'update': <function NodeComments.update>, 'remove': <function NodeComments.remove>, '__dict__': <attribute '__dict__' of 'NodeComments' objects>, '__weakref__': <attribute '__weakref__' of 'NodeComments' objects>, '__annotations__': {}})#
__init__(node: Node) None[source]#

Initialize the comments interface.

__module__ = 'aiida.orm.nodes.comments'#
__weakref__#

list of weak references to the object (if defined)

add(content: str, user: Optional[aiida.orm.users.User] = None) aiida.orm.comments.Comment[source]#

Add a new comment.

Parameters
  • content – string with comment

  • user – the user to associate with the comment, will use default if not supplied

Returns

the newly created comment

all() list[Comment][source]#

Return a sorted list of comments for this node.

Returns

the list of comments, sorted by pk

get(identifier: int) aiida.orm.comments.Comment[source]#

Return a comment corresponding to the given identifier.

Parameters

identifier – the comment pk

Raises
Returns

the comment

remove(identifier: int) None[source]#

Delete an existing comment.

Parameters

identifier – the comment pk

update(identifier: int, content: str) None[source]#

Update the content of an existing comment.

Parameters
  • identifier – the comment pk

  • content – the new comment content

Raises

Interface for links of a node instance.

Bases: object

Interface for links of a node instance.

__dict__ = mappingproxy({'__module__': 'aiida.orm.nodes.links', '__doc__': 'Interface for links of a node instance.', '__init__': <function NodeLinks.__init__>, '_add_incoming_cache': <function NodeLinks._add_incoming_cache>, 'add_incoming': <function NodeLinks.add_incoming>, 'validate_incoming': <function NodeLinks.validate_incoming>, 'validate_outgoing': <function NodeLinks.validate_outgoing>, 'get_stored_link_triples': <function NodeLinks.get_stored_link_triples>, 'get_incoming': <function NodeLinks.get_incoming>, 'get_outgoing': <function NodeLinks.get_outgoing>, '__dict__': <attribute '__dict__' of 'NodeLinks' objects>, '__weakref__': <attribute '__weakref__' of 'NodeLinks' objects>, '__annotations__': {'incoming_cache': 'list[LinkTriple]'}})#
__init__(node: Node) None[source]#

Initialize the links interface.

__module__ = 'aiida.orm.nodes.links'#
__weakref__#

list of weak references to the object (if defined)

_add_incoming_cache(source: Node, link_type: aiida.common.links.LinkType, link_label: str) None[source]#

Add an incoming link to the cache.

Parameters
  • source – the node from which the link is coming

  • link_type – the link type

  • link_label – the link label

Raises

aiida.common.UniquenessError – if the given link triple already exists in the cache

add_incoming(source: Node, link_type: aiida.common.links.LinkType, link_label: str) None[source]#

Add a link of the given type from a given node to ourself.

Parameters
  • source – the node from which the link is coming

  • link_type – the link type

  • link_label – the link label

Raises
  • TypeError – if source is not a Node instance or link_type is not a LinkType enum

  • ValueError – if the proposed link is invalid

get_incoming(node_class: Optional[Type[Node]] = None, link_type: Union[aiida.common.links.LinkType, Sequence[aiida.common.links.LinkType]] = (), link_label_filter: Optional[str] = None, only_uuid: bool = False) aiida.orm.utils.links.LinkManager[source]#

Return a list of link triples that are (directly) incoming into this node.

Parameters
  • node_class – If specified, should be a class or tuple of classes, and it filters only elements of that specific type (or a subclass of ‘type’)

  • link_type – If specified should be a string or tuple to get the inputs of this link type, if None then returns all inputs of all link types.

  • link_label_filter – filters the incoming nodes by its link label. Here wildcards (% and _) can be passed in link label filter as we are using “like” in QB.

  • only_uuid – project only the node UUID instead of the instance onto the NodeTriple.node entries

get_outgoing(node_class: Optional[Type[Node]] = None, link_type: Union[aiida.common.links.LinkType, Sequence[aiida.common.links.LinkType]] = (), link_label_filter: Optional[str] = None, only_uuid: bool = False) aiida.orm.utils.links.LinkManager[source]#

Return a list of link triples that are (directly) outgoing of this node.

Parameters
  • node_class – If specified, should be a class or tuple of classes, and it filters only elements of that specific type (or a subclass of ‘type’)

  • link_type – If specified should be a string or tuple to get the inputs of this link type, if None then returns all outputs of all link types.

  • link_label_filter – filters the outgoing nodes by its link label. Here wildcards (% and _) can be passed in link label filter as we are using “like” in QB.

  • only_uuid – project only the node UUID instead of the instance onto the NodeTriple.node entries

Return the list of stored link triples directly incoming to or outgoing of this node.

Note this will only return link triples that are stored in the database. Anything in the cache is ignored.

Parameters
  • node_class – If specified, should be a class, and it filters only elements of that (subclass of) type

  • link_type – Only get inputs of this link type, if empty tuple then returns all inputs of all link types.

  • link_label_filter – filters the incoming nodes by its link label. This should be a regex statement as one would pass directly to a QueryBuilder filter statement with the ‘like’ operation.

  • link_directionincoming or outgoing to get the incoming or outgoing links, respectively.

  • only_uuid – project only the node UUID instead of the instance onto the NodeTriple.node entries

validate_incoming(source: Node, link_type: aiida.common.links.LinkType, link_label: str) None[source]#

Validate adding a link of the given type from a given node to ourself.

This function will first validate the types of the inputs, followed by the node and link types and validate whether in principle a link of that type between the nodes of these types is allowed.

Subsequently, the validity of the “degree” of the proposed link is validated, which means validating the number of links of the given type from the given node type is allowed.

Parameters
  • source – the node from which the link is coming

  • link_type – the link type

  • link_label – the link label

Raises
  • TypeError – if source is not a Node instance or link_type is not a LinkType enum

  • ValueError – if the proposed link is invalid

validate_outgoing(target: Node, link_type: aiida.common.links.LinkType, link_label: str) None[source]#

Validate adding a link of the given type from ourself to a given node.

The validity of the triple (source, link, target) should be validated in the validate_incoming call. This method will be called afterwards and can be overriden by subclasses to add additional checks that are specific to that subclass.

Parameters
  • target – the node to which the link is going

  • link_type – the link type

  • link_label – the link label

Raises
  • TypeError – if target is not a Node instance or link_type is not a LinkType enum

  • ValueError – if the proposed link is invalid

Package for node ORM classes.

class aiida.orm.nodes.node.Node(backend: Optional[StorageBackend] = None, user: Optional[aiida.orm.users.User] = None, computer: Optional[aiida.orm.computers.Computer] = None, **kwargs: Any)[source]#

Bases: aiida.orm.entities.Entity[BackendNode]

Base class for all nodes in AiiDA.

Stores attributes starting with an underscore.

Caches files and attributes before the first save, and saves everything only on store(). After the call to store(), attributes cannot be changed.

Only after storing (or upon loading from uuid) extras can be modified and in this case they are directly set on the db.

In the plugin, also set the _plugin_type_string, to be set in the DB in the ‘type’ field.

Collection[source]#

alias of aiida.orm.nodes.node.NodeCollection

_CLS_COLLECTION#

alias of aiida.orm.nodes.node.NodeCollection

_CLS_NODE_CACHING#

alias of aiida.orm.nodes.caching.NodeCaching

alias of aiida.orm.nodes.links.NodeLinks

__abstractmethods__ = frozenset({})#
__annotations__ = {'_hash_ignored_attributes': typing.Tuple[str, ...], '_logger': typing.Union[logging.Logger, NoneType], '_plugin_type_string': typing.ClassVar[str], '_query_type_string': typing.ClassVar[str], '_updatable_attributes': typing.Tuple[str, ...]}#
__copy__()[source]#

Copying a Node is not supported in general, but only for the Data sub class.

__deepcopy__(memo)[source]#

Deep copying a Node is not supported in general, but only for the Data sub class.

__eq__(other: Any) bool[source]#

Fallback equality comparison by uuid (can be overwritten by specific types)

__getattr__(name: str) Any[source]#

This method is called when an attribute is not found in the instance.

It allows for the handling of deprecated mixin methods.

__hash__() int[source]#

Python-Hash: Implementation that is compatible with __eq__

__init__(backend: Optional[StorageBackend] = None, user: Optional[aiida.orm.users.User] = None, computer: Optional[aiida.orm.computers.Computer] = None, **kwargs: Any) None[source]#
Parameters

backend_entity – the backend model supporting this entity

__module__ = 'aiida.orm.nodes.node'#
__orig_bases__ = (aiida.orm.entities.Entity[ForwardRef('BackendNode')],)#
__parameters__ = ()#
__repr__() str[source]#

Return repr(self).

__str__() str[source]#

Return str(self).

_abc_impl = <_abc_data object>#
_add_outputs_from_cache(cache_node: aiida.orm.nodes.node.Node) None[source]#

Replicate the output links and nodes from the cached node onto this node.

_cachable = False#
_check_mutability_attributes(keys: Optional[List[str]] = None) None[source]#

Check if the entity is mutable and raise an exception if not.

This is called from NodeAttributes methods that modify the attributes.

Parameters

keys – the keys that will be mutated, or all if None

_deprecated_attr_methods = {'attributes': 'all', 'attributes_items': 'items', 'attributes_keys': 'keys', 'clear_attributes': 'clear', 'delete_attribute': 'delete', 'delete_attribute_many': 'delete_many', 'get_attribute': 'get', 'get_attribute_many': 'get_many', 'reset_attributes': 'reset', 'set_attribute': 'set', 'set_attribute_many': 'set_many'}#
_deprecated_caching_methods = {'_get_hash': '_get_hash', '_get_objects_to_hash': '_get_objects_to_hash', '_get_same_node': '_get_same_node', '_iter_all_same_nodes': '_iter_all_same_nodes', 'clear_hash': 'clear_hash', 'get_all_same_nodes': 'get_all_same_nodes', 'get_cache_source': 'get_cache_source', 'get_hash': 'get_hash', 'is_created_from_cache': 'is_created_from_cache', 'rehash': 'rehash'}#
_deprecated_comment_methods = {'add_comment': 'add', 'get_comment': 'get', 'get_comments': 'all', 'remove_comment': 'remove', 'update_comment': 'update'}#
_deprecated_extra_methods = {'clear_extras': 'clear', 'delete_extra': 'delete', 'delete_extra_many': 'delete_many', 'extras': 'all', 'extras_items': 'items', 'extras_keys': 'keys', 'get_extra': 'get', 'get_extra_many': 'get_many', 'reset_extras': 'reset', 'set_extra': 'set', 'set_extra_many': 'set_many'}#
_deprecated_repo_methods = {'copy_tree': 'copy_tree', 'delete_object': 'delete_object', 'get_object': 'get_object', 'get_object_content': 'get_object_content', 'glob': 'glob', 'list_object_names': 'list_object_names', 'list_objects': 'list_objects', 'open': 'open', 'put_object_from_file': 'put_object_from_file', 'put_object_from_filelike': 'put_object_from_filelike', 'put_object_from_tree': 'put_object_from_tree', 'repository_metadata': 'metadata', 'walk': 'walk'}#
_hash_ignored_attributes: Tuple[str, ...] = ()#
_logger: Optional[logging.Logger] = <Logger aiida.orm.nodes.node.Node (REPORT)>#
_plugin_type_string: ClassVar[str] = ''#
_query_type_string: ClassVar[str] = ''#
_storable = False#
_store(with_transaction: bool = True, clean: bool = True) aiida.orm.nodes.node.Node[source]#

Store the node in the database while saving its attributes and repository directory.

Parameters
  • with_transaction – if False, do not use a transaction because the caller will already have opened one.

  • clean – boolean, if True, will clean the attributes and extras before attempting to store

_store_from_cache(cache_node: aiida.orm.nodes.node.Node, with_transaction: bool) None[source]#

Store this node from an existing cache node.

Note

With the current implementation of the backend repository, which automatically deduplicates the content that it contains, we do not have to copy the contents of the source node. Since the content should be exactly equal, the repository will already contain it and there is nothing to copy. We simply replace the current repository instance with a clone of that of the source node, which does not actually copy any files.

_unstorable_message = 'only Data, WorkflowNode, CalculationNode or their subclasses can be stored'#
_updatable_attributes: Tuple[str, ...] = ()#
_validate() bool[source]#

Validate information stored in Node object.

For the Node base class, this check is always valid. Subclasses can override this method to perform additional checks and should usually call super()._validate() first!

This method is called automatically before storing the node in the DB. Therefore, use get() and similar methods that automatically read either from the DB or from the internal attribute cache.

_validate_storability() None[source]#

Verify that the current node is allowed to be stored.

Raises

aiida.common.exceptions.StoringNotAllowed – if the node does not match all requirements for storing

_verify_are_parents_stored() None[source]#

Verify that all parent nodes are already stored.

Raises

aiida.common.ModificationNotAllowed – if one of the source nodes of incoming links is not stored.

property base: aiida.orm.nodes.node.NodeBase#

Return the node base namespace.

class_node_type = ''#
property computer: Optional[aiida.orm.computers.Computer]#

Return the computer of this node.

property ctime: datetime.datetime#

Return the node ctime.

Returns

the ctime

property description: str#

Return the node description.

Returns

the description

get_description() str[source]#

Return a string with a description of the node.

Returns

a description string

property is_valid_cache: bool#

Hook to exclude certain Node classes from being considered a valid cache.

The base class assumes that all node instances are valid to cache from, unless the _VALID_CACHE_KEY extra has been set to False explicitly. Subclasses can override this property with more specific logic, but should probably also consider the value returned by this base class.

property label: str#

Return the node label.

Returns

the label

property logger: Optional[logging.Logger]#

Return the logger configured for this Node.

Returns

Logger object

property mtime: datetime.datetime#

Return the node mtime.

Returns

the mtime

property node_type: str#

Return the node type.

Returns

the node type

property process_type: Optional[str]#

Return the node process type.

Returns

the process type

store(with_transaction: bool = True) aiida.orm.nodes.node.Node[source]#

Store the node in the database while saving its attributes and repository directory.

After being called attributes cannot be changed anymore! Instead, extras can be changed only AFTER calling this store() function.

Note

After successful storage, those links that are in the cache, and for which also the parent node is already stored, will be automatically stored. The others will remain unstored.

Parameters

with_transaction – if False, do not use a transaction because the caller will already have opened one.

store_all(with_transaction: bool = True) aiida.orm.nodes.node.Node[source]#

Store the node, together with all input links.

Unstored nodes from cached incoming linkswill also be stored.

Parameters

with_transaction – if False, do not use a transaction because the caller will already have opened one.

property user: aiida.orm.users.User#

Return the user of this node.

property uuid: str#

Return the node UUID.

Returns

the string representation of the UUID

class aiida.orm.nodes.node.NodeBase(node: aiida.orm.nodes.node.Node)[source]#

Bases: object

A namespace for node related functionality, that is not directly related to its user-facing properties.

__dict__ = mappingproxy({'__module__': 'aiida.orm.nodes.node', '__doc__': 'A namespace for node related functionality, that is not directly related to its user-facing properties.', '__init__': <function NodeBase.__init__>, 'repository': <functools.cached_property object>, 'caching': <functools.cached_property object>, 'comments': <functools.cached_property object>, 'attributes': <functools.cached_property object>, 'extras': <functools.cached_property object>, 'links': <functools.cached_property object>, '__dict__': <attribute '__dict__' of 'NodeBase' objects>, '__weakref__': <attribute '__weakref__' of 'NodeBase' objects>, '__annotations__': {'_node': "'Node'"}})#
__init__(node: aiida.orm.nodes.node.Node) None[source]#

Construct a new instance of the base namespace.

__module__ = 'aiida.orm.nodes.node'#
__weakref__#

list of weak references to the object (if defined)

property attributes: aiida.orm.nodes.attributes.NodeAttributes#

Return an interface to interact with the attributes of this node.

property caching: aiida.orm.nodes.caching.NodeCaching#

Return an interface to interact with the caching of this node.

property comments: aiida.orm.nodes.comments.NodeComments#

Return an interface to interact with the comments of this node.

property extras: aiida.orm.extras.EntityExtras#

Return an interface to interact with the extras of this node.

Return an interface to interact with the links of this node.

property repository: aiida.orm.nodes.repository.NodeRepository#

Return the repository for this node.

class aiida.orm.nodes.node.NodeCollection(entity_class: Type[aiida.orm.entities.EntityType], backend: Optional[StorageBackend] = None)[source]#

Bases: aiida.orm.entities.Collection[aiida.orm.nodes.node.NodeType], Generic[aiida.orm.nodes.node.NodeType]

The collection of nodes.

__abstractmethods__ = frozenset({})#
__module__ = 'aiida.orm.nodes.node'#
__orig_bases__ = (aiida.orm.entities.Collection[~NodeType], typing.Generic[~NodeType])#
__parameters__ = (~NodeType,)#
_abc_impl = <_abc_data object>#
static _entity_base_cls() Type[aiida.orm.nodes.node.Node][source]#

The allowed entity class or subclasses thereof.

delete(pk: int) None[source]#

Delete a Node from the collection with the given id

Parameters

pk – the node id

iter_repo_keys(filters: Optional[dict] = None, subclassing: bool = True, batch_size: int = 100) Iterator[str][source]#

Iterate over all repository object keys for this Node class

Note

keys will not be deduplicated, wrap in a set to achieve this

Parameters
  • filters – Filters for the node query

  • subclassing – Whether to include subclasses of the given class

  • batch_size – The number of nodes to fetch data for at once

Interface to the file repository of a node instance.

class aiida.orm.nodes.repository.NodeRepository(node: Node)[source]#

Bases: object

Interface to the file repository of a node instance.

This is the compatibility layer between the Node class and the Repository class. The repository in principle has no concept of immutability, so it is implemented here. Any mutating operations will raise a ModificationNotAllowed exception if the node is stored. Otherwise the operation is just forwarded to the repository instance.

The repository instance keeps an internal mapping of the file hierarchy that it maintains, starting from an empty hierarchy if the instance was constructed normally, or from a specific hierarchy if reconstructred through the Repository.from_serialized classmethod. This is only the case for stored nodes, because unstored nodes do not have any files yet when they are constructed. Once the node get’s stored, the repository is asked to serialize its metadata contents which is then stored in the repository_metadata field of the backend node. This layer explicitly does not update the metadata of the node on a mutation action. The reason is that for stored nodes these actions are anyway forbidden and for unstored nodes, the final metadata will be stored in one go, once the node is stored, so there is no need to keep updating the node metadata intermediately. Note that this does mean that repository_metadata does not give accurate information, as long as the node is not yet stored.

__dict__ = mappingproxy({'__module__': 'aiida.orm.nodes.repository', '__doc__': "Interface to the file repository of a node instance.\n\n    This is the compatibility layer between the `Node` class and the `Repository` class. The repository in principle has\n    no concept of immutability, so it is implemented here. Any mutating operations will raise a `ModificationNotAllowed`\n    exception if the node is stored. Otherwise the operation is just forwarded to the repository instance.\n\n    The repository instance keeps an internal mapping of the file hierarchy that it maintains, starting from an empty\n    hierarchy if the instance was constructed normally, or from a specific hierarchy if reconstructred through the\n    ``Repository.from_serialized`` classmethod. This is only the case for stored nodes, because unstored nodes do not\n    have any files yet when they are constructed. Once the node get's stored, the repository is asked to serialize its\n    metadata contents which is then stored in the ``repository_metadata`` field of the backend node.\n    This layer explicitly does not update the metadata of the node on a mutation action.\n    The reason is that for stored nodes these actions are anyway forbidden and for unstored nodes,\n    the final metadata will be stored in one go, once the node is stored,\n    so there is no need to keep updating the node metadata intermediately.\n    Note that this does mean that ``repository_metadata`` does not give accurate information,\n    as long as the node is not yet stored.\n    ", '__init__': <function NodeRepository.__init__>, 'metadata': <property object>, '_update_repository_metadata': <function NodeRepository._update_repository_metadata>, '_check_mutability': <function NodeRepository._check_mutability>, '_repository': <property object>, '_store': <function NodeRepository._store>, '_copy': <function NodeRepository._copy>, '_clone': <function NodeRepository._clone>, 'serialize': <function NodeRepository.serialize>, 'hash': <function NodeRepository.hash>, 'list_objects': <function NodeRepository.list_objects>, 'list_object_names': <function NodeRepository.list_object_names>, 'open': <function NodeRepository.open>, 'get_object': <function NodeRepository.get_object>, 'get_object_content': <function NodeRepository.get_object_content>, 'put_object_from_bytes': <function NodeRepository.put_object_from_bytes>, 'put_object_from_filelike': <function NodeRepository.put_object_from_filelike>, 'put_object_from_file': <function NodeRepository.put_object_from_file>, 'put_object_from_tree': <function NodeRepository.put_object_from_tree>, 'walk': <function NodeRepository.walk>, 'glob': <function NodeRepository.glob>, 'copy_tree': <function NodeRepository.copy_tree>, 'delete_object': <function NodeRepository.delete_object>, 'erase': <function NodeRepository.erase>, '__dict__': <attribute '__dict__' of 'NodeRepository' objects>, '__weakref__': <attribute '__weakref__' of 'NodeRepository' objects>, '__annotations__': {'_node': "'Node'", '_repository_instance': 'Optional[Repository]'}})#
__init__(node: Node) None[source]#

Construct a new instance of the repository interface.

__module__ = 'aiida.orm.nodes.repository'#
__weakref__#

list of weak references to the object (if defined)

_check_mutability()[source]#

Check if the node is mutable.

Raises

ModificationNotAllowed – when the node is stored and therefore immutable.

_clone(repo: aiida.orm.nodes.repository.NodeRepository) None[source]#

Clone the repository from another instance.

This is used when cloning a node.

Parameters

repo – the repository to clone.

_copy(repo: aiida.orm.nodes.repository.NodeRepository) None[source]#

Copy a repository from another instance.

This is used when storing cached nodes.

Parameters

repo – the repository to clone.

property _repository: aiida.repository.repository.Repository#

Return the repository instance, lazily constructing it if necessary.

Note

this property is protected because a node’s repository should not be accessed outside of its scope.

Returns

the file repository instance.

_store() None[source]#

Store the repository in the backend.

_update_repository_metadata()[source]#

Refresh the repository metadata of the node if it is stored.

copy_tree(target: Union[str, pathlib.Path], path: Optional[Union[str, pathlib.PurePosixPath]] = None) None[source]#

Copy the contents of the entire node repository to another location on the local file system.

Parameters
  • target – absolute path of the directory where to copy the contents to.

  • path – optional relative path whose contents to copy.

delete_object(path: str)[source]#

Delete the object from the repository.

Parameters

key – fully qualified identifier for the object within the repository.

Raises
erase()[source]#

Delete all objects from the repository.

Raises

ModificationNotAllowed – when the node is stored and therefore immutable.

get_object(path: Optional[Union[str, pathlib.PurePosixPath]] = None) aiida.repository.common.File[source]#

Return the object at the given path.

Parameters

path – the relative path where to store the object in the repository.

Returns

the File representing the object located at the given relative path.

Raises
  • TypeError – if the path is not a string or Path, or is an absolute path.

  • FileNotFoundError – if no object exists for the given path.

get_object_content(path: str, mode='r') Union[str, bytes][source]#

Return the content of a object identified by key.

Parameters

key – fully qualified identifier for the object within the repository.

Raises
glob() Iterable[pathlib.PurePosixPath][source]#

Yield a recursive list of all paths (files and directories).

hash() str[source]#

Generate a hash of the repository’s contents.

Returns

the hash representing the contents of the repository.

list_object_names(path: Optional[str] = None) List[str][source]#

Return a sorted list of the object names contained in this repository, optionally in the given sub directory.

Parameters

path – the relative path where to store the object in the repository.

Returns

a list of File named tuples representing the objects present in directory with the given key.

Raises
list_objects(path: Optional[str] = None) List[aiida.repository.common.File][source]#

Return a list of the objects contained in this repository sorted by name, optionally in given sub directory.

Parameters

path – the relative path where to store the object in the repository.

Returns

a list of File named tuples representing the objects present in directory with the given key.

Raises
property metadata: Dict[str, Any]#

Return the repository metadata, representing the virtual file hierarchy.

Note, this is only accurate if the node is stored.

Returns

the repository metadata

open(path: str, mode='r') Iterator[Union[BinaryIO, TextIO]][source]#

Open a file handle to an object stored under the given key.

Note

this should only be used to open a handle to read an existing file. To write a new file use the method put_object_from_filelike instead.

Parameters

path – the relative path of the object within the repository.

Returns

yield a byte stream object.

Raises
put_object_from_bytes(content: bytes, path: str) None[source]#

Store the given content in the repository at the given path.

Parameters
  • path – the relative path where to store the object in the repository.

  • content – the content to store.

Raises
  • TypeError – if the path is not a string and relative path.

  • FileExistsError – if an object already exists at the given path.

put_object_from_file(filepath: str, path: str)[source]#

Store a new object under path with contents of the file located at filepath on the local file system.

Parameters
  • filepath – absolute path of file whose contents to copy to the repository

  • path – the relative path where to store the object in the repository.

Raises
  • TypeError – if the path is not a string and relative path, or the handle is not a byte stream.

  • ModificationNotAllowed – when the node is stored and therefore immutable.

put_object_from_filelike(handle: _io.BufferedReader, path: str)[source]#

Store the byte contents of a file in the repository.

Parameters
  • handle – filelike object with the byte content to be stored.

  • path – the relative path where to store the object in the repository.

Raises
put_object_from_tree(filepath: str, path: Optional[str] = None)[source]#

Store the entire contents of filepath on the local file system in the repository with under given path.

Parameters
  • filepath – absolute path of the directory whose contents to copy to the repository.

  • path – the relative path where to store the objects in the repository.

Raises
serialize() Dict[source]#

Serialize the metadata of the repository content into a JSON-serializable format.

Returns

dictionary with the content metadata.

walk(path: Optional[Union[str, pathlib.PurePosixPath]] = None) Iterable[Tuple[pathlib.PurePosixPath, List[str], List[str]]][source]#

Walk over the directories and files contained within this repository.

Note

the order of the dirname and filename lists that are returned is not necessarily sorted. This is in line with the os.walk implementation where the order depends on the underlying file system used.

Parameters

path – the relative path of the directory within the repository whose contents to walk.

Returns

tuples of root, dirnames and filenames just like os.walk, with the exception that the root path is always relative with respect to the repository root, instead of an absolute path and it is an instance of pathlib.PurePosixPath instead of a normal string