aiida.tools

Tools to operate on AiiDA ORM class instances

What functionality should go directly in the ORM class in aiida.orm and what in aiida.tools?

  • The ORM class should define basic functions to set and get data from the object

  • More advanced functionality to operate on the ORM class instances can be placed in aiida.tools

    to prevent the ORM namespace from getting too cluttered.

Note

Modules in this sub package may require the database environment to be loaded

Package Contents

Classes

CalculationTools

Base class for CalculationTools.

Graph

a class to create graphviz graphs of the AiiDA node provenance

GroupPath

A class to provide label delimited access to groups.

Orbital

Base class for Orbitals. Can handle certain basic fields, their setting and validation. More complex Orbital objects should then inherit from this class

RealhydrogenOrbital

Orbitals for hydrogen, largely follows the conventions used by wannier90 Object to handle the generation of real hydrogen orbitals and their hybrids, has methods for producing s, p, d, f, and sp, sp2, sp3, sp3d, sp3d2 hybrids. This method does not deal with the cannonical hydrogen orbitals which contain imaginary components.

Functions

default_link_styles

map link_pair to a graphviz edge style

default_node_styles

map a node to a graphviz node style

default_node_sublabels

function mapping nodes to a sublabel (e.g. specifying some attribute values)

delete_group_nodes

Delete nodes contained in a list of groups (not the groups themselves!).

delete_nodes

Delete nodes given a list of “starting” PKs.

get_explicit_kpoints_path

Returns a dictionary whose contents depend on the method but includes at least the following keys

get_kpoints_path

Returns a dictionary whose contents depend on the method but includes at least the following keys

pstate_node_styles

map a process node to a graphviz node style

spglib_tuple_to_structure

Convert a tuple of the format (cell, scaled_positions, element_numbers) to an AiiDA structure.

structure_to_spglib_tuple

Convert an AiiDA structure to a tuple of the format (cell, scaled_positions, element_numbers).

Data

API

class aiida.tools.CalculationTools(node)

Base class for CalculationTools.

Initialization

aiida.tools.DELETE_LOGGER = 'getChild(...)'
class aiida.tools.Graph(engine=None, graph_attr=None, global_node_style=None, global_edge_style=None, include_sublabels=True, link_style_fn=None, node_style_fn=None, node_sublabel_fn=None, node_id_type='pk', backend: Optional[aiida.orm.implementation.StorageBackend] = None)

a class to create graphviz graphs of the AiiDA node provenance

Initialization

a class to create graphviz graphs of the AiiDA node provenance

Nodes and edges, are cached, so that they are only created once

Parameters:
  • engine (str or None) – the graphviz engine, e.g. dot, circo (Default value = None)

  • graph_attr (dict or None) – attributes for the graphviz graph (Default value = None)

  • global_node_style (dict or None) – styles which will be added to all nodes. Note this will override any builtin attributes (Default value = None)

  • global_edge_style (dict or None) – styles which will be added to all edges. Note this will override any builtin attributes (Default value = None)

  • include_sublabels (bool) – if True, the note text will include node dependant sub-labels (Default value = True)

  • link_style_fn – callable mapping LinkType to graphviz style dict; link_style_fn(link_type) -> dict (Default value = None)

  • node_sublabel_fn – callable mapping nodes to a graphviz style dict; node_sublabel_fn(node) -> dict (Default value = None)

  • node_sublabel_fn – callable mapping data node to a sublabel (e.g. specifying some attribute values) node_sublabel_fn(node) -> str (Default value = None)

  • node_id_type (str) – the type of identifier to within the node text (‘pk’, ‘uuid’ or ‘label’)

property backend: aiida.orm.implementation.StorageBackend

The backend used to create the graph

property graphviz

return a copy of the graphviz.Digraph

property nodes

return a copy of the nodes

property edges

return a copy of the edges

_load_node(node)

load a node (if not already loaded)

Parameters:

node (int or str or aiida.orm.nodes.node.Node) – node or node pk/uuid

Returns:

aiida.orm.nodes.node.Node

If link_types is empty, it will return all the links_types

Parameters:

links – iterable with the link_types ()

Returns:

list of aiida.common.links.LinkType

add_node(node, style_override=None, overwrite=False)

add single node to the graph

Parameters:
  • node (int or str or aiida.orm.nodes.node.Node) – node or node pk/uuid

  • style_override (dict or None) – graphviz style parameters that will override default values

  • overwrite (bool) – whether to overrite an existing node (Default value = False)

add_edge(in_node, out_node, link_pair=None, style=None, overwrite=False)

add single node to the graph

Parameters:

