aiida.orm.nodes.data package#

Module with Node sub classes for data structures.

Subpackages#

Submodules#

Data sub class to be used as a base for data containers that represent base python data types.

class aiida.orm.nodes.data.base.BaseType(value=None, **kwargs)[source]#

Bases: Data

Data sub class to be used as a base for data containers that represent base python data types.

__abstractmethods__ = frozenset({})#
__eq__(other)[source]#

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

__hash__ = None#
__init__(value=None, **kwargs)[source]#

Construct a new instance, setting the source attribute if provided as a keyword argument.

__module__ = 'aiida.orm.nodes.data.base'#
__parameters__ = ()#
__qb_fields__: Sequence[QbField] = [QbField('value', is_attribute=True)]#
__str__()[source]#

Return str(self).

_abc_impl = <_abc._abc_data object>#
_logger: Logger | None = <Logger aiida.orm.nodes.data.base.BaseType (WARNING)>#
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]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str'}#
new(value=None)[source]#
property value#
aiida.orm.nodes.data.base.to_aiida_type(value)[source]#
aiida.orm.nodes.data.base.to_aiida_type(value: ndarray)
aiida.orm.nodes.data.base.to_aiida_type(value: bool_)
aiida.orm.nodes.data.base.to_aiida_type(value: bool)
aiida.orm.nodes.data.base.to_aiida_type(value: dict)
aiida.orm.nodes.data.base.to_aiida_type(value: Enum)
aiida.orm.nodes.data.base.to_aiida_type(value: Real)
aiida.orm.nodes.data.base.to_aiida_type(value: Integral)
aiida.orm.nodes.data.base.to_aiida_type(value: list)
aiida.orm.nodes.data.base.to_aiida_type(value: str)

Turns basic Python types (str, int, float, bool) into the corresponding AiiDA types.

Data sub class to represent a boolean value.

class aiida.orm.nodes.data.bool.Bool(value=None, **kwargs)[source]#

Bases: BaseType

Data sub class to represent a boolean value.

__abstractmethods__ = frozenset({})#
__bool__()[source]#
__int__()[source]#
__module__ = 'aiida.orm.nodes.data.bool'#
__parameters__ = ()#
__plugin_type_string: ClassVar[str]#
__query_type_string: ClassVar[str]#
_abc_impl = <_abc._abc_data object>#
_logger: Logger | None = <Logger aiida.orm.nodes.data.bool.Bool (WARNING)>#
_type#

alias of bool

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]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str',  'value': 'QbField(attributes.value) -> bool'}#
aiida.orm.nodes.data.bool._(value)[source]#
aiida.orm.nodes.data.bool.get_false_node()[source]#

Return a Bool node with value False

Note

this function serves as a substitute for defining the node as a module singleton, because that would be instantiated at import time, at which time not all required database resources may be defined.

Returns:

a Bool instance with the value False

aiida.orm.nodes.data.bool.get_true_node()[source]#

Return a Bool node with value True

Note

this function serves as a substitute for defining the node as a module singleton, because that would be instantiated at import time, at which time not all required database resources may be defined.

Returns:

a Bool instance with the value True

Tools for handling Crystallographic Information Files (CIF)

class aiida.orm.nodes.data.cif.CifData(ase=None, file=None, filename=None, values=None, scan_type=None, parse_policy=None, **kwargs)[source]#

Bases: SinglefileData

Wrapper for Crystallographic Interchange File (CIF)

Note

the file (physical) is held as the authoritative source of information, so all conversions are done through the physical file: when setting ase or values, a physical CIF file is generated first, the values are updated from the physical CIF file.

_PARSE_POLICIES = ('eager', 'lazy')#
_PARSE_POLICY_DEFAULT = 'eager'#
_SCAN_TYPES = ('standard', 'flex')#
_SCAN_TYPE_DEFAULT = 'standard'#
_SET_INCOMPATIBILITIES = [('ase', 'file'), ('ase', 'values'), ('file', 'values')]#
__abstractmethods__ = frozenset({})#
__init__(ase=None, file=None, filename=None, values=None, scan_type=None, parse_policy=None, **kwargs)[source]#

Construct a new instance and set the contents to that of the file.

Parameters:
  • file – an absolute filepath or filelike object for CIF. Hint: Pass io.BytesIO(b”my string”) to construct the SinglefileData directly from a string.

  • filename – specify filename to use (defaults to name of provided file).

  • ase – ASE Atoms object to construct the CifData instance from.

  • values – PyCifRW CifFile object to construct the CifData instance from.

  • scan_type – scan type string for parsing with PyCIFRW (‘standard’ or ‘flex’). See CifFile.ReadCif

  • parse_policy – ‘eager’ (parse CIF file on set_file) or ‘lazy’ (defer parsing until needed)

__module__ = 'aiida.orm.nodes.data.cif'#
__parameters__ = ()#
__qb_fields__: Sequence[QbField] = [QbArrayField('formulae', dtype=List[str], is_attribute=True), QbArrayField('spacegroup_numbers', dtype=List[str], is_attribute=True), QbStrField('md5', dtype=str, is_attribute=True)]#
_abc_impl = <_abc._abc_data object>#
_ase = None#
_get_object_ase()[source]#

Converts CifData to ase.Atoms

Returns:

an ase.Atoms object

_get_object_pycifrw()[source]#

Converts CifData to PyCIFRW.CifFile

Returns:

a PyCIFRW.CifFile object

_logger: Logger | None = <Logger aiida.orm.nodes.data.cif.CifData (WARNING)>#
_prepare_cif(**kwargs)[source]#

Return CIF string of CifData object.

If parsed values are present, a CIF string is created and written to file. If no parsed values are present, the CIF string is read from file.

_validate()[source]#

Validates MD5 hash of CIF file.

_values = None#
property ase#

ASE object, representing the CIF.

Note

requires ASE module.

