aiida.common package

Common data structures, utility classes and functions

Note

Modules in this sub package have to run without a loaded database environment

class aiida.common.CalcJobState[source]

Bases: enum.Enum

The sub state of a CalcJobNode while its Process is in an active state (i.e. Running or Waiting).

PARSING = 'parsing'
RETRIEVING = 'retrieving'
SUBMITTING = 'submitting'
UPLOADING = 'uploading'
WITHSCHEDULER = 'withscheduler'
__module__ = 'aiida.common.datastructures'
class aiida.common.CalcInfo(dictionary=None)[source]

Bases: aiida.common.extendeddicts.DefaultFieldsAttributeDict

This object will store the data returned by the calculation plugin and to be passed to the ExecManager.

In the following descriptions all paths have to be considered relative

  • retrieve_list: a list of strings or tuples that indicate files that are to be retrieved from the remote

    after the calculation has finished and stored in the repository in a FolderData. If the entry in the list is just a string, it is assumed to be the filepath on the remote and it will be copied to ‘.’ of the repository with name os.path.split(item)[1] If the entry is a tuple it is expected to have the following format

    (‘remotepath’, ‘localpath’, depth)

    If the ‘remotepath’ is a file or folder, it will be copied in the repository to ‘localpath’. However, if the ‘remotepath’ contains file patterns with wildcards, the ‘localpath’ should be set to ‘.’ and the depth parameter should be an integer that decides the localname. The ‘remotepath’ will be split on file separators and the local filename will be determined by joining the N last elements, where N is given by the depth variable.

    Example: (‘some/remote/path/files/pattern*[0-9].xml’, ‘.’, 2)

    Will result in all files that match the pattern to be copied to the local repository with path

    ‘files/pattern*[0-9].xml’

  • retrieve_temporary_list: a list of strings or tuples that indicate files that will be retrieved

    and stored temporarily in a FolderData, that will be available only during the parsing call. The format of the list is the same as that of ‘retrieve_list’

  • retrieve_singlefile_list: a list of tuples with format

    (‘linkname_from calc to singlefile’, ‘subclass of singlefile’, ‘filename’) Each tuple represents a file that will be retrieved from cluster and saved in SinglefileData nodes

    Deprecated since version 1.0.0: Will be removed in v2.0.0, use retrieve_temporary_list instead.

  • local_copy_list: a list of tuples with format (‘node_uuid’, ‘filename’, relativedestpath’)

  • remote_copy_list: a list of tuples with format (‘remotemachinename’, ‘remoteabspath’, ‘relativedestpath’)

  • remote_symlink_list: a list of tuples with format (‘remotemachinename’, ‘remoteabspath’, ‘relativedestpath’)

  • codes_info: a list of dictionaries used to pass the info of the execution of a code

  • codes_run_mode: a string used to specify the order in which multi codes can be executed

__module__ = 'aiida.common.datastructures'
_default_fields = ('job_environment', 'email', 'email_on_started', 'email_on_terminated', 'uuid', 'prepend_text', 'append_text', 'num_machines', 'num_mpiprocs_per_machine', 'priority', 'max_wallclock_seconds', 'max_memory_kb', 'rerunnable', 'retrieve_list', 'retrieve_temporary_list', 'retrieve_singlefile_list', 'local_copy_list', 'remote_copy_list', 'remote_symlink_list', 'codes_info', 'codes_run_mode')
class aiida.common.CodeInfo(dictionary=None)[source]

Bases: aiida.common.extendeddicts.DefaultFieldsAttributeDict

This attribute-dictionary contains the information needed to execute a code. Possible attributes are:

  • cmdline_params: a list of strings, containing parameters to be written on the command line right after the call to the code, as for example:

    code.x cmdline_params[0] cmdline_params[1] ... < stdin > stdout
    
  • stdin_name: (optional) the name of the standard input file. Note, it is only possible to use the stdin with the syntax:

    code.x < stdin_name
    

    If no stdin_name is specified, the string “< stdin_name” will not be passed to the code. Note: it is not possible to substitute/remove the ‘<’ if stdin_name is specified; if that is needed, avoid stdin_name and use instead the cmdline_params to specify a suitable syntax.

  • stdout_name: (optional) the name of the standard output file. Note, it is only possible to pass output to stdout_name with the syntax:

    code.x ... > stdout_name
    

    If no stdout_name is specified, the string “> stdout_name” will not be passed to the code. Note: it is not possible to substitute/remove the ‘>’ if stdout_name is specified; if that is needed, avoid stdout_name and use instead the cmdline_params to specify a suitable syntax.

  • stderr_name: (optional) a string, the name of the error file of the code.

  • join_files: (optional) if True, redirects the error to the output file. If join_files=True, the code will be called as:

    code.x ... > stdout_name 2>&1
    

    otherwise, if join_files=False and stderr is passed:

    code.x ... > stdout_name 2> stderr_name
    
  • withmpi: if True, executes the code with mpirun (or another MPI installed on the remote computer)

  • code_uuid: the uuid of the code associated to the CodeInfo

__module__ = 'aiida.common.datastructures'
_default_fields = ('cmdline_params', 'stdin_name', 'stdout_name', 'stderr_name', 'join_files', 'withmpi', 'code_uuid')
class aiida.common.CodeRunMode[source]

Bases: enum.IntEnum

Enum to indicate the way the codes of a calculation should be run.

For PARALLEL, the codes for a given calculation will be run in parallel by running them in the background:

code1.x &
code2.x &

For the SERIAL option, codes will be executed sequentially by running for example the following:

code1.x
code2.x
PARALLEL = 1
SERIAL = 0
__module__ = 'aiida.common.datastructures'
exception aiida.common.AiidaException[source]

Bases: Exception

Base class for all AiiDA exceptions.

Each module will have its own subclass, inherited from this (e.g. ExecManagerException, TransportException, …)

__module__ = 'aiida.common.exceptions'
__weakref__

list of weak references to the object (if defined)

exception aiida.common.NotExistent[source]

Bases: aiida.common.exceptions.AiidaException

Raised when the required entity does not exist.

__module__ = 'aiida.common.exceptions'
exception aiida.common.MultipleObjectsError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when more than one entity is found in the DB, but only one was expected.

__module__ = 'aiida.common.exceptions'
exception aiida.common.RemoteOperationError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when an error in a remote operation occurs, as in a failed kill() of a scheduler job.

__module__ = 'aiida.common.exceptions'
exception aiida.common.ContentNotExistent[source]

Bases: aiida.common.exceptions.NotExistent

Raised when trying to access an attribute, a key or a file in the result nodes that is not present

__module__ = 'aiida.common.exceptions'
exception aiida.common.FailedError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when accessing a calculation that is in the FAILED status

__module__ = 'aiida.common.exceptions'
exception aiida.common.StoringNotAllowed[source]

Bases: aiida.common.exceptions.AiidaException

Raised when the user tries to store an unstorable node (e.g. a base Node class)

__module__ = 'aiida.common.exceptions'
exception aiida.common.ModificationNotAllowed[source]

Bases: aiida.common.exceptions.AiidaException

Raised when the user tries to modify a field, object, property, … that should not be modified.

__module__ = 'aiida.common.exceptions'
exception aiida.common.IntegrityError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when there is an underlying data integrity error. This can be database related or a general data integrity error. This can happen if, e.g., a foreign key check fails. See PEP 249 for details.

__module__ = 'aiida.common.exceptions'
exception aiida.common.UniquenessError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when the user tries to violate a uniqueness constraint (on the DB, for instance).

__module__ = 'aiida.common.exceptions'
exception aiida.common.EntryPointError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when an entry point cannot be uniquely resolved and imported.

__module__ = 'aiida.common.exceptions'
exception aiida.common.MissingEntryPointError[source]

Bases: aiida.common.exceptions.EntryPointError

Raised when the requested entry point is not registered with the entry point manager.

__module__ = 'aiida.common.exceptions'
exception aiida.common.MultipleEntryPointError[source]

Bases: aiida.common.exceptions.EntryPointError

Raised when the requested entry point cannot uniquely be resolved by the entry point manager.

__module__ = 'aiida.common.exceptions'
exception aiida.common.LoadingEntryPointError[source]

Bases: aiida.common.exceptions.EntryPointError

Raised when the resource corresponding to requested entry point cannot be imported.

__module__ = 'aiida.common.exceptions'
exception aiida.common.InvalidOperation[source]

Bases: aiida.common.exceptions.AiidaException

The allowed operation is not valid (e.g., when trying to add a non-internal attribute before saving the entry), or deleting an entry that is protected (e.g., because it is referenced by foreign keys)

__module__ = 'aiida.common.exceptions'
exception aiida.common.ParsingError[source]

Bases: aiida.common.exceptions.AiidaException

Generic error raised when there is a parsing error

__module__ = 'aiida.common.exceptions'
exception aiida.common.InternalError[source]

Bases: aiida.common.exceptions.AiidaException

Error raised when there is an internal error of AiiDA.

__module__ = 'aiida.common.exceptions'
exception aiida.common.PluginInternalError[source]

Bases: aiida.common.exceptions.InternalError

Error raised when there is an internal error which is due to a plugin and not to the AiiDA infrastructure.

__module__ = 'aiida.common.exceptions'
exception aiida.common.ValidationError[source]

Bases: aiida.common.exceptions.AiidaException

Error raised when there is an error during the validation phase of a property.

__module__ = 'aiida.common.exceptions'
exception aiida.common.ConfigurationError[source]

Bases: aiida.common.exceptions.AiidaException

Error raised when there is a configuration error in AiiDA.

__module__ = 'aiida.common.exceptions'
exception aiida.common.ProfileConfigurationError[source]

Bases: aiida.common.exceptions.ConfigurationError

Configuration error raised when a wrong/inexistent profile is requested.

__module__ = 'aiida.common.exceptions'
exception aiida.common.MissingConfigurationError[source]