convert link types, which may be strings, to a member of LinkType

add_incoming(node, link_types=(), annotate_links=None, return_pks=True)

add nodes and edges for incoming links to a node

Parameters:
Returns:

list of nodes or node pks

add_outgoing(node, link_types=(), annotate_links=None, return_pks=True)

add nodes and edges for outgoing links to a node

Parameters:
Returns:

list of nodes or node pks

recurse_descendants(origin, depth=None, link_types=(), annotate_links=False, origin_style=MappingProxyType(_OVERRIDE_STYLES_DICT['origin_node']), include_process_inputs=False, highlight_classes=None)

add nodes and edges from an origin recursively, following outgoing links

Parameters:
  • origin (aiida.orm.nodes.node.Node or int) – node or node pk/uuid

  • depth (None or int) – if not None, stop after travelling a certain depth into the graph (Default value = None)

  • link_types (tuple or str) – filter by subset of link types (Default value = ())

  • annotate_links (bool or str) – label edges with the link ‘label’, ‘type’ or ‘both’ (Default value = False)

  • origin_style (None or dict) – node style map for origin node (Default value = None)

  • include_calculation_inputs (bool) – include incoming links for all processes (Default value = False)

  • highlight_classes – target class in exported graph expected to be highlight and other nodes are decolorized (Default value = None)

Typle highlight_classes:

tuple of class or class

recurse_ancestors(origin, depth=None, link_types=(), annotate_links=False, origin_style=MappingProxyType(_OVERRIDE_STYLES_DICT['origin_node']), include_process_outputs=False, highlight_classes=None)

add nodes and edges from an origin recursively, following incoming links

Parameters:
  • origin (aiida.orm.nodes.node.Node or int) – node or node pk/uuid

  • depth (None or int) – if not None, stop after travelling a certain depth into the graph (Default value = None)

  • link_types (tuple or str) – filter by subset of link types (Default value = ())

  • annotate_links (bool) – label edges with the link ‘label’, ‘type’ or ‘both’ (Default value = False)

  • origin_style (None or dict) – node style map for origin node (Default value = None)

  • include_process_outputs (bool) – include outgoing links for all processes (Default value = False)

  • highlight_classes – class label (as displayed in the graph, e.g. ‘StructureData’, ‘FolderData’, etc.) to be highlight and other nodes are decolorized (Default value = None)

Typle highlight_classes:

list or tuple of str

add_origin_to_targets(origin, target_cls, target_filters=None, include_target_inputs=False, include_target_outputs=False, origin_style=(), annotate_links=False)

Add nodes and edges from an origin node to all nodes of a target node class.

Parameters:
  • origin (aiida.orm.nodes.node.Node or int) – node or node pk/uuid

  • target_cls – target node class

  • target_filters (dict or None) – (Default value = None)

  • include_target_inputs (bool) – (Default value = False)

  • include_target_outputs (bool) – (Default value = False)

  • origin_style (dict or tuple) – node style map for origin node (Default value = ())

  • annotate_links (bool) – label edges with the link ‘label’, ‘type’ or ‘both’ (Default value = False)

add_origins_to_targets(origin_cls, target_cls, origin_filters=None, target_filters=None, include_target_inputs=False, include_target_outputs=False, origin_style=(), annotate_links=False)

Add nodes and edges from all nodes of an origin class to all node of a target node class.

Parameters:
  • origin_cls – origin node class

  • target_cls – target node class

  • origin_filters (dict or None) – (Default value = None)

  • target_filters (dict or None) – (Default value = None)

  • include_target_inputs (bool) – (Default value = False)

  • include_target_outputs (bool) – (Default value = False)

  • origin_style (dict or tuple) – node style map for origin node (Default value = ())

  • annotate_links (bool) – label edges with the link ‘label’, ‘type’ or ‘both’ (Default value = False)

exception aiida.tools.GroupNotFoundError(grouppath)

Bases: Exception

An exception raised when a path does not have an associated group.

Initialization

Initialize self. See help(type(self)) for accurate signature.

exception aiida.tools.GroupNotUniqueError(grouppath)

Bases: Exception

An exception raised when a path has multiple associated groups.

Initialization

Initialize self. See help(type(self)) for accurate signature.

class aiida.tools.GroupPath(path: str = '', cls: aiida.orm.groups.GroupMeta = orm.Group, warn_invalid_child: bool = True)

A class to provide label delimited access to groups.

See tests for usage examples.

Initialization

Instantiate the class.

Parameters:
  • path – The initial path of the group.

  • cls – The subclass of Group to operate on.

  • warn_invalid_child – Issue a warning, when iterating children, if a child path is invalid.

