aiida.common documentation

Internal functionality that is needed by multiple modules of AiiDA

Calculation datastructures

This module defines the main data structures used by the Calculation.

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

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


  • 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

  • local_copy_list: a list of tuples with format (‘localabspath’, ‘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

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

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

aiida.common.datastructures.sort_states(list_states, use_key=False)[source]

Given a list of state names, return a sorted list of states (the first is the most recent) sorted according to their logical appearance in the DB (i.e., NEW before of SUBMITTING before of FINISHED).


The order of the internal variable _sorted_datastates is used.

  • list_states – a list (or tuple) of state strings.
  • use_key – if True, expects that each element is not just a string, but a pair (someobject, string). Only string is used to sort (should be the state string), and only someobject is returned in the final list.

a sorted list of the given data states.


ValueError – if any of the given states is not a valid state.


This module defines the (physical) constants that are used throughout the code. Note that


exception aiida.common.exceptions.AiidaException[source]

Base class for all AiiDA exceptions.

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

exception aiida.common.exceptions.AuthenticationError[source]

Raised when a user tries to access a resource for which it is not authenticated, e.g. an aiidauser tries to access a computer for which there is no entry in the AuthInfo table.

exception aiida.common.exceptions.ConfigurationError[source]

Error raised when there is a configuration error in AiiDA.

exception aiida.common.exceptions.ContentNotExistent[source]

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

exception aiida.common.exceptions.DbContentError[source]

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

exception aiida.common.exceptions.FailedError[source]

Raised when accessing a calculation that is in the FAILED status

exception aiida.common.exceptions.FeatureDisabled[source]

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

exception aiida.common.exceptions.FeatureNotAvailable[source]

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

exception aiida.common.exceptions.InputValidationError[source]

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

exception aiida.common.exceptions.InternalError[source]

Error raised when there is an internal error of AiiDA.

exception aiida.common.exceptions.InvalidOperation[source]

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)

exception aiida.common.exceptions.LicensingException[source]

Raised when requirements for data licensing are not met.

exception aiida.common.exceptions.LoadingPluginFailed[source]

Raised when loading a plugin through the plugin loader fails

exception aiida.common.exceptions.LockPresent[source]

Raised when a lock is requested, but cannot be acquired.

exception aiida.common.exceptions.MissingPluginError[source]

Raised when the user tries to use a plugin that is not available or does not exist.

exception aiida.common.exceptions.ModificationNotAllowed[source]

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

exception aiida.common.exceptions.MultipleObjectsError[source]

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

exception aiida.common.exceptions.NotExistent[source]

Raised when the required entity does not exist.

exception aiida.common.exceptions.ParsingError[source]

Generic error raised when there is a parsing error

exception aiida.common.exceptions.PluginInternalError[source]

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

exception aiida.common.exceptions.ProfileConfigurationError[source]

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

exception aiida.common.exceptions.RemoteOperationError[source]

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

exception aiida.common.exceptions.TestsNotAllowedError[source]

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

This is to prevent data loss.

exception aiida.common.exceptions.UniquenessError[source]

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

exception aiida.common.exceptions.ValidationError[source]

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

exception aiida.common.exceptions.WorkflowInputValidationError[source]

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

Extended dictionaries

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

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.


Shallow copy.

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

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:


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.


Return the default keys defined in the instance.


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 the keys, if any validate_* method is available.

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

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')
classmethod get_valid_fields()[source]

Return the list of valid fields.


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

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


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?)


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).


The absolute path of the folder.


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(src_filelike, dest_name)[source]

Create a file from a file-like object.


if the current file position in src_filelike is not 0, only the contents from the current file position to the end of the file will be copied in the new file.

  • src_filelike – the file-like object (e.g., if you have a string called s, you can pass StringIO.StringIO(s))
  • dest_name – the destination filename will have this file name.

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

  • 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.

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.

Return True if the folder exists, False otherwise.


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.

  • 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='[!.]*'

  • 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.

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.

  • 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.

a Folder object pointing to the subfolder.

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

Copy a file to the folder.

  • 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.

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


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


Return the mode with which the folders should be created


Return the mode with which the files should be created

open(name, mode='r')[source]

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


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.

  • 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.

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


ValueError: if the section is not recognized.

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

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.


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


The section to which this folder belongs.


The subfolder within the section/uuid folder.


