aiida.orm.nodes package#

Module with Node sub classes for data and processes.

Subpackages#

Submodules#

Interface to the attributes of a node instance.

class aiida.orm.nodes.attributes.NodeAttributes(node: Node)[源代码]#

基类: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[源代码]#

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[源代码]#

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.

警告

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.

返回:

the attributes as a dictionary

clear() None[源代码]#

Delete all attributes.

delete(key: str) None[源代码]#

Delete an attribute.

参数:

key – name of the attribute

抛出:
delete_many(keys: List[str]) None[源代码]#

Delete multiple attributes.

参数:

keys – names of the attributes to delete

抛出:
get(key: str, default=()) Any[源代码]#

Return the value of an attribute.

警告

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.

参数:
  • key – name of the attribute

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

返回:

the value of the attribute

抛出:

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

get_many(keys: List[str]) List[Any][源代码]#

Return the values of multiple attributes.

警告

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.

参数:

keys – a list of attribute names

返回:

a list of attribute values

抛出:

AttributeError – if at least one attribute does not exist

items() Iterable[Tuple[str, Any]][源代码]#

Return an iterator over the attributes.

返回:

an iterator with attribute key value pairs

keys() Iterable[str][源代码]#

Return an iterator over the attribute keys.

返回:

an iterator with attribute keys

reset(attributes: Dict[str, Any]) None[源代码]#

Reset the attributes.

备注

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

参数:

attributes – a dictionary with the attributes to set

抛出:
set(key: str, value: Any) None[源代码]#

Set an attribute to the given value.

参数:
  • key – name of the attribute

  • value – value of the attribute

抛出:
set_many(attributes: Dict[str, Any]) None[源代码]#

Set multiple attributes.

备注

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

参数:

attributes – a dictionary with the attributes to set

抛出:

Interface to control caching of a node instance.

class aiida.orm.nodes.caching.NodeCaching(node: Node)[源代码]#

基类:object

Interface to control caching of a node instance.

CACHED_FROM_KEY: str = '_aiida_cached_from'#
_HASH_EXTRA_KEY: str = '_aiida_hash'#
_VALID_CACHE_KEY: str = '_aiida_valid_cache'#
__annotations__ = {'CACHED_FROM_KEY': 'str', '_HASH_EXTRA_KEY': 'str', '_VALID_CACHE_KEY': 'str'}#
__dict__ = mappingproxy({'__module__': 'aiida.orm.nodes.caching', '__annotations__': {'_HASH_EXTRA_KEY': 'str', '_VALID_CACHE_KEY': 'str', 'CACHED_FROM_KEY': 'str'}, '__doc__': 'Interface to control caching of a node instance.', '_HASH_EXTRA_KEY': '_aiida_hash', '_VALID_CACHE_KEY': '_aiida_valid_cache', 'CACHED_FROM_KEY': '_aiida_cached_from', '__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>, 'should_use_cache': <function NodeCaching.should_use_cache>, '_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[源代码]#

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: Any) str | None[源代码]#

Return the hash for this node based on its attributes.

This will always work, even before storing.

参数:

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

_get_objects_to_hash() list[Any][源代码]#

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

_get_same_node() 'Node' | None[源代码]#

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.

返回:

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) t.Iterator['Node'][源代码]#

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[源代码]#

Sets the stored hash of the Node to None.

get_all_same_nodes() list['Node'][源代码]#

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[源代码]#

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

返回:

source node UUID or None

get_hash(ignore_errors: bool = True, **kwargs: Any) str | None[源代码]#

Return the hash for this node based on its attributes.

参数:

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.

返回:

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[源代码]#

Regenerate the stored hash of the Node.

should_use_cache() bool[源代码]#

Return whether the cache should be considered when storing this node.

返回:

True if the cache should be considered, False otherwise.

Interface for comments of a node instance.

class aiida.orm.nodes.comments.NodeComments(node: Node)[源代码]#

基类: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[源代码]#

Initialize the comments interface.

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