Bases: aiida.common.exceptions.ConfigurationError

Configuration error raised when the configuration file is missing.

__module__ = 'aiida.common.exceptions'
exception aiida.common.ConfigurationVersionError[source]

Bases: aiida.common.exceptions.ConfigurationError

Configuration error raised when the configuration file version is not compatible with the current version.

__module__ = 'aiida.common.exceptions'
exception aiida.common.DbContentError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when the content of the DB is not valid. This should never happen if the user does not play directly with the DB.

__module__ = 'aiida.common.exceptions'
exception aiida.common.InputValidationError[source]

Bases: aiida.common.exceptions.ValidationError

The input data for a calculation did not validate (e.g., missing required input data, wrong data, …)

__module__ = 'aiida.common.exceptions'
exception aiida.common.FeatureNotAvailable[source]

Bases: aiida.common.exceptions.AiidaException

Raised when a feature is requested from a plugin, that is not available.

__module__ = 'aiida.common.exceptions'
exception aiida.common.FeatureDisabled[source]

Bases: aiida.common.exceptions.AiidaException

Raised when a feature is requested, but the user has chosen to disable it (e.g., for submissions on disabled computers).

__module__ = 'aiida.common.exceptions'
exception aiida.common.LicensingException[source]

Bases: aiida.common.exceptions.AiidaException

Raised when requirements for data licensing are not met.

__module__ = 'aiida.common.exceptions'
exception aiida.common.TestsNotAllowedError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when tests are required to be run/loaded, but we are not in a testing environment.

This is to prevent data loss.

__module__ = 'aiida.common.exceptions'
exception aiida.common.UnsupportedSpeciesError[source]

Bases: ValueError

Raised when StructureData operations are fed species that are not supported by AiiDA such as Deuterium

__module__ = 'aiida.common.exceptions'
__weakref__

list of weak references to the object (if defined)

exception aiida.common.TransportTaskException[source]

Bases: aiida.common.exceptions.AiidaException

Raised when a TransportTask, an task to be completed by the engine that requires transport, fails

__module__ = 'aiida.common.exceptions'
exception aiida.common.OutputParsingError[source]

Bases: aiida.common.exceptions.ParsingError

Can be raised by a Parser when it fails to parse the output generated by a CalcJob process.

__module__ = 'aiida.common.exceptions'
class aiida.common.AttributeDict(dictionary=None)[source]

Bases: dict

This class internally stores values in a dictionary, but exposes the keys also as attributes, i.e. asking for attrdict.key will return the value of attrdict[‘key’] and so on.

Raises an AttributeError if the key does not exist, when called as an attribute, while the usual KeyError if the key does not exist and the dictionary syntax is used.

__deepcopy__(memo=None)[source]

Deep copy.

__delattr__(attr)[source]

Delete a key as an attribute.

Raises

AttributeError – if the attribute does not correspond to an existing key.

__dict__ = mappingproxy({'__module__': 'aiida.common.extendeddicts', '__doc__': "\n This class internally stores values in a dictionary, but exposes\n the keys also as attributes, i.e. asking for attrdict.key\n will return the value of attrdict['key'] and so on.\n\n Raises an AttributeError if the key does not exist, when called as an attribute,\n while the usual KeyError if the key does not exist and the dictionary syntax is\n used.\n ", '__init__': <function AttributeDict.__init__>, '__repr__': <function AttributeDict.__repr__>, '__getattr__': <function AttributeDict.__getattr__>, '__setattr__': <function AttributeDict.__setattr__>, '__delattr__': <function AttributeDict.__delattr__>, '__deepcopy__': <function AttributeDict.__deepcopy__>, '__getstate__': <function AttributeDict.__getstate__>, '__setstate__': <function AttributeDict.__setstate__>, '__dir__': <function AttributeDict.__dir__>, '__dict__': <attribute '__dict__' of 'AttributeDict' objects>, '__weakref__': <attribute '__weakref__' of 'AttributeDict' objects>})
__dir__()[source]

Default dir() implementation.

__getattr__(attr)[source]

Read a key as an attribute.

Raises

AttributeError – if the attribute does not correspond to an existing key.

__getstate__()[source]

Needed for pickling this class.

__init__(dictionary=None)[source]

Recursively turn the dict and all its nested dictionaries into AttributeDict instance.

__module__ = 'aiida.common.extendeddicts'
__repr__()[source]

Representation of the object.

__setattr__(attr, value)[source]

Set a key as an attribute.

__setstate__(dictionary)[source]

Needed for pickling this class.

__weakref__

list of weak references to the object (if defined)

class aiida.common.FixedFieldsAttributeDict(init=None)[source]

Bases: aiida.common.extendeddicts.AttributeDict

A dictionary with access to the keys as attributes, and with filtering of valid attributes. This is only the base class, without valid attributes; use a derived class to do the actual work. E.g.:

class TestExample(FixedFieldsAttributeDict):
    _valid_fields = ('a','b','c')
__dir__()[source]

Default dir() implementation.

__init__(init=None)[source]

Recursively turn the dict and all its nested dictionaries into AttributeDict instance.

__module__ = 'aiida.common.extendeddicts'
__setattr__(attr, value)[source]

Overridden to allow direct access to fields with underscore.

__setitem__(item, value)[source]

Set a key as an attribute.

_valid_fields = ()
classmethod get_valid_fields()[source]

Return the list of valid fields.

class aiida.common.DefaultFieldsAttributeDict(dictionary=None)[source]

Bases: aiida.common.extendeddicts.AttributeDict

A dictionary with access to the keys as attributes, and with an internal value storing the ‘default’ keys to be distinguished from extra fields.

Extra methods defaultkeys() and extrakeys() divide the set returned by keys() in default keys (i.e. those defined at definition time) and other keys. There is also a method get_default_fields() to return the internal list.

Moreover, for undefined default keys, it returns None instead of raising a KeyError/AttributeError exception.

Remember to define the _default_fields in a subclass! E.g.:

class TestExample(DefaultFieldsAttributeDict):
    _default_fields = ('a','b','c')

When the validate() method is called, it calls in turn all validate_KEY methods, where KEY is one of the default keys. If the method is not present, the field is considered to be always valid. Each validate_KEY method should accept a single argument ‘value’ that will contain the value to be checked.

It raises a ValidationError if any of the validate_KEY function raises an exception, otherwise it simply returns. NOTE: the validate_* functions are called also for unset fields, so if the field can be empty on validation, you have to start your validation function with something similar to:

if value is None:
    return

Todo

Decide behavior if I set to None a field. Current behavior, if a is an instance and ‘def_field’ one of the default fields, that is undefined, we get:

  • a.get('def_field'): None

  • a.get('def_field','whatever'): ‘whatever’

  • Note that a.defaultkeys() does NOT contain ‘def_field’

if we do a.def_field = None, then the behavior becomes

  • a.get('def_field'): None

  • a.get('def_field','whatever'): None

  • Note that a.defaultkeys() DOES contain ‘def_field’

See if we want that setting a default field to None means deleting it.

__getitem__(key)[source]

Return None instead of raising an exception if the key does not exist but is in the list of default fields.

__module__ = 'aiida.common.extendeddicts'
__setattr__(attr, value)[source]

Overridden to allow direct access to fields with underscore.

_default_fields = ()
defaultkeys()[source]

Return the default keys defined in the instance.

extrakeys()[source]

Return the extra keys defined in the instance.

classmethod get_default_fields()[source]

Return the list of default fields, either defined in the instance or not.

validate()[source]

Validate the keys, if any validate_* method is available.

class aiida.common.GraphTraversalRule(link_type, direction, toggleable, default)

Bases: tuple

A namedtuple that defines a graph traversal rule.

When starting from a certain sub set of nodes, the graph traversal rules specify which links should be followed to add adjacent nodes to finally arrive at a set of nodes that represent a valid and consistent sub graph.

Parameters
  • link_type – the LinkType that the rule applies to

  • direction – whether the link type should be followed backwards or forwards

  • toggleable – boolean to indicate whether the rule can be changed from the default value. If this is False it means the default value can never be changed as it will result in an inconsistent graph.

  • default – boolean, the default value of the rule, if True means that the link type for the given direction should be followed.

__getnewargs__()

Return self as a plain tuple. Used by copy and pickle.

__module__ = 'aiida.common.links'
static __new__(_cls, link_type, direction, toggleable, default)

Create new instance of GraphTraversalRule(link_type, direction, toggleable, default)

__repr__()

Return a nicely formatted representation string

__slots__ = ()
_asdict()

Return a new OrderedDict which maps field names to their values.

_fields = ('link_type', 'direction', 'toggleable', 'default')
_fields_defaults = {}
classmethod _make(iterable)

Make a new GraphTraversalRule object from a sequence or iterable

_replace(**kwds)

Return a new GraphTraversalRule object replacing specified fields with new values

property default

Alias for field number 3

property direction

Alias for field number 1

Alias for field number 0

property toggleable

Alias for field number 2

class aiida.common.GraphTraversalRules[source]

Bases: enum.Enum

Graph traversal rules when deleting or exporting nodes.