fields: QbFields = {'attributes': 'QbDictField(attributes.*) -> Dict[str, Any]',  'ctime': 'QbNumericField(ctime) -> datetime',  'description': 'QbStrField(description) -> str',  'extras': 'QbDictField(extras.*) -> Dict[str, Any]',  'formulae': 'QbArrayField(attributes.formulae) -> List[str]',  'label': 'QbStrField(label) -> str',  'md5': 'QbStrField(attributes.md5) -> str',  'mtime': 'QbNumericField(mtime) -> datetime',  'node_type': 'QbStrField(node_type) -> str',  'pk': 'QbNumericField(pk) -> int',  'repository_metadata': 'QbDictField(repository_metadata) -> Dict[str, Any]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'spacegroup_numbers': 'QbArrayField(attributes.spacegroup_numbers) -> '                        'List[str]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str'}#
classmethod from_md5(md5, backend=None)[source]#

Return a list of all CIF files that match a given MD5 hash.

Note

the hash has to be stored in a _md5 attribute, otherwise the CIF file will not be found.

generate_md5()[source]#

Computes and returns MD5 hash of the CIF file.

get_ase(**kwargs)[source]#

Returns ASE object, representing the CIF. This function differs from the property ase by the possibility to pass the keyworded arguments (kwargs) to ase.io.cif.read_cif().

Note

requires ASE module.

get_formulae(mode='sum', custom_tags=None)[source]#

Return chemical formulae specified in CIF file.

Note: This does not compute the formula, it only reads it from the appropriate tag. Use refine_inline to compute formulae.

classmethod get_or_create(filename, use_first=False, store_cif=True)[source]#

Pass the same parameter of the init; if a file with the same md5 is found, that CifData is returned.

Parameters:
  • filename – an absolute filename on disk

  • use_first – if False (default), raise an exception if more than one CIF file is found. If it is True, instead, use the first available CIF file.

  • store_cif (bool) – If false, the CifData objects are not stored in the database. default=True.

Return (cif, created):

where cif is the CifData object, and create is either True if the object was created, or False if the object was retrieved from the DB.

get_spacegroup_numbers()[source]#

Get the spacegroup international number.

get_structure(converter='pymatgen', store=False, **kwargs)[source]#

Creates aiida.orm.nodes.data.structure.StructureData.

Parameters:
  • converter – specify the converter. Default ‘pymatgen’.

  • store – if True, intermediate calculation gets stored in the AiiDA database for record. Default False.

  • primitive_cell – if True, primitive cell is returned, conventional cell if False. Default False.

  • occupancy_tolerance – If total occupancy of a site is between 1 and occupancy_tolerance, the occupancies will be scaled down to 1. (pymatgen only)

  • site_tolerance – This tolerance is used to determine if two sites are sitting in the same position, in which case they will be combined to a single disordered site. Defaults to 1e-4. (pymatgen only)

Returns:

aiida.orm.nodes.data.structure.StructureData node.

property has_atomic_sites#

Returns whether there are any atomic sites defined in the cif data. That is to say, it will check all the values for the _atom_site_fract_* tags and if they are all equal to ? that means there are no relevant atomic sites defined and the function will return False. In all other cases the function will return True

Returns:

False when at least one atomic site fractional coordinate is not equal to ? and True otherwise

property has_attached_hydrogens#

Check if there are hydrogens without coordinates, specified as attached to the atoms of the structure.

Returns:

True if there are attached hydrogens, False otherwise.

property has_partial_occupancies#

Return if the cif data contains partial occupancies

A partial occupancy is defined as site with an occupancy that differs from unity, within a precision of 1E-6

Returns:

True if there are partial occupancies, False otherwise

property has_undefined_atomic_sites#

Return whether the cif data contains any undefined atomic sites.

An undefined atomic site is defined as a site where at least one of the fractional coordinates specified in the _atom_site_fract_* tags, cannot be successfully interpreted as a float. If the cif data contains any site that matches this description, or it does not contain any atomic site tags at all, the cif data is said to have undefined atomic sites.

Returns:

boolean, True if no atomic sites are defined or if any of the defined sites contain undefined positions and False otherwise

property has_unknown_species#

Returns whether the cif contains atomic species that are not recognized by AiiDA.

The known species are taken from the elements dictionary in aiida.common.constants, with the exception of the “unknown” placeholder element with symbol ‘X’, as this could not be used to construct a real structure. If any of the formula of the cif data contain species that are not in that elements dictionary, the function will return True and False in all other cases. If there is no formulae to be found, it will return None

Returns:

True when there are unknown species in any of the formulae, False if not, None if no formula found

parse(scan_type=None)[source]#

Parses CIF file and sets attributes.

Parameters:

scan_type – See set_scan_type

static read_cif(fileobj, index=-1, **kwargs)[source]#

A wrapper method that simulates the behavior of the old function ase.io.cif.read_cif by using the new generic ase.io.read function.

Somewhere from 3.12 to 3.17 the tag concept was bundled with each Atom object. When reading a CIF file, this is incremented and signifies the atomic species, even though the CIF file do not have specific tags embedded. On reading CIF files we thus force the ASE tag to zero for all Atom elements.

set_ase(aseatoms)[source]#

Set the contents of the CifData starting from an ASE atoms object

Parameters:

aseatoms – the ASE atoms object

set_file(file, filename=None)[source]#

Set the file.

If the source is set and the MD5 checksum of new file is different from the source, the source has to be deleted.

Parameters:
  • file – filepath or filelike object of the CIF file to store. Hint: Pass io.BytesIO(b”my string”) to construct the file directly from a string.

  • filename – specify filename to use (defaults to name of provided file).

set_parse_policy(parse_policy)[source]#

Set the parse policy.

Parameters:

parse_policy – Either ‘eager’ (parse CIF file on set_file) or ‘lazy’ (defer parsing until needed)

set_scan_type(scan_type)[source]#

Set the scan_type for PyCifRW.

The ‘flex’ scan_type of PyCifRW is faster for large CIF files but does not yet support the CIF2 format as of 02/2018. See the CifFile.ReadCif function

Parameters:

scan_type – Either ‘standard’ or ‘flex’ (see _scan_types)

set_values(values)[source]#

Set internal representation to values.

Warning: This also writes a new CIF file.

Parameters:

values – PyCifRW CifFile object

Note

requires PyCifRW module.

store(*args, **kwargs)[source]#

Store the node.

property values#

PyCifRW structure, representing the CIF datablocks.

Note

requires PyCifRW module.

aiida.orm.nodes.data.cif.cif_from_ase(ase, full_occupancies=False, add_fake_biso=False)[source]#

Construct a CIF datablock from the ASE structure. The code is taken from https://wiki.fysik.dtu.dk/ase/ase/io/formatoptions.html#ase.io.cif.write_cif, as the original ASE code contains a bug in printing the Hermann-Mauguin symmetry space group symbol.

Parameters:

ase – ASE “images”

Returns:

array of CIF datablocks

aiida.orm.nodes.data.cif.has_pycifrw()[source]#
Returns:

True if the PyCifRW module can be imported, False otherwise.

aiida.orm.nodes.data.cif.parse_formula(formula)[source]#

Parses the Hill formulae. Does not need spaces as separators. Works also for partial occupancies and for chemical groups enclosed in round/square/curly brackets. Elements are counted and a dictionary is returned. e.g. ‘C[NH2]3NO3’ –> {‘C’: 1, ‘N’: 4, ‘H’: 6, ‘O’: 3}

aiida.orm.nodes.data.cif.pycifrw_from_cif(datablocks, loops=None, names=None)[source]#

Constructs PyCifRW’s CifFile from an array of CIF datablocks.

Parameters:
  • datablocks – an array of CIF datablocks

  • loops – optional dict of lists of CIF tag loops.

  • names – optional list of datablock names

Returns:

CifFile

Module with Node sub class Data to be used as a base class for data structures.

class aiida.orm.nodes.data.data.Data(*args, source=None, **kwargs)[source]#

Bases: Node

The base class for all Data nodes.

AiiDA Data classes are subclasses of Node and must support multiple inheritance.

Architecture note: Calculation plugins are responsible for converting raw output data from simulation codes to Data nodes. Nodes are responsible for validating their content (see _validate method).

__abstractmethods__ = frozenset({})#
__annotations__ = {'_CLS_COLLECTION': 'Type[CollectionType]', '__plugin_type_string': 'ClassVar[str]', '__qb_fields__': 'Sequence[QbField]', '__query_type_string': 'ClassVar[str]', '_export_format_replacements': typing.Dict[str, str], '_hash_ignored_attributes': 'Tuple[str, ...]', '_logger': 'Optional[Logger]', '_updatable_attributes': 'Tuple[str, ...]', 'fields': 'QbFields'}#
__copy__()[source]#

Copying a Data node is not supported, use copy.deepcopy or call Data.clone().

__deepcopy__(memo)[source]#

Create a clone of the Data node by piping through to the clone method and return the result.

Returns:

an unstored clone of this Data node

__init__(*args, source=None, **kwargs)[source]#

Construct a new instance, setting the source attribute if provided as a keyword argument.

__module__ = 'aiida.orm.nodes.data.data'#
__parameters__ = ()#
__qb_fields__: Sequence[QbField] = [QbDictField('source', dtype=Optional[dict], is_attribute=True, is_subscriptable=True)]#
_abc_impl = <_abc._abc_data object>#
_export_format_replacements: Dict[str, str] = {}#
_exportcontent(fileformat, main_file_name='', **kwargs)[source]#

Converts a Data node to one (or multiple) files.

Note: Export plugins should return utf8-encoded bytes, which can be directly dumped to file.

Parameters:
  • fileformat (str) – the extension, uniquely specifying the file format.

  • main_file_name (str) – (empty by default) Can be used by plugin to infer sensible names for additional files, if necessary. E.g. if the main file is ‘../myplot.gnu’, the plugin may decide to store the dat file under ‘../myplot_data.dat’.

  • kwargs – other parameters are passed down to the plugin

Returns:

a tuple of length 2. The first element is the content of the otuput file. The second is a dictionary (possibly empty) in the format {filename: filecontent} for any additional file that should be produced.

Return type:

(bytes, dict)

_get_converters()[source]#

Get all implemented converter formats. The convention is to find all _get_object_… methods. Returns a list of strings.

_get_exporters()[source]#

Get all implemented export formats. The convention is to find all _prepare_… methods. Returns a dictionary of method_name: method_function

_get_importers()[source]#

Get all implemented import formats. The convention is to find all _parse_… methods. Returns a list of strings.

_logger: Logger | None = <Logger aiida.orm.nodes.data.data.Data (WARNING)>#
_source_attributes = ['db_name', 'db_uri', 'uri', 'id', 'version', 'extras', 'source_md5', 'description', 'license']#
_storable = True#
_unstorable_message = 'storing for this node has been disabled'#
clone()[source]#

Create a clone of the Data node.

Returns:

an unstored clone of this Data node

convert(object_format=None, *args)[source]#

Convert the AiiDA StructureData into another python object

Parameters:

object_format – Specify the output format

property creator#

Return the creator of this node or None if it does not exist.

Returns:

the creating node or None

export(path, fileformat=None, overwrite=False, **kwargs)[source]#

Save a Data object to a file.

Parameters:
  • fname – string with file name. Can be an absolute or relative path.

  • fileformat – kind of format to use for the export. If not present, it will try to use the extension of the file name.

  • overwrite – if set to True, overwrites file found at path. Default=False

  • kwargs – additional parameters to be passed to the _exportcontent method

Returns:

the list of files created

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]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str'}#
classmethod get_export_formats()[source]#

Get the list of valid export format strings

Returns:

a list of valid formats

importfile(fname, fileformat=None)[source]#

Populate a Data object from a file.

Parameters:
  • fname – string with file name. Can be an absolute or relative path.

  • fileformat – kind of format to use for the export. If not present, it will try to use the extension of the file name.

importstring(inputstring, fileformat, **kwargs)[source]#

Converts a Data object to other text format.

Parameters:

fileformat – a string (the extension) to describe the file format.

Returns:

a string with the structure description.

set_source(source)[source]#

Sets the dictionary describing the source of Data object.

property source: dict | None#

Gets the dictionary describing the source of Data object. Possible fields:

  • db_name: name of the source database.

  • db_uri: URI of the source database.

  • uri: URI of the object’s source. Should be a permanent link.

  • id: object’s source identifier in the source database.

  • version: version of the object’s source.

  • extras: a dictionary with other fields for source description.

  • source_md5: MD5 checksum of object’s source.

  • description: human-readable free form description of the object’s source.

  • license: a string with a type of license.

Note

some limitations for setting the data source exist, see _validate method.

Returns:

dictionary describing the source of Data object.

Data sub class to represent a dictionary.

class aiida.orm.nodes.data.dict.Dict(value=None, **kwargs)[source]#

Bases: Data

Data sub class to represent a dictionary.

The dictionary contents of a Dict node are stored in the database as attributes. The dictionary can be initialized through the dict argument in the constructor. After construction, values can be retrieved and updated through the item getters and setters, respectively:

node[‘key’] = ‘value’

Alternatively, the dict property returns an instance of the AttributeManager that can be used to get and set values through attribute notation:

node.dict.key = ‘value’

Note that trying to set dictionary values directly on the node, e.g. node.key = value, will not work as intended. It will merely set the key attribute on the node instance, but will not be stored in the database. As soon as the node goes out of scope, the value will be lost.

It is also relevant to note here the difference in something being an “attribute of a node” (in the sense that it is stored in the “attribute” column of the database when the node is stored) and something being an “attribute of a python object” (in the sense of being able to modify and access it as if it was a property of the variable, e.g. node.key = value). This is true of all types of nodes, but it becomes more relevant for Dict nodes where one is constantly manipulating these attributes.

Finally, all dictionary mutations will be forbidden once the node is stored.

__abstractmethods__ = frozenset({})#
__contains__(key: str) bool[source]#

Return whether the node contains a key.

__eq__(other)[source]#

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

__getitem__(key)[source]#
__hash__ = None#
__init__(value=None, **kwargs)[source]#

Initialise a Dict node instance.