list of weak references to the object (if defined)

add(content: str, user: User | None = None) Comment[源代码]#

Add a new comment.

参数:
  • content – string with comment

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

返回:

the newly created comment

all() list[Comment][源代码]#

Return a sorted list of comments for this node.

返回:

the list of comments, sorted by pk

get(identifier: int) Comment[源代码]#

Return a comment corresponding to the given identifier.

参数:

identifier – the comment pk

抛出:
返回:

the comment

remove(identifier: int) None[源代码]#

Delete an existing comment.

参数:

identifier – the comment pk

update(identifier: int, content: str) None[源代码]#

Update the content of an existing comment.

参数:
  • identifier – the comment pk

  • content – the new comment content

抛出:

基类: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[源代码]#

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: LinkType, link_label: str) None[源代码]#

Add an incoming link to the cache.

参数:
  • source – the node from which the link is coming

  • link_type – the link type

  • link_label – the link label

抛出:

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

add_incoming(source: Node, link_type: LinkType, link_label: str) None[源代码]#

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

参数:
  • source – the node from which the link is coming

  • link_type – the link type

  • link_label – the link label

抛出:
  • 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: t.Type['Node'] | None = None, link_type: t.Union[LinkType, t.Sequence[LinkType]] = (), link_label_filter: t.Optional[str] = None, only_uuid: bool = False) LinkManager[源代码]#

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

参数:
  • 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: t.Type['Node'] | None = None, link_type: t.Union[LinkType, t.Sequence[LinkType]] = (), link_label_filter: t.Optional[str] = None, only_uuid: bool = False) LinkManager[源代码]#

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

参数:
  • 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.

参数:
  • 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: LinkType, link_label: str) None[源代码]#

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.

参数:
  • source – the node from which the link is coming

  • link_type – the link type

  • link_label – the link label

抛出:
  • 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: LinkType, link_label: str) None[源代码]#

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.

参数:
  • target – the node to which the link is going

  • link_type – the link type

  • link_label – the link label

抛出:
  • 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: StorageBackend | None = None, user: User | None = None, computer: Computer | None = None, **kwargs: Any)[源代码]#

基类:Entity[BackendNode, NodeCollection]

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[源代码]#

NodeCollection 的别名

_CLS_COLLECTION#

NodeCollection 的别名

_CLS_NODE_CACHING#

NodeCaching 的别名

NodeLinks 的别名

__abstractmethods__ = frozenset({})#
__annotations__ = {'_CLS_COLLECTION': 'Type[CollectionType]', '_Node__plugin_type_string': typing.ClassVar[str], '_Node__query_type_string': typing.ClassVar[str], '__plugin_type_string': 'ClassVar[str]', '__qb_fields__': 'Sequence[QbField]', '__query_type_string': 'ClassVar[str]', '_hash_ignored_attributes': typing.Tuple[str, ...], '_logger': typing.Optional[logging.Logger], '_updatable_attributes': typing.Tuple[str, ...], 'fields': 'QbFields'}#
__copy__()[源代码]#

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

__deepcopy__(memo)[源代码]#

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

__eq__(other: Any) bool[源代码]#

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

__getattr__(name: str) Any[源代码]#

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

It allows for the handling of deprecated mixin methods.

__hash__() int[源代码]#

Python-Hash: Implementation that is compatible with __eq__

__init__(backend: StorageBackend | None = None, user: User | None = None, computer: Computer | None = None, **kwargs: Any) None[源代码]#
参数:

backend_entity – the backend model supporting this entity