DELETE = {'call_calc_backward': GraphTraversalRule(link_type=<LinkType.CALL_CALC: 'call_calc'>, direction='backward', toggleable=False, default=True), 'call_calc_forward': GraphTraversalRule(link_type=<LinkType.CALL_CALC: 'call_calc'>, direction='forward', toggleable=True, default=False), 'call_work_backward': GraphTraversalRule(link_type=<LinkType.CALL_WORK: 'call_work'>, direction='backward', toggleable=False, default=True), 'call_work_forward': GraphTraversalRule(link_type=<LinkType.CALL_WORK: 'call_work'>, direction='forward', toggleable=True, default=False), 'create_backward': GraphTraversalRule(link_type=<LinkType.CREATE: 'create'>, direction='backward', toggleable=False, default=True), 'create_forward': GraphTraversalRule(link_type=<LinkType.CREATE: 'create'>, direction='forward', toggleable=True, default=True), 'input_calc_backward': GraphTraversalRule(link_type=<LinkType.INPUT_CALC: 'input_calc'>, direction='backward', toggleable=False, default=False), 'input_calc_forward': GraphTraversalRule(link_type=<LinkType.INPUT_CALC: 'input_calc'>, direction='forward', toggleable=False, default=True), 'input_work_backward': GraphTraversalRule(link_type=<LinkType.INPUT_WORK: 'input_work'>, direction='backward', toggleable=False, default=False), 'input_work_forward': GraphTraversalRule(link_type=<LinkType.INPUT_WORK: 'input_work'>, direction='forward', toggleable=False, default=True), 'return_backward': GraphTraversalRule(link_type=<LinkType.RETURN: 'return'>, direction='backward', toggleable=False, default=True), 'return_forward': GraphTraversalRule(link_type=<LinkType.RETURN: 'return'>, direction='forward', toggleable=False, default=False)}
EXPORT = {'call_calc_backward': GraphTraversalRule(link_type=<LinkType.CALL_CALC: 'call_calc'>, direction='backward', toggleable=True, default=False), 'call_calc_forward': GraphTraversalRule(link_type=<LinkType.CALL_CALC: 'call_calc'>, direction='forward', toggleable=False, default=True), 'call_work_backward': GraphTraversalRule(link_type=<LinkType.CALL_WORK: 'call_work'>, direction='backward', toggleable=True, default=False), 'call_work_forward': GraphTraversalRule(link_type=<LinkType.CALL_WORK: 'call_work'>, direction='forward', toggleable=False, default=True), 'create_backward': GraphTraversalRule(link_type=<LinkType.CREATE: 'create'>, direction='backward', toggleable=True, default=True), 'create_forward': GraphTraversalRule(link_type=<LinkType.CREATE: 'create'>, direction='forward', toggleable=False, default=True), 'input_calc_backward': GraphTraversalRule(link_type=<LinkType.INPUT_CALC: 'input_calc'>, direction='backward', toggleable=False, default=True), 'input_calc_forward': GraphTraversalRule(link_type=<LinkType.INPUT_CALC: 'input_calc'>, direction='forward', toggleable=True, default=False), 'input_work_backward': GraphTraversalRule(link_type=<LinkType.INPUT_WORK: 'input_work'>, direction='backward', toggleable=False, default=True), 'input_work_forward': GraphTraversalRule(link_type=<LinkType.INPUT_WORK: 'input_work'>, direction='forward', toggleable=True, default=False), 'return_backward': GraphTraversalRule(link_type=<LinkType.RETURN: 'return'>, direction='backward', toggleable=True, default=False), 'return_forward': GraphTraversalRule(link_type=<LinkType.RETURN: 'return'>, direction='forward', toggleable=False, default=True)}
__module__ = 'aiida.common.links'
class aiida.common.LinkType[source]

Bases: enum.Enum

A simple enum of allowed link types.

CALL_CALC = 'call_calc'
CALL_WORK = 'call_work'
CREATE = 'create'
INPUT_CALC = 'input_calc'
INPUT_WORK = 'input_work'
RETURN = 'return'
__module__ = 'aiida.common.links'

Validate the given link label.

Valid link labels adhere to the following restrictions:

  • Has to be a valid python identifier

  • Can only contain alphanumeric characters and underscores

  • Can not start or end with an underscore

Raises
  • TypeError – if the link label is not a string type

  • ValueError – if the link label is invalid

aiida.common.override_log_level(level=50)[source]

Temporarily adjust the log-level of logger.

Submodules

Module to define the (physical) constants used throughout the code.

Module to define commonly used data structures.

class aiida.common.datastructures.CalcJobState[source]

Bases: enum.Enum

The sub state of a CalcJobNode while its Process is in an active state (i.e. Running or Waiting).

PARSING = 'parsing'
RETRIEVING = 'retrieving'
SUBMITTING = 'submitting'
UPLOADING = 'uploading'
WITHSCHEDULER = 'withscheduler'
__module__ = 'aiida.common.datastructures'
class aiida.common.datastructures.CalcInfo(dictionary=None)[source]

Bases: aiida.common.extendeddicts.DefaultFieldsAttributeDict

This object will store the data returned by the calculation plugin and to be passed to the ExecManager.

In the following descriptions all paths have to be considered relative

  • retrieve_list: a list of strings or tuples that indicate files that are to be retrieved from the remote

    after the calculation has finished and stored in the repository in a FolderData. If the entry in the list is just a string, it is assumed to be the filepath on the remote and it will be copied to ‘.’ of the repository with name os.path.split(item)[1] If the entry is a tuple it is expected to have the following format

    (‘remotepath’, ‘localpath’, depth)

    If the ‘remotepath’ is a file or folder, it will be copied in the repository to ‘localpath’. However, if the ‘remotepath’ contains file patterns with wildcards, the ‘localpath’ should be set to ‘.’ and the depth parameter should be an integer that decides the localname. The ‘remotepath’ will be split on file separators and the local filename will be determined by joining the N last elements, where N is given by the depth variable.

    Example: (‘some/remote/path/files/pattern*[0-9].xml’, ‘.’, 2)

    Will result in all files that match the pattern to be copied to the local repository with path

    ‘files/pattern*[0-9].xml’

  • retrieve_temporary_list: a list of strings or tuples that indicate files that will be retrieved

    and stored temporarily in a FolderData, that will be available only during the parsing call. The format of the list is the same as that of ‘retrieve_list’

  • retrieve_singlefile_list: a list of tuples with format

    (‘linkname_from calc to singlefile’, ‘subclass of singlefile’, ‘filename’) Each tuple represents a file that will be retrieved from cluster and saved in SinglefileData nodes

    Deprecated since version 1.0.0: Will be removed in v2.0.0, use retrieve_temporary_list instead.

  • local_copy_list: a list of tuples with format (‘node_uuid’, ‘filename’, relativedestpath’)

  • remote_copy_list: a list of tuples with format (‘remotemachinename’, ‘remoteabspath’, ‘relativedestpath’)

  • remote_symlink_list: a list of tuples with format (‘remotemachinename’, ‘remoteabspath’, ‘relativedestpath’)

  • codes_info: a list of dictionaries used to pass the info of the execution of a code

  • codes_run_mode: a string used to specify the order in which multi codes can be executed

__module__ = 'aiida.common.datastructures'
_default_fields = ('job_environment', 'email', 'email_on_started', 'email_on_terminated', 'uuid', 'prepend_text', 'append_text', 'num_machines', 'num_mpiprocs_per_machine', 'priority', 'max_wallclock_seconds', 'max_memory_kb', 'rerunnable', 'retrieve_list', 'retrieve_temporary_list', 'retrieve_singlefile_list', 'local_copy_list', 'remote_copy_list', 'remote_symlink_list', 'codes_info', 'codes_run_mode')
class aiida.common.datastructures.CodeInfo(dictionary=None)[source]

Bases: aiida.common.extendeddicts.DefaultFieldsAttributeDict

This attribute-dictionary contains the information needed to execute a code. Possible attributes are:

  • cmdline_params: a list of strings, containing parameters to be written on the command line right after the call to the code, as for example:

    code.x cmdline_params[0] cmdline_params[1] ... < stdin > stdout
    
  • stdin_name: (optional) the name of the standard input file. Note, it is only possible to use the stdin with the syntax:

    code.x < stdin_name
    

    If no stdin_name is specified, the string “< stdin_name” will not be passed to the code. Note: it is not possible to substitute/remove the ‘<’ if stdin_name is specified; if that is needed, avoid stdin_name and use instead the cmdline_params to specify a suitable syntax.

  • stdout_name: (optional) the name of the standard output file. Note, it is only possible to pass output to stdout_name with the syntax:

    code.x ... > stdout_name
    

    If no stdout_name is specified, the string “> stdout_name” will not be passed to the code. Note: it is not possible to substitute/remove the ‘>’ if stdout_name is specified; if that is needed, avoid stdout_name and use instead the cmdline_params to specify a suitable syntax.

  • stderr_name: (optional) a string, the name of the error file of the code.

  • join_files: (optional) if True, redirects the error to the output file. If join_files=True, the code will be called as:

    code.x ... > stdout_name 2>&1
    

    otherwise, if join_files=False and stderr is passed:

    code.x ... > stdout_name 2> stderr_name
    
  • withmpi: if True, executes the code with mpirun (or another MPI installed on the remote computer)

  • code_uuid: the uuid of the code associated to the CodeInfo

__module__ = 'aiida.common.datastructures'
_default_fields = ('cmdline_params', 'stdin_name', 'stdout_name', 'stderr_name', 'join_files', 'withmpi', 'code_uuid')
class aiida.common.datastructures.CodeRunMode[source]

Bases: enum.IntEnum

Enum to indicate the way the codes of a calculation should be run.

For PARALLEL, the codes for a given calculation will be run in parallel by running them in the background:

code1.x &
code2.x &

For the SERIAL option, codes will be executed sequentially by running for example the following:

code1.x
code2.x
PARALLEL = 1
SERIAL = 0
__module__ = 'aiida.common.datastructures'

Miscellaneous functions for escaping strings.

aiida.common.escaping.escape_for_bash(str_to_escape)[source]

This function takes any string and escapes it in a way that bash will interpret it as a single string.

Explanation:

At the end, in the return statement, the string is put within single quotes. Therefore, the only thing that I have to escape in bash is the single quote character. To do this, I substitute every single quote ‘ with ‘”’”’ which means:

First single quote: exit from the enclosing single quotes

Second, third and fourth character: “’” is a single quote character, escaped by double quotes

Last single quote: reopen the single quote to continue the string

Finally, note that for python I have to enclose the string ‘”’”’ within triple quotes to make it work, getting finally: the complicated string found below.

aiida.common.escaping.escape_for_sql_like(string)[source]