Usual rules for attribute names apply, in particular, keys cannot start with an underscore, or a ValueError will be raised.

Initial attributes can be changed, deleted or added as long as the node is not stored.

Parameters:

value – dictionary to initialise the Dict node from

__module__ = 'aiida.orm.nodes.data.dict'#
__parameters__ = ()#
__plugin_type_string: ClassVar[str]#
__qb_fields__: Sequence[QbField] = [QbDictField('dict', dtype=Dict[str, Any], is_attribute=False, is_subscriptable=True)]#
__query_type_string: ClassVar[str]#
__setitem__(key, value)[source]#
_abc_impl = <_abc._abc_data object>#
_logger: Logger | None = <Logger aiida.orm.nodes.data.dict.Dict (WARNING)>#
property dict#

Return an instance of AttributeManager that transforms the dictionary into an attribute dict.

Note

this will allow one to do node.dict.key as well as node.dict[key].

Returns:

an instance of the AttributeResultManager.

fields: QbFields = {'attributes': 'QbDictField(attributes.*) -> Dict[str, Any]',  'ctime': 'QbNumericField(ctime) -> datetime',  'description': 'QbStrField(description) -> str',  'dict': 'QbDictField(dict.*) -> Dict[str, Any]',  '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]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str'}#
get(key: str, default: Any | None = None, /)[source]#

Return the value for key if key is in the dictionary, else default.

Parameters:
  • key – The key whose value to return.

  • default – Optional default to return in case the key does not exist.

Returns:

The value if the key exists, otherwise the default.

get_dict()[source]#

Return a dictionary with the parameters currently set.

Returns:

dictionary

items()[source]#

Iterator of all items stored in the Dict node.

keys()[source]#

Iterator of valid keys stored in the Dict object.

Returns:

iterator over the keys of the current dictionary

set_dict(dictionary)[source]#

Replace the current dictionary with another one.

Parameters:

dictionary – dictionary to set

update_dict(dictionary)[source]#

Update the current dictionary with the keys provided in the dictionary.

Note

works exactly as dict.update() where new keys are simply added and existing keys are overwritten.

Parameters:

dictionary – a dictionary with the keys to substitute

aiida.orm.nodes.data.dict._(value)[source]#

Data plugin that allows to easily wrap an enum.Enum member.

Nomenclature is taken from Python documentation: https://docs.python.org/3/library/enum.html Given the following example implementation:

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2

The class Color is an enumeration (or enum). The attributes Color.RED and Color.GREEN are enumeration members (or enum members) and are functionally constants. The enum members have names and values: the name of Color.RED is RED and the value of Color.RED is 1.

class aiida.orm.nodes.data.enum.EnumData(member: Enum, *args, **kwargs)[source]#

Bases: Data

Data plugin that allows to easily wrap an enum.Enum member.

The enum member is stored in the database by storing the value, name and the identifier (string that represents the class of the enumeration) in the KEY_NAME, KEY_VALUE and KEY_IDENTIFIER attribute, respectively. The original enum member can be reconstructured from the (loaded) node through the get_member method. The enum itself can be retrieved from the get_enum method. Like a normal enum member, the EnumData plugin provides the name and value properties which return the name and value of the enum member, respectively.

KEY_IDENTIFIER = 'identifier'#
KEY_NAME = 'name'#
KEY_VALUE = 'value'#
__abstractmethods__ = frozenset({})#
__eq__(other: Any) bool[source]#

Return whether the other object is equivalent to ourselves.

__hash__ = None#
__init__(member: Enum, *args, **kwargs)[source]#

Construct the node for the to enum member that is to be wrapped.

__module__ = 'aiida.orm.nodes.data.enum'#
__parameters__ = ()#
__plugin_type_string: ClassVar[str]#
__query_type_string: ClassVar[str]#
_abc_impl = <_abc._abc_data object>#
_logger: Logger | None = <Logger aiida.orm.nodes.data.enum.EnumData (WARNING)>#
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]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str'}#
get_enum() Type[EnumType][source]#

Return the enum class reconstructed from the serialized identifier stored in the database.

Raises:

ImportError – if the enum class represented by the stored identifier cannot be imported.

get_member() EnumType[source]#

Return the enum member reconstructed from the serialized data stored in the database.

For the enum member to be successfully reconstructed, the class of course has to still be importable and its implementation should not have changed since the node was stored. That is to say, the value of the member when it was stored, should still be a valid value for the enum class now.

Raises:
  • ImportError – if the enum class represented by the stored identifier cannot be imported.

  • ValueError – if the stored enum member value is no longer valid for the imported enum class.

property name: str#

Return the name of the enum member.

property value: Any#

Return the value of the enum member.

aiida.orm.nodes.data.enum._(value)[source]#

Data sub class to represent a float value.

class aiida.orm.nodes.data.float.Float(value=None, **kwargs)[source]#

Bases: NumericType

Data sub class to represent a float value.

__abstractmethods__ = frozenset({})#
__module__ = 'aiida.orm.nodes.data.float'#
__parameters__ = ()#
__plugin_type_string: ClassVar[str]#
__query_type_string: ClassVar[str]#
_abc_impl = <_abc._abc_data object>#
_logger: Logger | None = <Logger aiida.orm.nodes.data.float.Float (WARNING)>#
_type#

alias of float

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]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str',  'value': 'QbNumericField(attributes.value) -> float'}#
aiida.orm.nodes.data.float._(value)[source]#

Data sub class to represent a folder on a file system.

class aiida.orm.nodes.data.folder.FolderData(**kwargs)[source]#

Bases: Data

Data sub class to represent a folder on a file system.

__abstractmethods__ = frozenset({})#
__init__(**kwargs)[source]#

Construct a new FolderData to which any files and folders can be added.

Use the tree keyword to simply wrap a directory:

folder = FolderData(tree=’/absolute/path/to/directory’)

Alternatively, one can construct the node first and then use the various repository methods to add objects:

folder = FolderData() folder.put_object_from_tree(‘/absolute/path/to/directory’) folder.put_object_from_filepath(‘/absolute/path/to/file.txt’) folder.put_object_from_filelike(filelike_object)

Parameters:

tree (str) – absolute path to a folder to wrap

__module__ = 'aiida.orm.nodes.data.folder'#
__parameters__ = ()#
__plugin_type_string: ClassVar[str]#
__query_type_string: ClassVar[str]#
_abc_impl = <_abc._abc_data object>#
_logger: Logger | None = <Logger aiida.orm.nodes.data.folder.FolderData (WARNING)>#
as_path(path: str | PurePosixPath | None = None) Iterator[Path][source]#

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

Parameters:

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

Returns:

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

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

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

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

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

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

  • path – optional relative path whose contents to copy.

delete_object(path: str) None[source]#

Delete the object from the repository.

Parameters:

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

Raises:
erase() None[source]#

Delete all objects from the repository.

Raises:

ModificationNotAllowed – when the node is stored and therefore immutable.

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]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str'}#
get_object(path: str | PurePosixPath | None = None) File[source]#

Return the object at the given path.

Parameters:

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

Returns:

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

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

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

get_object_content(path: str, mode: Literal['r']) str[source]#
get_object_content(path: str, mode: Literal['rb']) bytes

Return the content of a object identified by key.

Parameters:

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

Raises:
glob() Iterable[PurePosixPath][source]#

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

list_object_names(path: str | None = None) list[str][source]#

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

Parameters:

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

Returns:

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

Raises:
list_objects(path: str | None = None) list[File][source]#

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

Parameters:

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

Returns:

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

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

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

Note

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

Parameters:

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

Returns:

yield a byte stream object.

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

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

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

  • content – the content to store.

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

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

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

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

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

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

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

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

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

Store the byte contents of a file in the repository.

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

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

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

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

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

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

Raises:
walk(path: str | PurePosixPath | None = None) Iterable[tuple[PurePosixPath, list[str], list[str]]][source]#

Walk over the directories and files contained within this repository.

Note

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

Parameters:

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

Returns:

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

Data sub class to represent an integer value.

class aiida.orm.nodes.data.int.Int(value=None, **kwargs)[source]#

Bases: NumericType

Data sub class to represent an integer value.

__abstractmethods__ = frozenset({})#
__module__ = 'aiida.orm.nodes.data.int'#
__parameters__ = ()#
__plugin_type_string: ClassVar[str]#
__query_type_string: ClassVar[str]#
_abc_impl = <_abc._abc_data object>#
_logger: Logger | None = <Logger aiida.orm.nodes.data.int.Int (WARNING)>#
_type#

alias of int

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]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str',  'value': 'QbNumericField(attributes.value) -> int'}#
aiida.orm.nodes.data.int._(value)[source]#

Data plugin that allows to easily wrap objects that are JSON-able.

class aiida.orm.nodes.data.jsonable.JsonSerializableProtocol(*args, **kwargs)[source]#

Bases: Protocol

__abstractmethods__ = frozenset({})#
__dict__ = mappingproxy({'__module__': 'aiida.orm.nodes.data.jsonable', 'as_dict': <function JsonSerializableProtocol.as_dict>, '__dict__': <attribute '__dict__' of 'JsonSerializableProtocol' objects>, '__weakref__': <attribute '__weakref__' of 'JsonSerializableProtocol' objects>, '__doc__': None, '__parameters__': (), '_is_protocol': True, '__subclasshook__': <function Protocol.__init_subclass__.<locals>._proto_hook>, '__init__': <function _no_init_or_replace_init>, '__abstractmethods__': frozenset(), '_abc_impl': <_abc._abc_data object>, '__annotations__': {}})#
__init__(*args, **kwargs)#
__module__ = 'aiida.orm.nodes.data.jsonable'#
__parameters__ = ()#
__subclasshook__()#

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

__weakref__#

list of weak references to the object (if defined)

_abc_impl = <_abc._abc_data object>#
_is_protocol = True#
as_dict() MutableMapping[Any, Any][source]#
class aiida.orm.nodes.data.jsonable.JsonableData(obj: JsonSerializableProtocol, *args, **kwargs)[source]#