__module__ = 'aiida.orm.nodes.node'#
__orig_bases__ = (aiida.orm.entities.Entity[ForwardRef('BackendNode'), aiida.orm.nodes.node.NodeCollection],)#
__parameters__ = ()#
__plugin_type_string: ClassVar[str] = ''#
__qb_fields__: Sequence[QbField] = [QbStrField('uuid', dtype=str, is_attribute=False), QbStrField('label', dtype=str, is_attribute=False), QbStrField('description', dtype=str, is_attribute=False), QbStrField('node_type', dtype=str, is_attribute=False), QbNumericField('ctime', dtype=datetime, is_attribute=False), QbNumericField('mtime', dtype=datetime, is_attribute=False), QbDictField('repository_metadata', dtype=Dict[str, Any], is_attribute=False), QbDictField('extras', dtype=Dict[str, Any], is_attribute=False, is_subscriptable=True), QbNumericField('user_pk', dtype=int, is_attribute=False), QbDictField('attributes', dtype=Dict[str, Any], is_attribute=False, is_subscriptable=True)]#
__query_type_string: ClassVar[str] = ''#
__repr__() str[源代码]#

Return repr(self).

__str__() str[源代码]#

Return str(self).

_abc_impl = <_abc._abc_data object>#
_add_outputs_from_cache(cache_node: Node) None[源代码]#

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

_cachable = False#
_check_mutability_attributes(keys: List[str] | None = None) None[源代码]#

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

This is called from NodeAttributes methods that modify the attributes.

参数:

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: Logger | None = <Logger aiida.orm.nodes.node.Node (WARNING)>#
_plugin_type_string = ''#
_query_type_string = ''#
_storable = False#
_store(clean: bool = True) Node[源代码]#

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

参数:

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

_store_from_cache(cache_node: Node) None[源代码]#

Store this node from an existing cache node.

备注

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[源代码]#

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[源代码]#

Verify that the current node is allowed to be stored.

抛出:

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

_verify_are_parents_stored() None[源代码]#

Verify that all parent nodes are already stored.

抛出:

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

property base: NodeBase#

Return the node base namespace.

class_node_type = ''#
property computer: Computer | None#

Return the computer of this node.

property ctime: datetime#

Return the node ctime.

返回:

the ctime

property description: str#

Return the node description.

返回:

the description

entry_point = None#
fields: QbFields = {'attributes': 'QbDictField(attributes.*) -> Dict[str, Any]',  'ctime': 'QbNumericField(ctime) -> datetime',  'description': 'QbStrField(description) -> str',  'extras': 'QbDictField(extras.*) -> Dict[str, Any]',  'label': 'QbStrField(label) -> str',  'mtime': 'QbNumericField(mtime) -> datetime',  'node_type': 'QbStrField(node_type) -> str',  'pk': 'QbNumericField(pk) -> int',  'repository_metadata': 'QbDictField(repository_metadata) -> Dict[str, Any]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str'}#
get_description() str[源代码]#

Return a string with a description of the node.

返回:

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.

返回:

the label

property logger: Logger | None#

Return the logger configured for this Node.

返回:

Logger object

property mtime: datetime#

Return the node mtime.

返回:

the mtime

property node_type: str#

Return the node type.

返回:

the node type

property process_type: str | None#

Return the node process type.

返回:

the process type

store() Node[源代码]#

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.

store_all() Node[源代码]#

Store the node, together with all input links.

Unstored nodes from cached incoming linkswill also be stored.

property user: User#

Return the user of this node.

property uuid: str#

Return the node UUID.

返回:

the string representation of the UUID

class aiida.orm.nodes.node.NodeBase(node: Node)[源代码]#

基类: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: Node) None[源代码]#

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: NodeAttributes#

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

property caching: NodeCaching#

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

property comments: NodeComments#

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

property 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: NodeRepository#

Return the repository for this node.

class aiida.orm.nodes.node.NodeCollection(entity_class: Type[EntityType], backend: 'StorageBackend' | None = None)[源代码]#

基类:Collection[NodeType], Generic[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._abc_data object>#
static _entity_base_cls() Type[Node][源代码]#

The allowed entity class or subclasses thereof.

delete(pk: int) None[源代码]#

Delete a Node from the collection with the given id

参数:

pk – the node id

iter_repo_keys(filters: dict | None = None, subclassing: bool = True, batch_size: int = 100) Iterator[str][源代码]#

Iterate over all repository object keys for this Node class

备注

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

参数:
  • 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)[源代码]#