Function that escapes % or _ symbols provided by user

SQL LIKE syntax summary:

  • % -> match any number of characters

  • _ -> match exactly one character

aiida.common.escaping.get_regex_pattern_from_sql(sql_pattern)[source]

Convert a string providing a pattern to match in SQL syntax into a string performing the same match as a regex.

SQL LIKE syntax summary:

  • % -> match any number of characters

  • _ -> match exactly one character

Moreover, \ is the escape character (by default), so:

  • \\ -> single backslash

  • \% -> literal % symbol

  • \_ -> literal _ symbol

and moreover the string should begin at the beginning of the line and end at the end of the line.

Parameters

sql_pattern – the string with the pattern in SQL syntax

Returns

a string with the pattern in regex syntax

aiida.common.escaping.sql_string_match(string, pattern)[source]

Check if the string matches the provided pattern, specified using SQL syntax.

See documentation of get_regex_pattern_from_sql() for an explanation of the syntax.

Parameters
  • string – the string to check

  • pattern – the SQL pattern

Returns

True if the string matches, False otherwise

Module that define the exceptions that are thrown by AiiDA’s internal code.

exception aiida.common.exceptions.AiidaException[source]

Bases: Exception

Base class for all AiiDA exceptions.

Each module will have its own subclass, inherited from this (e.g. ExecManagerException, TransportException, …)

__module__ = 'aiida.common.exceptions'
__weakref__

list of weak references to the object (if defined)

exception aiida.common.exceptions.NotExistent[source]

Bases: aiida.common.exceptions.AiidaException

Raised when the required entity does not exist.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.MultipleObjectsError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when more than one entity is found in the DB, but only one was expected.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.RemoteOperationError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when an error in a remote operation occurs, as in a failed kill() of a scheduler job.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.ContentNotExistent[source]

Bases: aiida.common.exceptions.NotExistent

Raised when trying to access an attribute, a key or a file in the result nodes that is not present

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.FailedError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when accessing a calculation that is in the FAILED status

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.StoringNotAllowed[source]

Bases: aiida.common.exceptions.AiidaException

Raised when the user tries to store an unstorable node (e.g. a base Node class)

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.ModificationNotAllowed[source]

Bases: aiida.common.exceptions.AiidaException

Raised when the user tries to modify a field, object, property, … that should not be modified.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.IntegrityError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when there is an underlying data integrity error. This can be database related or a general data integrity error. This can happen if, e.g., a foreign key check fails. See PEP 249 for details.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.UniquenessError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when the user tries to violate a uniqueness constraint (on the DB, for instance).

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.EntryPointError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when an entry point cannot be uniquely resolved and imported.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.MissingEntryPointError[source]

Bases: aiida.common.exceptions.EntryPointError

Raised when the requested entry point is not registered with the entry point manager.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.MultipleEntryPointError[source]

Bases: aiida.common.exceptions.EntryPointError

Raised when the requested entry point cannot uniquely be resolved by the entry point manager.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.LoadingEntryPointError[source]

Bases: aiida.common.exceptions.EntryPointError

Raised when the resource corresponding to requested entry point cannot be imported.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.InvalidOperation[source]

Bases: aiida.common.exceptions.AiidaException

The allowed operation is not valid (e.g., when trying to add a non-internal attribute before saving the entry), or deleting an entry that is protected (e.g., because it is referenced by foreign keys)

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.ParsingError[source]

Bases: aiida.common.exceptions.AiidaException

Generic error raised when there is a parsing error

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.InternalError[source]

Bases: aiida.common.exceptions.AiidaException

Error raised when there is an internal error of AiiDA.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.PluginInternalError[source]

Bases: aiida.common.exceptions.InternalError

Error raised when there is an internal error which is due to a plugin and not to the AiiDA infrastructure.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.ValidationError[source]

Bases: aiida.common.exceptions.AiidaException

Error raised when there is an error during the validation phase of a property.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.ConfigurationError[source]

Bases: aiida.common.exceptions.AiidaException

Error raised when there is a configuration error in AiiDA.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.ProfileConfigurationError[source]

Bases: aiida.common.exceptions.ConfigurationError

Configuration error raised when a wrong/inexistent profile is requested.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.MissingConfigurationError[source]

Bases: aiida.common.exceptions.ConfigurationError

Configuration error raised when the configuration file is missing.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.ConfigurationVersionError[source]

Bases: aiida.common.exceptions.ConfigurationError

Configuration error raised when the configuration file version is not compatible with the current version.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.DbContentError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when the content of the DB is not valid. This should never happen if the user does not play directly with the DB.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.InputValidationError[source]

Bases: aiida.common.exceptions.ValidationError

The input data for a calculation did not validate (e.g., missing required input data, wrong data, …)

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.FeatureNotAvailable[source]

Bases: aiida.common.exceptions.AiidaException

Raised when a feature is requested from a plugin, that is not available.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.FeatureDisabled[source]

Bases: aiida.common.exceptions.AiidaException

Raised when a feature is requested, but the user has chosen to disable it (e.g., for submissions on disabled computers).

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.LicensingException[source]

Bases: aiida.common.exceptions.AiidaException

Raised when requirements for data licensing are not met.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.TestsNotAllowedError[source]

Bases: aiida.common.exceptions.AiidaException

Raised when tests are required to be run/loaded, but we are not in a testing environment.

This is to prevent data loss.

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.UnsupportedSpeciesError[source]

Bases: ValueError

Raised when StructureData operations are fed species that are not supported by AiiDA such as Deuterium

__module__ = 'aiida.common.exceptions'
__weakref__

list of weak references to the object (if defined)

exception aiida.common.exceptions.TransportTaskException[source]

Bases: aiida.common.exceptions.AiidaException

Raised when a TransportTask, an task to be completed by the engine that requires transport, fails

__module__ = 'aiida.common.exceptions'
exception aiida.common.exceptions.OutputParsingError[source]

Bases: aiida.common.exceptions.ParsingError

Can be raised by a Parser when it fails to parse the output generated by a CalcJob process.

__module__ = 'aiida.common.exceptions'

Various dictionary types with extended functionality.

class aiida.common.extendeddicts.AttributeDict(dictionary=None)[source]

Bases: dict

This class internally stores values in a dictionary, but exposes the keys also as attributes, i.e. asking for attrdict.key will return the value of attrdict[‘key’] and so on.

Raises an AttributeError if the key does not exist, when called as an attribute, while the usual KeyError if the key does not exist and the dictionary syntax is used.

__deepcopy__(memo=None)[source]

Deep copy.

__delattr__(attr)[source]

Delete a key as an attribute.

Raises

AttributeError – if the attribute does not correspond to an existing key.

__dict__ = mappingproxy({'__module__': 'aiida.common.extendeddicts', '__doc__': "\n This class internally stores values in a dictionary, but exposes\n the keys also as attributes, i.e. asking for attrdict.key\n will return the value of attrdict['key'] and so on.\n\n Raises an AttributeError if the key does not exist, when called as an attribute,\n while the usual KeyError if the key does not exist and the dictionary syntax is\n used.\n ", '__init__': <function AttributeDict.__init__>, '__repr__': <function AttributeDict.__repr__>, '__getattr__': <function AttributeDict.__getattr__>, '__setattr__': <function AttributeDict.__setattr__>, '__delattr__': <function AttributeDict.__delattr__>, '__deepcopy__': <function AttributeDict.__deepcopy__>, '__getstate__': <function AttributeDict.__getstate__>, '__setstate__': <function AttributeDict.__setstate__>, '__dir__': <function AttributeDict.__dir__>, '__dict__': <attribute '__dict__' of 'AttributeDict' objects>, '__weakref__': <attribute '__weakref__' of 'AttributeDict' objects>})
__dir__()[source]

Default dir() implementation.

__getattr__(attr)[source]

Read a key as an attribute.

Raises

AttributeError – if the attribute does not correspond to an existing key.

__getstate__()[source]

Needed for pickling this class.

__init__(dictionary=None)[source]

Recursively turn the dict and all its nested dictionaries into AttributeDict instance.

__module__ = 'aiida.common.extendeddicts'
__repr__()[source]

Representation of the object.

__setattr__(attr, value)[source]

Set a key as an attribute.

__setstate__(dictionary)[source]

Needed for pickling this class.

__weakref__

list of weak references to the object (if defined)

class aiida.common.extendeddicts.FixedFieldsAttributeDict(init=None)[source]

Bases: aiida.common.extendeddicts.AttributeDict

A dictionary with access to the keys as attributes, and with filtering of valid attributes. This is only the base class, without valid attributes; use a derived class to do the actual work. E.g.:

class TestExample(FixedFieldsAttributeDict):
    _valid_fields = ('a','b','c')
__dir__()[source]

Default dir() implementation.

__init__(init=None)[source]

Recursively turn the dict and all its nested dictionaries into AttributeDict instance.

__module__ = 'aiida.common.extendeddicts'
__setattr__(attr, value)[source]

Overridden to allow direct access to fields with underscore.

__setitem__(item, value)[source]

Set a key as an attribute.

_valid_fields = ()
classmethod get_valid_fields()[source]

Return the list of valid fields.

class aiida.common.extendeddicts.DefaultFieldsAttributeDict(dictionary=None)[source]

Bases: aiida.common.extendeddicts.AttributeDict

A dictionary with access to the keys as attributes, and with an internal value storing the ‘default’ keys to be distinguished from extra fields.

Extra methods defaultkeys() and extrakeys() divide the set returned by keys() in default keys (i.e. those defined at definition time) and other keys. There is also a method get_default_fields() to return the internal list.

Moreover, for undefined default keys, it returns None instead of raising a KeyError/AttributeError exception.

Remember to define the _default_fields in a subclass! E.g.:

class TestExample(DefaultFieldsAttributeDict):
    _default_fields = ('a','b','c')