Bases: Data

Data plugin that allows to easily wrap objects that are JSON-able.

Any class that implements the as_dict method, returning a dictionary that is a JSON serializable representation of the object, can be wrapped and stored by this data plugin.

As an example, take the Molecule class of the pymatgen library, which respects the spec described above. To store an instance as a JsonableData simply pass an instance as an argument to the constructor as follows:

from pymatgen.core import Molecule
molecule = Molecule(['H']. [0, 0, 0])
node = JsonableData(molecule)
node.store()

Since Molecule.as_dict returns a dictionary that is JSON-serializable, the data plugin will call it and store the dictionary as the attributes of the JsonableData node in the database.

Note

A JSON-serializable dictionary means a dictionary that when passed to json.dumps does not except but produces a valid JSON string representation of the dictionary.

If the wrapped class implements a class-method from_dict, the wrapped instance can easily be recovered from a previously stored node that was optionally loaded from the database. The from_dict method should simply accept a single argument which is the dictionary that is returned by the as_dict method. If this criteria is satisfied, an instance wrapped and stored in a JsonableData node can be recovered through the obj property:

loaded = load_node(node.pk)
molecule = loaded.obj

Of course, this requires that the class of the originally wrapped instance can be imported in the current environment, or an ImportError will be raised.

__abstractmethods__ = frozenset({})#
__init__(obj: JsonSerializableProtocol, *args, **kwargs)[source]#

Construct the node for the to be wrapped object.

__module__ = 'aiida.orm.nodes.data.jsonable'#
__parameters__ = ()#
__plugin_type_string: ClassVar[str]#
__query_type_string: ClassVar[str]#
_abc_impl = <_abc._abc_data object>#
classmethod _deserialize_float_constants(data: Any)[source]#

Deserialize the contents of a dictionary data deserializing infinity and NaN string constants.

The data dictionary is recursively checked for the Infinity, -Infinity and NaN strings, which are the Javascript string equivalents to the Python float('inf'), -float('inf') and float('nan') float constants. If one of the strings is encountered, the Python float constant is returned and otherwise the original value is returned.

_get_object() JsonSerializableProtocol[source]#

Return the cached wrapped object.

Note

If the object is not yet present in memory, for example if the node was loaded from the database, the object will first be reconstructed from the state stored in the node attributes.

_logger: Logger | None = <Logger aiida.orm.nodes.data.jsonable.JsonableData (WARNING)>#
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]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str'}#
property obj: JsonSerializableProtocol#

Return the wrapped object.

Note

This property caches the deserialized object, this means that when the node is loaded from the database, the object is deserialized only once and stored in memory as an attribute. Subsequent calls will simply return this cached object and not reload it from the database. This is fine, since nodes that are loaded from the database are by definition stored and therefore immutable, making it safe to assume that the object that is represented can not change. Note, however, that the caching also applies to unstored nodes. That means that manually changing the attributes of an unstored JsonableData can lead to inconsistencies with the object returned by this property.

Data sub class to represent a list.

class aiida.orm.nodes.data.list.List(value=None, **kwargs)[source]#

Bases: Data, MutableSequence

Data sub class to represent a list.

_LIST_KEY = 'list'#
__abstractmethods__ = frozenset({})#
__delitem__(key)[source]#
__eq__(other)[source]#

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

__getitem__(item)[source]#
__hash__ = None#
__init__(value=None, **kwargs)[source]#

Initialise a List node instance.

Parameters:

value – list to initialise the List node from

__len__()[source]#
__module__ = 'aiida.orm.nodes.data.list'#
__parameters__ = ()#
__plugin_type_string: ClassVar[str]#
__query_type_string: ClassVar[str]#
__setitem__(key, value)[source]#
__str__()[source]#

Return str(self).

_abc_impl = <_abc._abc_data object>#
_logger: Logger | None = <Logger aiida.orm.nodes.data.list.List (WARNING)>#
_using_list_reference()[source]#

This function tells the class if we are using a list reference. This means that calls to self.get_list return a reference rather than a copy of the underlying list and therefore self.set_list need not be called. This knwoledge is essential to make sure this class is performant.

Currently the implementation assumes that if the node needs to be stored then it is using the attributes cache which is a reference.

Returns:

True if using self.get_list returns a reference to the underlying sequence. False otherwise.

Return type:

bool

append(value)[source]#

S.append(value) – append value to the end of the sequence

count(value)[source]#

Return number of occurrences of value.

extend(value)[source]#

S.extend(iterable) – extend sequence by appending elements from the iterable

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]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str'}#
get_list()[source]#

Return the contents of this node.

Returns:

a list

index(value)[source]#

Return first index of value..

insert(i, value)[source]#

S.insert(index, value) – insert value before index

pop(**kwargs)[source]#

Remove and return item at index (default last).

remove(value)[source]#

S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.

reverse()[source]#

S.reverse() – reverse IN PLACE

set_list(data)[source]#

Set the contents of this node.

Parameters:

data – the list to set

sort(key=None, reverse=False)[source]#
aiida.orm.nodes.data.list._(value)[source]#

Module for defintion of base Data sub class for numeric based data types.

class aiida.orm.nodes.data.numeric.NumericType(value=None, **kwargs)[source]#

Bases: BaseType

Sub class of Data to store numbers, overloading common operators (+, *, …).

__abs__()[source]#
__abstractmethods__ = frozenset({})#
__add__(other)[source]#

Decorator wrapper.

__div__(other)[source]#

Decorator wrapper.

__float__()[source]#
__floordiv__(other)[source]#

Decorator wrapper.

__ge__(other)[source]#

Decorator wrapper.

__gt__(other)[source]#

Decorator wrapper.

__int__()[source]#
__le__(other)[source]#

Decorator wrapper.

__lt__(other)[source]#

Decorator wrapper.

__mod__(other)[source]#

Decorator wrapper.

__module__ = 'aiida.orm.nodes.data.numeric'#
__mul__(other)[source]#

Decorator wrapper.

__neg__()[source]#
__parameters__ = ()#
__plugin_type_string: ClassVar[str]#
__pos__()[source]#
__pow__(other)[source]#

Decorator wrapper.

__query_type_string: ClassVar[str]#
__radd__(other)[source]#

Decorator wrapper.

__rdiv__(other)[source]#

Decorator wrapper.

__rfloordiv__(other)[source]#

Decorator wrapper.

__rmod__(other)[source]#

Decorator wrapper.

__rmul__(other)[source]#

Decorator wrapper.

__rsub__(other)[source]#

Decorator wrapper.

__rtruediv__(other)[source]#

Decorator wrapper.

__sub__(other)[source]#

Decorator wrapper.

__truediv__(other)[source]#

Decorator wrapper.

_abc_impl = <_abc._abc_data object>#
_logger: Logger | None = <Logger aiida.orm.nodes.data.numeric.NumericType (WARNING)>#
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]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str'}#
aiida.orm.nodes.data.numeric._left_operator(func)[source]#

Function decorator to treat a method as the left operator.

aiida.orm.nodes.data.numeric._right_operator(func)[source]#

Function decorator to treat a method as the right operator.

Data plugin to model an atomic orbital.

class aiida.orm.nodes.data.orbital.OrbitalData(*args, source=None, **kwargs)[source]#

Bases: Data

Used for storing collections of orbitals, as well as providing methods for accessing them internally.

__abstractmethods__ = frozenset({})#
__module__ = 'aiida.orm.nodes.data.orbital'#
__parameters__ = ()#
__plugin_type_string: ClassVar[str]#
__query_type_string: ClassVar[str]#
_abc_impl = <_abc._abc_data object>#
_logger: Logger | None = <Logger aiida.orm.nodes.data.orbital.OrbitalData (WARNING)>#
clear_orbitals()[source]#

Remove all orbitals that were added to the class Cannot work if OrbitalData has been already stored

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]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str'}#
get_orbitals(**kwargs)[source]#

Returns all orbitals by default. If a site is provided, returns all orbitals cooresponding to the location of that site, additional arguments may be provided, which act as filters on the retrieved orbitals.

Parameters:

site – if provided, returns all orbitals with position of site

Kwargs:

attributes than can filter the set of returned orbitals

Return list_of_outputs:

a list of orbitals

set_orbitals(orbitals)[source]#

Sets the orbitals into the database. Uses the orbital’s inherent set_orbital_dict method to generate a orbital dict string.

Parameters:

orbital – an orbital or list of orbitals to be set

Data class that can be used to store a single file in its repository.

class aiida.orm.nodes.data.singlefile.SinglefileData(file: str | Path | IO, filename: str | Path | None = None, **kwargs: Any)[source]#

Bases: Data

Data class that can be used to store a single file in its repository.

DEFAULT_FILENAME = 'file.txt'#
__abstractmethods__ = frozenset({})#
__init__(file: str | Path | IO, filename: str | Path | None = None, **kwargs: Any) None[source]#

Construct a new instance and set the contents to that of the file.

Parameters:
  • file – an absolute filepath or filelike object whose contents to copy. Hint: Pass io.BytesIO(b”my string”) to construct the SinglefileData directly from a string.

  • filename – specify filename to use (defaults to name of provided file).

__module__ = 'aiida.orm.nodes.data.singlefile'#
__parameters__ = ()#
__plugin_type_string: ClassVar[str]#
__query_type_string: ClassVar[str]#
_abc_impl = <_abc._abc_data object>#
_logger: Logger | None = <Logger aiida.orm.nodes.data.singlefile.SinglefileData (WARNING)>#
_validate() bool[source]#

Ensure that there is one object stored in the repository, whose key matches value set for filename attr.

as_path() Iterator[Path][source]#

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

Parameters:

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

Returns:

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

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

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

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]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str'}#
property filename: str#

Return the name of the file stored.

Returns:

the filename under which the file is stored in the repository

classmethod from_string(content: str, filename: str | Path | None = None, **kwargs: Any) SinglefileData[source]#

Construct a new instance and set content as its contents.

Parameters:
  • content – The content as a string.

  • filename – Specify filename to use (defaults to file.txt).