_validate_path(path)

Validate the supplied path.

__repr__() str

Represent the instantiated class.

__eq__(other: Any) bool

Compare equality of path and Group subclass to another GroupPath object.

__lt__(other: Any) bool

Compare less-than operator of path and Group subclass to another GroupPath object.

property path: str

Return the path string.

property path_list: List[str]

Return a list of the path components.

property key: Optional[str]

Return the final component of the the path.

property delimiter: str

Return the delimiter used to split path into components.

property cls: aiida.orm.groups.GroupMeta

Return the cls used to query for and instantiate a Group with.

property parent: Optional[aiida.tools.groups.paths.GroupPath]

Return the parent path.

__truediv__(path: str) aiida.tools.groups.paths.GroupPath

Return a child GroupPath, with a new path formed by appending path to the current path.

__getitem__(path: str) aiida.tools.groups.paths.GroupPath

Return a child GroupPath, with a new path formed by appending path to the current path.

get_group() Optional[aiida.tools.groups.paths.GroupPath]

Return the concrete group associated with this path.

property group_ids: List[int]

Return all the UUID associated with this GroupPath.

Returns:

and empty list, if no group associated with this label, or can be multiple if cls was None

This is an efficient method for checking existence, which does not require the (slow) loading of the ORM entity.

property is_virtual: bool

Return whether there is one or more concrete groups associated with this path.

get_or_create_group() Tuple[aiida.orm.Group, bool]

Return the concrete group associated with this path or, create it, if it does not already exist.

delete_group()

Delete the concrete group associated with this path.

Raises:

GroupNotFoundError, GroupNotUniqueError

property children: Iterator[aiida.tools.groups.paths.GroupPath]

Iterate through all (direct) children of this path.

__iter__() Iterator[aiida.tools.groups.paths.GroupPath]

Iterate through all (direct) children of this path.

__len__() int

Return the number of children for this path.

__contains__(key: str) bool

Return whether a child exists for this key.

walk(return_virtual: bool = True) Iterator[aiida.tools.groups.paths.GroupPath]

Recursively iterate through all children of this path.

walk_nodes(filters: Optional[dict] = None, node_class: Optional[aiida.orm.Node] = None, query_batch: Optional[int] = None) Iterator[aiida.tools.groups.paths.WalkNodeResult]

Recursively iterate through all nodes of this path and its children.

Parameters:
  • filters – filters to apply to the node query

  • node_class – return only nodes of a certain class (or list of classes)

  • query_batch – The size of the batches to ask the backend to batch results in subcollections. You can optimize the speed of the query by tuning this parameter. Be aware though that is only safe if no commit will take place during this transaction.

property browse

Return a GroupAttr instance, for attribute access to children.

exception aiida.tools.InvalidPath

Bases: Exception

An exception to indicate that a path is not valid.

Initialization

Initialize self. See help(type(self)) for accurate signature.

exception aiida.tools.NoGroupsInPathError(grouppath)

Bases: Exception

An exception raised when a path has multiple associated groups.

Initialization

Initialize self. See help(type(self)) for accurate signature.

class aiida.tools.Orbital(**kwargs)

Base class for Orbitals. Can handle certain basic fields, their setting and validation. More complex Orbital objects should then inherit from this class

Parameters:
  • position – the absolute position (three floats) units in angstrom

  • x_orientation – x,y,z unit vector defining polar angle theta in spherical coordinates unitless

  • z_orientation – x,y,z unit vector defining azimuthal angle phi in spherical coordinates unitless

  • orientation_spin – x,y,z unit vector defining the spin orientation unitless

  • diffusivity – Float controls the radial term in orbital equation units are reciprocal Angstrom.

Initialization

_base_fields_required = (('position',),)
_base_fields_optional = 'tuple(...)'
__repr__()
__str__() str
_validate_keys(input_dict)

Checks all the input_dict and tries to validate them, to ensure that they have been properly set raises Exceptions indicating any problems that should arise during the validation

Parameters:

input_dict – a dictionary of inputs

Returns:

input_dict: the original dictionary with all validated kyes now removed

Returns:

validated_dict: a dictionary containing all the input keys which have now been validated.

set_orbital_dict(init_dict)

Sets the orbital_dict, which can vary depending on the particular implementation of this base class.

Parameters:

init_dict – the initialization dictionary

get_orbital_dict()

returns the internal keys as a dictionary

class aiida.tools.RealhydrogenOrbital(**kwargs)

Bases: aiida.tools.data.orbital.orbital.Orbital