When the validate() method is called, it calls in turn all validate_KEY methods, where KEY is one of the default keys. If the method is not present, the field is considered to be always valid. Each validate_KEY method should accept a single argument ‘value’ that will contain the value to be checked.

It raises a ValidationError if any of the validate_KEY function raises an exception, otherwise it simply returns. NOTE: the validate_* functions are called also for unset fields, so if the field can be empty on validation, you have to start your validation function with something similar to:

if value is None:
    return

Todo

Decide behavior if I set to None a field. Current behavior, if a is an instance and ‘def_field’ one of the default fields, that is undefined, we get:

  • a.get('def_field'): None

  • a.get('def_field','whatever'): ‘whatever’

  • Note that a.defaultkeys() does NOT contain ‘def_field’

if we do a.def_field = None, then the behavior becomes

  • a.get('def_field'): None

  • a.get('def_field','whatever'): None

  • Note that a.defaultkeys() DOES contain ‘def_field’

See if we want that setting a default field to None means deleting it.

__getitem__(key)[source]

Return None instead of raising an exception if the key does not exist but is in the list of default fields.

__module__ = 'aiida.common.extendeddicts'
__setattr__(attr, value)[source]

Overridden to allow direct access to fields with underscore.

_default_fields = ()
defaultkeys()[source]

Return the default keys defined in the instance.

extrakeys()[source]

Return the extra keys defined in the instance.

classmethod get_default_fields()[source]

Return the list of default fields, either defined in the instance or not.

validate()[source]

Validate the keys, if any validate_* method is available.

Utility functions to operate on filesystem files.

aiida.common.files.get_mode_string(mode)[source]

Convert a file’s mode to a string of the form ‘-rwxrwxrwx’. Taken (simplified) from cpython 3.3 stat module: https://hg.python.org/cpython/file/3.3/Lib/stat.py

aiida.common.files.md5_file(filepath, block_size_factor=128)[source]

Create the hexdigested md5 checksum of the contents from

Parameters
  • filepath – the filepath of the file for which we want the md5sum

  • block_size_factor – the file is read at chunks of size block_size_factor * md5.block_size, where md5.block_size is the block_size used internally by the hashlib module.

Returns

a string with the hexdigest md5.

Raises

No checks are done on the file, so if it doesn’t exists it may raise IOError.

aiida.common.files.md5_from_filelike(filelike, block_size_factor=128)[source]

Create the hexdigested md5 checksum of the contents from a filelike object.

Parameters
  • filelike – the filelike object for whose contents to generate the md5 checksum

  • block_size_factor – the file is read at chunks of size block_size_factor * md5.block_size, where md5.block_size is the block_size used internally by the hashlib module.

Returns

a string with the hexdigest md5.

Raises

no checks are done on the filelike object, so it may raise IOError if it cannot be read from.

aiida.common.files.sha1_file(filename, block_size_factor=128)[source]

Open a file and return its sha1sum (hexdigested).

Parameters
  • filename – the filename of the file for which we want the sha1sum

  • block_size_factor – the file is read at chunks of size block_size_factor * sha1.block_size, where sha1.block_size is the block_size used internally by the hashlib module.

Returns

a string with the hexdigest sha1.

Raises

No checks are done on the file, so if it doesn’t exists it may raise IOError.

aiida.common.files.which(cmd, mode=1, path=None)[source]

Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file.

mode defaults to os.F_OK | os.X_OK. path defaults to the result of os.environ.get(“PATH”), or can be overridden with a custom search path.

Utility functions to operate on filesystem folders.

class aiida.common.folders.Folder(abspath, folder_limit=None)[source]

Bases: object

A class to manage generic folders, avoiding to get out of specific given folder borders.

Todo

fix this, os.path.commonprefix of /a/b/c and /a/b2/c will give a/b, check if this is wanted or if we want to put trailing slashes. (or if we want to use os.path.relpath and check for a string starting with os.pardir?)

Todo

rethink whether the folder_limit option is still useful. If not, remove it alltogether (it was a nice feature, but unfortunately all the calls to os.path.abspath or normpath are quite slow).

__dict__ = mappingproxy({'__module__': 'aiida.common.folders', '__doc__': '\n A class to manage generic folders, avoiding to get out of\n specific given folder borders.\n\n .. todo::\n fix this, os.path.commonprefix of /a/b/c and /a/b2/c will give\n a/b, check if this is wanted or if we want to put trailing slashes.\n (or if we want to use os.path.relpath and check for a string starting\n with os.pardir?)\n\n .. todo::\n rethink whether the folder_limit option is still useful. If not, remove\n it alltogether (it was a nice feature, but unfortunately all the calls\n to os.path.abspath or normpath are quite slow).\n ', '__init__': <function Folder.__init__>, 'mode_dir': <property object>, 'mode_file': <property object>, 'get_subfolder': <function Folder.get_subfolder>, 'get_content_list': <function Folder.get_content_list>, 'create_symlink': <function Folder.create_symlink>, 'insert_path': <function Folder.insert_path>, 'create_file_from_filelike': <function Folder.create_file_from_filelike>, 'remove_path': <function Folder.remove_path>, 'get_abs_path': <function Folder.get_abs_path>, 'open': <function Folder.open>, 'abspath': <property object>, 'folder_limit': <property object>, 'exists': <function Folder.exists>, 'isfile': <function Folder.isfile>, 'isdir': <function Folder.isdir>, 'erase': <function Folder.erase>, 'create': <function Folder.create>, 'replace_with_folder': <function Folder.replace_with_folder>, '__dict__': <attribute '__dict__' of 'Folder' objects>, '__weakref__': <attribute '__weakref__' of 'Folder' objects>})
__init__(abspath, folder_limit=None)[source]

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

__module__ = 'aiida.common.folders'
__weakref__

list of weak references to the object (if defined)

property abspath

The absolute path of the folder.

create()[source]

Creates the folder, if it does not exist on the disk yet.

It will also create top directories, if absent.

It is always safe to call it, it will do nothing if the folder already exists.

create_file_from_filelike(filelike, filename, mode='wb', encoding=None)[source]

Create a file with the given filename from a filelike object.

Parameters
  • filelike – a filelike object whose contents to copy

  • filename – the filename for the file that is to be created

  • mode – the mode with which the target file will be written

  • encoding – the encoding with which the target file will be written

Returns

the absolute filepath of the created file

Create a symlink inside the folder to the location ‘src’.

Parameters
  • src – the location to which the symlink must point. Can be either a relative or an absolute path. Should, however, be relative to work properly also when the repository is moved!

  • name – the filename of the symlink to be created.

erase(create_empty_folder=False)[source]

Erases the folder. Should be called only in very specific cases, in general folder should not be erased!

Doesn’t complain if the folder does not exist.

Parameters

create_empty_folder – if True, after erasing, creates an empty dir.

exists()[source]

Return True if the folder exists, False otherwise.

property folder_limit

The folder limit that cannot be crossed when creating files and folders.

get_abs_path(relpath, check_existence=False)[source]

Return an absolute path for a file or folder in this folder.

The advantage of using this method is that it checks that filename is a valid filename within this folder, and not something e.g. containing slashes.

Parameters
  • filename – The file or directory.

  • check_existence – if False, just return the file path. Otherwise, also check if the file or directory actually exists. Raise OSError if it does not.

get_content_list(pattern='*', only_paths=True)[source]

Return a list of files (and subfolders) in the folder, matching a given pattern.

Example: If you want to exclude files starting with a dot, you can call this method with pattern='[!.]*'

Parameters
  • pattern – a pattern for the file/folder names, using Unix filename pattern matching (see Python standard module fnmatch). By default, pattern is ‘*’, matching all files and folders.

  • only_paths – if False (default), return pairs (name, is_file). if True, return only a flat list.

Returns

a list of tuples of two elements, the first is the file name and the second is True if the element is a file, False if it is a directory.

get_subfolder(subfolder, create=False, reset_limit=False)[source]

Return a Folder object pointing to a subfolder.

Parameters
  • subfolder – a string with the relative path of the subfolder, relative to the absolute path of this object. Note that this may also contain ‘..’ parts, as far as this does not go beyond the folder_limit.

  • create – if True, the new subfolder is created, if it does not exist.

  • reset_limit – when doing b = a.get_subfolder('xxx', reset_limit=False), the limit of b will be the same limit of a. if True, the limit will be set to the boundaries of folder b.

Returns

a Folder object pointing to the subfolder.

insert_path(src, dest_name=None, overwrite=True)[source]

Copy a file to the folder.

Parameters
  • src – the source filename to copy

  • dest_name – if None, the same basename of src is used. Otherwise, the destination filename will have this file name.

  • overwrite – if False, raises an error on existing destination; otherwise, delete it first.

isdir(relpath)[source]

Return True if ‘relpath’ exists inside the folder and is a directory, False otherwise.

isfile(relpath)[source]

Return True if ‘relpath’ exists inside the folder and is a file, False otherwise.

property mode_dir

Return the mode with which the folders should be created

property mode_file

Return the mode with which the files should be created

open(name, mode='r', encoding='utf8', check_existence=False)[source]

Open a file in the current folder and return the corresponding file object.

Parameters

check_existence – if False, just return the file path. Otherwise, also check if the file or directory actually exists. Raise OSError if it does not.

remove_path(filename)[source]

Remove a file or folder from the folder.

Parameters

filename – the relative path name to remove

replace_with_folder(srcdir, move=False, overwrite=False)[source]

This routine copies or moves the source folder ‘srcdir’ to the local folder pointed by this Folder object.

Parameters
  • srcdir – the source folder on the disk; this must be a string with an absolute path

  • move – if True, the srcdir is moved to the repository. Otherwise, it is only copied.

  • overwrite – if True, the folder will be erased first. if False, a IOError is raised if the folder already exists. Whatever the value of this flag, parent directories will be created, if needed.

Raises

OSError or IOError: in case of problems accessing or writing the files.

Raises