get_content(mode: str = 'r') str | bytes[source]#

Return the content of the single file stored for this data node.

Parameters:

mode – the mode with which to open the file handle (default: read mode)

Returns:

the content of the file as a string or bytes, depending on mode.

open(path: FilePath, mode: t.Literal['r'] = 'r') t.Iterator[t.TextIO][source]#
open(path: FilePath, mode: t.Literal['rb']) t.Iterator[t.BinaryIO]
open(path: None = None, mode: t.Literal['r'] = 'r') t.Iterator[t.TextIO]
open(path: None = None, mode: t.Literal['rb'] = 'r') t.Iterator[t.BinaryIO]

Return an open file handle to the content of this data node.

Parameters:
  • path – the relative path of the object within the repository.

  • mode – the mode with which to open the file handle (default: read mode)

Returns:

a file handle

set_file(file: str | Path | IO, filename: str | Path | None = None) None[source]#

Store the content of the file in the node’s repository, deleting any other existing objects.

Parameters:
  • file – an absolute filepath or filelike object whose contents to copy Hint: Pass io.BytesIO(b”my string”) to construct the file directly from a string.

  • filename – specify filename to use (defaults to name of provided file).

Data sub class to represent a string value.

class aiida.orm.nodes.data.str.Str(value=None, **kwargs)[source]#

Bases: BaseType

Data sub class to represent a string value.

__abstractmethods__ = frozenset({})#
__module__ = 'aiida.orm.nodes.data.str'#
__parameters__ = ()#
__plugin_type_string: ClassVar[str]#
__query_type_string: ClassVar[str]#
_abc_impl = <_abc._abc_data object>#
_logger: Logger | None = <Logger aiida.orm.nodes.data.str.Str (WARNING)>#
_type#

alias of str

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]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str',  'value': 'QbStrField(attributes.value) -> str'}#
aiida.orm.nodes.data.str._(value)[source]#

This module defines the classes for structures and all related functions to operate on them.

class aiida.orm.nodes.data.structure.Kind(**kwargs)[source]#

Bases: object

This class contains the information about the species (kinds) of the system.

It can be a single atom, or an alloy, or even contain vacancies.

__dict__ = mappingproxy({'__module__': 'aiida.orm.nodes.data.structure', '__doc__': 'This class contains the information about the species (kinds) of the system.\n\n    It can be a single atom, or an alloy, or even contain vacancies.\n    ', '__init__': <function Kind.__init__>, 'get_raw': <function Kind.get_raw>, 'reset_mass': <function Kind.reset_mass>, 'name': <property object>, 'set_automatic_kind_name': <function Kind.set_automatic_kind_name>, 'compare_with': <function Kind.compare_with>, 'mass': <property object>, 'weights': <property object>, 'get_symbols_string': <function Kind.get_symbols_string>, 'symbol': <property object>, 'symbols': <property object>, 'set_symbols_and_weights': <function Kind.set_symbols_and_weights>, 'is_alloy': <property object>, 'has_vacancies': <property object>, '__repr__': <function Kind.__repr__>, '__str__': <function Kind.__str__>, '__dict__': <attribute '__dict__' of 'Kind' objects>, '__weakref__': <attribute '__weakref__' of 'Kind' objects>, '__annotations__': {}})#
__init__(**kwargs)[source]#

Create a site. One can either pass:

Parameters:
  • raw – the raw python dictionary that will be converted to a Kind object.

  • ase – an ase Atom object

  • kind – a Kind object (to get a copy)

Or alternatively the following parameters:

Parameters:
  • symbols – a single string for the symbol of this site, or a list of symbol strings

  • weights – (optional) the weights for each atomic species of this site. If only a single symbol is provided, then this value is optional and the weight is set to 1.

  • mass – (optional) the mass for this site in atomic mass units. If not provided, the mass is set by the self.reset_mass() function.

  • name – a string that uniquely identifies the kind, and that is used to identify the sites.

__module__ = 'aiida.orm.nodes.data.structure'#
__repr__()[source]#

Return repr(self).

__str__()[source]#

Return str(self).

__weakref__#

list of weak references to the object (if defined)

compare_with(other_kind)[source]#

Compare with another Kind object to check if they are different.

Note

This does NOT check the ‘type’ attribute. Instead, it compares (with reasonable thresholds, where applicable): the mass, and the list of symbols and of weights. Moreover, it compares the _internal_tag, if defined (at the moment, defined automatically only when importing the Kind from ASE, if the atom has a non-zero tag). Note that the _internal_tag is only used while the class is loaded, but is not persisted on the database.

Returns:

A tuple with two elements. The first one is True if the two sites are ‘equivalent’ (same mass, symbols and weights), False otherwise. The second element of the tuple is a string, which is either None (if the first element was True), or contains a ‘human-readable’ description of the first difference encountered between the two sites.

get_raw()[source]#

Return the raw version of the site, mapped to a suitable dictionary. This is the format that is actually used to store each kind of the structure in the DB.

Returns:

a python dictionary with the kind.

get_symbols_string()[source]#

Return a string that tries to match as good as possible the symbols of this kind. If there is only one symbol (no alloy) with 100% occupancy, just returns the symbol name. Otherwise, groups the full string in curly brackets, and try to write also the composition (with 2 precision only).

Note

If there is a vacancy (sum of weights<1), we indicate it with the X symbol followed by 1-sum(weights) (still with 2 digits precision, so it can be 0.00)

Note

Note the difference with respect to the symbols and the symbol properties!

property has_vacancies#

Return whether the Kind contains vacancies, i.e. when the sum of the weights is less than one.

Note

the property uses the internal variable _SUM_THRESHOLD as a threshold.

Returns:

boolean, True if the sum of the weights is less than one, False otherwise

property is_alloy#

Return whether the Kind is an alloy, i.e. contains more than one element

Returns:

boolean, True if the kind has more than one element, False otherwise.

property mass#

The mass of this species kind.

Returns:

a float

property name#

Return the name of this kind. The name of a kind is used to identify the species of a site.

Returns:

a string

reset_mass()[source]#

Reset the mass to the automatic calculated value.

The mass can be set manually; by default, if not provided, it is the mass of the constituent atoms, weighted with their weight (after the weight has been normalized to one to take correctly into account vacancies).

This function uses the internal _symbols and _weights values and thus assumes that the values are validated.

It sets the mass to None if the sum of weights is zero.

set_automatic_kind_name(tag=None)[source]#

Set the type to a string obtained with the symbols appended one after the other, without spaces, in alphabetical order; if the site has a vacancy, a X is appended at the end too.

set_symbols_and_weights(symbols, weights)[source]#

Set the chemical symbols and the weights for the site.

Note

Note that the kind name remains unchanged.

property symbol#

If the kind has only one symbol, return it; otherwise, raise a ValueError.

property symbols#

List of symbols for this site. If the site is a single atom, pass a list of one element only, or simply the string for that atom. For alloys, a list of elements.

Note

Note that if you change the list of symbols, the kind name remains unchanged.

property weights#

Weights for this species kind. Refer also to :func:validate_symbols_tuple for the validation rules on the weights.

class aiida.orm.nodes.data.structure.Site(**kwargs)[source]#

Bases: object

This class contains the information about a given site of the system.

It can be a single atom, or an alloy, or even contain vacancies.

__dict__ = mappingproxy({'__module__': 'aiida.orm.nodes.data.structure', '__doc__': 'This class contains the information about a given site of the system.\n\n    It can be a single atom, or an alloy, or even contain vacancies.\n    ', '__init__': <function Site.__init__>, 'get_raw': <function Site.get_raw>, 'get_ase': <function Site.get_ase>, 'kind_name': <property object>, 'position': <property object>, '__repr__': <function Site.__repr__>, '__str__': <function Site.__str__>, '__dict__': <attribute '__dict__' of 'Site' objects>, '__weakref__': <attribute '__weakref__' of 'Site' objects>, '__annotations__': {}})#
__init__(**kwargs)[source]#

Create a site.

Parameters:
  • kind_name – a string that identifies the kind (species) of this site. This has to be found in the list of kinds of the StructureData object. Validation will be done at the StructureData level.

  • position – the absolute position (three floats) in angstrom

__module__ = 'aiida.orm.nodes.data.structure'#
__repr__()[source]#

Return repr(self).

__str__()[source]#

Return str(self).

__weakref__#

list of weak references to the object (if defined)

get_ase(kinds)[source]#

Return a ase.Atom object for this site.

Parameters:

kinds – the list of kinds from the StructureData object.

Note

If any site is an alloy or has vacancies, a ValueError is raised (from the site.get_ase() routine).

get_raw()[source]#

Return the raw version of the site, mapped to a suitable dictionary. This is the format that is actually used to store each site of the structure in the DB.

Returns:

a python dictionary with the site.

property kind_name#

Return the kind name of this site (a string).

The type of a site is used to decide whether two sites are identical (same mass, symbols, weights, …) or not.

property position#

Return the position of this site in absolute coordinates, in angstrom.

class aiida.orm.nodes.data.structure.StructureData(cell=None, pbc=None, ase=None, pymatgen=None, pymatgen_structure=None, pymatgen_molecule=None, **kwargs)[source]#

Bases: Data

Data class that represents an atomic structure.

The data is organized as a collection of sites together with a cell, the boundary conditions (whether they are periodic or not) and other related useful information.

__abstractmethods__ = frozenset({})#
__init__(cell=None, pbc=None, ase=None, pymatgen=None, pymatgen_structure=None, pymatgen_molecule=None, **kwargs)[source]#

Construct a new instance, setting the source attribute if provided as a keyword argument.