Orbitals for hydrogen, largely follows the conventions used by wannier90 Object to handle the generation of real hydrogen orbitals and their hybrids, has methods for producing s, p, d, f, and sp, sp2, sp3, sp3d, sp3d2 hybrids. This method does not deal with the cannonical hydrogen orbitals which contain imaginary components.

The orbitals described here are chiefly concerned with the symmetric aspects of the oribitals without the context of space. Therefore diffusitivity, position and atomic labels should be handled in the OrbitalData class.

Following the notation of table 3.1, 3.2 of Wannier90 user guide (which can be downloaded from http://www.wannier.org/support/) A brief description of what is meant by each of these labels:

Parameters:
  • radial_nodes – the number of radial nodes (or inflections) if no radial nodes are supplied, defaults to 0

  • angular_momentum – Angular quantum number, using real orbitals

  • magnetic_number – Magnetic quantum number, using real orbitals

  • spin – spin, up (1) down (-1) or unspecified (0)

The conventions regarding L and M correpsond to those used in wannier90 for all L greater than 0 the orbital is not hyrbridized see table 3.1 and for L less than 0 the orbital is hybridized see table 3.2. M then indexes all the possible orbitals from 0 to 2L for L > 0 and from 0 to (-L) for L < 0.

Initialization

_base_fields_required = 'tuple(...)'
_base_fields_optional = 'tuple(...)'
__str__()
_validate_keys(input_dict)

Validates the keys otherwise raise ValidationError. Does basic validation from the parent followed by validations for the quantum numbers. Raises exceptions should the input_dict fail the valiation or if it contains any unsupported keywords.

Parameters:

input_dict – the dictionary of keys to be validated

Return validated_dict:

a validated dictionary

classmethod get_name_from_quantum_numbers(angular_momentum, magnetic_number=None)

Returns the orbital_name correponding to the angular_momentum alone, or to both angular_number with magnetic_number. For example using angular_momentum=1 and magnetic_number=1 will return “Px”

classmethod get_quantum_numbers_from_name(name)

Returns all the angular and magnetic numbers corresponding to name. For example, using “P” as name will return all quantum numbers associated with a “P” orbital, while “Px” will return only one set of quantum numbers, the ones associated with “Px”

map link_pair to a graphviz edge style

Parameters:
Return type:

dict

aiida.tools.default_node_styles(node)

map a node to a graphviz node style

Parameters:

node (aiida.orm.nodes.node.Node) – the node to map

Return type:

dict

aiida.tools.default_node_sublabels(node)

function mapping nodes to a sublabel (e.g. specifying some attribute values)

Parameters:

node (aiida.orm.nodes.node.Node) – the node to map

Return type:

str

aiida.tools.delete_group_nodes(pks: Iterable[int], dry_run: Union[bool, Callable[[Set[int]], bool]] = True, backend=None, **traversal_rules: bool) Tuple[Set[int], bool]

Delete nodes contained in a list of groups (not the groups themselves!).

This command will delete not only the nodes, but also the ones that are linked to these and should be also deleted in order to keep a consistent provenance according to the rules explained in the concepts section of the documentation. In summary:

  1. If a DATA node is deleted, any process nodes linked to it will also be deleted.

2. If a CALC node is deleted, any incoming WORK node (callers) will be deleted as well whereas any incoming DATA node (inputs) will be kept. Outgoing DATA nodes (outputs) will be deleted by default but this can be disabled.

3. If a WORK node is deleted, any incoming WORK node (callers) will be deleted as well, but all DATA nodes will be kept. Outgoing WORK or CALC nodes will be kept by default, but deletion of either of both kind of connected nodes can be enabled.

These rules are ‘recursive’, so if a CALC node is deleted, then its output DATA nodes will be deleted as well, and then any CALC node that may have those as inputs, and so on.

Parameters:
  • pks – a list of the groups

  • dry_run – If True, return the pks to delete without deleting anything. If False, delete the pks without confirmation If callable, a function that return True/False, based on the pks, e.g. dry_run=lambda pks: True

  • traversal_rules – graph traversal rules. See aiida.common.links.GraphTraversalRules what rule names are toggleable and what the defaults are.

Returns:

(node pks to delete, whether they were deleted)

aiida.tools.delete_nodes(pks: Iterable[int], dry_run: Union[bool, Callable[[Set[int]], bool]] = True, backend=None, **traversal_rules: bool) Tuple[Set[int], bool]

Delete nodes given a list of “starting” PKs.

This command will delete not only the specified nodes, but also the ones that are linked to these and should be also deleted in order to keep a consistent provenance according to the rules explained in the Topics - Provenance section of the documentation. In summary:

  1. If a DATA node is deleted, any process nodes linked to it will also be deleted.

2. If a CALC node is deleted, any incoming WORK node (callers) will be deleted as well whereas any incoming DATA node (inputs) will be kept. Outgoing DATA nodes (outputs) will be deleted by default but this can be disabled.

3. If a WORK node is deleted, any incoming WORK node (callers) will be deleted as well, but all DATA nodes will be kept. Outgoing WORK or CALC nodes will be kept by default, but deletion of either of both kind of connected nodes can be enabled.

These rules are ‘recursive’, so if a CALC node is deleted, then its output DATA nodes will be deleted as well, and then any CALC node that may have those as inputs, and so on.

Parameters:
  • pks – a list of starting PKs of the nodes to delete (the full set will be based on the traversal rules)

  • dry_run – If True, return the pks to delete without deleting anything. If False, delete the pks without confirmation If callable, a function that return True/False, based on the pks, e.g. dry_run=lambda pks: True

  • traversal_rules – graph traversal rules. See aiida.common.links.GraphTraversalRules for what rule names are toggleable and what the defaults are.

Returns:

(pks to delete, whether they were deleted)

aiida.tools.get_explicit_kpoints_path(structure, method='seekpath', **kwargs)

Returns a dictionary whose contents depend on the method but includes at least the following keys

  • parameters: Dict node

  • explicit_kpoints: KpointsData node with explicit kpoints path

The contents of the parameters depends on the method but contains at least the keys

  • ‘point_coords’: a dictionary with ‘kpoints-label’: [float coordinates]

  • ‘path’: a list of length-2 tuples, with the labels of the starting

    and ending point of each label section

The ‘seekpath’ method which is the default also returns the following additional nodes

  • primitive_structure: StructureData with the primitive cell

  • conv_structure: StructureData with the conventional cell

Note that the generated kpoints for the seekpath method only apply on the returned primitive_structure and not on the input structure that was provided

Parameters:
  • structure – a StructureData node

  • method – the method to use for kpoint generation, options are ‘seekpath’ and ‘legacy’. It is strongly advised to use the default ‘seekpath’ as the ‘legacy’ implementation is known to have bugs for certain structure cells

  • kwargs – optional keyword arguments that depend on the selected method

Returns:

dictionary as described above in the docstring

aiida.tools.get_kpoints_path(structure, method='seekpath', **kwargs)

Returns a dictionary whose contents depend on the method but includes at least the following keys

  • parameters: Dict node

The contents of the parameters depends on the method but contains at least the keys

  • ‘point_coords’: a dictionary with ‘kpoints-label’: [float coordinates]

  • ‘path’: a list of length-2 tuples, with the labels of the starting

    and ending point of each label section

The ‘seekpath’ method which is the default also returns the following additional nodes

  • primitive_structure: StructureData with the primitive cell

  • conv_structure: StructureData with the conventional cell

Note that the generated kpoints for the seekpath method only apply on the returned primitive_structure and not on the input structure that was provided

Parameters:
  • structure – a StructureData node

  • method – the method to use for kpoint generation, options are ‘seekpath’ and ‘legacy’. It is strongly advised to use the default ‘seekpath’ as the ‘legacy’ implementation is known to have bugs for certain structure cells

  • kwargs – optional keyword arguments that depend on the selected method

Returns:

dictionary as described above in the docstring

aiida.tools.pstate_node_styles(node)

map a process node to a graphviz node style

Parameters:

node (aiida.orm.nodes.node.Node) – the node to map

Return type:

dict

aiida.tools.spglib_tuple_to_structure(structure_tuple, kind_info=None, kinds=None)

Convert a tuple of the format (cell, scaled_positions, element_numbers) to an AiiDA structure.

Unless the element_numbers are identical to the Z number of the atoms, you should pass both kind_info and kinds, with the same format as returned by get_tuple_from_aiida_structure.

Parameters:
  • structure_tuple – the structure in format (structure_tuple, kind_info)

  • kind_info – a dictionary mapping the kind_names to the numbers used in element_numbers. If not provided, assumes {element_name: element_Z}

  • kinds – a list of the kinds of the structure.

aiida.tools.structure_to_spglib_tuple(structure)

Convert an AiiDA structure to a tuple of the format (cell, scaled_positions, element_numbers).

Parameters:

structure – the AiiDA structure

Returns:

(structure_tuple, kind_info, kinds) where structure_tuple is a tuple of format (cell, scaled_positions, element_numbers); kind_info is a dictionary mapping the kind_names to the numbers used in element_numbers. When possible, it uses the Z number of the element, otherwise it uses numbers > 1000; kinds is a list of the kinds of the structure.