ValueError: if the section is not recognized.

class aiida.common.folders.RepositoryFolder(section, uuid, subfolder='.')[source]

Bases: aiida.common.folders.Folder

A class to manage the local AiiDA repository folders.

__init__(section, uuid, subfolder='.')[source]

Initializes the object by pointing it to a folder in the repository.

Pass the uuid as a string.

__module__ = 'aiida.common.folders'
get_topdir()[source]

Returns the top directory, i.e., the section/uuid folder object.

property section

The section to which this folder belongs.

property subfolder

The subfolder within the section/uuid folder.

property uuid

The uuid to which this folder belongs.

class aiida.common.folders.SandboxFolder(sandbox_in_repo=True)[source]

Bases: aiida.common.folders.Folder

A class to manage the creation and management of a sandbox folder.

Note: this class must be used within a context manager, i.e.:

with SandboxFolder as f:

## do something with f

In this way, the sandbox folder is removed from disk (if it wasn’t removed already) when exiting the ‘with’ block.

Todo

Implement check of whether the folder has been removed.

__enter__()[source]

Called when entering in the with statement

__exit__(exc_type, exc_value, traceback)[source]

In exit, I remove the sandbox folder from disk, if it still exists

__init__(sandbox_in_repo=True)[source]

Initializes the object by creating a new temporary folder in the sandbox.

Parameters

sandbox_in_repo (bool) – If True (default), creates the folder in the repository. If false, relies on the defaults of tempfile.mkdtemp

__module__ = 'aiida.common.folders'
class aiida.common.folders.SubmitTestFolder(basepath='submit_test')[source]

Bases: aiida.common.folders.Folder

Sandbox folder that can be used for the test submission of CalcJobs.

The directory will be created in the current working directory with a configurable basename. Then a sub folder will be created within this base folder based on the current date and an index in order to not overwrite already existing created test folders.

__enter__()[source]

Return the sub folder that should be Called when entering in the with statement.

__exit__(exc_type, exc_value, traceback)[source]

When context manager is exited, do not delete the folder.

__init__(basepath='submit_test')[source]

Construct and create the sandbox folder.

The directory will be created in the current working directory with the name given by basepath. Then a sub folder will be created within this base folder based on the current date and an index in order to not overwrite already existing created test folders.

Parameters

basepath – name of the base directory that will be created in the current working directory

__module__ = 'aiida.common.folders'
_sub_folder = None

Common password and hash generation functions.

aiida.common.hashing._(folder, **kwargs)[source]

Hash the content of a Folder object. The name of the folder itself is actually ignored :param ignored_folder_content: list of filenames to be ignored for the hashing

aiida.common.hashing._make_hash(object_to_hash, **_)[source]

Implementation of the make_hash function. The hash is created as a 28 byte integer, and only later converted to a string.

aiida.common.hashing._single_digest(obj_type, obj_bytes=b'')[source]
aiida.common.hashing.float_to_text(value, sig)[source]

Convert float to text string for computing hash. Preseve up to N significant number given by sig.

Parameters
  • value – the float value to convert

  • sig – choose how many digits after the comma should be output

aiida.common.hashing.get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')[source]

Returns a securely generated random string.

The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits

aiida.common.hashing.make_hash(object_to_hash, **kwargs)[source]

Makes a hash from a dictionary, list, tuple or set to any level, that contains only other hashable or nonhashable types (including lists, tuples, sets, and dictionaries).

Parameters

object_to_hash – the object to hash

Returns

a unique hash

There are a lot of modules providing functionalities to create unique hashes for hashable values. However, getting hashes for nonhashable items like sets or dictionaries is not easily doable because order is not fixed. This leads to the peril of getting different hashes for the same dictionary.

This function avoids this by recursing through nonhashable items and hashing iteratively. Uses python’s sorted function to sort unsorted sets and dictionaries by sorting the hashed keys.

Abstracts JSON usage to ensure compatibility with Python2 and Python3.

Use this module prefentially over standard json to ensure compatibility. Also note the conventions for using io.open for dump and dumps.

aiida.common.json.dump(data, fhandle, **kwargs)[source]

Write JSON encoded ‘data’ to a file-like object, fhandle In Py2/3, use io.open(filename, ‘wb’) to write. The utf8write object is used to ensure that the resulting serialised data is encoding as UTF8. Any strings with non-ASCII characters need to be unicode strings. We use ensure_ascii=False to write unicode characters specifically as this improves the readability of the json and reduces the file size.

aiida.common.json.dumps(data, **kwargs)[source]

Write JSON encoded ‘data’ to a string. simplejson is useful here as it always returns unicode if ensure_ascii=False is used, unlike the standard library json, rather than being dependant on the input. We use also ensure_ascii=False to write unicode characters specifically as this improves the readability of the json and reduces the file size. When writing to file, use io.open(filename, ‘w’, encoding=’utf8’)

aiida.common.json.load(fhandle, **kwargs)[source]

Deserialise a JSON file.

For Py2/Py3 compatibility, io.open(filename, ‘r’, encoding=’utf8’) should be used.

Raises

ValueError – if no valid JSON object could be decoded

aiida.common.json.loads(json_string, **kwargs)[source]

Deserialise a JSON string.

Raises

ValueError – if no valid JSON object could be decoded

Utilities that extend the basic python language.

class aiida.common.lang.EmptyContextManager[source]

Bases: object

A dummy/no-op context manager.

__dict__ = mappingproxy({'__module__': 'aiida.common.lang', '__doc__': '\n A dummy/no-op context manager.\n ', '__enter__': <function EmptyContextManager.__enter__>, '__exit__': <function EmptyContextManager.__exit__>, '__dict__': <attribute '__dict__' of 'EmptyContextManager' objects>, '__weakref__': <attribute '__weakref__' of 'EmptyContextManager' objects>})
__enter__()[source]
__exit__(exc_type, exc_value, traceback)[source]
__module__ = 'aiida.common.lang'
__weakref__

list of weak references to the object (if defined)

class aiida.common.lang.abstractclassmethod(callable)[source]

Bases: classmethod

A decorator indicating abstract classmethods.

Backported from python3.

__init__(callable)[source]

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

__isabstractmethod__ = True
__module__ = 'aiida.common.lang'
__weakref__

list of weak references to the object (if defined)

class aiida.common.lang.abstractstaticmethod(callable)[source]

Bases: staticmethod

A decorator indicating abstract staticmethods.

Similar to abstractmethod. Backported from python3.

__init__(callable)[source]

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

__isabstractmethod__ = True
__module__ = 'aiida.common.lang'
__weakref__

list of weak references to the object (if defined)

class aiida.common.lang.classproperty(getter)[source]

Bases: object

A class that, when used as a decorator, works as if the two decorators @property and @classmethod where applied together (i.e., the object works as a property, both for the Class and for any of its instance; and is called with the class cls rather than with the instance as its first argument).

__dict__ = mappingproxy({'__module__': 'aiida.common.lang', '__doc__': '\n A class that, when used as a decorator, works as if the\n two decorators @property and @classmethod where applied together\n (i.e., the object works as a property, both for the Class and for any\n of its instance; and is called with the class cls rather than with the\n instance as its first argument).\n ', '__init__': <function classproperty.__init__>, '__get__': <function classproperty.__get__>, '__dict__': <attribute '__dict__' of 'classproperty' objects>, '__weakref__': <attribute '__weakref__' of 'classproperty' objects>})
__get__(instance, owner)[source]
__init__(getter)[source]

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

__module__ = 'aiida.common.lang'
__weakref__

list of weak references to the object (if defined)

class aiida.common.lang.combomethod(method)[source]

Bases: object

A decorator that wraps a function that can be both a classmethod or instancemethod and behaves accordingly:

class A():

    @combomethod
    def do(self, **kwargs):
        isclass = kwargs.get('isclass')
        if isclass:
            print("I am a class", self)
        else:
            print("I am an instance", self)

A.do()
A().do()

>>> I am a class __main__.A
>>> I am an instance <__main__.A instance at 0x7f2efb116e60>

Attention: For ease of handling, pass keyword isclass equal to True if this was called as a classmethod and False if this was called as an instance. The argument self is therefore ambiguous!

__dict__ = mappingproxy({'__module__': 'aiida.common.lang', '__doc__': '\n A decorator that wraps a function that can be both a classmethod or\n instancemethod and behaves accordingly::\n\n class A():\n\n @combomethod\n def do(self, **kwargs):\n isclass = kwargs.get(\'isclass\')\n if isclass:\n print("I am a class", self)\n else:\n print("I am an instance", self)\n\n A.do()\n A().do()\n\n >>> I am a class __main__.A\n >>> I am an instance <__main__.A instance>\n\n Attention: For ease of handling, pass keyword **isclass**\n equal to True if this was called as a classmethod and False if this\n was called as an instance.\n The argument self is therefore ambiguous!\n ', '__init__': <function combomethod.__init__>, '__get__': <function combomethod.__get__>, '__dict__': <attribute '__dict__' of 'combomethod' objects>, '__weakref__': <attribute '__weakref__' of 'combomethod' objects>})
__get__(obj=None, objtype=None)[source]
__init__(method)[source]

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

__module__ = 'aiida.common.lang'
__weakref__

list of weak references to the object (if defined)

aiida.common.lang.isidentifier(identifier)[source]

Return whether the given string is a valid python identifier.

Returns

boolean, True if identifier is valid, False otherwise

Raises

TypeError – if identifier is not string type

aiida.common.lang.override(func)
aiida.common.lang.override_decorator(check=False)[source]

Decorator to signal that a method from a base class is being overridden completely.

aiida.common.lang.protected(func)
aiida.common.lang.protected_decorator(check=False)[source]

Decorator to ensure that the decorated method is not called from outside the class hierarchy.

aiida.common.lang.type_check(what, of_type, msg=None, allow_none=False)[source]

Verify that object ‘what’ is of type ‘of_type’ and if not the case, raise a TypeError.

