Source code for aiida.orm.utils.links

###########################################################################
# Copyright (c), The AiiDA team. All rights reserved.                     #
# This file is part of the AiiDA code.                                    #
#                                                                         #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida-core #
# For further information on the license, see the LICENSE.txt file        #
# For further information please visit http://www.aiida.net               #
###########################################################################
"""Utilities for dealing with links between nodes."""

from collections import OrderedDict
from collections.abc import Mapping
from typing import TYPE_CHECKING, Generator, Iterator, List, NamedTuple, Optional

from aiida.common import exceptions
from aiida.common.lang import type_check

if TYPE_CHECKING:
    from aiida.common.links import LinkType
    from aiida.orm import Node
    from aiida.orm.implementation.storage_backend import StorageBackend

__all__ = ('LinkPair', 'LinkTriple', 'LinkManager', 'validate_link')


[docs] class LinkPair(NamedTuple): link_type: 'LinkType' link_label: str
[docs] class LinkTriple(NamedTuple): node: 'Node' link_type: 'LinkType' link_label: str
[docs] class LinkQuadruple(NamedTuple): source_id: int target_id: int link_type: 'LinkType' link_label: str
[docs] class 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. """
[docs] def __init__(self, link_triples: List[LinkTriple]): """Initialise the collection.""" self.link_triples = link_triples
[docs] def __iter__(self) -> Iterator[LinkTriple]: """Return an iterator of LinkTriple instances. :return: iterator of LinkTriple instances """ return iter(self.link_triples)
[docs] def __next__(self) -> Generator[LinkTriple, None, None]: """Return the next element in the iterator. :return: LinkTriple """ for link_triple in self.link_triples: yield link_triple
[docs] def __bool__(self): return bool(len(self.link_triples))
[docs] def next(self) -> Generator[LinkTriple, None, None]: """Return the next element in the iterator. :return: LinkTriple """ return self.__next__()
[docs] def one(self) -> LinkTriple: """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 """ if self.link_triples: if len(self.link_triples) > 1: raise ValueError('more than one entry found') return self.link_triples[0] raise ValueError('no entries found')
[docs] def first(self) -> Optional[LinkTriple]: """Return the first entry from the iterator. :return: LinkTriple instance or None if no entries were matched """ if self.link_triples: return self.link_triples[0] return None
[docs] def all(self) -> List[LinkTriple]: """Return all entries from the list. :return: list of LinkTriple instances """ return self.link_triples
[docs] def all_nodes(self) -> List['Node']: """Return a list of all nodes. :return: list of nodes """ return [entry.node for entry in self.all()]
[docs] def get_node_by_label(self, label: str) -> 'Node': """Return the node from list for given label. :return: node that corresponds to the given label :raises aiida.common.NotExistent: if the label is not present among the link_triples """ matching_entry = None for entry in self.link_triples: if entry.link_label == label: if matching_entry is None: matching_entry = entry.node else: raise exceptions.MultipleObjectsError(f'more than one neighbor with the label {label} found') if matching_entry is None: raise exceptions.NotExistent(f'no neighbor with the label {label} found') return matching_entry
[docs] def nested(self, sort=True): """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. :return: dictionary of nested namespaces :raises KeyError: if there are duplicate link labels in a namespace """ from aiida.engine.processes.ports import PORT_NAMESPACE_SEPARATOR nested: dict = {} for entry in self.link_triples: current_namespace = nested breadcrumbs = entry.link_label.split(PORT_NAMESPACE_SEPARATOR) # The last element is the "leaf" port name the preceding elements are nested port namespaces port_name = breadcrumbs[-1] port_namespaces = breadcrumbs[:-1] # Get the nested namespace for subspace in port_namespaces: current_namespace = current_namespace.setdefault(subspace, {}) # Insert the node at the given port name if port_name in current_namespace: raise KeyError(f"duplicate label '{port_name}' in namespace '{'.'.join(port_namespaces)}'") current_namespace[port_name] = entry.node if sort: return OrderedDict(sorted(nested.items(), key=lambda x: (not isinstance(x[1], Mapping), x))) return nested