基类: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 reconstructed 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 reconstructed 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. This layer\n    explicitly does not update the metadata of the node on a mutation action. The reason is that for stored nodes these\n    actions are anyway forbidden and for unstored nodes, the final metadata will be stored in one go, once the node is\n    stored, so there is no need to keep updating the node metadata intermediately. Note that this does mean that\n    ``repository_metadata`` does not give accurate information, 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>, 'as_path': <function NodeRepository.as_path>, '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': 'Repository | None'}})#
__init__(node: Node) None[源代码]#

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()[源代码]#

Check if the node is mutable.

抛出:

ModificationNotAllowed – when the node is stored and therefore immutable.

_clone(repo: NodeRepository) None[源代码]#

Clone the repository from another instance.

This is used when cloning a node.

参数:

repo – the repository to clone.

_copy(repo: NodeRepository) None[源代码]#

Copy a repository from another instance.

This is used when storing cached nodes.

参数:

repo – the repository to clone.

property _repository: Repository#

Return the repository instance, lazily constructing it if necessary.

备注

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

返回:

the file repository instance.

_store() None[源代码]#

Store the repository in the backend.

_update_repository_metadata()[源代码]#

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

as_path(path: str | PurePosixPath | None = None) Iterator[Path][源代码]#

Make the contents of the repository available as a normal filepath on the local file system.

参数:

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

返回:

the filepath of the content of the repository or object if path is specified.

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

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

copy_tree(target: str | Path, path: str | PurePosixPath | None = None) None[源代码]#

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

参数:
  • target – absolute path of the directory where to copy the contents to.

  • path – optional relative path whose contents to copy.

delete_object(path: str)[源代码]#

Delete the object from the repository.

参数:

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

抛出:
erase()[源代码]#

Delete all objects from the repository.

抛出:

ModificationNotAllowed – when the node is stored and therefore immutable.

get_object(path: str | PurePosixPath | None = None) File[源代码]#

Return the object at the given path.

参数:

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

返回:

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

抛出:
  • 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: Literal['r']) str[源代码]#
get_object_content(path: str, mode: Literal['rb']) bytes

Return the content of a object identified by key.

参数:

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

抛出:
glob() Iterable[PurePosixPath][源代码]#

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

hash() str[源代码]#

Generate a hash of the repository’s contents.

返回:

the hash representing the contents of the repository.

list_object_names(path: str | None = None) list[str][源代码]#

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

参数:

path – optional relative path inside the repository whose objects to list.

返回:

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

抛出:
list_objects(path: str | None = None) list[File][源代码]#

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

参数:

path – optional relative path inside the repository whose objects to list.

返回:

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

抛出:
property metadata: dict[str, Any]#

Return the repository metadata, representing the virtual file hierarchy.

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

返回:

the repository metadata

open(path: FilePath, mode: t.Literal['r']) t.Iterator[t.TextIO][源代码]#
open(path: FilePath, mode: t.Literal['rb']) t.Iterator[t.BinaryIO]

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

备注

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.

参数:

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

返回:

yield a byte stream object.

抛出:
put_object_from_bytes(content: bytes, path: str) None[源代码]#

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

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

  • content – the content to store.

抛出:
  • 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)[源代码]#

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

参数:
  • filepath – absolute path of file whose contents to copy to the repository

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

抛出:
  • 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: BufferedReader, path: str)[源代码]#

Store the byte contents of a file in the repository.

参数:
  • handle – filelike object with the byte content to be stored.

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

抛出:
put_object_from_tree(filepath: str, path: str | None = None)[源代码]#

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

参数:
  • 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.

抛出:
serialize() dict[源代码]#

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

返回:

dictionary with the content metadata.

walk(path: str | PurePosixPath | None = None) Iterable[tuple[PurePosixPath, list[str], list[str]]][源代码]#

Walk over the directories and files contained within this repository.

备注

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.

参数:

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

返回:

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