Parameters
  • what – the object to check

  • of_type – the type (or tuple of types) to compare to

  • msg – if specified, allows to customize the message that is passed within the TypeError exception

  • allow_none – boolean, if True will not raise if the passed what is None

Module with utilities and data structures pertaining to links between nodes in the provenance graph.

class aiida.common.links.GraphTraversalRule(link_type, direction, toggleable, default)

Bases: tuple

A namedtuple that defines a graph traversal rule.

When starting from a certain sub set of nodes, the graph traversal rules specify which links should be followed to add adjacent nodes to finally arrive at a set of nodes that represent a valid and consistent sub graph.

Parameters
  • link_type – the LinkType that the rule applies to

  • direction – whether the link type should be followed backwards or forwards

  • toggleable – boolean to indicate whether the rule can be changed from the default value. If this is False it means the default value can never be changed as it will result in an inconsistent graph.

  • default – boolean, the default value of the rule, if True means that the link type for the given direction should be followed.

__getnewargs__()

Return self as a plain tuple. Used by copy and pickle.

__module__ = 'aiida.common.links'
static __new__(_cls, link_type, direction, toggleable, default)

Create new instance of GraphTraversalRule(link_type, direction, toggleable, default)

__repr__()

Return a nicely formatted representation string

__slots__ = ()
_asdict()

Return a new OrderedDict which maps field names to their values.

_fields = ('link_type', 'direction', 'toggleable', 'default')
_fields_defaults = {}
classmethod _make(iterable)

Make a new GraphTraversalRule object from a sequence or iterable

_replace(**kwds)

Return a new GraphTraversalRule object replacing specified fields with new values

property default

Alias for field number 3

property direction

Alias for field number 1

Alias for field number 0

property toggleable

Alias for field number 2

class aiida.common.links.GraphTraversalRules[source]

Bases: enum.Enum

Graph traversal rules when deleting or exporting nodes.

DELETE = {'call_calc_backward': GraphTraversalRule(link_type=<LinkType.CALL_CALC: 'call_calc'>, direction='backward', toggleable=False, default=True), 'call_calc_forward': GraphTraversalRule(link_type=<LinkType.CALL_CALC: 'call_calc'>, direction='forward', toggleable=True, default=False), 'call_work_backward': GraphTraversalRule(link_type=<LinkType.CALL_WORK: 'call_work'>, direction='backward', toggleable=False, default=True), 'call_work_forward': GraphTraversalRule(link_type=<LinkType.CALL_WORK: 'call_work'>, direction='forward', toggleable=True, default=False), 'create_backward': GraphTraversalRule(link_type=<LinkType.CREATE: 'create'>, direction='backward', toggleable=False, default=True), 'create_forward': GraphTraversalRule(link_type=<LinkType.CREATE: 'create'>, direction='forward', toggleable=True, default=True), 'input_calc_backward': GraphTraversalRule(link_type=<LinkType.INPUT_CALC: 'input_calc'>, direction='backward', toggleable=False, default=False), 'input_calc_forward': GraphTraversalRule(link_type=<LinkType.INPUT_CALC: 'input_calc'>, direction='forward', toggleable=False, default=True), 'input_work_backward': GraphTraversalRule(link_type=<LinkType.INPUT_WORK: 'input_work'>, direction='backward', toggleable=False, default=False), 'input_work_forward': GraphTraversalRule(link_type=<LinkType.INPUT_WORK: 'input_work'>, direction='forward', toggleable=False, default=True), 'return_backward': GraphTraversalRule(link_type=<LinkType.RETURN: 'return'>, direction='backward', toggleable=False, default=True), 'return_forward': GraphTraversalRule(link_type=<LinkType.RETURN: 'return'>, direction='forward', toggleable=False, default=False)}
EXPORT = {'call_calc_backward': GraphTraversalRule(link_type=<LinkType.CALL_CALC: 'call_calc'>, direction='backward', toggleable=True, default=False), 'call_calc_forward': GraphTraversalRule(link_type=<LinkType.CALL_CALC: 'call_calc'>, direction='forward', toggleable=False, default=True), 'call_work_backward': GraphTraversalRule(link_type=<LinkType.CALL_WORK: 'call_work'>, direction='backward', toggleable=True, default=False), 'call_work_forward': GraphTraversalRule(link_type=<LinkType.CALL_WORK: 'call_work'>, direction='forward', toggleable=False, default=True), 'create_backward': GraphTraversalRule(link_type=<LinkType.CREATE: 'create'>, direction='backward', toggleable=True, default=True), 'create_forward': GraphTraversalRule(link_type=<LinkType.CREATE: 'create'>, direction='forward', toggleable=False, default=True), 'input_calc_backward': GraphTraversalRule(link_type=<LinkType.INPUT_CALC: 'input_calc'>, direction='backward', toggleable=False, default=True), 'input_calc_forward': GraphTraversalRule(link_type=<LinkType.INPUT_CALC: 'input_calc'>, direction='forward', toggleable=True, default=False), 'input_work_backward': GraphTraversalRule(link_type=<LinkType.INPUT_WORK: 'input_work'>, direction='backward', toggleable=False, default=True), 'input_work_forward': GraphTraversalRule(link_type=<LinkType.INPUT_WORK: 'input_work'>, direction='forward', toggleable=True, default=False), 'return_backward': GraphTraversalRule(link_type=<LinkType.RETURN: 'return'>, direction='backward', toggleable=True, default=False), 'return_forward': GraphTraversalRule(link_type=<LinkType.RETURN: 'return'>, direction='forward', toggleable=False, default=True)}
__module__ = 'aiida.common.links'
class aiida.common.links.LinkType[source]

Bases: enum.Enum

A simple enum of allowed link types.

CALL_CALC = 'call_calc'
CALL_WORK = 'call_work'
CREATE = 'create'
INPUT_CALC = 'input_calc'
INPUT_WORK = 'input_work'
RETURN = 'return'
__module__ = 'aiida.common.links'

Validate the given link label.

Valid link labels adhere to the following restrictions:

  • Has to be a valid python identifier

  • Can only contain alphanumeric characters and underscores

  • Can not start or end with an underscore

Raises
  • TypeError – if the link label is not a string type

  • ValueError – if the link label is invalid

Module for all logging methods/classes that don’t need the ORM.

aiida.common.log.override_log_level(level=50)[source]

Temporarily adjust the log-level of logger.

Utility functions to operate on datetime objects.

aiida.common.timezone.datetime_to_isoformat(value)[source]

Convert a datetime object to string representations in ISO format.

Parameters

value – a datetime object

aiida.common.timezone.delta(from_time, to_time=None)[source]

Return the datetime object representing the different between two datetime objects.

Parameters
  • from_time – starting datetime object

  • to_time – end datetime object

Returns

the delta datetime object

aiida.common.timezone.get_current_timezone()[source]

Return the current timezone.

Returns

current timezone

aiida.common.timezone.is_aware(value)[source]

Return whether the given datetime object is timezone aware

Returns

boolean, True if aware, False otherwise

aiida.common.timezone.is_naive(value)[source]

Return whether the given datetime object is timezone naive

Returns

boolean, True if naive, False otherwise

aiida.common.timezone.isoformat_to_datetime(value)[source]

Convert string representation of a datetime in ISO format to a datetime object.

Parameters

value – a ISO format string representation of a datetime object

aiida.common.timezone.localtime(value, timezone=None)[source]

Converts an aware datetime.datetime to local time.

Local time is defined by the current time zone, unless another time zone is specified.

aiida.common.timezone.make_aware(value, timezone=None, is_dst=None)[source]

Make the given datetime object timezone aware.

Parameters
  • value – datetime object to make aware

  • timezone

  • is_dst

Returns

aiida.common.timezone.now()[source]

Return the datetime object of the current time.

Returns

datetime object represeting current time

Miscellaneous generic utility functions and classes.

class aiida.common.utils.ArrayCounter[source]

Bases: object

A counter & a method that increments it and returns its value. It is used in various tests.

__dict__ = mappingproxy({'__module__': 'aiida.common.utils', '__doc__': '\n A counter & a method that increments it and returns its value.\n It is used in various tests.\n ', 'seq': None, '__init__': <function ArrayCounter.__init__>, 'array_counter': <function ArrayCounter.array_counter>, '__dict__': <attribute '__dict__' of 'ArrayCounter' objects>, '__weakref__': <attribute '__weakref__' of 'ArrayCounter' objects>})
__init__()[source]

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

__module__ = 'aiida.common.utils'
__weakref__

list of weak references to the object (if defined)

array_counter()[source]
seq = None
class aiida.common.utils.Capturing(capture_stderr=False)[source]

Bases: object

This class captures stdout and returns it (as a list, split by lines).

Note: if you raise a SystemExit, you have to catch it outside. E.g., in our tests, this works:

import sys
with self.assertRaises(SystemExit):
    with Capturing() as output:
        sys.exit()

But out of the testing environment, the code instead just exits.

To use it, access the obj.stdout_lines, or just iterate over the object

Parameters

capture_stderr – if True, also captures sys.stderr. To access the lines, use obj.stderr_lines. If False, obj.stderr_lines is None.

__dict__ = mappingproxy({'__module__': 'aiida.common.utils', '__doc__': '\n This class captures stdout and returns it\n (as a list, split by lines).\n\n Note: if you raise a SystemExit, you have to catch it outside.\n E.g., in our tests, this works::\n\n import sys\n with self.assertRaises(SystemExit):\n with Capturing() as output:\n sys.exit()\n\n But out of the testing environment, the code instead just exits.\n\n To use it, access the obj.stdout_lines, or just iterate over the object\n\n :param capture_stderr: if True, also captures sys.stderr. To access the\n lines, use obj.stderr_lines. If False, obj.stderr_lines is None.\n ', '__init__': <function Capturing.__init__>, '__enter__': <function Capturing.__enter__>, '__exit__': <function Capturing.__exit__>, '__str__': <function Capturing.__str__>, '__iter__': <function Capturing.__iter__>, '__dict__': <attribute '__dict__' of 'Capturing' objects>, '__weakref__': <attribute '__weakref__' of 'Capturing' objects>})
__enter__()[source]