The uuid to which this folder belongs.

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

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.


Implement check of whether the folder has been removed.


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


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


class aiida.common.orbital.Orbital[source]

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

  • position – the absolute position (three floats) units in angstrom
  • x_orientation – x,y,z unit vector defining polar angle theta in spherical coordinates unitless
  • z_orientation – x,y,z unit vector defining azimuthal angle phi in spherical coordinates unitless
  • orientation_spin – x,y,z unit vector defining the spin orientation unitless
  • diffusivity – Float controls the radial term in orbital equation units are reciprocal Angstrom.
  • module_name – internal parameter, stores orbital type

returns the internal keys as a dictionary


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

Parameters:init_dict – the initialization dictionary

Factory method that returns a suitable Orbital subclass.

Parameters:module – a valid string recognized as a Orbital subclass

Orbital subclasses

The following are Orbital classes inheriting from Orbitals.


class aiida.common.orbital.realhydrogen.RealhydrogenOrbital[source]

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

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

Following the notation of table 3.1, 3.2 of Wannier90 user guide A brief description of what is meant by each of these labels:

  • radial_nodes – the number of radial nodes (or inflections) if no radial nodes are supplied, defaults to 0
  • angular_momentum – Angular quantum number, using real orbitals
  • magnetic_number – Magnetic quantum number, using real orbitals
  • spin – spin, up (1) down (-1) or unspecified (0)

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

classmethod get_name_from_quantum_numbers(angular_momentum, magnetic_number=None)[source]

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

classmethod get_quantum_numbers_from_name(name)[source]

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

Plugin loaders

Extension and eventually replacement of the aiida.common.old_pluginloader module

Allows loading plugins registered as setuptools entry points by separate pip-installed packages. defines drop-in replacement functionality to use the old filesystem based and the new setuptools based plugin systems in parallel.

aiida.common.pluginloader.BaseFactory(module, base_class, base_modname, suffix=None)[source]

Return a plugin class, also find external plugins

This is a front end to aiida.common.old_pluginloader.BaseFactory with a fallback to aiida.common.pluginloader.get_plugin check their relative docs for more info.

Note not all possible notations work for new plugins. Example:

BaseFactory('quantumespresso.cp', JobCalculation,
            suffix='Calculation') # <- finds cp also if new style

BaseFactory('job.quantumespresso.cp', Calculation,
            'aiida.orm.calculation') <- will find cp only if old style

find old and new plugins

If both are available for a given name, the old style plugin takes precedence.


gives group and entry point name for a given module if module is registered

Returns:tuple (group, entrypoint-name) if one entry point is found

create a mapping of modules to entry point groups / names

Parameters:short_group_name – bool, if True the leading ‘aiida.’ is cut off group names
Returns:dictionary, keys are modules, values are (group, entrypoint-name)
aiida.common.pluginloader.get_plugin(category, name)[source]

Return an instance of the class registered under the given name and for the specified plugin category.

  • category – the plugin category to load the plugin from, e.g. ‘transports’.
  • name – the name of the plugin
aiida.common.pluginloader.load_plugin(base_class, plugins_module, plugin_type)[source]

load file or extension point plugins using the file plugin interface.

Prefer file plugins and if not found, translate the arguments to extension point notation

Params:Look at the docstring of aiida.common.old_pluginloader.load_plugin for more Info
Returns:The plugin class

Get a list of plugins for the given category.

Passing example for the category will list all plugins registered under the entry point aiida.example.


class aiida.common.utils.ArrayCounter[source]

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

class aiida.common.utils.Prettifier(format)[source]

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

classmethod get_prettifiers()[source]

Return a list of valid prettifier strings

Returns:a list of strings

Prettify a label using the format passed in the initializer

Parameters:label – the string to prettify
Returns:a prettified string
class aiida.common.utils.abstractclassmethod(callable)[source]

A decorator indicating abstract classmethods.

Backported from python3.

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

A decorator indicating abstract staticmethods.

Similar to abstractmethod. Backported from python3.

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.ask_question(question, reply_type, allow_none_as_answer=True)[source]

This method asks a specific question, tries to parse the given reply and then it verifies the parsed answer. :param question: The question to be asked. :param reply_type: The type of the expected answer (int, datetime etc). It is needed for the parsing of the answer. :param allow_none_as_answer: Allow empty answers? :return: The parsed reply.

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

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).

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

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