__module__ = 'aiida.orm.nodes.data.structure'#
__parameters__ = ()#
__plugin_type_string: ClassVar[str]#
__qb_fields__: Sequence[QbField] = [QbField('pbc1', dtype=bool, is_attribute=True), QbField('pbc2', dtype=bool, is_attribute=True), QbField('pbc3', dtype=bool, is_attribute=True), QbArrayField('cell', dtype=List[List[float]], is_attribute=True), QbArrayField('kinds', dtype=Optional[List[dict]], is_attribute=True), QbArrayField('sites', dtype=Optional[List[dict]], is_attribute=True)]#
__query_type_string: ClassVar[str]#
_abc_impl = <_abc._abc_data object>#
_adjust_default_cell(vacuum_factor=1.0, vacuum_addition=10.0, pbc=(False, False, False))[source]#

If the structure was imported from an xyz file, it lacks a cell. This method will adjust the cell

_dimensionality_label = {0: '', 1: 'length', 2: 'surface', 3: 'volume'}#
_get_object_ase()[source]#

Converts StructureData to ase.Atoms

Returns:

an ase.Atoms object

_get_object_phonopyatoms()[source]#

Converts StructureData to PhonopyAtoms

Returns:

a PhonopyAtoms object

_get_object_pymatgen(**kwargs)[source]#

Converts StructureData to pymatgen object

Returns:

a pymatgen Structure for structures with periodic boundary conditions (in three dimensions) and Molecule otherwise

Note

Requires the pymatgen module (version >= 3.0.13, usage of earlier versions may cause errors).

_get_object_pymatgen_molecule(**kwargs)[source]#

Converts StructureData to pymatgen Molecule object

Returns:

a pymatgen Molecule object corresponding to this StructureData object.

Note

Requires the pymatgen module (version >= 3.0.13, usage of earlier versions may cause errors)

_get_object_pymatgen_structure(**kwargs)[source]#

Converts StructureData to pymatgen Structure object :param add_spin: True to add the spins to the pymatgen structure. Default is False (no spin added).

Note

The spins are set according to the following rule:

  • if the kind name ends with 1 -> spin=+1

  • if the kind name ends with 2 -> spin=-1

Returns:

a pymatgen Structure object corresponding to this StructureData object

Raises:

ValueError – if the cell is not set (i.e. is the default one); if there are partial occupancies together with spins (defined by kind names ending with ‘1’ or ‘2’).

Note

Requires the pymatgen module (version >= 3.0.13, usage of earlier versions may cause errors)

_internal_kind_tags = None#
_logger: Logger | None = <Logger aiida.orm.nodes.data.structure.StructureData (WARNING)>#
_parse_xyz(inputstring)[source]#

Read the structure from a string of format XYZ.

_prepare_chemdoodle(main_file_name='')[source]#

Write the given structure to a string of format required by ChemDoodle.

_prepare_cif(main_file_name='')[source]#

Write the given structure to a string of format CIF.

_prepare_xsf(main_file_name='')[source]#

Write the given structure to a string of format XSF (for XCrySDen).

_prepare_xyz(main_file_name='')[source]#

Write the given structure to a string of format XYZ.

_set_incompatibilities = [('ase', 'cell'), ('ase', 'pbc'), ('ase', 'pymatgen'), ('ase', 'pymatgen_molecule'), ('ase', 'pymatgen_structure'), ('cell', 'pymatgen'), ('cell', 'pymatgen_molecule'), ('cell', 'pymatgen_structure'), ('pbc', 'pymatgen'), ('pbc', 'pymatgen_molecule'), ('pbc', 'pymatgen_structure'), ('pymatgen', 'pymatgen_molecule'), ('pymatgen', 'pymatgen_structure'), ('pymatgen_molecule', 'pymatgen_structure')]#
_validate()[source]#

Performs some standard validation tests.

append_atom(**kwargs)[source]#

Append an atom to the Structure, taking care of creating the corresponding kind.

Parameters:
  • ase – the ase Atom object from which we want to create a new atom (if present, this must be the only parameter)

  • position – the position of the atom (three numbers in angstrom)

  • symbols – passed to the constructor of the Kind object.

  • weights – passed to the constructor of the Kind object.

  • name – passed to the constructor of the Kind object. See also the note below.

Note

Note on the ‘name’ parameter (that is, the name of the kind):

  • if specified, no checks are done on existing species. Simply, a new kind with that name is created. If there is a name clash, a check is done: if the kinds are identical, no error is issued; otherwise, an error is issued because you are trying to store two different kinds with the same name.

  • if not specified, the name is automatically generated. Before adding the kind, a check is done. If other species with the same properties already exist, no new kinds are created, but the site is added to the existing (identical) kind. (Actually, the first kind that is encountered). Otherwise, the name is made unique first, by adding to the string containing the list of chemical symbols a number starting from 1, until an unique name is found

Note

checks of equality of species are done using the compare_with() method.

append_kind(kind)[source]#

Append a kind to the StructureData. It makes a copy of the kind.

Parameters:

kind – the site to append, must be a Kind object.

append_site(site)[source]#

Append a site to the StructureData. It makes a copy of the site.

Parameters:

site – the site to append. It must be a Site object.

property cell: List[List[float]]#

Returns the cell shape.

Returns:

a 3x3 list of lists.

property cell_angles#

Get the angles between the cell lattice vectors in degrees.

property cell_lengths#

Get the lengths of cell lattice vectors in angstroms.

clear_kinds()[source]#

Removes all kinds for the StructureData object.

Note

Also clear all sites!

clear_sites()[source]#

Removes all sites for the StructureData object.

fields: QbFields = {'attributes': 'QbDictField(attributes.*) -> Dict[str, Any]',  'cell': 'QbArrayField(attributes.cell) -> List[List[float]]',  'ctime': 'QbNumericField(ctime) -> datetime',  'description': 'QbStrField(description) -> str',  'extras': 'QbDictField(extras.*) -> Dict[str, Any]',  'kinds': 'QbArrayField(attributes.kinds) -> Optional[List[dict]]',  'label': 'QbStrField(label) -> str',  'mtime': 'QbNumericField(mtime) -> datetime',  'node_type': 'QbStrField(node_type) -> str',  'pbc1': 'QbField(attributes.pbc1) -> bool',  'pbc2': 'QbField(attributes.pbc2) -> bool',  'pbc3': 'QbField(attributes.pbc3) -> bool',  'pk': 'QbNumericField(pk) -> int',  'repository_metadata': 'QbDictField(repository_metadata) -> Dict[str, Any]',  'sites': 'QbArrayField(attributes.sites) -> Optional[List[dict]]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str'}#
get_ase()[source]#

Get the ASE object. Requires to be able to import ase.

Returns:

an ASE object corresponding to this StructureData object.

Note

If any site is an alloy or has vacancies, a ValueError is raised (from the site.get_ase() routine).

get_cell_volume()[source]#

Returns the three-dimensional cell volume in Angstrom^3.

Use the get_dimensionality method in order to get the area/length of lower-dimensional cells.

Returns:

a float.

get_cif(converter='ase', store=False, **kwargs)[source]#

Creates aiida.orm.nodes.data.cif.CifData.

Parameters:
  • converter – specify the converter. Default ‘ase’.

  • store – If True, intermediate calculation gets stored in the AiiDA database for record. Default False.

Returns:

aiida.orm.nodes.data.cif.CifData node.

get_composition(mode='full')[source]#

Returns the chemical composition of this structure as a dictionary, where each key is the kind symbol (e.g. H, Li, Ba), and each value is the number of occurences of that element in this structure.

Parameters:

mode – Specify the mode of the composition to return. Choose from full, reduced or fractional. For example, given the structure with formula Ba2Zr2O6, the various modes operate as follows. full: The default, the counts are left unnnormalized. reduced: The counts are renormalized to the greatest common denominator. fractional: The counts are renormalized such that the sum equals 1.

Returns:

a dictionary with the composition

get_description()[source]#

Returns a string with infos retrieved from StructureData node’s properties

Parameters:

self – the StructureData node

Returns:

retsrt: the description string

get_dimensionality()[source]#

Return the dimensionality of the structure and its length/surface/volume.

Zero-dimensional structures are assigned “volume” 0.

Returns:

returns a dictionary with keys “dim” (dimensionality integer), “label” (dimensionality label) and “value” (numerical length/surface/volume).

get_formula(mode='hill', separator='')[source]#

Return a string with the chemical formula.

Parameters:
  • mode

    a string to specify how to generate the formula, can assume one of the following values:

    • ’hill’ (default): count the number of atoms of each species, then use Hill notation, i.e. alphabetical order with C and H first if one or several C atom(s) is (are) present, e.g. ['C','H','H','H','O','C','H','H','H'] will return 'C2H6O' ['S','O','O','H','O','H','O'] will return 'H2O4S' From E. A. Hill, J. Am. Chem. Soc., 22 (8), pp 478-494 (1900)

    • ’hill_compact’: same as hill but the number of atoms for each species is divided by the greatest common divisor of all of them, e.g. ['C','H','H','H','O','C','H','H','H','O','O','O'] will return 'CH3O2'

    • ’reduce’: group repeated symbols e.g. ['Ba', 'Ti', 'O', 'O', 'O', 'Ba', 'Ti', 'O', 'O', 'O', 'Ba', 'Ti', 'Ti', 'O', 'O', 'O'] will return 'BaTiO3BaTiO3BaTi2O3'

    • ’group’: will try to group as much as possible parts of the formula e.g. ['Ba', 'Ti', 'O', 'O', 'O', 'Ba', 'Ti', 'O', 'O', 'O', 'Ba', 'Ti', 'Ti', 'O', 'O', 'O'] will return '(BaTiO3)2BaTi2O3'

    • ’count’: same as hill (i.e. one just counts the number of atoms of each species) without the re-ordering (take the order of the atomic sites), e.g. ['Ba', 'Ti', 'O', 'O', 'O','Ba', 'Ti', 'O', 'O', 'O'] will return 'Ba2Ti2O6'

    • ’count_compact’: same as count but the number of atoms for each species is divided by the greatest common divisor of all of them, e.g. ['Ba', 'Ti', 'O', 'O', 'O','Ba', 'Ti', 'O', 'O', 'O'] will return 'BaTiO3'

  • separator – a string used to concatenate symbols. Default empty.

Returns:

a string with the formula

Note