Enter the context where all output is captured.

__exit__(*args)[source]

Exit the context where all output is captured.

__init__(capture_stderr=False)[source]

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

__iter__()[source]
__module__ = 'aiida.common.utils'
__str__()[source]

Return str(self).

__weakref__

list of weak references to the object (if defined)

class aiida.common.utils.ErrorAccumulator(*error_cls)[source]

Bases: object

Allows to run a number of functions and collect all the errors they raise

This allows to validate multiple things and tell the user about all the errors encountered at once. Works best if the individual functions do not depend on each other.

Does not allow to trace the stack of each error, therefore do not use for debugging, but for semantical checking with user friendly error messages.

__dict__ = mappingproxy({'__module__': 'aiida.common.utils', '__doc__': '\n Allows to run a number of functions and collect all the errors they raise\n\n This allows to validate multiple things and tell the user about all the\n errors encountered at once. Works best if the individual functions do not depend on each other.\n\n Does not allow to trace the stack of each error, therefore do not use for debugging, but for\n semantical checking with user friendly error messages.\n ', '__init__': <function ErrorAccumulator.__init__>, 'run': <function ErrorAccumulator.run>, 'success': <function ErrorAccumulator.success>, 'result': <function ErrorAccumulator.result>, 'raise_errors': <function ErrorAccumulator.raise_errors>, '__dict__': <attribute '__dict__' of 'ErrorAccumulator' objects>, '__weakref__': <attribute '__weakref__' of 'ErrorAccumulator' objects>})
__init__(*error_cls)[source]

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

__module__ = 'aiida.common.utils'
__weakref__

list of weak references to the object (if defined)

raise_errors(raise_cls)[source]
result(raise_error=<class 'Exception'>)[source]
run(function, *args, **kwargs)[source]
success()[source]
class aiida.common.utils.Prettifier(format)[source]

Bases: object

Class to manage prettifiers (typically for labels of kpoints in band plots)

__dict__ = mappingproxy({'__module__': 'aiida.common.utils', '__doc__': '\n Class to manage prettifiers (typically for labels of kpoints\n in band plots)\n ', '_prettify_label_pass': <classmethod object>, '_prettify_label_agr': <classmethod object>, '_prettify_label_agr_simple': <classmethod object>, '_prettify_label_gnuplot': <classmethod object>, '_prettify_label_gnuplot_simple': <classmethod object>, '_prettify_label_latex': <classmethod object>, '_prettify_label_latex_simple': <classmethod object>, 'prettifiers': <aiida.common.lang.classproperty object>, 'get_prettifiers': <classmethod object>, '__init__': <function Prettifier.__init__>, 'prettify': <function Prettifier.prettify>, '__dict__': <attribute '__dict__' of 'Prettifier' objects>, '__weakref__': <attribute '__weakref__' of 'Prettifier' objects>})
__init__(format)[source]

Create a class to pretttify strings of a given format

Parameters

format – a string with the format to use to prettify. Valid formats are obtained from self.prettifiers

__module__ = 'aiida.common.utils'
__weakref__

list of weak references to the object (if defined)

classmethod _prettify_label_agr(label)[source]

Prettifier for XMGrace

Parameters

label – a string to prettify

classmethod _prettify_label_agr_simple(label)[source]

Prettifier for XMGrace (for old label names)

Parameters

label – a string to prettify

classmethod _prettify_label_gnuplot(label)[source]

Prettifier for Gnuplot

Note

uses unicode, returns unicode strings (potentially, if needed)

Parameters

label – a string to prettify

classmethod _prettify_label_gnuplot_simple(label)[source]

Prettifier for Gnuplot (for old label names)

Note

uses unicode, returns unicode strings (potentially, if needed)

Parameters

label – a string to prettify

classmethod _prettify_label_latex(label)[source]

Prettifier for matplotlib, using LaTeX syntax

Parameters

label – a string to prettify

classmethod _prettify_label_latex_simple(label)[source]

Prettifier for matplotlib, using LaTeX syntax (for old label names)

Parameters

label – a string to prettify

classmethod _prettify_label_pass(label)[source]

No-op prettifier, simply returns the same label

Parameters

label – a string to prettify

classmethod get_prettifiers()[source]

Return a list of valid prettifier strings

Returns

a list of strings

prettifiers = {'agr_seekpath': <bound method Prettifier._prettify_label_agr of <class 'aiida.common.utils.Prettifier'>>, 'agr_simple': <bound method Prettifier._prettify_label_agr_simple of <class 'aiida.common.utils.Prettifier'>>, 'gnuplot_seekpath': <bound method Prettifier._prettify_label_gnuplot of <class 'aiida.common.utils.Prettifier'>>, 'gnuplot_simple': <bound method Prettifier._prettify_label_gnuplot_simple of <class 'aiida.common.utils.Prettifier'>>, 'latex_seekpath': <bound method Prettifier._prettify_label_latex of <class 'aiida.common.utils.Prettifier'>>, 'latex_simple': <bound method Prettifier._prettify_label_latex_simple of <class 'aiida.common.utils.Prettifier'>>, 'pass': <bound method Prettifier._prettify_label_pass of <class 'aiida.common.utils.Prettifier'>>}
prettify(label)[source]

Prettify a label using the format passed in the initializer

Parameters

label – the string to prettify

Returns

a prettified string

aiida.common.utils.are_dir_trees_equal(dir1, dir2)[source]

Compare two directories recursively. Files in each directory are assumed to be equal if their names and contents are equal.

@param dir1: First directory path @param dir2: Second directory path

@return: True if the directory trees are the same and

there were no errors while accessing the directories or files, False otherwise.

aiida.common.utils.get_class_string(obj)[source]

Return the string identifying the class of the object (module + object name, joined by dots).

It works both for classes and for class instances.

aiida.common.utils.get_new_uuid()[source]

Return a new UUID (typically to be used for new nodes). It uses the UUID version specified in aiida.backends.settings.AIIDANODES_UUID_VERSION

aiida.common.utils.get_object_from_string(class_string)[source]

Given a string identifying an object (as returned by the get_class_string method) load and return the actual object.

aiida.common.utils.get_repository_folder(subfolder=None)[source]

Return the top folder of the local repository.

aiida.common.utils.get_unique_filename(filename, list_of_filenames)[source]

Return a unique filename that can be added to the list_of_filenames.

If filename is not in list_of_filenames, it simply returns the filename string itself. Otherwise, it appends a integer number to the filename (before the extension) until it finds a unique filename.

Parameters
  • filename – the filename to add

  • list_of_filenames – the list of filenames to which filename should be added, without name duplicates

Returns

Either filename or its modification, with a number appended between the name and the extension.

aiida.common.utils.grouper(n, iterable)[source]

Given an iterable, returns an iterable that returns tuples of groups of elements from iterable of length n, except the last one that has the required length to exaust iterable (i.e., there is no filling applied).

Parameters
  • n – length of each tuple (except the last one,that will have length <= n

  • iterable – the iterable to divide in groups

aiida.common.utils.join_labels(labels, join_symbol='|', threshold=1e-06)[source]

Join labels with a joining symbol when they are very close

Parameters
  • labels – a list of length-2 tuples, in the format(position, label)

  • join_symbol – the string to use to join different paths. By default, a pipe

  • threshold – the threshold to decide if two float values are the same and should be joined

Returns

the same list as labels, but with the second value possibly replaced with strings joined when close enough

aiida.common.utils.prettify_labels(labels, format=None)[source]

Prettify label for typesetting in various formats

Parameters
  • labels – a list of length-2 tuples, in the format(position, label)

  • format – a string with the format for the prettifier (e.g. ‘agr’, ‘matplotlib’, …)

Returns

the same list as labels, but with the second value possibly replaced with a prettified version that typesets nicely in the selected format

aiida.common.utils.str_timedelta(dt, max_num_fields=3, short=False, negative_to_zero=False)[source]

Given a dt in seconds, return it in a HH:MM:SS format.

Parameters
  • dt – a TimeDelta object

  • max_num_fields – maximum number of non-zero fields to show (for instance if the number of days is non-zero, shows only days, hours and minutes, but not seconds)

  • short – if False, print always max_num_fields fields, even if they are zero. If True, do not print the first fields, if they are zero.

  • negative_to_zero – if True, set dt = 0 if dt < 0.

aiida.common.utils.strip_prefix(full_string, prefix)[source]

Strip the prefix from the given string and return it. If the prefix is not present the original string will be returned unaltered

Parameters
  • full_string – the string from which to remove the prefix

  • prefix – the prefix to remove

Returns

the string with prefix removed

aiida.common.utils.validate_list_of_string_tuples(val, tuple_length)[source]

Check that:

  1. val is a list or tuple

  2. each element of the list:

  1. is a list or tuple

  2. is of length equal to the parameter tuple_length

  3. each of the two elements is a string

Return if valid, raise ValidationError if invalid

Define warnings that can be thrown by AiiDA.

exception aiida.common.warnings.AiidaDeprecationWarning[source]

Bases: Warning

Class for AiiDA deprecations.

It does not inherit, on purpose, from DeprecationWarning as this would be filtered out by default. Enabled by default, you can disable it by running in the shell:

verdi config warnings.showdeprecations False
__module__ = 'aiida.common.warnings'
__weakref__

list of weak references to the object (if defined)

exception aiida.common.warnings.AiidaEntryPointWarning[source]

Bases: Warning

Class for warnings concerning AiiDA entry points.

It does not inherit, on purpose, from DeprecationWarning as this would be filtered out by default.

__module__ = 'aiida.common.warnings'
__weakref__

list of weak references to the object (if defined)