Utilities related to the ORM.
aiida.orm.utils.
load_code
Load a Code instance by one of its identifiers: pk, uuid or label
If the type of the identifier is unknown simply pass it without a keyword and the loader will attempt to automatically infer the type.
identifier – pk (integer), uuid (string) or label (string) of a Code
pk – pk of a Code
uuid – uuid of a Code, or the beginning of the uuid
label – label of a Code
sub_classes – an optional tuple of orm classes to narrow the queryset. Each class should be a strict sub class of the ORM class of the given entity loader.
query_with_dashes (bool) – allow to query for a uuid with dashes
the Code instance
ValueError – if none or more than one of the identifiers are supplied
TypeError – if the provided identifier has the wrong type
aiida.common.NotExistent – if no matching Code is found
aiida.common.MultipleObjectsError – if more than one Code was found
load_computer
Load a Computer instance by one of its identifiers: pk, uuid or label
identifier – pk (integer), uuid (string) or label (string) of a Computer
pk – pk of a Computer
uuid – uuid of a Computer, or the beginning of the uuid
label – label of a Computer
the Computer instance
aiida.common.NotExistent – if no matching Computer is found
aiida.common.MultipleObjectsError – if more than one Computer was found
load_group
Load a Group instance by one of its identifiers: pk, uuid or label
identifier – pk (integer), uuid (string) or label (string) of a Group
pk – pk of a Group
uuid – uuid of a Group, or the beginning of the uuid
label – label of a Group
the Group instance
aiida.common.NotExistent – if no matching Group is found
aiida.common.MultipleObjectsError – if more than one Group was found
load_node
Load a node by one of its identifiers: pk or uuid. If the type of the identifier is unknown simply pass it without a keyword and the loader will attempt to infer the type
identifier – pk (integer) or uuid (string)
pk – pk of a node
uuid – uuid of a node, or the beginning of the uuid
label – label of a Node
the node instance
aiida.common.NotExistent – if no matching Node is found
aiida.common.MultipleObjectsError – if more than one Node was found
Utilities to operate on CalcJobNode instances.
aiida.orm.utils.calcjob.
CalcJobResultManager
Bases: object
object
Utility class to easily access the contents of the ‘default output’ node of a CalcJobNode.
A CalcJob process can mark one of its outputs as the ‘default output’. The default output node will always be returned by the CalcJob and will always be a Dict node.
If a CalcJob defines such a default output node, this utility class will simplify retrieving the result of said node through the CalcJobNode instance produced by the execution of the CalcJob.
The default results are only defined if the CalcJobNode has a process_type that can be successfully used to load the corresponding CalcJob process class and if its process spec defines a default_output_node. If both these conditions are met, the results are defined as the dictionary contained within the default output node.
__dict__
__dir__
Add the keys of the results dictionary such that they can be autocompleted.
__getattr__
Return an attribute from the results dictionary.
name – name of the result return
value of the attribute
AttributeError – if the results node cannot be retrieved or it does not contain the name attribute
__getitem__
KeyError – if the results node cannot be retrieved or it does not contain the name attribute
__init__
Construct an instance of the CalcJobResultManager.
calc – the CalcJobNode instance.
__iter__
Return an iterator over the keys of the result dictionary.
__module__
__weakref__
list of weak references to the object (if defined)
_load_results
Try to load the results for the CalcJobNode of this result manager.
ValueError – if no default output node could be loaded
get_results
Return the results dictionary of the default results node of the calculation node.
This property will lazily load the dictionary.
the dictionary of the default result node
node
Return the CalcJobNode associated with this result manager instance.
Utilities for dealing with links between nodes.
aiida.orm.utils.links.
LinkManager
Class to convert a list of LinkTriple tuples into an iterator.
It defines convenience methods to retrieve certain subsets of LinkTriple while checking for consistency. For example:
LinkManager.one(): returns the only entry in the list or it raises an exception LinkManager.first(): returns the first entry from the list LinkManager.all(): returns all entries from list
The methods all_nodes and all_link_labels are syntactic sugar wrappers around all to get a list of only the incoming nodes or link labels, respectively.
__bool__
Initialise the collection.
Return an iterator of LinkTriple instances.
iterator of LinkTriple instances
__next__
Return the next element in the iterator.
LinkTriple
all
Return all entries from the list.
list of LinkTriple instances
all_link_labels
Return a list of all link labels.
list of link labels
all_link_pairs
Return a list of all link pairs.
list of LinkPair instances
all_nodes
Return a list of all nodes.
list of nodes
first
Return the first entry from the iterator.
LinkTriple instance or None if no entries were matched
get_node_by_label
Return the node from list for given label.
node that corresponds to the given label
aiida.common.NotExistent – if the label is not present among the link_triples
nested
Construct (nested) dictionary of matched nodes that mirrors the original nesting of link namespaces.
Process input and output namespaces can be nested, however the link labels that represent them in the database have a flat hierarchy, and so the link labels are flattened representations of the nested namespaces. This function reconstructs the original node nesting based on the flattened links.
dictionary of nested namespaces
KeyError – if there are duplicate link labels in a namespace
next
one
Return a single entry from the iterator.
If the iterator contains no or more than one entry, an exception will be raised :return: LinkTriple instance :raises ValueError: if the iterator contains anything but one entry
LinkPair
Bases: tuple
tuple
__getnewargs__
Return self as a plain tuple. Used by copy and pickle.
__new__
Create new instance of LinkPair(link_type, link_label)
__repr__
Return a nicely formatted representation string
__slots__
_asdict
Return a new dict which maps field names to their values.
_field_defaults
_fields
_fields_defaults
_make
Make a new LinkPair object from a sequence or iterable
_replace
Return a new LinkPair object replacing specified fields with new values
link_label
Alias for field number 1
link_type
Alias for field number 0
Create new instance of LinkTriple(node, link_type, link_label)
Make a new LinkTriple object from a sequence or iterable
Return a new LinkTriple object replacing specified fields with new values
Alias for field number 2
validate_link
Validate adding a link of the given type and label from a given node to ourself.
This function will first validate the class types of the inputs and will subsequently validate whether a link of the specified type is allowed at all between the nodes types of the source and target.
Subsequently, the validity of the “indegree” and “outdegree” of the proposed link is validated, which means validating that the uniqueness constraints of the incoming links into the target node and the outgoing links from the source node are not violated. In AiiDA’s provenance graph each link type has one of the following three types of “degree” character:
* unique * unique pair * unique triple
Each degree character has a different unique constraint on its links, here defined for the indegree:
* unique: any target node, it can only have a single incoming link of this type, regardless of the link label. * unique pair: a node can have an infinite amount of incoming links of this type, as long as the labels within that sub set, are unique. In short, it is the link pair, i.e. the tuple of the link type and label, that has a uniquess constraint for the incoming links to a given node. * unique triple: a node can have an infinite amount of incoming links of this type, as long as the triple tuple of source node, link type and link label is unique. In other words, it is the link triple that has a uniqueness constraint for the incoming links.
The same holds for outdegree, but then it concerns outgoing links from the source node to the target node.
For illustration purposes, consider the following example provenance graphs that are considered legal, where WN, DN and CN represent a WorkflowNode, a DataNode and a CalculationNode, respectively:
1 2 3 ______ ______ ______ ______ ______ | | | | | | | | | | | WN | | DN | | DN | | WN | | WN | |______| |______| |______| |______| |______| | / | | | / a | / a a | | b a | / a _|___/ |___|_ _|___/ | | | | | | | CN | | CN | | DN | |______| |______| |______|
In example 1, the link uniqueness constraint is not violated because despite the labels having the same label a, their link types, CALL_CALC and INPUT_CALC, respectively, are different and their unique_pair indegree is not violated.
Similarly, in the second example, the constraint is not violated, because despite both links having the same link type INPUT_CALC, the have different labels, so the unique_pair indegree of the INPUT_CALC is not violated.
Finally, in the third example, we see two WorkflowNodes both returning the same DataNode and with the same label. Despite the two incoming links here having both the same type as well as the same label, the uniqueness constraint is not violated, because the indegree for RETURN links is unique_triple which means that the triple of source node and link type and label should be unique.
source – the node from which the link is coming
target – the node to which the link is going
link_type – the type of link
link_label – link label
TypeError – if source or target is not a Node instance, or link_type is not a LinkType enum
ValueError – if the proposed link is invalid
Module with OrmEntityLoader and its sub classes that simplify loading entities through their identifiers.
aiida.orm.utils.loaders.
CalculationEntityLoader
Bases: aiida.orm.utils.loaders.OrmEntityLoader
aiida.orm.utils.loaders.OrmEntityLoader
Loader for the Calculation entity and sub classes.
_get_query_builder_label_identifier
Return the query builder instance that attempts to map the identifier onto an entity of the orm class, defined for this loader class, interpreting the identifier as a LABEL like identifier
identifier – the LABEL identifier
classes – a tuple of orm classes to which the identifier should be mapped
operator – the operator to use in the query
project – the property or properties to project for entities matching the query
the query builder instance that should retrieve the entity corresponding to the identifier
ValueError – if the identifier is invalid
aiida.common.NotExistent – if the orm base class does not support a LABEL like identifier
orm_base_class
alias of aiida.orm.nodes.process.calculation.calculation.CalculationNode
aiida.orm.nodes.process.calculation.calculation.CalculationNode
CodeEntityLoader
Loader for the Code entity and sub classes.
alias of aiida.orm.nodes.data.code.Code
aiida.orm.nodes.data.code.Code
ComputerEntityLoader
Loader for the Computer entity and sub classes.
alias of aiida.orm.computers.Computer
aiida.orm.computers.Computer
GroupEntityLoader
Loader for the Group entity and sub classes.
alias of aiida.orm.groups.Group
aiida.orm.groups.Group
NodeEntityLoader
Loader for the Node entity and sub classes.
alias of aiida.orm.nodes.node.Node
aiida.orm.nodes.node.Node
OrmEntityLoader
Base class for entity loaders.
_get_query_builder_id_identifier
Return the query builder instance that attempts to map the identifier onto an entity of the orm class, defined for this loader class, interpreting the identifier as an ID like identifier
identifier – the ID identifier
the query builder instance
_get_query_builder_uuid_identifier
Return the query builder instance that attempts to map the identifier onto an entity of the orm class, defined for this loader class, interpreting the identifier as a UUID like identifier
identifier – the UUID identifier
get_options
Return the list of entities that match the incomplete identifier.
Note
For the time being only LABEL auto-completion is supported so the identifier type is not inferred but hard-coded to be IdentifierType.LABEL
incomplete – the incomplete identifier
project – the field(s) to project for each entity that matches the incomplete identifier
list of entities matching the incomplete identifier
get_query_builder
Return the query builder instance that attempts to map the identifier onto an entity of the orm class, defined for this loader class, inferring the identifier type if it is not defined.
identifier – the identifier
identifier_type – the type of the identifier
sub_classes – an optional tuple of orm classes, that should each be strict sub classes of the base orm class of the loader, that will narrow the queryset
the query builder instance and a dictionary of used query parameters
get_query_classes
Get the tuple of classes to be used for the entity query. If sub_classes is defined, each class will be validated by verifying that it is a sub class of the loader’s orm base class. Validate a tuple of classes if a user passes in a specific one when attempting to load an entity. Each class should be a sub class of the entity loader’s orm base class
the tuple of orm classes to be used for the entity query
ValueError – if any of the classes are not a sub class of the entity loader’s orm base class
infer_identifier_type
This method will attempt to automatically distinguish which identifier type is implied for the given value, if the value itself has no type from which it can be inferred.
The strategy is to first attempt to convert the value to an integer. If successful, it is assumed that the value represents an ID. If that fails, we attempt to interpret the value as a base 16 encoded integer, after having removed any dashes from the string. If that succeeds, it is most likely a UUID. If it seems to be neither an ID nor a UUID, it is assumed to be a LABEL like identifier.
With this approach there is the possibility for ambiguity. Since it is allowed to pass a partial UUID, it is possible that the partial UUID is also a valid ID. Likewise, a LABEL identifier might also be a valid ID, or a valid (partial) UUID. Fortunately, these ambiguities can be solved though:
ID/UUID: can always be solved by passing a partial UUID with at least one dash ID/LABEL: appending an exclamation point ! to the identifier, will force LABEL interpretation UUID/LABEL: appending an exclamation point ! to the identifier, will force LABEL interpretation
ID/UUID: can always be solved by passing a partial UUID with at least one dash
ID/LABEL: appending an exclamation point ! to the identifier, will force LABEL interpretation
UUID/LABEL: appending an exclamation point ! to the identifier, will force LABEL interpretation
As one can see, the user will always be able to include at least one dash of the UUID identifier to prevent it from being interpreted as an ID. For the potential ambiguities in LABEL identifiers, we had to introduce a special marker to provide a surefire way of breaking any ambiguity that may arise. Adding an exclamation point will break the normal strategy and the identifier will directly be interpreted as a LABEL identifier.
value – the value of the identifier
the identifier and identifier type
ValueError – if the value is an invalid identifier
label_ambiguity_breaker
load_entity
Load an entity that uniquely corresponds to the provided identifier of the identifier type.
the loaded entity
aiida.common.MultipleObjectsError – if the identifier maps onto multiple entities
aiida.common.NotExistent – if the identifier maps onto not a single entity
A class that, when used as a decorator, works as if the two decorators @property and @classmethod where applied together (i.e., the object works as a property, both for the Class and for any of its instance; and is called with the class cls rather than with the instance as its first argument).
get_loader
Return the correct OrmEntityLoader for the given orm class.
orm_class – the orm class
a subclass of OrmEntityLoader
ValueError – if no OrmEntityLoader subclass can be found for the given orm class
Module for logging methods/classes that need the ORM.
aiida.orm.utils.log.
DBLogHandler
Bases: logging.Handler
logging.Handler
A custom db log handler for writing logs tot he database
emit
Do whatever it takes to actually log the specified logging record.
This version is intended to be implemented by subclasses and so raises a NotImplementedError.
create_logger_adapter
Create a logger adapter for the given Node instance.
logger – the logger to adapt
node – the node instance to create the adapter for
the logger adapter
logging.LoggerAdapter
get_dblogger_extra
Return the additional information necessary to attach any log records to the given node instance.
node – a Node instance
Contain utility classes for “managers”, i.e., classes that allow to access members of other classes via TAB-completable attributes (e.g. the class underlying calculation.inputs to allow to do calculation.inputs.<label>).
aiida.orm.utils.managers.
AttributeManager
An object used internally to return the attributes as a dictionary. This is currently used in Dict, for instance.
Dict
Important! It cannot be used to change variables, just to read them. To change values (of unstored nodes), use the proper Node methods.
Allow to list the keys of the dictionary
Interface to get to dictionary values, using the key as an attribute.
it works only for attributes that only contain letters, numbers and underscores, and do not start with a number.
name – name of the key whose value is required.
Interface to get to dictionary values as a dictionary.
node – the node object.
Return the keys as an iterator
__setattr__
Implement setattr(self, name, value).
_get_dict
Return the internal dictionary
NodeLinksManager
A manager that allows to inspect, with tab-completion, nodes linked to a given one. See an example of its use in CalculationNode.inputs.
Allow to list all valid input links
name – name of the attribute to be asked to the parser results.
interface to get to the parser results as a dictionary.
Initialise the link manager.
node – the reference node object
link_type – the link_type to inspect
incoming – if True, inspect incoming links, otherwise inspect outgoing links
Return repr(self).
__str__
Return a string representation of the manager
_construct_attribute_dict
Construct an attribute dict from all links of the node, recreating nested namespaces from flat link labels.
incoming – if True, inspect incoming links, otherwise inspect outgoing links.
_get_keys
Return the valid link labels, used e.g. to make getattr() work
_get_node_by_link_label
Return the linked node with a given link label.
Nested namespaces in link labels get represented by double underscores in the database. Up until now, the link manager didn’t automatically unroll these again into nested namespaces and so a user was forced to pass the link with double underscores to dereference the corresponding node. For example, when used with the inputs attribute of a ProcessNode one had to do:
inputs
ProcessNode
node.inputs.nested__sub__namespace
Now it is possible to do
node.inputs.nested.sub.namespace
which is more intuitive since the double underscore replacement is just for the database and the user shouldn’t even have to know about it. For compatibility we support the old version a bit longer and it will emit a deprecation warning.
label – the link label connecting the current node to the node to get.
Mixin classes for ORM classes.
aiida.orm.utils.mixins.
FunctionCalculationMixin
This mixin should be used for ProcessNode subclasses that are used to record the execution of a python function. For example the process nodes that are used for a function that was wrapped by the workfunction or calcfunction function decorators. The store_source_info method can then be called with the wrapped function to store information about that function in the calculation node through the inspect module. Various property getters are defined to later retrieve that information from the node
FUNCTION_NAMESPACE_KEY
FUNCTION_NAME_KEY
FUNCTION_SOURCE_FILE_PATH
FUNCTION_STARTING_LINE_KEY
_set_function_name
Set the function name of the wrapped function.
function_name – the function name
_set_function_namespace
Set the function namespace of the wrapped function.
function_namespace – the function namespace
_set_function_starting_line_number
Set the starting line number of the wrapped function in its source file.
function_starting_line_number – the starting line number
function_name
Return the function name of the wrapped function.
the function name or None
function_namespace
Return the function namespace of the wrapped function.
the function namespace or None
function_starting_line_number
Return the starting line number of the wrapped function in its source file.
the starting line number or None
get_function_source_code
Return the absolute path to the source file in the repository.
the absolute path of the source file in the repository, or None if it does not exist
store_source_info
Retrieve source information about the wrapped function func through the inspect module, and store it in the attributes and repository of the node. The function name, namespace and the starting line number in the source file will be stored in the attributes. The source file itself will be copied into the repository
func – the function to inspect and whose information to store in the node
Sealable
Mixin to mark a Node as sealable.
SEALED_KEY
_updatable_attributes
check_mutability
Check if the node is mutable.
ModificationNotAllowed – when the node is sealed and therefore immutable.
delete_attribute
Delete an attribute.
key – name of the attribute
AttributeError – if the attribute does not exist
aiida.common.exceptions.ModificationNotAllowed – if the node is already sealed or if the node is already stored and the attribute is not updatable.
delete_object
Delete the object from the repository.
key – fully qualified identifier for the object within the repository.
TypeError – if the path is not a string and relative path.
FileNotFoundError – if the file does not exist.
IsADirectoryError – if the object is a directory and not a file.
OSError – if the file could not be deleted.
aiida.common.exceptions.ModificationNotAllowed – when the node is sealed and therefore immutable.
is_sealed
Returns whether the node is sealed, i.e. whether the sealed attribute has been set to True.
put_object_from_file
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.
put_object_from_filelike
Store the byte contents of a file in the repository.
handle – filelike object with the byte content to be stored.
put_object_from_tree
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.
seal
Seal the node by setting the sealed attribute to True.
set_attribute
Set an attribute to the given value.
value – value of the attribute
validate_incoming
Validate adding a link of the given type from a given node to ourself.
Adding an incoming link to a sealed node is forbidden.
link_type – the link type
link_label – the link label
aiida.common.ModificationNotAllowed – if the target node (self) is sealed
validate_outgoing
Validate adding a link of the given type from ourself to a given node.
Adding an outgoing link from a sealed node is forbidden.
aiida.common.ModificationNotAllowed – if the source node (self) is sealed
Utilities to operate on Node classes.
aiida.orm.utils.node.
AbstractNodeMeta
Bases: abc.ABCMeta
abc.ABCMeta
Some python black magic to set correctly the logger also in subclasses.
Create and return a new object. See help(type) for accurate signature.
get_query_type_from_type_string
Take the type string of a Node and create the queryable type string
type_string – the plugin_type_string attribute of a Node
the type string that can be used to query for
get_type_string_from_class
Given the module and name of a class, determine the orm_class_type string, which codifies the orm class that is to be used. The returned string will always have a terminating period, which is required to query for the string in the database
class_module – module of the class
class_name – name of the class
load_node_class
Return the Node sub class that corresponds to the given type string.
type_string – the type string of the node
a sub class of Node
Utilities for operations on files on remote computers.
aiida.orm.utils.remote.
clean_remote
Recursively remove a remote folder, with the given absolute path, and all its contents. The path should be made accessible through the transport channel, which should already be open
transport – an open Transport channel
path – an absolute path on the remote made available through the transport
get_calcjob_remote_paths
Return a mapping of computer uuids to a list of remote paths, for a given set of calcjobs. The set of calcjobs will be determined by a query with filters based on the pks, past_days, older_than, computers and user arguments.
pks – onlu include calcjobs with a pk in this list
past_days – only include calcjobs created since past_days
older_than – only include calcjobs older than
computers – only include calcjobs that were ran on these computers
user – only include calcjobs of this user
mapping of computer uuid and list of remote paths, or None
Serialisation functions for AiiDA types
WARNING: Changing the representation of things here may break people’s current saved e.g. things like checkpoints and messages in the RabbitMQ queue so do so with caution. It is fine to add representers for new types though.
aiida.orm.utils.serialize.
AiiDADumper
Bases: yaml.dumper.Dumper
yaml.dumper.Dumper
Custom AiiDA yaml dumper.
Needed so that we don’t have to encode each type in the AiiDA graph hierarchy separately using a custom representer.
represent_data
yaml_representers
AiiDALoader
Bases: yaml.loader.FullLoader
yaml.loader.FullLoader
AiiDA specific yaml loader
we subclass the FullLoader which is the one that since pyyaml>=5.1 is the loader that prevents arbitrary code execution. Even though this is in principle only used internally, one could imagine someone sharing a database with a maliciously crafted process instance dump, which when reloaded could execute arbitrary code. This load prevents this: https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation
yaml_constructors
bundle_constructor
Construct an plumpy.Bundle from the representation
loader (yaml.loader.Loader) – the yaml loader
yaml.loader.Loader
bundle – the bundle representation
the mapping type
computer_constructor
Load a computer from the yaml representation.
loader – the yaml loader
computer – the yaml representation
the aiida computer
aiida.orm.Computer
deserialize
Deserialize a yaml dump that represents a serialized data structure.
no need to use yaml.safe_load here because the Loader will ensure that loading is safe.
serialized – a yaml serialized string representation
the deserialized data structure
group_constructor
Load a group from the yaml representation.
group – the yaml representation
the aiida group
aiida.orm.Group
mapping_constructor
Construct a mapping from the representation.
mapping_type – the class of the mapping to construct, must accept a dictionary as a sole constructor argument to be compatible.
mapping – the mapping representation
the reconstructed mapping
node_constructor
Load a node from the yaml representation.
node – the yaml representation
the aiida node
represent_bundle
Represent an plumpy.Bundle in yaml
tag – the yaml tag to use
dumper (yaml.dumper.Dumper) – the dumper to use
bundle – the bundle to represent
the representation
represent_computer
Represent a computer in yaml.
dumper – the dumper to use
computer (aiida.orm.Computer) – the computer to represent
represent_group
Represent a group in yaml.
group (aiida.orm.Group) – the group to represent
represent_mapping
Represent a mapping in yaml.
mapping – the mapping to represent
represent_node
Represent a node in yaml.
node (aiida.orm.nodes.node.Node) – the node to represent
serialize
Serialize the given data structure into a yaml dump.
The function supports standard data containers such as maps and lists as well as AiiDA nodes which will be serialized into strings, before the whole data structure is dumped into a string using yaml.
data – the general data to serialize
encoding – optional encoding for the serialized string
string representation of the serialized data structure or byte array if specific encoding is specified