in modes reduce, group, count and count_compact, the initial order in which the atoms were appended by the user is used to group and/or order the symbols in the formula

get_kind(kind_name)[source]#

Return the kind object associated with the given kind name.

Parameters:

kind_name – String, the name of the kind you want to get

Returns:

The Kind object associated with the given kind_name, if a Kind with the given name is present in the structure.

Raise:

ValueError if the kind_name is not present.

get_kind_names()[source]#

Return a list of kind names (in the same order of the self.kinds property, but return the names rather than Kind objects)

Note

This is NOT necessarily a list of chemical symbols! Use get_symbols_set for chemical symbols

Returns:

a list of strings.

get_pymatgen(**kwargs)[source]#

Get pymatgen object. Returns pymatgen Structure for structures with periodic boundary conditions (in 1D, 2D, 3D) and Molecule otherwise. :param add_spin: True to add the spins to the pymatgen structure. Default is False (no spin added).

Note

The spins are set according to the following rule:

  • if the kind name ends with 1 -> spin=+1

  • if the kind name ends with 2 -> spin=-1

Note

Requires the pymatgen module (version >= 3.0.13, usage of earlier versions may cause errors).

get_pymatgen_molecule()[source]#

Get the pymatgen Molecule object.

Note

Requires the pymatgen module (version >= 3.0.13, usage of earlier versions may cause errors).

Returns:

a pymatgen Molecule object corresponding to this StructureData object.

get_pymatgen_structure(**kwargs)[source]#

Get the pymatgen Structure object with any PBC, provided the cell is not singular. :param add_spin: True to add the spins to the pymatgen structure. Default is False (no spin added).

Note

The spins are set according to the following rule:

  • if the kind name ends with 1 -> spin=+1

  • if the kind name ends with 2 -> spin=-1

Note

Requires the pymatgen module (version >= 3.0.13, usage of earlier versions may cause errors).

Returns:

a pymatgen Structure object corresponding to this StructureData object.

Raises:

ValueError – if the cell is singular, e.g. when it has not been set. Use get_pymatgen_molecule instead, or set a proper cell.

get_site_kindnames()[source]#

Return a list with length equal to the number of sites of this structure, where each element of the list is the kind name of the corresponding site.

Note

This is NOT necessarily a list of chemical symbols! Use [ self.get_kind(s.kind_name).get_symbols_string() for s in self.sites] for chemical symbols

Returns:

a list of strings

get_symbols_set()[source]#

Return a set containing the names of all elements involved in this structure (i.e., for it joins the list of symbols for each kind k in the structure).

Returns:

a set of strings of element names.

property has_vacancies#

Return whether the structure has vacancies in the structure.

Returns:

a boolean, True if at least one kind has a vacancy

property is_alloy#

Return whether the structure contains any alloy kinds.

Returns:

a boolean, True if at least one kind is an alloy

property kinds#

Returns a list of kinds.

property pbc#

Get the periodic boundary conditions.

Returns:

a tuple of three booleans, each one tells if there are periodic boundary conditions for the i-th real-space direction (i=1,2,3)

reset_cell(new_cell)[source]#

Reset the cell of a structure not yet stored to a new value.

Parameters:

new_cell – list specifying the cell vectors

Raises:

ModificationNotAllowed: if object is already stored

reset_sites_positions(new_positions, conserve_particle=True)[source]#

Replace all the Site positions attached to the Structure

Parameters:
  • new_positions – list of (3D) positions for every sites.

  • conserve_particle – if True, allows the possibility of removing a site. currently not implemented.

Raises:

Note

it is assumed that the order of the new_positions is given in the same order of the one it’s substituting, i.e. the kind of the site will not be checked.

set_ase(aseatoms)[source]#

Load the structure from a ASE object

set_cell(value)[source]#

Set the cell.

set_cell_angles(value)[source]#
set_cell_lengths(value)[source]#
set_pbc(value)[source]#

Set the periodic boundary conditions.

set_pymatgen(obj, **kwargs)[source]#

Load the structure from a pymatgen object.

Note

Requires the pymatgen module (version >= 3.0.13, usage of earlier versions may cause errors).

set_pymatgen_molecule(mol, margin=5)[source]#

Load the structure from a pymatgen Molecule object.

Parameters:

margin – the margin to be added in all directions of the bounding box of the molecule.

Note

Requires the pymatgen module (version >= 3.0.13, usage of earlier versions may cause errors).

set_pymatgen_structure(struct)[source]#

Load the structure from a pymatgen Structure object.

Note

periodic boundary conditions are set to True in all three directions.

Note

Requires the pymatgen module (version >= 3.3.5, usage of earlier versions may cause errors).

Raises:

ValueError – if there are partial occupancies together with spins.

property sites#

Returns a list of sites.

aiida.orm.nodes.data.structure._create_symbols_tuple(symbols)[source]#

Returns a tuple with the symbols provided. If a string is provided, this is converted to a tuple with one single element.

aiida.orm.nodes.data.structure._create_weights_tuple(weights)[source]#

Returns a tuple with the weights provided. If a number is provided, this is converted to a tuple with one single element. If None is provided, this is converted to the tuple (1.,)

aiida.orm.nodes.data.structure._get_dimensionality(pbc, cell)[source]#

Return the dimensionality of the structure and its length/surface/volume.

Zero-dimensional structures are assigned “volume” 0.

Returns:

returns a dictionary with keys “dim” (dimensionality integer), “label” (dimensionality label) and “value” (numerical length/surface/volume).

aiida.orm.nodes.data.structure._get_valid_cell(inputcell)[source]#

Return the cell in a valid format from a generic input.

Raises:

ValueError – whenever the format is not valid.

aiida.orm.nodes.data.structure._validate_dimensionality(pbc, cell)[source]#

Check whether the given pbc and cell vectors are consistent.

aiida.orm.nodes.data.structure.ase_refine_cell(aseatoms, **kwargs)[source]#

Detect the symmetry of the structure, remove symmetric atoms and refine unit cell.

Parameters:
  • aseatoms – an ase.atoms.Atoms instance

  • symprec – symmetry precision, used by spglib

Return newase:

refined cell with reduced set of atoms

Return symmetry:

a dictionary describing the symmetry space group

aiida.orm.nodes.data.structure.atom_kinds_to_html(atom_kind)[source]#

Construct in html format

an alloy with 0.5 Ge, 0.4 Si and 0.1 vacancy is represented as Ge<sub>0.5</sub> + Si<sub>0.4</sub> + vacancy<sub>0.1</sub>

Args:#

atom_kind: a string with the name of the atomic kind, as printed by kind.get_symbols_string(), e.g. Ba0.80Ca0.10X0.10

Returns:#

html code for rendered formula

aiida.orm.nodes.data.structure.calc_cell_volume(cell)[source]#

Compute the three-dimensional cell volume in Angstrom^3.

Parameters:

cell – the cell vectors; the must be a 3x3 list of lists of floats

Returns:

the cell volume.

aiida.orm.nodes.data.structure.create_automatic_kind_name(symbols, weights)[source]#

Create a string obtained with the symbols appended one after the other, without spaces, in alphabetical order; if the site has a vacancy, a X is appended at the end too.

aiida.orm.nodes.data.structure.get_formula(symbol_list, mode='hill', separator='')[source]#

Return a string with the chemical formula.

Parameters:
  • symbol_list – a list of symbols, e.g. ['H','H','O']

  • mode

    a string to specify how to generate the formula, can assume one of the following values:

    • ’hill’ (default): count the number of atoms of each species, then use Hill notation, i.e. alphabetical order with C and H first if one or several C atom(s) is (are) present, e.g. ['C','H','H','H','O','C','H','H','H'] will return 'C2H6O' ['S','O','O','H','O','H','O'] will return 'H2O4S' From E. A. Hill, J. Am. Chem. Soc., 22 (8), pp 478-494 (1900)

    • ’hill_compact’: same as hill but the number of atoms for each species is divided by the greatest common divisor of all of them, e.g. ['C','H','H','H','O','C','H','H','H','O','O','O'] will return 'CH3O2'

    • ’reduce’: group repeated symbols e.g. ['Ba', 'Ti', 'O', 'O', 'O', 'Ba', 'Ti', 'O', 'O', 'O', 'Ba', 'Ti', 'Ti', 'O', 'O', 'O'] will return 'BaTiO3BaTiO3BaTi2O3'

    • ’group’: will try to group as much as possible parts of the formula e.g. ['Ba', 'Ti', 'O', 'O', 'O', 'Ba', 'Ti', 'O', 'O', 'O', 'Ba', 'Ti', 'Ti', 'O', 'O', 'O'] will return '(BaTiO3)2BaTi2O3'

    • ’count’: same as hill (i.e. one just counts the number of atoms of each species) without the re-ordering (take the order of the atomic sites), e.g. ['Ba', 'Ti', 'O', 'O', 'O','Ba', 'Ti', 'O', 'O', 'O'] will return 'Ba2Ti2O6'

    • ’count_compact’: same as count but the number of atoms for each species is divided by the greatest common divisor of all of them, e.g. ['Ba', 'Ti', 'O', 'O', 'O','Ba', 'Ti', 'O', 'O', 'O'] will return 'BaTiO3'

  • separator – a string used to concatenate symbols. Default empty.

Returns:

a string with the formula

Note

in modes reduce, group, count and count_compact, the initial order in which the atoms were appended by the user is used to group and/or order the symbols in the formula

aiida.orm.nodes.data.structure.get_formula_from_symbol_list(_list, separator='')[source]#

Return a string with the formula obtained from the list of symbols.

Examples#

  • [[1,'Ba'],[1,'Ti'],[3,'O']] will return 'BaTiO3'

  • [[2, [ [1, 'Ba'], [1, 'Ti'] ] ]] will return '(BaTi)2'

param _list:

a list of symbols and multiplicities as obtained from the function group_symbols

param separator:

a string used to concatenate symbols. Default empty.

return:

a string

aiida.orm.nodes.data.structure.get_formula_group(symbol_list, separator='')[source]#