class A():

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

>>> 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!

aiida.common.utils.conv_to_fortran(val, quote_strings=True)[source]
Parameters:val – the value to be read and converted to a Fortran-friendly string.
aiida.common.utils.conv_to_fortran_withlists(val, quote_strings=True)[source]

Same as conv_to_fortran but with extra logic to handle lists :param val: the value to be read and converted to a Fortran-friendly string.


Given a string, creates the suitable “default” display name: replace underscores with spaces, and capitalize each word.

Returns:the converted string

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


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.


Sharding of the UUID for the import/export


Flattens a list or a tuple In [2]: flatten_list([[[[[4],3]],[3],[‘a’,[3]]]]) Out[2]: [4, 3, 3, ‘a’, 3]

Parameters:value – A value, whether iterable or not
Returns:a list of nesting level 1

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

It works both for classes and for class instances.


Return the email (that is used as the username) configured during the first verdi install.


returns the minimum and maximum value for each dimension in the positions given

aiida.common.utils.get_fortfloat(key, txt, be_case_sensitive=True)[source]

Matches a fortran compatible specification of a float behind a defined key in a string. :param key: The key to look for :param txt: The string where to search for the key :param be_case_sensitive: An optional boolean whether to search case-sensitive, defaults to True

If abc is a key, and f is a float, number, than this regex will match t and return f in the following cases:

  • charsbefore, abc = f, charsafter
  • charsbefore abc = f charsafter
  • charsbefore, abc = f charsafter

and vice-versa. If no float is matched, returns None

Exampes of matchable floats are:

  • 0.1d2
  • 0.D-3
  • .2e1
  • -0.23
  • 232

Convert a file’s mode to a string of the form ‘-rwxrwxrwx’. Taken (simplified) from cpython 3.3 stat module:


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


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


Get a string that identifies this object which can be used to retrieve it via get_object_from_string().

Parameters:obj – The object to get the string for
Returns:The string that identifies the object

Return the top folder of the local repository.

aiida.common.utils.get_suggestion(provided_string, allowed_strings)[source]

Given a string and a list of allowed_strings, it returns a string to print on screen, with sensible text depending on whether no suggestion is found, or one or more than one suggestions are found.

provided_string: the string to compare allowed_strings: a list of valid strings
A string to print on output, to suggest to the user a possible valid value.
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.

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

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).

  • n – length of each tuple (except the last one,that will have length <= n
  • iterable – the iterable to divide in groups

Gunzip string contents.

Parameters:string – a gzipped string
Returns:a string

Gzip string contents.

Parameters:string – a string
Returns:a gzipped string

Checks whether a noun is singular :param pluralForm: a string defining an English noun :return: the t-ple (singular, pluralform). singular: True/Flalse if noun is singular/plural pluralfrom: (a string with the noun in the plural form))

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

Join labels with a joining symbol when they are very close

  • 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

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

aiida.common.utils.md5_file(filename, block_size_factor=128)[source]

Open a file and return its md5sum (hexdigested).

  • filename – the filename 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.

a string with the hexdigest md5.


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

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

Prettify label for typesetting in various formats

  • 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’, ...)

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.query_string(question, default)[source]

Asks a question (with the option to have a default, predefined answer, and depending on the default answer and the answer of the user the following options are available: - If the user replies (with a non empty answer), then his answer is returned. - If the default answer is None then the user has to reply with a non-empty answer. - If the default answer is not None, then it is returned if the user gives an empty answer. In the case of empty default answer and empty reply from the user, None is returned. :param question: The question that we want to ask the user. :param default: The default answer (if there is any) to the question asked. :return: The returned reply.

aiida.common.utils.query_yes_no(question, default='yes')[source]

Ask a yes/no question via raw_input() and return their answer.

“question” is a string that is presented to the user. “default” is the presumed answer if the user just hits <Enter>. It must be “yes” (the default), “no” or None (meaning an answer is required of the user).

The “answer” return value is True for “yes” or False for “no”.

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

Open a file and return its sha1sum (hexdigested).

  • 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.

a string with the hexdigest sha1.


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

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.

  • 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.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


Yields a tuple (natoms, comment, atomiter)`for each frame in a XYZ file where `atomiter is an iterator yielding a nested tuple (symbol, (x, y, z)) for each entry.

Parameters:string – a string containing XYZ-structured text