Return a string with the chemical formula from a list of chemical symbols. The formula is written in a compact” way, i.e. trying to group as much as possible parts of the formula.

Note

it works for instance very well if structure was obtained from an ASE supercell.

Example of result: ['Ba', 'Ti', 'O', 'O', 'O', 'Ba', 'Ti', 'O', 'O', 'O', 'Ba', 'Ti', 'Ti', 'O', 'O', 'O'] will return '(BaTiO3)2BaTi2O3'.

Parameters:
  • symbol_list – list of symbols (e.g. [‘Ba’,’Ti’,’O’,’O’,’O’])

  • separator – a string used to concatenate symbols. Default empty.

Returns:

a string with the chemical formula for the given structure.

aiida.orm.nodes.data.structure.get_pymatgen_version()[source]#
Returns:

string with pymatgen version, None if can not import.

aiida.orm.nodes.data.structure.get_symbols_string(symbols, weights)[source]#

Return a string that tries to match as good as possible the symbols and weights. If there is only one symbol (no alloy) with 100% occupancy, just returns the symbol name. Otherwise, groups the full string in curly brackets, and try to write also the composition (with 2 precision only). If (sum of weights<1), we indicate it with the X symbol followed by 1-sum(weights) (still with 2 digits precision, so it can be 0.00)

Parameters:
  • symbols – the symbols as obtained from <kind>._symbols

  • weights – the weights as obtained from <kind>._weights

Note

Note the difference with respect to the symbols and the symbol properties!

aiida.orm.nodes.data.structure.get_valid_pbc(inputpbc)[source]#

Return a list of three booleans for the periodic boundary conditions, in a valid format from a generic input.

Raises:

ValueError – if the format is not valid.

aiida.orm.nodes.data.structure.group_symbols(_list)[source]#

Group a list of symbols to a list containing the number of consecutive identical symbols, and the symbol itself.

Examples#

  • ['Ba','Ti','O','O','O','Ba'] will return [[1,'Ba'],[1,'Ti'],[3,'O'],[1,'Ba']]

  • [ [ [1,'Ba'],[1,'Ti'] ],[ [1,'Ba'],[1,'Ti'] ] ] will return [[2, [ [1, 'Ba'], [1, 'Ti'] ] ]]

param _list:

a list of elements representing a chemical formula

return:

a list of length-2 lists of the form [ multiplicity , element ]

aiida.orm.nodes.data.structure.has_ase()[source]#
Returns:

True if the ase module can be imported, False otherwise.

aiida.orm.nodes.data.structure.has_pymatgen()[source]#
Returns:

True if the pymatgen module can be imported, False otherwise.

aiida.orm.nodes.data.structure.has_spglib()[source]#
Returns:

True if the spglib module can be imported, False otherwise.

aiida.orm.nodes.data.structure.has_vacancies(weights)[source]#

Returns True if the sum of the weights is less than one. It uses the internal variable _SUM_THRESHOLD as a threshold. :param weights: the weights :return: a boolean

aiida.orm.nodes.data.structure.is_ase_atoms(ase_atoms)[source]#

Check if the ase_atoms parameter is actually a ase.Atoms object.

Parameters:

ase_atoms – an object, expected to be an ase.Atoms.

Returns:

a boolean.

Requires the ability to import ase, by doing ‘import ase’.

aiida.orm.nodes.data.structure.is_valid_symbol(symbol)[source]#

Validates the chemical symbol name.

Returns:

True if the symbol is a valid chemical symbol (with correct capitalization), or the dummy X, False otherwise.

Recognized symbols are for elements from hydrogen (Z=1) to lawrencium (Z=103). In addition, a dummy element unknown name (Z=0) is supported.

aiida.orm.nodes.data.structure.symop_fract_from_ortho(cell)[source]#

Creates a matrix for conversion from fractional to orthogonal coordinates.

Taken from svn://www.crystallography.net/cod-tools/trunk/lib/perl5/Fractional.pm, revision 850.

Parameters:

cell – array of cell parameters (three lengths and three angles)

aiida.orm.nodes.data.structure.symop_ortho_from_fract(cell)[source]#

Creates a matrix for conversion from orthogonal to fractional coordinates.

Taken from svn://www.crystallography.net/cod-tools/trunk/lib/perl5/Fractional.pm, revision 850.

Parameters:

cell – array of cell parameters (three lengths and three angles)

aiida.orm.nodes.data.structure.validate_symbols_tuple(symbols_tuple)[source]#

Used to validate whether the chemical species are valid.

Parameters:

symbols_tuple – a tuple (or list) with the chemical symbols name.

Raises:

UnsupportedSpeciesError if any symbol in the tuple is not a valid chemical symbol (with correct capitalization).

Refer also to the documentation of :func:is_valid_symbol

aiida.orm.nodes.data.structure.validate_weights_tuple(weights_tuple, threshold)[source]#

Validates the weight of the atomic kinds.

Raise:

ValueError if the weights_tuple is not valid.

Parameters:
  • weights_tuple – the tuple to validate. It must be a a tuple of floats (as created by :func:_create_weights_tuple).

  • threshold – a float number used as a threshold to check that the sum of the weights is <= 1.

If the sum is less than one, it means that there are vacancies. Each element of the list must be >= 0, and the sum must be <= 1.

Module of Data sub class to represent a pseudopotential single file in UPF format and related utilities.

class aiida.orm.nodes.data.upf.UpfData(*args, **kwargs)[source]#

Bases: SinglefileData

Data sub class to represent a pseudopotential single file in UPF format.

__abstractmethods__ = frozenset({})#
__init__(*args, **kwargs)[source]#

Construct a new instance and set the contents to that of the file.

Parameters:
  • file – an absolute filepath or filelike object whose contents to copy. Hint: Pass io.BytesIO(b”my string”) to construct the SinglefileData directly from a string.

  • filename – specify filename to use (defaults to name of provided file).

__module__ = 'aiida.orm.nodes.data.upf'#
__parameters__ = ()#
__plugin_type_string: ClassVar[str]#
__query_type_string: ClassVar[str]#
_abc_impl = <_abc._abc_data object>#
_logger: Logger | None = <Logger aiida.orm.nodes.data.upf.UpfData (WARNING)>#
_prepare_json(main_file_name='')[source]#

Returns UPF PP in json format.

_prepare_upf(main_file_name='')[source]#

Return UPF content.

_validate()[source]#

Validate the UPF potential file stored for this node.

property element#

Return the element of the UPF pseudopotential.

Returns:

the element

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]',  'source': 'QbDictField(attributes.source.*) -> Optional[dict]',  'user_pk': 'QbNumericField(user_pk) -> int',  'uuid': 'QbStrField(uuid) -> str'}#
classmethod from_md5(md5, backend=None)[source]#

Return a list of all UpfData that match the given md5 hash.

Note

assumes hash of stored UpfData nodes is stored in the md5 attribute

Parameters:

md5 – the file hash

Returns:

list of existing UpfData nodes that have the same md5 hash

classmethod get_or_create(filepath, use_first=False, store_upf=True, backend=None)[source]#

Get the UpfData with the same md5 of the given file, or create it if it does not yet exist.

Parameters:
  • filepath – an absolute filepath on disk

  • use_first – if False (default), raise an exception if more than one potential is found. If it is True, instead, use the first available pseudopotential.

  • store_upf – boolean, if false, the UpfData if created will not be stored.

Returns:

tuple of UpfData and boolean indicating whether it was created.

get_upf_family_names()[source]#

Get the list of all upf family names to which the pseudo belongs.

classmethod get_upf_group(group_label)[source]#

Return the UPF family group with the given label.

Parameters:

group_label – the family group label

Returns:

the Group with the given label, if it exists

classmethod get_upf_groups(filter_elements=None, user=None, backend=None)[source]#

Return all names of groups of type UpfFamily, possibly with some filters.

Parameters:
  • filter_elements – A string or a list of strings. If present, returns only the groups that contains one UPF for every element present in the list. The default is None, meaning that all families are returned.

  • user – if None (default), return the groups for all users. If defined, it should be either a User instance or the user email.

Returns:

list of Group entities of type UPF.

property md5sum#

Return the md5 checksum of the UPF pseudopotential file.

Returns:

the md5 checksum

set_file(file, filename=None)[source]#

Store the file in the repository and parse it to set the element and md5 attributes.

Parameters:
  • file – filepath or filelike object of the UPF potential file to store. Hint: Pass io.BytesIO(b”my string”) to construct the file directly from a string.

  • filename – specify filename to use (defaults to name of provided file).

store(*args, **kwargs)[source]#

Store the node, reparsing the file so that the md5 and the element are correctly reset.

aiida.orm.nodes.data.upf.emit_deprecation()[source]#
aiida.orm.nodes.data.upf.get_pseudos_from_structure(structure, family_name)[source]#

Return a dictionary mapping each kind name of the structure to corresponding UpfData from given family.

Parameters:
  • structure – a StructureData

  • family_name – the name of a UPF family group

Returns:

dictionary mapping each structure kind name onto UpfData of corresponding element

Raises:
aiida.orm.nodes.data.upf.parse_upf(fname, check_filename=True, encoding='utf-8')[source]#

Try to get relevant information from the UPF. For the moment, only the element name. Note that even UPF v.2 cannot be parsed with the XML minidom! (e.g. due to the & characters in the human-readable section).

If check_filename is True, raise a ParsingError exception if the filename does not start with the element name.

aiida.orm.nodes.data.upf.upload_upf_family(folder, group_label, group_description, stop_if_existing=True, backend=None)[source]#

Upload a set of UPF files in a given group.

Parameters:
  • folder – a path containing all UPF files to be added. Only files ending in .UPF (case-insensitive) are considered.

  • group_label – the name of the group to create. If it exists and is non-empty, a UniquenessError is raised.

  • group_description – string to be set as the group description. Overwrites previous descriptions.

  • stop_if_existing – if True, check for the md5 of the files and, if the file already exists in the DB, raises a MultipleObjectsError. If False, simply adds the existing UPFData node to the group.